diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/AudioScore Ultimate 2020.1 V9.0.0 Crack How to Convert Audio to MIDI in Minutes.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/AudioScore Ultimate 2020.1 V9.0.0 Crack How to Convert Audio to MIDI in Minutes.md deleted file mode 100644 index 69c0711ad2051b7e5781127bd21dc288855b85b1..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/AudioScore Ultimate 2020.1 V9.0.0 Crack How to Convert Audio to MIDI in Minutes.md +++ /dev/null @@ -1,23 +0,0 @@ -
-

AudioScore Ultimate 2020.1 V9.0.0 Crack: A Powerful Audio Editing Software

- Are you looking for a software that can help you create, edit and transcribe audio files with ease? Do you want to record your own songs, import audio files from different sources, adjust the pitch and length of notes, and decipher your project into a score? If yes, then you might want to check out **AudioScore Ultimate**, a smug audio editing software that can do all these tasks and more. In this article, we will tell you everything you need to know about AudioScore Ultimate, including what it is, how to use it, why you need the cracked version of it, how to download and install it, and some frequently asked questions.

What is AudioScore Ultimate?

-

A brief introduction to the software and its features

- AudioScore Ultimate is a special application that allows you to record songs through a connected microphone device, import audio files from your PC or other sources, convert them to MIDI notes, edit them with various tools, and transcribe them into a score that can be printed or exported. AudioScore Ultimate has many useful features, such as: - It can recognize notes from polyphonic music, including chords, pitch changes, clefs, key signatures, tempo changes, etc. - It can handle complex rhythms and meters, including triplets, duplets, swing, syncopation, etc. - It can create scores with lyrics that are aligned with the notes automatically. - It can export scores to MusicXML or MIDI formats that can be opened by other music software such as Sibelius or Finale. - It can play back your project at any time with realistic sounds and effects.

How to use AudioScore Ultimate to record, import, edit and transcribe audio files

- Using AudioScore Ultimate is easy and intuitive. Here are some basic steps to get you started: - To record audio from your microphone, click on the Record button on the toolbar and follow the instructions on the screen. You can also adjust the recording settings such as sample rate, bit depth, etc. - To import audio files from your PC or other sources, click on the File menu and select Open. You can also drag and drop files into the main window. You can import WAV, MP3, WMA, AAC, AIFF or OGG files. - To edit your audio files, use the tools on the toolbar or the menus. You can cut, copy, paste, delete, move or resize notes; change their pitch or length; add or remove rests; insert or delete bars; transpose or quantize notes; add dynamics or articulations; etc. - To transcribe your audio files into a score, click on the Transcribe button on the toolbar and wait for the process to finish. You can also adjust the transcription settings such as accuracy level, note range, instrument type, etc. - To view your score in different ways, use the tabs at the bottom of the window. You can switch between Piano Roll View (which shows notes as horizontal bars), Notation View (which shows notes as symbols on a staff), Lyrics View (which shows lyrics below notes), or Playback View (which shows notes as they are played). - To print or export your score, click on the File menu and select Print or Export. You can print your score directly from AudioScore Ultimate or save it as a PDF file. You can also export your score as a MusicXML or MIDI file that can be opened by other music software.

Why do you need AudioScore Ultimate 2020.1 V9.0.0 Crack?

-

The benefits of using the cracked version of the software

- AudioScore Ultimate is a powerful audio editing software that can help you create amazing music projects. However, it is not free to use. The official price of AudioScore Ultimate is $249 USD for a single user license. That's quite expensive for many people who want to use this software for personal or educational purposes. That's why some people look for a cracked version of AudioScore Ultimate that can bypass the activation process and unlock all the features of the software without paying anything. By using AudioScore Ultimate 2020.1 V9.0.0 Crack, you can enjoy these benefits: - You can save money by not buying a license for AudioScore Ultimate. - You can access all the features and functions of AudioScore Ultimate without any limitations or restrictions. - You can use AudioScore Ultimate on any PC without needing an internet connection or a registration code.

The risks and drawbacks of using the cracked version of the software

- While using AudioScore Ultimate 2020.1 V9.0.0 Crack may seem tempting, it is not without risks and drawbacks. Here are some of them: - You may violate the intellectual property rights of Neuratron Ltd., the developer of AudioScore Ultimate, and face legal consequences for piracy. - You may expose your PC to malware or viruses that may be hidden in the crack file or downloaded from unreliable sources. - You may experience errors or bugs in the software that may affect its performance or functionality. - You may not receive updates or technical support from Neuratron Ltd., which may result in compatibility issues with other software or devices.

How to download and install AudioScore Ultimate 2020.1 V9.0.0 Crack?

-

The steps to download the crack file from a reliable source

- If you decide to use AudioScore Ultimate 2020.1 V9.0.0 Crack despite its risks and drawbacks, you need to be careful about where you download it from. There are many websites that claim to offer crack files for various software, but not all of them are trustworthy or safe. To avoid downloading malware or viruses, you should look for a reliable source that has positive reviews and feedback from other users who have used it before. One such source is KoLomPC.com, a website that provides crack files for various multimedia software. To download AudioScore Ultimate 2020.1 V9.0.0 Crack from KoLomPC.com, follow these steps: - Go to https://kolompc.com/neuratron-audioscore-ultimate/ on your web browser. - Scroll down until you see a green button that says "Download Neuratron AudioScore Ultimate 2020". - Click on that button and choose one of the download links that appear below it (IntoUpload, upload-4ever, or Rapidgator). - Wait for a few seconds until you see another button that says "Download File". - Click on that button and save the file (AudioScore.Ultimate.2020.v9.rar) on your PC.

The steps to install the crack file and activate the software

- After downloading AudioScore.Ultimate.v9.rar from KoLomPC.com, you need to install it on your PC and activate it with the crack file. To do that, follow these steps: - Extract AudioScore.Ultimate.v9.rar using WinRAR or any other file archiver program. - Open the extracted folder (AudioScore.Ultimate.v9) and run Setup.exe as administrator. - Follow the installation wizard until it finishes installing AudioScore Ultimate on your PC. - Do not launch AudioScore Ultimate yet after installation. - Go back to the extracted folder (AudioScore.Ultimate.v9) and open another folder called "Crack". - Copy all three files inside this folder (AudioEngine.dll, AudioEngine64.dll, and ASUltimate.exe) and paste them into the installation directory of AudioScore Ultimate (usually C:\Program Files\Neuratron\Audio Score). - Replace any existing files if prompted.

Conclusion

-

A summary of the main points and a call to action

- AudioScore Ultimate is a powerful audio editing software that can help you record, import, edit and transcribe audio files with ease. It has many useful features that can make your music projects more professional and impressive. However, AudioScore Ultimate is not free to use and requires a license that costs $249 USD. If you want to use AudioScore Ultimate without paying anything, you can try using AudioScore Ultimate 2020.1 V9.0.0 Crack, which can unlock all the features and functions of the software. However, using the cracked version of AudioScore Ultimate also comes with risks and drawbacks, such as legal issues, malware infection, errors or bugs, and lack of updates or support. Therefore, you should be careful about where you download the crack file from and how you install it on your PC. If you are interested in using AudioScore Ultimate 2020.1 V9.0.0 Crack, you can follow the steps we have provided in this article to download and install it from a reliable source such as KoLomPC.com. However, we do not recommend or endorse using the cracked version of AudioScore Ultimate or any other software, as it may violate the intellectual property rights of the developers and cause harm to your PC or data. We suggest that you use the official version of AudioScore Ultimate or look for other legal alternatives that can suit your needs and budget.

FAQs

-

What are the system requirements for AudioScore Ultimate?

- According to the official website of Neuratron Ltd., the system requirements for AudioScore Ultimate are: - Windows 10/8/7/Vista (32-bit or 64-bit) - 1 GB RAM - 200 MB hard disk space - Microphone or other audio input device - Internet connection (for activation and updates)

Is AudioScore Ultimate compatible with other music software?

- Yes, AudioScore Ultimate is compatible with other music software that can open MusicXML or MIDI files, such as Sibelius, Finale, Dorico, MuseScore, etc. You can export your score from AudioScore Ultimate as a MusicXML or MIDI file and then import it into your preferred music software for further editing or playback.

How can I get technical support for AudioScore Ultimate?

- If you have any questions or issues with AudioScore Ultimate, you can contact the technical support team of Neuratron Ltd. by email at support@neuratron.com or by phone at +44 (0)20 8977 2744. You can also visit their website at https://www.neuratron.com/support.htm for more information and resources.

Is AudioScore Ultimate safe and legal to use?

- AudioScore Ultimate is safe and legal to use if you buy a license from the official website of Neuratron Ltd. or from an authorized reseller. However, if you use a cracked version of AudioScore Ultimate that bypasses the activation process and unlocks all the features without paying anything, you may be violating the intellectual property rights of Neuratron Ltd. and face legal consequences for piracy. You may also expose your PC to malware or viruses that may be hidden in the crack file or downloaded from unreliable sources.

What are some alternatives to AudioScore Ultimate?

- If you are looking for other software that can help you create, edit and transcribe audio files, here are some alternatives to AudioScore Ultimate that you may want to consider: - AnthemScore: A software that can automatically transcribe music from audio files into sheet music. - Melodyne: A software that can edit audio files with various tools such as pitch correction, time stretching, harmonization, etc. - Transcribe!: A software that can help you transcribe music from audio files by slowing down the playback, adjusting the pitch, looping sections, etc. - AmazingMIDI: A software that can convert WAV files into MIDI files with high accuracy.

-

AudioScore Ultimate 2020.1 V9.0.0 Crack


DOWNLOADhttps://byltly.com/2uKvpk



0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Discografia Completa Del Grupo Samuray Cmo se Form Evolucion y Triunf en el Escenario.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Discografia Completa Del Grupo Samuray Cmo se Form Evolucion y Triunf en el Escenario.md deleted file mode 100644 index 543c08c3e22528c0017dbb8be0293fdc8544febb..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Discografia Completa Del Grupo Samuray Cmo se Form Evolucion y Triunf en el Escenario.md +++ /dev/null @@ -1,119 +0,0 @@ - -

Discografia Completa Del Grupo Samuray

-

If you are a fan of romantic ballads with a touch of pop, you have probably heard of Grupo Samuray. This Mexican band has been making music since 1991, captivating audiences with their catchy melodies and heartfelt lyrics. They have released 15 albums, each one with its own style and charm, and have sold millions of copies worldwide.

-

In this article, we will explore their complete discography, from their debut album Tiernas Mentiras to their latest live recording En Vivo [CD & DVD]. We will also learn more about their history, their influences, and their most popular songs. Whether you are a longtime follower or a new listener, you will discover something new and exciting about this amazing group.

-

Discografia Completa Del Grupo Samuray


Download ✶✶✶ https://byltly.com/2uKzl8



-

Tiernas Mentiras (1991)

-

This was the first album released by Grupo Samuray, under the label Disa. It featured 10 tracks, including their breakthrough hit "Tiernas Mentiras", which reached number one on several radio stations in Mexico. The song talks about a lover who lies to his partner to avoid hurting her feelings, but ends up losing her anyway.

-

Other notable songs on this album are "Contigo O Sin Ti", "Amor Imposible", and "Donde Esta Mi Padre". The latter is a poignant ballad about a son who misses his father who left him when he was young. The album showcases the group's talent for singing emotional stories with a smooth and melodic voice.

-

Descargar discografia completa del grupo samuray gratis
-Escuchar todas las canciones del grupo samuray online
-Discografia completa del grupo samuray mega
-Canciones mas populares del grupo samuray
-Discografia completa del grupo samuray mp3
-Como conseguir la discografia completa del grupo samuray
-Discografia completa del grupo samuray en Spotify
-Historia y biografia del grupo samuray
-Discografia completa del grupo samuray zip
-Letras de las canciones del grupo samuray
-Discografia completa del grupo samuray rar
-Videos musicales del grupo samuray
-Discografia completa del grupo samuray utorrent
-Albumes y singles del grupo samuray
-Discografia completa del grupo samuray youtube
-Conciertos y giras del grupo samuray
-Discografia completa del grupo samuray mediafire
-Fotos y posters del grupo samuray
-Discografia completa del grupo samuray google drive
-Curiosidades y anecdotas del grupo samuray
-Discografia completa del grupo samuray amazon
-Influencias y genero musical del grupo samuray
-Discografia completa del grupo samuray itunes
-Premios y nominaciones del grupo samuray
-Discografia completa del grupo samuray apple music
-Integrantes y ex integrantes del grupo samuray
-Discografia completa del grupo samuray deezer
-Colaboraciones y duetos del grupo samuray
-Discografia completa del grupo samuray soundcloud
-Merchandising y productos oficiales del grupo samuray
-Discografia completa del grupo samuray flac
-Criticas y reseñas de la discografia completa del grupo samuray
-Discografia completa del grupo samuray shazam
-Tributos y covers de las canciones del grupo samuray
-Discografia completa del grupo samuray last.fm
-Recomendaciones de musica similar al grupo samuray
-Discografia completa del grupo samuray tidal
-Entrevistas y reportajes al grupo samuray
-Discografia completa del grupo samuray bandcamp
-Fan clubs y comunidades del grupo samuray
-Discografia completa del grupo samuray audiomack
-Podcasts y programas sobre el grupo samuray
-Discografia completa del grupo samuray napster
-Peliculas y series relacionadas con el grupo samuray
-Discografia completa del grupo samuray pandora
-Libros y revistas sobre el grupo samuray
-Discografia completa del grupo samuray tunein radio
-Documentales y biopics sobre el grupo samuray
-Discografia completa del grupo samuray mixcloud
-Frases y citas celebres del grupo samuray

-

Los Guerreros del Amor (1992)

-

This was the second album released by Grupo Samuray, also under Disa. It featured 12 tracks, including their second smash hit "Lagrimillas Tontas", which topped several charts in Mexico and Latin America. The song is about a man who regrets breaking up with his girlfriend, but realizes it is too late to get her back.

-

Other notable songs on this album are "Solo Amor", "Como Sufro", and "Los Guerreros del Amor". The latter is an upbeat song that celebrates love as a powerful force that can overcome any obstacle. The album demonstrates the group's versatility for singing different genres, from pop to cumbia to ranchera.

-

Solo Amor (1993)

-

This was the third album released by Grupo Samuray, again under Disa. It featured 10 tracks, including their third major hit "Solo Amor", which became one of their signature songs. The song is about a man who declares his unconditional love for his partner, despite all their problems and difficulties.

-

Other notable songs on this album are "Cuando Amanezca", "Nada Va a Cambiar Mi Corazon Por Ti", and "Te Necesito". The latter is a romantic duet with singer Marisela, who also wrote some of the songs on this album. The album showcases the group's ability to collaborate with other artists and create beautiful harmonies.

-

Cuando Amanezca (1995)

-

This was the fourth album released by Grupo Samuray, under Fonovisa. It featured 10 tracks, including their fourth big hit "Cuando Amanezca", which reached number one on several radio stations in Mexico. The song is about a man who promises to stay with his lover until dawn, even if they have to face many challenges.

-

Other notable songs on this album are "Te Quiero Te Quiero", "No Me Digas Adios", and "Como Un Angel". The latter is a tender ballad that compares love to an angel that protects and guides us. The album shows the group's maturity and growth as musicians and composers.

-

Todo Mexico Lo Sabe (1996)

-

This was the fifth album released by Grupo Samuray, also under Fonovisa. It featured 10 tracks, including their fifth huge hit "Todo Mexico Lo Sabe", which became an anthem for Mexican pride and identity. The song is about a man who proclaims his love for his country and its culture, no matter where he goes.

-

Other notable songs on this album are "Corazon Pandido", "El Primer Samuray Mexicano", and "De Ti Me Enamore". The latter is a catchy cumbia that tells how love can happen unexpectedly and change our lives. The album reflects the group's passion for their roots and their fans.

-

Corazon Pandido (1996)

-

This was the sixth album released by Grupo Samuray, under Disa. It featured 10 tracks, including their sixth massive hit "Corazon Pandido", which became one of their most requested songs at concerts. The song is about a man who confesses his infidelity to his partner, but asks for forgiveness and another chance.

-

Nada Va a Cambiar Mi Corazon Por Ti (1996)

-

This was the seventh album released by Grupo Samuray, also under Disa. It featured 10 tracks, including their seventh major hit "Nada Va a Cambiar Mi Corazon Por Ti", which became a classic of their repertoire. The song is about a man who declares his eternal love for his partner, despite all the obstacles and temptations they face.

-

Other notable songs on this album are "Al Rojo Vivo", "Enamorado de Ti", and "Como Un Loco". The latter is a lively song that describes how love can make us act crazy and do anything for our beloved. The album showcases the group's enthusiasm and energy as performers and entertainers.

-

Al Rojo Vivo (1997)

-

This was the eighth album released by Grupo Samuray, under EMI Music Distribution. It featured 10 tracks, including their eighth big hit "Al Rojo Vivo", which became a favorite among their fans. The song is about a man who expresses his intense and passionate love for his partner, making her feel special and unique.

-

Other notable songs on this album are "Donde Estas Amor", "Te Extraño", and "No Llores Mas". The latter is a comforting song that offers support and hope to someone who is suffering from a broken heart. The album demonstrates the group's sensitivity and empathy as artists and friends.

-

Donde Vas Chiquilla (1997)

-

This was the ninth album released by Grupo Samuray, also under EMI Music Distribution. It featured 10 tracks, including their ninth huge hit "Donde Vas Chiquilla", which became a hit in several countries. The song is about a man who tries to stop his girlfriend from leaving him, but realizes he has lost her forever.

-

Other notable songs on this album are "Un Nuevo Amanecer", "Tres Palabras", and "Amor de Internet". The latter is a humorous song that mocks the online dating scene and its pitfalls. The album shows the group's humor and creativity as writers and comedians.

-

Un Dia Sin Ti (1998)

-

This was the tenth album released by Grupo Samuray, also under EMI Music Distribution. It featured 10 tracks, including their tenth massive hit "Un Dia Sin Ti", which became one of their most emotional songs. The song is about a man who misses his partner who has died, and wishes he could see her again.

-

Other notable songs on this album are "Te Necesito Tanto Amor", "Vuelve Conmigo", and "No Te Vayas". The latter is a desperate song that begs for a second chance from a lover who has left. The album reveals the group's depth and sorrow as human beings and lovers.

-

Con Estilo Ranchero (1999)

-

This was the eleventh album released by Grupo Samuray, under Disa. It featured 10 tracks, including a different style of music with ranchero influences. The group decided to experiment with this genre to pay tribute to their Mexican roots and culture.

-

Tres Palabras (2000)

-

This was the twelfth album released by Grupo Samuray, under Disa. It featured 10 tracks, including their eleventh major hit "Tres Palabras", which became a romantic anthem for many couples. The song is about a man who expresses his love for his partner with three simple words: "Te quiero mucho".

-

Other notable songs on this album are "Contigo O Sin Ti", "Como Un Angel", and "Te Quiero Te Quiero". The latter is a remake of the song by Nino Bravo, a famous Spanish singer who died in a car accident. The album showcases the group's admiration and tribute for other artists and legends.

-

Un Nuevo Amanecer (2002)

-

This was the thirteenth album released by Grupo Samuray, under Fonovisa. It featured 10 tracks, including their twelfth big hit "Un Nuevo Amanecer", which became a motivational song for many people. The song is about a man who decides to start a new life after overcoming a difficult situation, and thanks God for his blessings.

-

Other notable songs on this album are "De Ti Me Enamore", "Donde Estas Amor", and "No Llores Mas". The latter is a duet with singer Ana Bárbara, who also wrote some of the songs on this album. The album demonstrates the group's collaboration and friendship with other talented singers and composers.

-

El Primer Samuray Mexicano (2004)

-

This was the fourteenth album released by Grupo Samuray, under Fonovisa. It featured 10 tracks, including a tribute to their fans and their country. The group decided to dedicate this album to their loyal followers who have supported them throughout their career, and to their homeland Mexico, which they love and respect.

-

Some of the songs on this album are "El Primer Samuray Mexicano", "Todo Mexico Lo Sabe", and "Mexico Lindo Y Querido". The latter is a cover of the traditional song by Chucho Monge, one of the most emblematic songs of Mexican patriotism. The album reflects the group's gratitude and pride for their people and their nation.

-

En Vivo [CD & DVD] (2004)

-

This was the fifteenth and last album released by Grupo Samuray, under Disa. It featured a live performance of their greatest hits, recorded at the Auditorio Nacional in Mexico City. The group decided to celebrate their 13 years of musical career with this special concert, where they sang with passion and emotion in front of thousands of fans.

-

Some of the songs on this album are "Tiernas Mentiras", "Lagrimillas Tontas", "Solo Amor", "Cuando Amanezca", "Todo Mexico Lo Sabe", "Corazon Pandido", "Nada Va a Cambiar Mi Corazon Por Ti", "Al Rojo Vivo", "Donde Vas Chiquilla", "Un Dia Sin Ti", "Tres Palabras", and "Un Nuevo Amanecer". The album captures the group's essence and charisma as performers and entertainers.

-

Conclusion

-

In this article, we have explored the complete discography of Grupo Samuray, one of the most successful and beloved groups of romantic ballads in Mexico and Latin America. We have learned more about their history, their influences, and their most popular songs. We have also discovered how they have evolved and experimented with different genres and styles throughout their career.

-

Grupo Samuray has left an indelible mark on the music industry, with 15 albums, millions of copies sold, countless awards and recognitions, and a loyal fan base that still follows them today. They have also inspired many other artists and groups who have followed their footsteps and admired their work.

-

If you want to listen to more of their music, you can find their albums on streaming platforms like Spotify or YouTube. You can also follow them on social media like Facebook or Instagram, where they share news and updates about their projects and activities. You can also visit their official website www.gruposamuray.com.mx for more information.

-

We hope you have enjoyed this article and learned something new about this amazing group. Thank you for reading and until next time!

-

FAQs

-
    -
  1. When was Grupo Samuray formed?
  2. -

    Grupo Samuray was formed in 1991 in Aguascalientes, Mexico, by brothers Ignacio and Rogelio Romo as vocalists, along with other musicians.

    -
  3. Who are the members of Grupo Samuray?
  4. -

    The current members of Grupo Samuray are Ignacio Romo (lead vocals), Rogelio Romo (backing vocals), José Luis Romo (keyboard), Juan Carlos Romo (guitar), José Luis González (bass), José Luis Martínez (drums), and José Luis Hernández (percussion).

    -
  5. What is the genre of Grupo Samuray?
  6. -

    The genre of Grupo Samuray is mainly romantic ballads with pop influences, but they have also experimented with other genres like cumbia, ranchera, mariachi, and norteña.

    -
  7. How many albums has Grupo Samuray released?
  8. -

    Grupo Samuray has released 15 albums between 1991 and 2004: Tiernas Mentiras (1991), Los Guerreros del Amor (1992), Solo Amor (1993), Cuando Amanezca (1995), Todo Mexico Lo Sabe (1996), Corazon Pandido (1996), Nada Va a Cambiar Mi Corazon Por Ti (1996), Al Rojo Vivo (1997), Donde Vas Chiquilla (1997), Un Dia Sin Ti (1998), Con Estilo Ranchero (1999), Tres Palabras (2000), Un Nuevo Amanecer (2002), El Primer Samuray Mexicano (2004), and En Vivo [CD & DVD] (2004).

    -
  9. What are some of their most famous songs?
  10. -

    Some of their most famous songs are "Tiernas Mentiras", "Lagrimillas Tontas", "Solo Amor", "Cuando Amanezca", "Todo Mexico Lo Sabe", "Corazon Pandido", "Nada Va a Cambiar Mi Corazon Por Ti", "Al Rojo Vivo", "Donde Vas Chiquilla", "Un Dia Sin Ti", "Tres Palabras", and "Un Nuevo Amanecer".

    -
-

0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/3 Idiots Full Movie Tagalog Version Kapamilya Blockbuster.md b/spaces/1gistliPinn/ChatGPT4/Examples/3 Idiots Full Movie Tagalog Version Kapamilya Blockbuster.md deleted file mode 100644 index 3a3a8e97ce71ee0b049271b25bba28c590d18c0b..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/3 Idiots Full Movie Tagalog Version Kapamilya Blockbuster.md +++ /dev/null @@ -1,9 +0,0 @@ -

3 idiots full movie tagalog version kapamilya blockbuster


Download Zip - https://imgfil.com/2uxZEm



- -anu courier? Copyright disclaimer: I DO NOT own this video/track or the image used in this video. #39;Another episode created by a patron as we honor the request of patron Aaron G. "We don't want to lose touch with this channel," he said. -In the March 2018 issue of The Unknown Heart, it was revealed that Aaron G. was very anxious about his child and his relationship with her. -In a 2014 interview with the Daily Caller, Aaron G. said: -"I've never been a particularly religious father and I still don't find myself seeing how my son tends, I don't know... not to be completely pious in my opinion, but it really excites me.## #Watch full movie in Hindi 3 Idiots on YouTube. Directed by Sumiya Supriya, starring Vivek Trivedi, Pamela. ##3 Idiots dubbed in Tagalog by Full Pinoy Movie. Pinoy's latest movie in HD quality Download for free. We publish the latest Pinoy movies daily. ➡ Pinoy ➡ Pinoy full movie ➡ Pinoy 2018 full ➡ Pinoy download on YouTube ➡ Pinoy watch online ➡ Pinoy free download ➡ Pinoy all parts free download without registration � 8a78ff9644
-
-
-

diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Adobe Photoshop Cc Multi Language Xforce Keygen Downloadtrmdsf.md b/spaces/1gistliPinn/ChatGPT4/Examples/Adobe Photoshop Cc Multi Language Xforce Keygen Downloadtrmdsf.md deleted file mode 100644 index 35878083600715398c09ff513712ab17296fc807..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Adobe Photoshop Cc Multi Language Xforce Keygen Downloadtrmdsf.md +++ /dev/null @@ -1,6 +0,0 @@ -

Adobe Photoshop Cc Multi Language Xforce Keygen Downloadtrmdsf


Download ✑ ✑ ✑ https://imgfil.com/2uy0bc



- - d5da3c52bf
-
-
-

diff --git a/spaces/1line/AutoGPT/autogpt/json_utils/json_fix_general.py b/spaces/1line/AutoGPT/autogpt/json_utils/json_fix_general.py deleted file mode 100644 index 7010fa3b9c1909de0e5a7f6ec13ca8aa418fe6c7..0000000000000000000000000000000000000000 --- a/spaces/1line/AutoGPT/autogpt/json_utils/json_fix_general.py +++ /dev/null @@ -1,124 +0,0 @@ -"""This module contains functions to fix JSON strings using general programmatic approaches, suitable for addressing -common JSON formatting issues.""" -from __future__ import annotations - -import contextlib -import json -import re -from typing import Optional - -from autogpt.config import Config -from autogpt.json_utils.utilities import extract_char_position - -CFG = Config() - - -def fix_invalid_escape(json_to_load: str, error_message: str) -> str: - """Fix invalid escape sequences in JSON strings. - - Args: - json_to_load (str): The JSON string. - error_message (str): The error message from the JSONDecodeError - exception. - - Returns: - str: The JSON string with invalid escape sequences fixed. - """ - while error_message.startswith("Invalid \\escape"): - bad_escape_location = extract_char_position(error_message) - json_to_load = ( - json_to_load[:bad_escape_location] + json_to_load[bad_escape_location + 1 :] - ) - try: - json.loads(json_to_load) - return json_to_load - except json.JSONDecodeError as e: - if CFG.debug_mode: - print("json loads error - fix invalid escape", e) - error_message = str(e) - return json_to_load - - -def balance_braces(json_string: str) -> Optional[str]: - """ - Balance the braces in a JSON string. - - Args: - json_string (str): The JSON string. - - Returns: - str: The JSON string with braces balanced. - """ - - open_braces_count = json_string.count("{") - close_braces_count = json_string.count("}") - - while open_braces_count > close_braces_count: - json_string += "}" - close_braces_count += 1 - - while close_braces_count > open_braces_count: - json_string = json_string.rstrip("}") - close_braces_count -= 1 - - with contextlib.suppress(json.JSONDecodeError): - json.loads(json_string) - return json_string - - -def add_quotes_to_property_names(json_string: str) -> str: - """ - Add quotes to property names in a JSON string. - - Args: - json_string (str): The JSON string. - - Returns: - str: The JSON string with quotes added to property names. - """ - - def replace_func(match: re.Match) -> str: - return f'"{match[1]}":' - - property_name_pattern = re.compile(r"(\w+):") - corrected_json_string = property_name_pattern.sub(replace_func, json_string) - - try: - json.loads(corrected_json_string) - return corrected_json_string - except json.JSONDecodeError as e: - raise e - - -def correct_json(json_to_load: str) -> str: - """ - Correct common JSON errors. - Args: - json_to_load (str): The JSON string. - """ - - try: - if CFG.debug_mode: - print("json", json_to_load) - json.loads(json_to_load) - return json_to_load - except json.JSONDecodeError as e: - if CFG.debug_mode: - print("json loads error", e) - error_message = str(e) - if error_message.startswith("Invalid \\escape"): - json_to_load = fix_invalid_escape(json_to_load, error_message) - if error_message.startswith( - "Expecting property name enclosed in double quotes" - ): - json_to_load = add_quotes_to_property_names(json_to_load) - try: - json.loads(json_to_load) - return json_to_load - except json.JSONDecodeError as e: - if CFG.debug_mode: - print("json loads error - add quotes", e) - error_message = str(e) - if balanced_str := balance_braces(json_to_load): - return balanced_str - return json_to_load diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Boost Your SketchUp Productivity with JHS Powerbar 2019 - Free Download for SketchUp 2016 Users.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Boost Your SketchUp Productivity with JHS Powerbar 2019 - Free Download for SketchUp 2016 Users.md deleted file mode 100644 index 5fc441ffc14451fd1e66fe963c24386153a6654f..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Boost Your SketchUp Productivity with JHS Powerbar 2019 - Free Download for SketchUp 2016 Users.md +++ /dev/null @@ -1,117 +0,0 @@ -
-

How to Download JHS Powerbar Sketchup 2016 Free

-

If you are looking for a way to enhance your Sketchup experience with more tools and features, you might want to try JHS Powerbar Sketchup. This is a plugin that adds a powerful toolbar to your Sketchup interface, giving you access to many useful functions and commands. In this article, we will show you how to download JHS Powerbar Sketchup 2016 free and how to use it effectively.

-

What is JHS Powerbar Sketchup?

-

JHS Powerbar Sketchup is a plugin developed by CadFather (Max Coppoletta) that extends the capabilities of Sketchup. It is compatible with Sketchup versions from 2015 to 2021, but in this article we will focus on the version for Sketchup 2016. JHS Powerbar Sketchup adds a toolbar with several buttons that allow you to perform various actions in Sketchup, such as:

-

download jhs powerbar sketchup 2016 free


Download Ziphttps://urlin.us/2uSZyZ



- -

Why use JHS Powerbar Sketchup 2016?

-

There are many reasons why you might want to use JHS Powerbar Sketchup 2016. Here are some of them:

- -

How to download JHS Powerbar Sketchup 2016 free?

-

Downloading JHS Powerbar Sketchup 2016 free is a simple process that involves four steps:

-
    -
  1. Step 1: Download Sketchup 2016 from the official website or a trusted source. You can find the download link here: . Make sure you choose the right version for your operating system and architecture. Install Sketchup 2016 on your computer and launch it.
  2. -
  3. Step 2: Download JHS Powerbar Sketchup 2016 from SketchUcation or another reliable site. You can find the download link here: . You will need to register for a free account to download the plugin. After downloading, unzip the file and you will see two folders: jhs_powerbar and jhs_powerbar_icons.
  4. -
  5. Step 3: Copy the plugin files to the Sketchup plugins folder. The location of this folder may vary depending on your operating system and installation settings, but you can usually find it here: C:\Users\YourUserName\AppData\Roaming\SketchUp\SketchUp 2016\SketchUp\Plugins. Copy both folders (jhs_powerbar and jhs_powerbar_icons) to this folder.
  6. -
  7. Step 4: Restart Sketchup and enjoy JHS Powerbar Sketchup 2016. You should see a new toolbar with several buttons on your screen. You can also access the toolbar from the View menu or by right-clicking on the screen. To learn more about how to use JHS Powerbar Sketchup 2016, you can watch this video tutorial: .
  8. -
-

Conclusion

-

JHS Powerbar Sketchup 2016 is a great plugin that adds many useful tools and features to your Sketchup interface. It is compatible with Sketchup 2016, a popular and free version of Sketchup. It is easy to install and use, and it enhances your productivity and creativity in Sketchup. You can download JHS Powerbar Sketchup 2016 free by following the steps we have shown you in this article.

-

We hope you found this article helpful and informative. If you have any questions or feedback, please feel free to leave a comment below or contact us through our website. We would love to hear from you!

-

How to use jhs powerbar plugin in sketchup 2016
-Jhs powerbar sketchup 2016 tutorial video
-Jhs powerbar sketchup 2016 extension download link
-Jhs powerbar sketchup 2016 features and benefits
-Jhs powerbar sketchup 2016 review and rating
-Jhs powerbar sketchup 2016 installation guide
-Jhs powerbar sketchup 2016 compatibility and requirements
-Jhs powerbar sketchup 2016 best practices and tips
-Jhs powerbar sketchup 2016 alternatives and comparisons
-Jhs powerbar sketchup 2016 support and feedback
-Jhs powerbar sketchup 2016 free trial and license
-Jhs powerbar sketchup 2016 update and upgrade
-Jhs powerbar sketchup 2016 tools and functions
-Jhs powerbar sketchup 2016 examples and projects
-Jhs powerbar sketchup 2016 forum and community
-Jhs powerbar sketchup 2016 error and troubleshooting
-Jhs powerbar sketchup 2016 discount and coupon
-Jhs powerbar sketchup 2016 testimonials and case studies
-Jhs powerbar sketchup 2016 pros and cons
-Jhs powerbar sketchup 2016 faq and help
-Jhs powerbar sketchup 2016 online course and training
-Jhs powerbar sketchup 2016 ebook and pdf
-Jhs powerbar sketchup 2016 webinar and workshop
-Jhs powerbar sketchup 2016 blog and news
-Jhs powerbar sketchup 2016 affiliate and referral program
-Jhs powerbar sketchup 2016 developer and creator
-Jhs powerbar sketchup 2016 source code and github
-Jhs powerbar sketchup 2016 crack and keygen
-Jhs powerbar sketchup 2016 mod and hack
-Jhs powerbar sketchup 2016 premium and pro version
-Jhs powerbar sketchup 2016 for mac and windows
-Jhs powerbar sketchup 2016 for beginners and experts
-Jhs powerbar sketchup 2016 for architects and designers
-Jhs powerbar sketchup 2016 for engineers and builders
-Jhs powerbar sketchup 2016 for students and teachers
-Jhs powerbar sketchup 2016 for hobbyists and enthusiasts
-Jhs powerbar sketchup 2016 for interior and exterior design
-Jhs powerbar sketchup 2016 for furniture and product design
-Jhs powerbar sketchup 2016 for landscape and urban design
-Jhs powerbar sketchup 2016 for animation and rendering
-Jhs powerbar sketchup 2016 for modeling and editing
-Jhs powerbar sketchup 2016 for scaling and rotating
-Jhs powerbar sketchup 2016 for extruding and offsetting
-Jhs powerbar sketchup 2016 for mirroring and welding
-Jhs powerbar sketchup 2016 for subdividing and smoothing
-Jhs powerbar sketchup 2016 for piping and tubing
-Jhs powerbar sketchup 2016 for copying and aligning
-Jhs powerbar sketchup 2016 for randomizing and proxifying

-

FAQs

-

Q1: What are the system requirements for JHS Powerbar Sketchup 2016?

-

A1: JHS Powerbar Sketchup 2016 requires Sketchup 2016, which has the following system requirements:

- - - - - - - -
Operating SystemWindows 7/8/10 or Mac OS X 10.9/10.10/10.11
Processor1 GHz or faster
RAM4 GB or more
Disk Space500 MB or more
Graphics Card3D class with 512 MB or more of memory and support for hardware acceleration
Internet ConnectionRequired for installation, activation, updates, and some features
-

Q2: How to update JHS Powerbar Sketchup 2016 to the latest version?

-

A2: To update JHS Powerbar Sketchup 2016 to the latest version, you need to download the new version from SketchUcation or another reliable site, and replace the old plugin files with the new ones in the Sketchup plugins folder. Then, restart Sketchup and check if the update was successful.

-

Q3: How to uninstall JHS Powerbar Sketchup 2016?

-

A3: To uninstall JHS Powerbar Sketchup 2016, you need to delete the plugin files (jhs_powerbar and jhs_powerbar_icons) from the Sketchup plugins folder. You can find the location of this folder in the previous answer. Then, restart Sketchup and check if the plugin is gone.

-

Q4: What are some alternatives to JHS Powerbar Sketchup 2016?

-

A4: There are many other plugins that can enhance your Sketchup experience, such as:

- -

Q5: Where can I find more tutorials or tips on using JHS Powerbar Sketchup 2016?

-

A5: You can find more tutorials or tips on using JHS Powerbar Sketchup 2016 on the following sites:

-

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/1920 Evil Returns - The Ultimate Horror Movie Soundtrack - Download Now.md b/spaces/1phancelerku/anime-remove-background/1920 Evil Returns - The Ultimate Horror Movie Soundtrack - Download Now.md deleted file mode 100644 index 3ce1b20b65b0247332910f03b87bf7f3192444ae..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/1920 Evil Returns - The Ultimate Horror Movie Soundtrack - Download Now.md +++ /dev/null @@ -1,65 +0,0 @@ - -

How to Download 1920 Evil Returns Songs

-

1920 Evil Returns is a 2012 Indian horror film that is a quasi-sequel to the 2008 film 1920. The film features Aftab Shivdasani, Tia Bajpai, Vidya Malvade, and Sharad Kelkar in the lead roles. The film has a haunting soundtrack composed by Chirantan Bhatt, with lyrics by Shakeel Azmi, Manoj Yadav, and Junaid Wasi. The songs are sung by various artists, including Arijit Singh, Mahalakshmi Iyer, Sonu Nigam, and K.K. If you are a fan of the film or its music, you might want to download the songs and listen to them offline. But how can you do that? In this article, we will show you how to download 1920 Evil Returns songs legally and ethically, as well as some alternative methods that may not be as safe or legal.

-

download 1920 evil returns songs


Download Zip ✒ ✒ ✒ https://jinyurl.com/2uNQh1



-

Legal and ethical issues of downloading music from YouTube

-

One of the most popular sources of free music online is YouTube. You can find almost any song or album on YouTube, uploaded by official channels or users. However, downloading music from YouTube is not as simple or legal as it may seem. According to YouTube's terms of service, you are not allowed to download any audio content from the site, unless it is specifically permitted by the service or you have prior written permission from YouTube or the respective rights holder. This means that you cannot use third-party software or websites to download music from YouTube videos without violating the site's rules or breaking the law. You may also face legal consequences if you download copyrighted music without the owner's consent. Therefore, downloading music from YouTube is not recommended unless you are sure that the music is royalty-free, copyright-free, or covered by a Creative Commons license.

-

How to buy music from iTunes or Google Play

-

The safest and most legal way to download music from the internet is to buy it from official sources like iTunes or Google Play. These platforms offer millions of songs and albums that you can purchase and download legally and ethically. You can also enjoy high-quality audio and support the artists and creators of the music. Here are the steps to buy music from iTunes or Google Play:

-
    -
  1. Install iTunes on your Windows computer or open it on your Mac. If you are using a smartphone, you can use the iTunes Store app on iPhone or the Play Music app on Android.
  2. -
  3. Sign in with your Apple ID or Google account.
  4. -
  5. Search for 1920 Evil Returns songs or album in the search bar.
  6. -
  7. Select the song or album you want to buy and click on the price.
  8. -
  9. Enter your password or use Touch ID or Face ID to confirm your purchase.
  10. -
  11. The song or album will be added to your library and downloaded to your device.
  12. -
-

How to download free music from YouTube or SoundCloud

-

If you don't want to spend money on buying music online, you can try downloading free music from YouTube or SoundCloud. These sites offer a lot of free music that you can listen to online or download offline. However, as we mentioned before, downloading music from YouTube is not legal or ethical unless the music is free of any rights. SoundCloud is more lenient in this regard, as it allows some artists and users to offer their music for free download. However, you still need to respect their wishes and follow their instructions. Here are the steps to download free music from YouTube or SoundCloud:

-

download 1920 evil returns full songs jukebox
-download khud ko tere paas song from 1920 evil returns
-download uska hi banana song from 1920 evil returns
-download 1920 evil returns mp3 songs free
-download 1920 evil returns songs in high quality
-download 1920 evil returns songs zip file
-download 1920 evil returns video songs hd
-download 1920 evil returns songs lyrics
-download 1920 evil returns songs ringtone
-download 1920 evil returns songs pagalworld
-download 1920 evil returns songs mr jatt
-download 1920 evil returns songs djmaza
-download 1920 evil returns songs wapking
-download 1920 evil returns songs gaana
-download 1920 evil returns songs saavn
-download 1920 evil returns songs hungama
-download 1920 evil returns songs spotify
-download 1920 evil returns songs apple music
-download 1920 evil returns songs amazon music
-download 1920 evil returns songs youtube music
-download aftab shivdasani and tia bajpai songs from 1920 evil returns
-download chirantan bhatt songs from 1920 evil returns
-download arijit singh songs from 1920 evil returns
-download mahalakshmi iyer songs from 1920 evil returns
-download sonu nigam songs from 1920 evil returns
-download kk songs from 1920 evil returns
-download amit mishra songs from 1920 evil returns
-download sukhwinder singh songs from 1920 evil returns
-download shakeel azmi lyrics from 1920 evil returns
-download manoj yadav lyrics from 1920 evil returns
-download junaid wasi lyrics from 1920 evil returns
-how to download 1920 evil returns songs for free
-where to download 1920 evil returns songs legally
-best sites to download 1920 evil returns songs online
-best apps to download 1920 evil returns songs on mobile
-best quality to download 1920 evil returns songs in mp3 format
-best format to download 1920 evil returns songs in video format
-best way to download 1920 evil returns songs offline
-best method to download 1920 evil returns songs fast and easy
-best tips to download 1920 evil returns songs without any hassle

-
    -
  1. Find a song or album on YouTube or SoundCloud MP3 file. Third-party apps are software that you can install on your device and use to download and convert YouTube videos to MP3 files. However, you should be careful when using these methods, as they may not be legal or ethical, and they may harm your device or compromise your security. You should always check the reviews and ratings of the online converters or third-party apps before using them, and scan the downloaded files for any viruses or malware.

    -

    Q: How can I play downloaded music on my device or media player?

    -

    A: You can play downloaded music on your device or media player by using the built-in music app or any other music app that supports MP3 files. You can also create playlists, shuffle songs, adjust the volume, and control the playback using the app's features. You can also use headphones, speakers, or earphones to enhance your listening experience.

    -

    I hope you enjoyed reading this article and learned something new. If you liked this article, please share it with your friends and family who may also be interested in downloading 1920 Evil Returns songs. Thank you for your time and attention.

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Download Rope Hero Vice Town 2.3 APK - Free Action Game for Android.md b/spaces/1phancelerku/anime-remove-background/Download Rope Hero Vice Town 2.3 APK - Free Action Game for Android.md deleted file mode 100644 index 628e22b04430c0b082686489d5c9d3f4e87d04d7..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Download Rope Hero Vice Town 2.3 APK - Free Action Game for Android.md +++ /dev/null @@ -1,118 +0,0 @@ -
    -

    Rope Hero Vice Town 2.3 APK: A Superhero Game with Unlimited Possibilities

    -

    If you are looking for a fun and exciting superhero game for your Android device, you should check out Rope Hero Vice Town 2.3 APK. This is a game that lets you play as a blue hero with a super rope that can swing, jump, and fly around a 3D open world filled with crime and adventure. You can choose to be a hero or a villain, fight against gangs and police, complete quests and challenges, and customize your character with various weapons, vehicles, and outfits. In this article, we will tell you more about what Rope Hero Vice Town is, what are its features, how to download and install it, and what are some tips and tricks for playing it.

    -

    rope hero vice town 2.3 apk


    DOWNLOADhttps://jinyurl.com/2uNQMl



    -

    What is Rope Hero Vice Town?

    -

    Rope Hero Vice Town is an action-packed game by Naxeex Action & RPG Games that combines elements of action, adventure, and role-playing games. It is a superhero simulator that gives you the freedom to explore a fictional city called Vice Town, where you can use your super powers to fight crime or cause chaos.

    -

    A 3D open world action game with RPG elements

    -

    Rope Hero Vice Town is a game that lets you roam freely in a huge 3D open world that has realistic graphics and physics. You can interact with various objects, buildings, vehicles, and people in the city, as well as engage in combat with enemies using guns, melee weapons, or your super powers. You can also level up your hero by completing quests, gaining experience, and collecting money. You can use these resources to upgrade your skills, buy new weapons and vehicles, and change your appearance.

    -

    A superhero simulator with a blue hero and a super rope

    -

    Rope Hero Vice Town is a game that puts you in the shoes of a blue hero who has a super rope that can do amazing things. You can use the rope to swing from one building to another like Spider-Man, perform mega jumps and power landings like Hulk, or climb walls like Batman. You can also use the rope to grab enemies or objects and throw them around. The rope is not your only super power though. You also have super strength, speed, stamina, and durability that make you a formidable fighter.

    -

    A game with multiple modes, quests, and activities

    -

    Rope Hero Vice Town is a game that offers you a lot of variety and content to keep you entertained for hours. You can choose to follow the main story line that involves testing a new prototype suit that gives you super powers but also erases your memory. You have to find out who you are and what happened to you by completing missions and fighting against crime bosses. Alternatively, you can ignore the main story line and do whatever you want in the city. You can be a hero or a villain, help or harm the police and civilians, participate in races and arena battles, or just have fun with the mini-games and activities scattered around the city.

    -

    What are the features of Rope Hero Vice Town 2.3 APK?

    -

    Rope Hero Vice Town 2.3 APK is the latest version of the game that has been updated with new features and improvements. Some of the features of the game are:

    -

    Improved graphics and performance

    -

    Rope Hero Vice Town 2.3 APK has enhanced the graphics and performance of the game to make it more realistic and smooth. You can enjoy the stunning visuals of the city, the vehicles, the weapons, and the characters, as well as the dynamic lighting and shadows, the weather effects, and the explosions. You can also adjust the graphics settings to suit your device and preferences. The game also runs faster and smoother, with less bugs and glitches, and more stability and compatibility.

    -

    New weapons, vehicles, and archetypes

    -

    Rope Hero Vice Town 2.3 APK has added new weapons, vehicles, and archetypes to the game to give you more options and variety. You can choose from a wide range of firearms, melee weapons, lasers, and super weapons to suit your playstyle and strategy. You can also drive or fly different types of vehicles, such as cars, bikes, tanks, helicopters, planes, and assault mechs. You can even equip different archetypes that transform your hero into a different form, such as an aircraft robot, a tank robot, or a stone giant.

    -

    New mini-games and collectibles

    -

    Rope Hero Vice Town 2.3 APK has also added new mini-games and collectibles to the game to make it more fun and rewarding. You can participate in various mini-games that test your skills and abilities, such as gangster shootouts, gravity gun challenges, ATM hacking, and more. You can also find hidden collectibles around the city that give you bonus rewards, such as money, experience, or items. Be sure not to miss anything!

    -

    How to download and install Rope Hero Vice Town 2.3 APK?

    -

    If you want to download and install Rope Hero Vice Town 2.3 APK on your Android device, you need to follow these simple steps:

    -

    rope hero vice town 2.3 apk download
    -rope hero vice town 2.3 apk mod
    -rope hero vice town 2.3 apk free
    -rope hero vice town 2.3 apk latest version
    -rope hero vice town 2.3 apk online
    -rope hero vice town 2.3 apk android
    -rope hero vice town 2.3 apk unlimited money
    -rope hero vice town 2.3 apk hack
    -rope hero vice town 2.3 apk pure
    -rope hero vice town 2.3 apk mirror
    -rope hero vice town 2.3 apk update
    -rope hero vice town 2.3 apk offline
    -rope hero vice town 2.3 apk install
    -rope hero vice town 2.3 apk gameplay
    -rope hero vice town 2.3 apk review
    -rope hero vice town 2.3 apk cheats
    -rope hero vice town 2.3 apk old version
    -rope hero vice town 2.3 apk for pc
    -rope hero vice town 2.3 apk obb
    -rope hero vice town 2.3 apk revdl
    -rope hero vice town 2.3 apk rexdl
    -rope hero vice town 2.3 apk uptodown
    -rope hero vice town 2.3 apk apkpure
    -rope hero vice town 2.3 apk appvn
    -rope hero vice town 2.3 apk mob.org
    -rope hero vice town 2.3 apk android oyun club
    -rope hero vice town 2.3 apk andropalace
    -rope hero vice town 2.3 apk blackmod
    -rope hero vice town 2.3 apk by naxeex action & rpg games
    -rope hero vice town 2.3 apk cracked
    -rope hero vice town 2.3 apk data file host
    -rope hero vice town 2.3 apk direct link
    -rope hero vice town 2.3 apk file download for android mobile phone and tablet from android mobile zone.
    -rope hero vice town 2.3 apk full version free download for android devices.
    -rope hero vice town 2.3 apk game download for android phone and tablet.
    -rope hero vice town 2.3 apk highly compressed download for android devices.
    -rope hero vice town 2.3 apk indir for android devices.
    -rope hero vice town 2.3 apk latest mod version download for android devices.
    -rope hero vice town 2.3 apk mega mod download for android devices.
    -rope hero vice town 2.3 apk no root download for android devices.
    -rope hero vice town 2.3 apk original version download for android devices.
    -rope hero vice town 2.3 apk premium version download for android devices.
    -rope hero vice town 2.3 apk pro version download for android devices.
    -rope hero vice town 2.3 apk super mod download for android devices.
    -rope hero vice town 2.3 apk unlimited everything download for android devices.
    -rope hero vice town 2.3 apk vip mod download for android devices.
    -rope hero vice town 2.3 apkpure.com download for android devices.
    -how to download and install the latest version of the game Rope Hero: Vice Town APK on your Android device?
    -how to play the game Rope Hero: Vice Town APK on your Android device?

    -

    Download the APK file from a trusted source

    -

    The first step is to download the APK file of Rope Hero Vice Town 2.3 from a trusted source. You can use the link below to download it from APKCombo.com, a reliable website that offers free and safe APK downloads for Android apps and games.

    -

    Download Rope Hero Vice Town 2.3 APK from APKCombo.com

    -

    Enable unknown sources on your device

    -

    The second step is to enable unknown sources on your device. This is necessary because Rope Hero Vice Town 2.3 APK is not available on the Google Play Store, so you need to allow your device to install apps from sources other than the official store. To do this, you need to go to your device settings, then security or privacy settings, then find and enable the option that says unknown sources or allow installation of apps from unknown sources.

    -

    Install the APK file and enjoy the game

    -

    The third step is to install the APK file and enjoy the game. To do this, you need to locate the downloaded APK file on your device storage or file manager app, then tap on it to start the installation process. Follow the instructions on the screen to complete the installation. Once done, you can launch the game from your app drawer or home screen and start playing.

    -

    What are some tips and tricks for playing Rope Hero Vice Town?

    -

    If you want to play Rope Hero Vice Town like a pro, you need to know some tips and tricks that will help you master the game. Here are some of them:

    -

    Master the rope and other super powers

    -

    The rope is your main tool and weapon in Rope Hero Vice Town. You can use it to swing across buildings, climb walls, grab enemies or objects, or perform stunts. You need to master how to use it effectively in different situations. You also need to learn how to use your other super powers, such as super strength, speed, stamina, durability, mega jumps, power landings, etc. These powers will help you fight better, move faster, survive longer, and have more fun.

    -

    Level up your hero and customize your character

    -

    Rope Hero Vice Town is also an RPG game that lets you level up your hero by completing quests and gaining experience and money. You can use these resources to upgrade your skills, such as health, damage, speed, rope length, etc. You can also customize your character by buying new weapons, vehicles, and outfits from the shop. You can find different types of weapons, such as pistols, rifles, shotguns, grenades, rocket launchers, etc. You can also find different types of vehicles, such as cars, bikes, tanks, helicopters, planes, etc. You can also find different types of outfits, such as suits, masks, hats, glasses, etc. You can mix and match these items to create your own unique look and style.

    -

    Explore the city and find hidden secrets

    -

    Rope Hero Vice Town is a game that has a lot of secrets and surprises for you to discover. You can explore the city and find hidden locations, such as underground bases, secret labs, alien spaceships, etc. You can also find hidden collectibles, such as money bags, stars, cards, etc. that give you bonus rewards. You can also find hidden mini-games and activities that are fun and challenging. You can also encounter random events and situations that are unpredictable and hilarious. Be curious and adventurous and you will never get bored.

    -

    Conclusion

    -

    Rope Hero Vice Town 2.3 APK is a game that offers you a thrilling and immersive superhero experience on your Android device. You can play as a blue hero with a super rope that can do amazing things in a 3D open world filled with crime and adventure. You can choose to be a hero or a villain, fight against gangs and police, complete quests and challenges, and customize your character with various weapons, vehicles, and outfits. You can also enjoy the improved graphics and performance, the new weapons, vehicles, and archetypes, and the new mini-games and collectibles of the latest version of the game. If you want to download and install Rope Hero Vice Town 2.3 APK on your device, you just need to follow the simple steps we have provided in this article. If you want to play Rope Hero Vice Town like a pro, you just need to follow the tips and tricks we have shared in this article. Rope Hero Vice Town is a game that will keep you entertained for hours with its unlimited possibilities and fun.

    -

    FAQs

    -

    Here are some frequently asked questions about Rope Hero Vice Town 2.3 APK:

    - - - - - - - - - - - - - - - - - - - - - - - - - -
    QuestionAnswer
    Is Rope Hero Vice Town 2.3 APK free?Yes, Rope Hero Vice Town 2.3 APK is free to download and play. However, it may contain ads and in-app purchases that require real money.
    Is Rope Hero Vice Town 2.3 APK safe?Yes, Rope Hero Vice Town 2.3 APK is safe to download and install on your device. However, you need to make sure that you download it from a trusted source like APKCombo.com and enable unknown sources on your device settings.
    Is Rope Hero Vice Town 2.3 APK compatible with my device?Rope Hero Vice Town 2.3 APK is compatible with most Android devices that have Android 4.4 or higher versions. However, some devices may have different specifications or features that may affect the performance or compatibility of the game.
    How can I contact the developer of Rope Hero Vice Town 2.3 APK?You can contact the developer of Rope Hero Vice Town 2.3 APK by sending an email to naxeexaction@gmail.com or visiting their website at https://naxeex.com/.
    How can I rate or review Rope Hero Vice Town 2.3 APK?You can rate or review Rope Hero Vice Town 2.3 APK by visiting its page on Google Play Store or APKCombo.com and leaving your feedback or comments.

    197e85843d
    -
    -
    \ No newline at end of file diff --git a/spaces/2gauravc/search_summary_chatgpt/README.md b/spaces/2gauravc/search_summary_chatgpt/README.md deleted file mode 100644 index b36587bd1724da20f9addb5e7549089e0e0cf888..0000000000000000000000000000000000000000 --- a/spaces/2gauravc/search_summary_chatgpt/README.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Search Summary Chatgpt -emoji: 🚀 -colorFrom: green -colorTo: red -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - - -## Business Use case -For the customer to have a good on-boarding experience, it is imperative to have an efficient KYC process. However KYC processes today are mostly resource intensive with long turnaround time. - -One of the key pain points is having to look through Google searches of the related parties. Analysts have to click through each search, read it and determine if they is any material adverse news. - -Enter ChatGPT !! - -What if we could use ChatGPT to give a summary of the content and give its view if there is adverse news or not. - -## Using the App - -1. Enter the name of a person or business entity -2. Enter search keywords -3. Enter additional data points -4. Hit Search -5. Use 'Download Report' to dwonload the report to your desktop - - - - - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/2ndelement/voicevox/build_util/modify_pyinstaller.bash b/spaces/2ndelement/voicevox/build_util/modify_pyinstaller.bash deleted file mode 100644 index de4815fd2c85c4b0a01f4035f48a40cbca91db3d..0000000000000000000000000000000000000000 --- a/spaces/2ndelement/voicevox/build_util/modify_pyinstaller.bash +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -# PyInstallerをカスタマイズしてから再インストールする -# 良いGPUが自動的に選択されるようにしている -# https://github.com/VOICEVOX/voicevox_engine/issues/502 - -set -eux - -pyinstaller_version=$(pyinstaller -v) -tempdir=$(mktemp -dt modify_pyinstaller.XXXXXXXX) -trap 'rm -rf "$tempdir"' EXIT -git clone https://github.com/pyinstaller/pyinstaller.git "$tempdir" -b "v$pyinstaller_version" --depth 1 -cat > "$tempdir/bootloader/src/symbols.c" << EOF -#ifdef _WIN32 -#include - -// https://docs.nvidia.com/gameworks/content/technologies/desktop/optimus.htm -__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; - -// https://gpuopen.com/learn/amdpowerxpressrequesthighperformance/ -__declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001; -#endif -EOF -(cd "$tempdir/bootloader" && python ./waf all) -pip install -U "$tempdir" diff --git a/spaces/AIConsultant/MusicGen/audiocraft/grids/musicgen/musicgen_base_cached_32khz.py b/spaces/AIConsultant/MusicGen/audiocraft/grids/musicgen/musicgen_base_cached_32khz.py deleted file mode 100644 index d9a43f37d7369b5de4542fba87c4c8739d58b1e8..0000000000000000000000000000000000000000 --- a/spaces/AIConsultant/MusicGen/audiocraft/grids/musicgen/musicgen_base_cached_32khz.py +++ /dev/null @@ -1,67 +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 ._explorers import LMExplorer -from ...environment import AudioCraftEnvironment - - -@LMExplorer -def explorer(launcher): - partitions = AudioCraftEnvironment.get_slurm_partitions(['team', 'global']) - launcher.slurm_(gpus=32, partition=partitions) - launcher.bind_(solver='musicgen/musicgen_base_32khz') - # replace this by the desired music dataset - launcher.bind_(dset='internal/music_400k_32khz') - - fsdp = {'autocast': False, 'fsdp.use': True} - medium = {'model/lm/model_scale': 'medium'} - large = {'model/lm/model_scale': 'large'} - - cfg_low = {'classifier_free_guidance.training_dropout': 0.2} - wd_low = {'conditioners.description.t5.word_dropout': 0.2} - - adam = {'optim.optimizer': 'adamw', 'optim.lr': 1e-4} - - # BEGINNING OF CACHE WRITING JOBS. - cache_write = { - 'cache.path': '/fsx-codegen/defossez/cache/interleave_stereo_nv_32k', - 'cache.write': True, - 'generate.every': 500, - 'evaluate.every': 500, - 'logging.log_updates': 50, - } - - cache_sub = launcher.bind({'model/lm/model_scale': 'xsmall', 'conditioner': 'none'}) - cache_sub.bind_({'deadlock.use': True}) - cache_sub.slurm_(gpus=8) - with launcher.job_array(): - num_shards = 10 # total number of jobs running in parallel. - for shard in range(0, num_shards): - launcher(cache_write, {'cache.write_num_shards': num_shards, 'cache.write_shard': shard}) - - # REMOVE THE FOLLOWING RETURN STATEMENT ONCE THE ABOVE JOBS ARE DONE, - # OR SUFFICIENTLY AHEAD. - return - - cache = { - 'cache.path': '/fsx-codegen/defossez/cache/interleave_stereo_nv_32k', - } - launcher.bind_(fsdp, cache) - - launcher.slurm_(gpus=32).bind_(label='32gpus') - with launcher.job_array(): - sub = launcher.bind() - sub() - - launcher.slurm_(gpus=64).bind_(label='64gpus') - with launcher.job_array(): - sub = launcher.bind() - sub(medium, adam) - - launcher.slurm_(gpus=96).bind_(label='96gpus') - with launcher.job_array(): - sub = launcher.bind() - sub(large, cfg_low, wd_low, adam, {'optim.max_norm': 3}) diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov6/yolov6_l_syncbn_fast_8xb32-300e_coco.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov6/yolov6_l_syncbn_fast_8xb32-300e_coco.py deleted file mode 100644 index ad5ecf347e4aa0b3194b8be33d9c294915dd9e56..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov6/yolov6_l_syncbn_fast_8xb32-300e_coco.py +++ /dev/null @@ -1,28 +0,0 @@ -_base_ = './yolov6_m_syncbn_fast_8xb32-300e_coco.py' - -# ======================= Possible modified parameters ======================= -# -----model related----- -# The scaling factor that controls the depth of the network structure -deepen_factor = 1 -# The scaling factor that controls the width of the network structure -widen_factor = 1 - -# ============================== Unmodified in most cases =================== -model = dict( - backbone=dict( - deepen_factor=deepen_factor, - widen_factor=widen_factor, - hidden_ratio=1. / 2, - block_cfg=dict( - type='ConvWrapper', - norm_cfg=dict(type='BN', momentum=0.03, eps=0.001)), - act_cfg=dict(type='SiLU', inplace=True)), - neck=dict( - deepen_factor=deepen_factor, - widen_factor=widen_factor, - hidden_ratio=1. / 2, - block_cfg=dict( - type='ConvWrapper', - norm_cfg=dict(type='BN', momentum=0.03, eps=0.001)), - block_act_cfg=dict(type='SiLU', inplace=True)), - bbox_head=dict(head_module=dict(widen_factor=widen_factor))) diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet152.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet152.py deleted file mode 100644 index 94a718c3cec213727a7a2f11baeb3594fd37532e..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet152.py +++ /dev/null @@ -1,17 +0,0 @@ -# model settings -model = dict( - type='ImageClassifier', - backbone=dict( - type='ResNet', - depth=152, - num_stages=4, - out_indices=(3, ), - style='pytorch'), - neck=dict(type='GlobalAveragePooling'), - head=dict( - type='LinearClsHead', - num_classes=1000, - in_channels=2048, - loss=dict(type='CrossEntropyLoss', loss_weight=1.0), - topk=(1, 5), - )) diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet50_cifar_cutmix.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet50_cifar_cutmix.py deleted file mode 100644 index 73c38be271a90b1655ae63e4f36cf6c3a3c5fdc4..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/models/resnet50_cifar_cutmix.py +++ /dev/null @@ -1,18 +0,0 @@ -# model settings -model = dict( - type='ImageClassifier', - backbone=dict( - type='ResNet_CIFAR', - depth=50, - num_stages=4, - out_indices=(3, ), - style='pytorch'), - neck=dict(type='GlobalAveragePooling'), - head=dict( - type='MultiLabelLinearClsHead', - num_classes=10, - in_channels=2048, - loss=dict(type='CrossEntropyLoss', loss_weight=1.0, use_soft=True)), - train_cfg=dict( - augments=dict(type='BatchCutMix', alpha=1.0, num_classes=10, - prob=1.0))) diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/resnet/resnet34_8xb32_in1k.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/resnet/resnet34_8xb32_in1k.py deleted file mode 100644 index 7749261c80defef7cbf94c4e1284c26382246dc6..0000000000000000000000000000000000000000 --- a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/resnet/resnet34_8xb32_in1k.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = [ - '../_base_/models/resnet34.py', '../_base_/datasets/imagenet_bs32.py', - '../_base_/schedules/imagenet_bs256.py', '../_base_/default_runtime.py' -] diff --git a/spaces/AUBMC-AIM/OCTaGAN/app.py b/spaces/AUBMC-AIM/OCTaGAN/app.py deleted file mode 100644 index 94681bf393a774a55bb68bb334b0ee280d8478df..0000000000000000000000000000000000000000 --- a/spaces/AUBMC-AIM/OCTaGAN/app.py +++ /dev/null @@ -1,32 +0,0 @@ -import os -import gradio as gr -from PIL import Image -from huggingface_hub import hf_hub_url, cached_download - - -os.system("git clone https://github.com/AK391/stylegan2-ada-pytorch") - - -os.chdir("stylegan2-ada-pytorch") - -os.mkdir("outputs") -os.mkdir("outputs/images") - -config_file_url = hf_hub_url("AUBMC-AIM/OCTaGAN", filename="OCTaGAN.pkl") -cached_file = cached_download(config_file_url) - -def inference(truncation,seeds): - os.system("python generate.py --outdir=./outputs/images/ --trunc="+str(truncation)+" --seeds="+str(int(seeds))+" --network="+cached_file) - seeds = int(seeds) - image = Image.open(f"./outputs/images/seed{seeds:04d}.png") - return image - -title = "OCTaGAN" -description = "Gradio demo for OCTaGAN. OCTaGAN is a GAN trained on wide-field corneal Optical Coherence Tomography (OCT) scans to generate cornea scans with a variety of pathologies (e.g.keratoconus disease) and surgical procedures (e.g. Implantable Collamer Lens surgery, intrastromal corneal ring segment surgery, and Laser vision correction). OCTaGAN can be used for educational purposes as well as for generating training examples for ML algorithms." - -article = "

    OCTaGAN

    Open In Colab

    visitor badge
    " - - -gr.Interface(inference,[gr.inputs.Slider(label="truncation",minimum=0, maximum=5, step=0.1, default=0.8),gr.inputs.Slider(label="Seed",minimum=0, maximum=1000, step=1, default=0)],"pil",title=title,description=description,article=article, examples=[ - [0.8,0] - ]).launch(enable_queue=True,cache_examples=True) \ No newline at end of file diff --git a/spaces/AUST001/video/README.md b/spaces/AUST001/video/README.md deleted file mode 100644 index f83fe6ba30a76998bc6078e28e9661cbdb1e3433..0000000000000000000000000000000000000000 --- a/spaces/AUST001/video/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Video -emoji: 🏃 -colorFrom: blue -colorTo: gray -sdk: gradio -sdk_version: 3.18.0 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Aditya9790/yolo7-object-tracking/train_aux.py b/spaces/Aditya9790/yolo7-object-tracking/train_aux.py deleted file mode 100644 index 0e8053f8503ba762843f6dd56219f1e6c4e74ccc..0000000000000000000000000000000000000000 --- a/spaces/Aditya9790/yolo7-object-tracking/train_aux.py +++ /dev/null @@ -1,699 +0,0 @@ -import argparse -import logging -import math -import os -import random -import time -from copy import deepcopy -from pathlib import Path -from threading import Thread - -import numpy as np -import torch.distributed as dist -import torch.nn as nn -import torch.nn.functional as F -import torch.optim as optim -import torch.optim.lr_scheduler as lr_scheduler -import torch.utils.data -import yaml -from torch.cuda import amp -from torch.nn.parallel import DistributedDataParallel as DDP -from torch.utils.tensorboard import SummaryWriter -from tqdm import tqdm - -import test # import test.py to get mAP after each epoch -from models.experimental import attempt_load -from models.yolo import Model -from utils.autoanchor import check_anchors -from utils.datasets import create_dataloader -from utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \ - fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \ - check_requirements, print_mutation, set_logging, one_cycle, colorstr -from utils.google_utils import attempt_download -from utils.loss import ComputeLoss, ComputeLossAuxOTA -from utils.plots import plot_images, plot_labels, plot_results, plot_evolution -from utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first, is_parallel -from utils.wandb_logging.wandb_utils import WandbLogger, check_wandb_resume - -logger = logging.getLogger(__name__) - - -def train(hyp, opt, device, tb_writer=None): - logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items())) - save_dir, epochs, batch_size, total_batch_size, weights, rank = \ - Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank - - # Directories - wdir = save_dir / 'weights' - wdir.mkdir(parents=True, exist_ok=True) # make dir - last = wdir / 'last.pt' - best = wdir / 'best.pt' - results_file = save_dir / 'results.txt' - - # Save run settings - with open(save_dir / 'hyp.yaml', 'w') as f: - yaml.dump(hyp, f, sort_keys=False) - with open(save_dir / 'opt.yaml', 'w') as f: - yaml.dump(vars(opt), f, sort_keys=False) - - # Configure - plots = not opt.evolve # create plots - cuda = device.type != 'cpu' - init_seeds(2 + rank) - with open(opt.data) as f: - data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict - is_coco = opt.data.endswith('coco.yaml') - - # Logging- Doing this before checking the dataset. Might update data_dict - loggers = {'wandb': None} # loggers dict - if rank in [-1, 0]: - opt.hyp = hyp # add hyperparameters - run_id = torch.load(weights).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None - wandb_logger = WandbLogger(opt, Path(opt.save_dir).stem, run_id, data_dict) - loggers['wandb'] = wandb_logger.wandb - data_dict = wandb_logger.data_dict - if wandb_logger.wandb: - weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming - - nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes - names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names - assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check - - # Model - pretrained = weights.endswith('.pt') - if pretrained: - with torch_distributed_zero_first(rank): - attempt_download(weights) # download if not found locally - ckpt = torch.load(weights, map_location=device) # load checkpoint - model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create - exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys - state_dict = ckpt['model'].float().state_dict() # to FP32 - state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect - model.load_state_dict(state_dict, strict=False) # load - logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report - else: - model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create - with torch_distributed_zero_first(rank): - check_dataset(data_dict) # check - train_path = data_dict['train'] - test_path = data_dict['val'] - - # Freeze - freeze = [] # parameter names to freeze (full or partial) - for k, v in model.named_parameters(): - v.requires_grad = True # train all layers - if any(x in k for x in freeze): - print('freezing %s' % k) - v.requires_grad = False - - # Optimizer - nbs = 64 # nominal batch size - accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing - hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay - logger.info(f"Scaled weight_decay = {hyp['weight_decay']}") - - pg0, pg1, pg2 = [], [], [] # optimizer parameter groups - for k, v in model.named_modules(): - if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): - pg2.append(v.bias) # biases - if isinstance(v, nn.BatchNorm2d): - pg0.append(v.weight) # no decay - elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): - pg1.append(v.weight) # apply decay - if hasattr(v, 'im'): - if hasattr(v.im, 'implicit'): - pg0.append(v.im.implicit) - else: - for iv in v.im: - pg0.append(iv.implicit) - if hasattr(v, 'imc'): - if hasattr(v.imc, 'implicit'): - pg0.append(v.imc.implicit) - else: - for iv in v.imc: - pg0.append(iv.implicit) - if hasattr(v, 'imb'): - if hasattr(v.imb, 'implicit'): - pg0.append(v.imb.implicit) - else: - for iv in v.imb: - pg0.append(iv.implicit) - if hasattr(v, 'imo'): - if hasattr(v.imo, 'implicit'): - pg0.append(v.imo.implicit) - else: - for iv in v.imo: - pg0.append(iv.implicit) - if hasattr(v, 'ia'): - if hasattr(v.ia, 'implicit'): - pg0.append(v.ia.implicit) - else: - for iv in v.ia: - pg0.append(iv.implicit) - if hasattr(v, 'attn'): - if hasattr(v.attn, 'logit_scale'): - pg0.append(v.attn.logit_scale) - if hasattr(v.attn, 'q_bias'): - pg0.append(v.attn.q_bias) - if hasattr(v.attn, 'v_bias'): - pg0.append(v.attn.v_bias) - if hasattr(v.attn, 'relative_position_bias_table'): - pg0.append(v.attn.relative_position_bias_table) - if hasattr(v, 'rbr_dense'): - if hasattr(v.rbr_dense, 'weight_rbr_origin'): - pg0.append(v.rbr_dense.weight_rbr_origin) - if hasattr(v.rbr_dense, 'weight_rbr_avg_conv'): - pg0.append(v.rbr_dense.weight_rbr_avg_conv) - if hasattr(v.rbr_dense, 'weight_rbr_pfir_conv'): - pg0.append(v.rbr_dense.weight_rbr_pfir_conv) - if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_idconv1'): - pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_idconv1) - if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_conv2'): - pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_conv2) - if hasattr(v.rbr_dense, 'weight_rbr_gconv_dw'): - pg0.append(v.rbr_dense.weight_rbr_gconv_dw) - if hasattr(v.rbr_dense, 'weight_rbr_gconv_pw'): - pg0.append(v.rbr_dense.weight_rbr_gconv_pw) - if hasattr(v.rbr_dense, 'vector'): - pg0.append(v.rbr_dense.vector) - - if opt.adam: - optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum - else: - optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True) - - optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay - optimizer.add_param_group({'params': pg2}) # add pg2 (biases) - logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0))) - del pg0, pg1, pg2 - - # Scheduler https://arxiv.org/pdf/1812.01187.pdf - # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR - if opt.linear_lr: - lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear - else: - lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf'] - scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) - # plot_lr_scheduler(optimizer, scheduler, epochs) - - # EMA - ema = ModelEMA(model) if rank in [-1, 0] else None - - # Resume - start_epoch, best_fitness = 0, 0.0 - if pretrained: - # Optimizer - if ckpt['optimizer'] is not None: - optimizer.load_state_dict(ckpt['optimizer']) - best_fitness = ckpt['best_fitness'] - - # EMA - if ema and ckpt.get('ema'): - ema.ema.load_state_dict(ckpt['ema'].float().state_dict()) - ema.updates = ckpt['updates'] - - # Results - if ckpt.get('training_results') is not None: - results_file.write_text(ckpt['training_results']) # write results.txt - - # Epochs - start_epoch = ckpt['epoch'] + 1 - if opt.resume: - assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs) - if epochs < start_epoch: - logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' % - (weights, ckpt['epoch'], epochs)) - epochs += ckpt['epoch'] # finetune additional epochs - - del ckpt, state_dict - - # Image sizes - gs = max(int(model.stride.max()), 32) # grid size (max stride) - nl = model.model[-1].nl # number of detection layers (used for scaling hyp['obj']) - imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples - - # DP mode - if cuda and rank == -1 and torch.cuda.device_count() > 1: - model = torch.nn.DataParallel(model) - - # SyncBatchNorm - if opt.sync_bn and cuda and rank != -1: - model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device) - logger.info('Using SyncBatchNorm()') - - # Trainloader - dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, - hyp=hyp, augment=True, cache=opt.cache_images, rect=opt.rect, rank=rank, - world_size=opt.world_size, workers=opt.workers, - image_weights=opt.image_weights, quad=opt.quad, prefix=colorstr('train: ')) - mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class - nb = len(dataloader) # number of batches - assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1) - - # Process 0 - if rank in [-1, 0]: - testloader = create_dataloader(test_path, imgsz_test, batch_size * 2, gs, opt, # testloader - hyp=hyp, cache=opt.cache_images and not opt.notest, rect=True, rank=-1, - world_size=opt.world_size, workers=opt.workers, - pad=0.5, prefix=colorstr('val: '))[0] - - if not opt.resume: - labels = np.concatenate(dataset.labels, 0) - c = torch.tensor(labels[:, 0]) # classes - # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency - # model._initialize_biases(cf.to(device)) - if plots: - #plot_labels(labels, names, save_dir, loggers) - if tb_writer: - tb_writer.add_histogram('classes', c, 0) - - # Anchors - if not opt.noautoanchor: - check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) - model.half().float() # pre-reduce anchor precision - - # DDP mode - if cuda and rank != -1: - model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank, - # nn.MultiheadAttention incompatibility with DDP https://github.com/pytorch/pytorch/issues/26698 - find_unused_parameters=any(isinstance(layer, nn.MultiheadAttention) for layer in model.modules())) - - # Model parameters - hyp['box'] *= 3. / nl # scale to layers - hyp['cls'] *= nc / 80. * 3. / nl # scale to classes and layers - hyp['obj'] *= (imgsz / 640) ** 2 * 3. / nl # scale to image size and layers - hyp['label_smoothing'] = opt.label_smoothing - model.nc = nc # attach number of classes to model - model.hyp = hyp # attach hyperparameters to model - model.gr = 1.0 # iou loss ratio (obj_loss = 1.0 or iou) - model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights - model.names = names - - # Start training - t0 = time.time() - nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations) - # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training - maps = np.zeros(nc) # mAP per class - results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls) - scheduler.last_epoch = start_epoch - 1 # do not move - scaler = amp.GradScaler(enabled=cuda) - compute_loss_ota = ComputeLossAuxOTA(model) # init loss class - compute_loss = ComputeLoss(model) # init loss class - logger.info(f'Image sizes {imgsz} train, {imgsz_test} test\n' - f'Using {dataloader.num_workers} dataloader workers\n' - f'Logging results to {save_dir}\n' - f'Starting training for {epochs} epochs...') - torch.save(model, wdir / 'init.pt') - for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------ - model.train() - - # Update image weights (optional) - if opt.image_weights: - # Generate indices - if rank in [-1, 0]: - cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights - iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights - dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx - # Broadcast if DDP - if rank != -1: - indices = (torch.tensor(dataset.indices) if rank == 0 else torch.zeros(dataset.n)).int() - dist.broadcast(indices, 0) - if rank != 0: - dataset.indices = indices.cpu().numpy() - - # Update mosaic border - # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs) - # dataset.mosaic_border = [b - imgsz, -b] # height, width borders - - mloss = torch.zeros(4, device=device) # mean losses - if rank != -1: - dataloader.sampler.set_epoch(epoch) - pbar = enumerate(dataloader) - logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'labels', 'img_size')) - if rank in [-1, 0]: - pbar = tqdm(pbar, total=nb) # progress bar - optimizer.zero_grad() - for i, (imgs, targets, paths, _) in pbar: # batch ------------------------------------------------------------- - ni = i + nb * epoch # number integrated batches (since train start) - imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0 - - # Warmup - if ni <= nw: - xi = [0, nw] # x interp - # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou) - accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round()) - for j, x in enumerate(optimizer.param_groups): - # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 - x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)]) - if 'momentum' in x: - x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']]) - - # Multi-scale - if opt.multi_scale: - sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size - sf = sz / max(imgs.shape[2:]) # scale factor - if sf != 1: - ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple) - imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False) - - # Forward - with amp.autocast(enabled=cuda): - pred = model(imgs) # forward - loss, loss_items = compute_loss_ota(pred, targets.to(device), imgs) # loss scaled by batch_size - if rank != -1: - loss *= opt.world_size # gradient averaged between devices in DDP mode - if opt.quad: - loss *= 4. - - # Backward - scaler.scale(loss).backward() - - # Optimize - if ni % accumulate == 0: - scaler.step(optimizer) # optimizer.step - scaler.update() - optimizer.zero_grad() - if ema: - ema.update(model) - - # Print - if rank in [-1, 0]: - mloss = (mloss * i + loss_items) / (i + 1) # update mean losses - mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB) - s = ('%10s' * 2 + '%10.4g' * 6) % ( - '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1]) - pbar.set_description(s) - - # Plot - if plots and ni < 10: - f = save_dir / f'train_batch{ni}.jpg' # filename - Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start() - # if tb_writer: - # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch) - # tb_writer.add_graph(torch.jit.trace(model, imgs, strict=False), []) # add model graph - elif plots and ni == 10 and wandb_logger.wandb: - wandb_logger.log({"Mosaics": [wandb_logger.wandb.Image(str(x), caption=x.name) for x in - save_dir.glob('train*.jpg') if x.exists()]}) - - # end batch ------------------------------------------------------------------------------------------------ - # end epoch ---------------------------------------------------------------------------------------------------- - - # Scheduler - lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard - scheduler.step() - - # DDP process 0 or single-GPU - if rank in [-1, 0]: - # mAP - ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride', 'class_weights']) - final_epoch = epoch + 1 == epochs - if not opt.notest or final_epoch: # Calculate mAP - wandb_logger.current_epoch = epoch + 1 - results, maps, times = test.test(data_dict, - batch_size=batch_size * 2, - imgsz=imgsz_test, - model=ema.ema, - single_cls=opt.single_cls, - dataloader=testloader, - save_dir=save_dir, - verbose=nc < 50 and final_epoch, - plots=plots and final_epoch, - wandb_logger=wandb_logger, - compute_loss=compute_loss, - is_coco=is_coco, - v5_metric=opt.v5_metric) - - # Write - with open(results_file, 'a') as f: - f.write(s + '%10.4g' * 7 % results + '\n') # append metrics, val_loss - if len(opt.name) and opt.bucket: - os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name)) - - # Log - tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss - 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', - 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss - 'x/lr0', 'x/lr1', 'x/lr2'] # params - for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags): - if tb_writer: - tb_writer.add_scalar(tag, x, epoch) # tensorboard - if wandb_logger.wandb: - wandb_logger.log({tag: x}) # W&B - - # Update best mAP - fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95] - if fi > best_fitness: - best_fitness = fi - wandb_logger.end_epoch(best_result=best_fitness == fi) - - # Save model - if (not opt.nosave) or (final_epoch and not opt.evolve): # if save - ckpt = {'epoch': epoch, - 'best_fitness': best_fitness, - 'training_results': results_file.read_text(), - 'model': deepcopy(model.module if is_parallel(model) else model).half(), - 'ema': deepcopy(ema.ema).half(), - 'updates': ema.updates, - 'optimizer': optimizer.state_dict(), - 'wandb_id': wandb_logger.wandb_run.id if wandb_logger.wandb else None} - - # Save last, best and delete - torch.save(ckpt, last) - if best_fitness == fi: - torch.save(ckpt, best) - if (best_fitness == fi) and (epoch >= 200): - torch.save(ckpt, wdir / 'best_{:03d}.pt'.format(epoch)) - if epoch == 0: - torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch)) - elif ((epoch+1) % 25) == 0: - torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch)) - elif epoch >= (epochs-5): - torch.save(ckpt, wdir / 'epoch_{:03d}.pt'.format(epoch)) - if wandb_logger.wandb: - if ((epoch + 1) % opt.save_period == 0 and not final_epoch) and opt.save_period != -1: - wandb_logger.log_model( - last.parent, opt, epoch, fi, best_model=best_fitness == fi) - del ckpt - - # end epoch ---------------------------------------------------------------------------------------------------- - # end training - if rank in [-1, 0]: - # Plots - if plots: - plot_results(save_dir=save_dir) # save as results.png - if wandb_logger.wandb: - files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]] - wandb_logger.log({"Results": [wandb_logger.wandb.Image(str(save_dir / f), caption=f) for f in files - if (save_dir / f).exists()]}) - # Test best.pt - logger.info('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600)) - if opt.data.endswith('coco.yaml') and nc == 80: # if COCO - for m in (last, best) if best.exists() else (last): # speed, mAP tests - results, _, _ = test.test(opt.data, - batch_size=batch_size * 2, - imgsz=imgsz_test, - conf_thres=0.001, - iou_thres=0.7, - model=attempt_load(m, device).half(), - single_cls=opt.single_cls, - dataloader=testloader, - save_dir=save_dir, - save_json=True, - plots=False, - is_coco=is_coco, - v5_metric=opt.v5_metric) - - # Strip optimizers - final = best if best.exists() else last # final model - for f in last, best: - if f.exists(): - strip_optimizer(f) # strip optimizers - if opt.bucket: - os.system(f'gsutil cp {final} gs://{opt.bucket}/weights') # upload - if wandb_logger.wandb and not opt.evolve: # Log the stripped model - wandb_logger.wandb.log_artifact(str(final), type='model', - name='run_' + wandb_logger.wandb_run.id + '_model', - aliases=['last', 'best', 'stripped']) - wandb_logger.finish_run() - else: - dist.destroy_process_group() - torch.cuda.empty_cache() - return results - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('--weights', type=str, default='yolo7.pt', help='initial weights path') - parser.add_argument('--cfg', type=str, default='', help='model.yaml path') - parser.add_argument('--data', type=str, default='data/coco.yaml', help='data.yaml path') - parser.add_argument('--hyp', type=str, default='data/hyp.scratch.p5.yaml', help='hyperparameters path') - parser.add_argument('--epochs', type=int, default=300) - parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs') - parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes') - parser.add_argument('--rect', action='store_true', help='rectangular training') - parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training') - parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') - parser.add_argument('--notest', action='store_true', help='only test final epoch') - parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check') - parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters') - parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') - parser.add_argument('--cache-images', action='store_true', help='cache images for faster training') - parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training') - parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') - parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%') - parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class') - parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer') - parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode') - parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify') - parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers') - parser.add_argument('--project', default='runs/train', help='save to project/name') - parser.add_argument('--entity', default=None, help='W&B entity') - parser.add_argument('--name', default='exp', help='save to project/name') - parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') - parser.add_argument('--quad', action='store_true', help='quad dataloader') - parser.add_argument('--linear-lr', action='store_true', help='linear LR') - parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon') - parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table') - parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B') - parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch') - parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used') - parser.add_argument('--v5-metric', action='store_true', help='assume maximum recall as 1.0 in AP calculation') - opt = parser.parse_args() - - # Set DDP variables - opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1 - opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1 - set_logging(opt.global_rank) - #if opt.global_rank in [-1, 0]: - # check_git_status() - # check_requirements() - - # Resume - wandb_run = check_wandb_resume(opt) - if opt.resume and not wandb_run: # resume an interrupted run - ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path - assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist' - apriori = opt.global_rank, opt.local_rank - with open(Path(ckpt).parent.parent / 'opt.yaml') as f: - opt = argparse.Namespace(**yaml.load(f, Loader=yaml.SafeLoader)) # replace - opt.cfg, opt.weights, opt.resume, opt.batch_size, opt.global_rank, opt.local_rank = '', ckpt, True, opt.total_batch_size, *apriori # reinstate - logger.info('Resuming training from %s' % ckpt) - else: - # opt.hyp = opt.hyp or ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml') - opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files - assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified' - opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test) - opt.name = 'evolve' if opt.evolve else opt.name - opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve) # increment run - - # DDP mode - opt.total_batch_size = opt.batch_size - device = select_device(opt.device, batch_size=opt.batch_size) - if opt.local_rank != -1: - assert torch.cuda.device_count() > opt.local_rank - torch.cuda.set_device(opt.local_rank) - device = torch.device('cuda', opt.local_rank) - dist.init_process_group(backend='nccl', init_method='env://') # distributed backend - assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count' - opt.batch_size = opt.total_batch_size // opt.world_size - - # Hyperparameters - with open(opt.hyp) as f: - hyp = yaml.load(f, Loader=yaml.SafeLoader) # load hyps - - # Train - logger.info(opt) - if not opt.evolve: - tb_writer = None # init loggers - if opt.global_rank in [-1, 0]: - prefix = colorstr('tensorboard: ') - logger.info(f"{prefix}Start with 'tensorboard --logdir {opt.project}', view at http://localhost:6006/") - tb_writer = SummaryWriter(opt.save_dir) # Tensorboard - train(hyp, opt, device, tb_writer) - - # Evolve hyperparameters (optional) - else: - # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit) - meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3) - 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf) - 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1 - 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay - 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok) - 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum - 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr - 'box': (1, 0.02, 0.2), # box loss gain - 'cls': (1, 0.2, 4.0), # cls loss gain - 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight - 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels) - 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight - 'iou_t': (0, 0.1, 0.7), # IoU training threshold - 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold - 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore) - 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5) - 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction) - 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction) - 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction) - 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg) - 'translate': (1, 0.0, 0.9), # image translation (+/- fraction) - 'scale': (1, 0.0, 0.9), # image scale (+/- gain) - 'shear': (1, 0.0, 10.0), # image shear (+/- deg) - 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001 - 'flipud': (1, 0.0, 1.0), # image flip up-down (probability) - 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability) - 'mosaic': (1, 0.0, 1.0), # image mixup (probability) - 'mixup': (1, 0.0, 1.0)} # image mixup (probability) - - with open(opt.hyp, errors='ignore') as f: - hyp = yaml.safe_load(f) # load hyps dict - if 'anchors' not in hyp: # anchors commented in hyp.yaml - hyp['anchors'] = 3 - - assert opt.local_rank == -1, 'DDP mode not implemented for --evolve' - opt.notest, opt.nosave = True, True # only test/save final epoch - # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices - yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here - if opt.bucket: - os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists - - for _ in range(300): # generations to evolve - if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate - # Select parent(s) - parent = 'single' # parent selection method: 'single' or 'weighted' - x = np.loadtxt('evolve.txt', ndmin=2) - n = min(5, len(x)) # number of previous results to consider - x = x[np.argsort(-fitness(x))][:n] # top n mutations - w = fitness(x) - fitness(x).min() # weights - if parent == 'single' or len(x) == 1: - # x = x[random.randint(0, n - 1)] # random selection - x = x[random.choices(range(n), weights=w)[0]] # weighted selection - elif parent == 'weighted': - x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination - - # Mutate - mp, s = 0.8, 0.2 # mutation probability, sigma - npr = np.random - npr.seed(int(time.time())) - g = np.array([x[0] for x in meta.values()]) # gains 0-1 - ng = len(meta) - v = np.ones(ng) - while all(v == 1): # mutate until a change occurs (prevent duplicates) - v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0) - for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300) - hyp[k] = float(x[i + 7] * v[i]) # mutate - - # Constrain to limits - for k, v in meta.items(): - hyp[k] = max(hyp[k], v[1]) # lower limit - hyp[k] = min(hyp[k], v[2]) # upper limit - hyp[k] = round(hyp[k], 5) # significant digits - - # Train mutation - results = train(hyp.copy(), opt, device) - - # Write mutation results - print_mutation(hyp.copy(), results, yaml_file, opt.bucket) - - # Plot results - plot_evolution(yaml_file) - print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n' - f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}') diff --git a/spaces/AgentVerse/agentVerse/agentverse/llms/__init__.py b/spaces/AgentVerse/agentVerse/agentverse/llms/__init__.py deleted file mode 100644 index 5c0cd5047f5e8b71ebe30e5631d709564e782fe8..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/llms/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from agentverse.registry import Registry - -llm_registry = Registry(name="LLMRegistry") - -from .base import BaseLLM, BaseChatModel, BaseCompletionModel, LLMResult -from .openai import OpenAIChat diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/states/BaseState.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/states/BaseState.js deleted file mode 100644 index 80a12629376ede43985e3a1a9ef272f3bd7d1dfe..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/states/BaseState.js +++ /dev/null @@ -1,36 +0,0 @@ -import FSM from '../../../plugins/fsm.js'; - -class BaseState extends FSM { - constructor(bejeweled, config) { - super(config); - - this.bejeweled = bejeweled; // Bejeweled - this.board = bejeweled.board; // Bejeweled.board - this.waitEvents = bejeweled.waitEvents; // Bejeweled.waitEvents - } - - shutdown() { - super.shutdown(); - this.bejeweled = undefined; - this.board = undefined; - this.waitEvents = undefined; - } - - destroy() { - this.shutdown(); - return this; - } - - next() { - // Wait until all events are completed - if (this.waitEvents.noWaitEvent) { - // Go to next state - super.next(); - } else { - // Try again later - this.waitEvents.setCompleteCallback(this.next, this); - } - } -} - -export default BaseState \ No newline at end of file diff --git a/spaces/Aki004/herta-so-vits/modules/attentions.py b/spaces/Aki004/herta-so-vits/modules/attentions.py deleted file mode 100644 index f9c11ca4a3acb86bf1abc04d9dcfa82a4ed4061f..0000000000000000000000000000000000000000 --- a/spaces/Aki004/herta-so-vits/modules/attentions.py +++ /dev/null @@ -1,349 +0,0 @@ -import copy -import math -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - -import modules.commons as commons -import modules.modules as modules -from modules.modules import LayerNorm - - -class FFT(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers=1, kernel_size=1, p_dropout=0., - proximal_bias=False, proximal_init=True, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - for i in range(self.n_layers): - self.self_attn_layers.append( - MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, - proximal_init=proximal_init)) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.ffn_layers.append( - FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - x = x * x_mask - return x - - -class Encoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.window_size = window_size - - self.drop = nn.Dropout(p_dropout) - self.attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask): - attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.attn_layers[i](x, x, attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class Decoder(nn.Module): - def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs): - super().__init__() - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - - self.drop = nn.Dropout(p_dropout) - self.self_attn_layers = nn.ModuleList() - self.norm_layers_0 = nn.ModuleList() - self.encdec_attn_layers = nn.ModuleList() - self.norm_layers_1 = nn.ModuleList() - self.ffn_layers = nn.ModuleList() - self.norm_layers_2 = nn.ModuleList() - for i in range(self.n_layers): - self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init)) - self.norm_layers_0.append(LayerNorm(hidden_channels)) - self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout)) - self.norm_layers_1.append(LayerNorm(hidden_channels)) - self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True)) - self.norm_layers_2.append(LayerNorm(hidden_channels)) - - def forward(self, x, x_mask, h, h_mask): - """ - x: decoder input - h: encoder output - """ - self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype) - encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1) - x = x * x_mask - for i in range(self.n_layers): - y = self.self_attn_layers[i](x, x, self_attn_mask) - y = self.drop(y) - x = self.norm_layers_0[i](x + y) - - y = self.encdec_attn_layers[i](x, h, encdec_attn_mask) - y = self.drop(y) - x = self.norm_layers_1[i](x + y) - - y = self.ffn_layers[i](x, x_mask) - y = self.drop(y) - x = self.norm_layers_2[i](x + y) - x = x * x_mask - return x - - -class MultiHeadAttention(nn.Module): - def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False): - super().__init__() - assert channels % n_heads == 0 - - self.channels = channels - self.out_channels = out_channels - self.n_heads = n_heads - self.p_dropout = p_dropout - self.window_size = window_size - self.heads_share = heads_share - self.block_length = block_length - self.proximal_bias = proximal_bias - self.proximal_init = proximal_init - self.attn = None - - self.k_channels = channels // n_heads - self.conv_q = nn.Conv1d(channels, channels, 1) - self.conv_k = nn.Conv1d(channels, channels, 1) - self.conv_v = nn.Conv1d(channels, channels, 1) - self.conv_o = nn.Conv1d(channels, out_channels, 1) - self.drop = nn.Dropout(p_dropout) - - if window_size is not None: - n_heads_rel = 1 if heads_share else n_heads - rel_stddev = self.k_channels**-0.5 - self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev) - - nn.init.xavier_uniform_(self.conv_q.weight) - nn.init.xavier_uniform_(self.conv_k.weight) - nn.init.xavier_uniform_(self.conv_v.weight) - if proximal_init: - with torch.no_grad(): - self.conv_k.weight.copy_(self.conv_q.weight) - self.conv_k.bias.copy_(self.conv_q.bias) - - def forward(self, x, c, attn_mask=None): - q = self.conv_q(x) - k = self.conv_k(c) - v = self.conv_v(c) - - x, self.attn = self.attention(q, k, v, mask=attn_mask) - - x = self.conv_o(x) - return x - - def attention(self, query, key, value, mask=None): - # reshape [b, d, t] -> [b, n_h, t, d_k] - b, d, t_s, t_t = (*key.size(), query.size(2)) - query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3) - key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3) - - scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1)) - if self.window_size is not None: - assert t_s == t_t, "Relative attention is only available for self-attention." - key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s) - rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings) - scores_local = self._relative_position_to_absolute_position(rel_logits) - scores = scores + scores_local - if self.proximal_bias: - assert t_s == t_t, "Proximal bias is only available for self-attention." - scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype) - if mask is not None: - scores = scores.masked_fill(mask == 0, -1e4) - if self.block_length is not None: - assert t_s == t_t, "Local attention is only available for self-attention." - block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length) - scores = scores.masked_fill(block_mask == 0, -1e4) - p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s] - p_attn = self.drop(p_attn) - output = torch.matmul(p_attn, value) - if self.window_size is not None: - relative_weights = self._absolute_position_to_relative_position(p_attn) - value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s) - output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings) - output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t] - return output, p_attn - - def _matmul_with_relative_values(self, x, y): - """ - x: [b, h, l, m] - y: [h or 1, m, d] - ret: [b, h, l, d] - """ - ret = torch.matmul(x, y.unsqueeze(0)) - return ret - - def _matmul_with_relative_keys(self, x, y): - """ - x: [b, h, l, d] - y: [h or 1, m, d] - ret: [b, h, l, m] - """ - ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1)) - return ret - - def _get_relative_embeddings(self, relative_embeddings, length): - max_relative_position = 2 * self.window_size + 1 - # Pad first before slice to avoid using cond ops. - pad_length = max(length - (self.window_size + 1), 0) - slice_start_position = max((self.window_size + 1) - length, 0) - slice_end_position = slice_start_position + 2 * length - 1 - if pad_length > 0: - padded_relative_embeddings = F.pad( - relative_embeddings, - commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]])) - else: - padded_relative_embeddings = relative_embeddings - used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position] - return used_relative_embeddings - - def _relative_position_to_absolute_position(self, x): - """ - x: [b, h, l, 2*l-1] - ret: [b, h, l, l] - """ - batch, heads, length, _ = x.size() - # Concat columns of pad to shift from relative to absolute indexing. - x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]])) - - # Concat extra elements so to add up to shape (len+1, 2*len-1). - x_flat = x.view([batch, heads, length * 2 * length]) - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]])) - - # Reshape and slice out the padded elements. - x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:] - return x_final - - def _absolute_position_to_relative_position(self, x): - """ - x: [b, h, l, l] - ret: [b, h, l, 2*l-1] - """ - batch, heads, length, _ = x.size() - # padd along column - x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]])) - x_flat = x.view([batch, heads, length**2 + length*(length -1)]) - # add 0's in the beginning that will skew the elements after reshape - x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]])) - x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:] - return x_final - - def _attention_bias_proximal(self, length): - """Bias for self-attention to encourage attention to close positions. - Args: - length: an integer scalar. - Returns: - a Tensor with shape [1, 1, length, length] - """ - r = torch.arange(length, dtype=torch.float32) - diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1) - return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0) - - -class FFN(nn.Module): - def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.activation = activation - self.causal = causal - - if causal: - self.padding = self._causal_padding - else: - self.padding = self._same_padding - - self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size) - self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size) - self.drop = nn.Dropout(p_dropout) - - def forward(self, x, x_mask): - x = self.conv_1(self.padding(x * x_mask)) - if self.activation == "gelu": - x = x * torch.sigmoid(1.702 * x) - else: - x = torch.relu(x) - x = self.drop(x) - x = self.conv_2(self.padding(x * x_mask)) - return x * x_mask - - def _causal_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = self.kernel_size - 1 - pad_r = 0 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x - - def _same_padding(self, x): - if self.kernel_size == 1: - return x - pad_l = (self.kernel_size - 1) // 2 - pad_r = self.kernel_size // 2 - padding = [[0, 0], [0, 0], [pad_l, pad_r]] - x = F.pad(x, commons.convert_pad_shape(padding)) - return x diff --git a/spaces/Alpaca233/ChatPDF-GUI/gpt_reader/model_interface.py b/spaces/Alpaca233/ChatPDF-GUI/gpt_reader/model_interface.py deleted file mode 100644 index f3c04a45373ad34216fb7616bd06de52c7008604..0000000000000000000000000000000000000000 --- a/spaces/Alpaca233/ChatPDF-GUI/gpt_reader/model_interface.py +++ /dev/null @@ -1,32 +0,0 @@ -from typing import List -import openai - - -class ModelInterface(object): - - def __init__(self) -> None: - pass - - def send_msg(self, *args): - pass - - -class OpenAIModel(object): - - def __init__(self, api_key, model='gpt-3.5-turbo', temperature=0.2) -> None: - openai.api_key = api_key - self.model = model - self.temperature = temperature - - def send_msg(self, msg: List[dict], return_raw_text=True): - - response = openai.ChatCompletion.create( - model=self.model, - messages=msg, - temperature=self.temperature - ) - - if return_raw_text: - return response["choices"][0]["message"]["content"] - else: - return response diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/kandinsky/test_kandinsky_inpaint.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/kandinsky/test_kandinsky_inpaint.py deleted file mode 100644 index 7f1841d608073f337305766eb2588cbf1e2449f9..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/kandinsky/test_kandinsky_inpaint.py +++ /dev/null @@ -1,346 +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 gc -import random -import unittest - -import numpy as np -import torch -from PIL import Image -from transformers import XLMRobertaTokenizerFast - -from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNet2DConditionModel, VQModel -from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP -from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device -from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu - -from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference - - -enable_full_determinism() - - -class Dummies: - @property - def text_embedder_hidden_size(self): - return 32 - - @property - def time_input_dim(self): - return 32 - - @property - def block_out_channels_0(self): - return self.time_input_dim - - @property - def time_embed_dim(self): - return self.time_input_dim * 4 - - @property - def cross_attention_dim(self): - return 32 - - @property - def dummy_tokenizer(self): - tokenizer = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base") - return tokenizer - - @property - def dummy_text_encoder(self): - torch.manual_seed(0) - config = MCLIPConfig( - numDims=self.cross_attention_dim, - transformerDimensions=self.text_embedder_hidden_size, - hidden_size=self.text_embedder_hidden_size, - intermediate_size=37, - num_attention_heads=4, - num_hidden_layers=5, - vocab_size=1005, - ) - - text_encoder = MultilingualCLIP(config) - text_encoder = text_encoder.eval() - - return text_encoder - - @property - def dummy_unet(self): - torch.manual_seed(0) - - model_kwargs = { - "in_channels": 9, - # Out channels is double in channels because predicts mean and variance - "out_channels": 8, - "addition_embed_type": "text_image", - "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), - "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), - "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", - "block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2), - "layers_per_block": 1, - "encoder_hid_dim": self.text_embedder_hidden_size, - "encoder_hid_dim_type": "text_image_proj", - "cross_attention_dim": self.cross_attention_dim, - "attention_head_dim": 4, - "resnet_time_scale_shift": "scale_shift", - "class_embed_type": None, - } - - model = UNet2DConditionModel(**model_kwargs) - return model - - @property - def dummy_movq_kwargs(self): - return { - "block_out_channels": [32, 64], - "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], - "in_channels": 3, - "latent_channels": 4, - "layers_per_block": 1, - "norm_num_groups": 8, - "norm_type": "spatial", - "num_vq_embeddings": 12, - "out_channels": 3, - "up_block_types": [ - "AttnUpDecoderBlock2D", - "UpDecoderBlock2D", - ], - "vq_embed_dim": 4, - } - - @property - def dummy_movq(self): - torch.manual_seed(0) - model = VQModel(**self.dummy_movq_kwargs) - return model - - def get_dummy_components(self): - text_encoder = self.dummy_text_encoder - tokenizer = self.dummy_tokenizer - unet = self.dummy_unet - movq = self.dummy_movq - - scheduler = DDIMScheduler( - num_train_timesteps=1000, - beta_schedule="linear", - beta_start=0.00085, - beta_end=0.012, - clip_sample=False, - set_alpha_to_one=False, - steps_offset=1, - prediction_type="epsilon", - thresholding=False, - ) - - components = { - "text_encoder": text_encoder, - "tokenizer": tokenizer, - "unet": unet, - "scheduler": scheduler, - "movq": movq, - } - - return components - - def get_dummy_inputs(self, device, seed=0): - image_embeds = floats_tensor((1, self.cross_attention_dim), rng=random.Random(seed)).to(device) - negative_image_embeds = floats_tensor((1, self.cross_attention_dim), rng=random.Random(seed + 1)).to(device) - # create init_image - image = floats_tensor((1, 3, 64, 64), rng=random.Random(seed)).to(device) - image = image.cpu().permute(0, 2, 3, 1)[0] - init_image = Image.fromarray(np.uint8(image)).convert("RGB").resize((256, 256)) - # create mask - mask = np.zeros((64, 64), dtype=np.float32) - mask[:32, :32] = 1 - - if str(device).startswith("mps"): - generator = torch.manual_seed(seed) - else: - generator = torch.Generator(device=device).manual_seed(seed) - inputs = { - "prompt": "horse", - "image": init_image, - "mask_image": mask, - "image_embeds": image_embeds, - "negative_image_embeds": negative_image_embeds, - "generator": generator, - "height": 64, - "width": 64, - "num_inference_steps": 2, - "guidance_scale": 4.0, - "output_type": "np", - } - return inputs - - -class KandinskyInpaintPipelineFastTests(PipelineTesterMixin, unittest.TestCase): - pipeline_class = KandinskyInpaintPipeline - params = ["prompt", "image_embeds", "negative_image_embeds", "image", "mask_image"] - batch_params = [ - "prompt", - "negative_prompt", - "image_embeds", - "negative_image_embeds", - "image", - "mask_image", - ] - required_optional_params = [ - "generator", - "height", - "width", - "latents", - "guidance_scale", - "negative_prompt", - "num_inference_steps", - "return_dict", - "guidance_scale", - "num_images_per_prompt", - "output_type", - "return_dict", - ] - test_xformers_attention = False - - def get_dummy_components(self): - dummies = Dummies() - return dummies.get_dummy_components() - - def get_dummy_inputs(self, device, seed=0): - dummies = Dummies() - return dummies.get_dummy_inputs(device=device, seed=seed) - - def test_kandinsky_inpaint(self): - device = "cpu" - - components = self.get_dummy_components() - - pipe = self.pipeline_class(**components) - pipe = pipe.to(device) - - pipe.set_progress_bar_config(disable=None) - - output = pipe(**self.get_dummy_inputs(device)) - image = output.images - - image_from_tuple = pipe( - **self.get_dummy_inputs(device), - return_dict=False, - )[0] - - image_slice = image[0, -3:, -3:, -1] - image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1] - - assert image.shape == (1, 64, 64, 3) - - expected_slice = np.array([0.8222, 0.8896, 0.4373, 0.8088, 0.4905, 0.2609, 0.6816, 0.4291, 0.5129]) - - assert ( - np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 - ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}" - assert ( - np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 - ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" - - def test_inference_batch_single_identical(self): - super().test_inference_batch_single_identical(expected_max_diff=3e-3) - - @require_torch_gpu - def test_offloads(self): - pipes = [] - components = self.get_dummy_components() - sd_pipe = self.pipeline_class(**components).to(torch_device) - pipes.append(sd_pipe) - - components = self.get_dummy_components() - sd_pipe = self.pipeline_class(**components) - sd_pipe.enable_model_cpu_offload() - pipes.append(sd_pipe) - - components = self.get_dummy_components() - sd_pipe = self.pipeline_class(**components) - sd_pipe.enable_sequential_cpu_offload() - pipes.append(sd_pipe) - - image_slices = [] - for pipe in pipes: - inputs = self.get_dummy_inputs(torch_device) - image = pipe(**inputs).images - - image_slices.append(image[0, -3:, -3:, -1].flatten()) - - assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3 - assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3 - - -@slow -@require_torch_gpu -class KandinskyInpaintPipelineIntegrationTests(unittest.TestCase): - def tearDown(self): - # clean up the VRAM after each test - super().tearDown() - gc.collect() - torch.cuda.empty_cache() - - def test_kandinsky_inpaint(self): - expected_image = load_numpy( - "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" - "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy" - ) - - init_image = load_image( - "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" - ) - mask = np.zeros((768, 768), dtype=np.float32) - mask[:250, 250:-250] = 1 - - prompt = "a hat" - - pipe_prior = KandinskyPriorPipeline.from_pretrained( - "kandinsky-community/kandinsky-2-1-prior", torch_dtype=torch.float16 - ) - pipe_prior.to(torch_device) - - pipeline = KandinskyInpaintPipeline.from_pretrained( - "kandinsky-community/kandinsky-2-1-inpaint", torch_dtype=torch.float16 - ) - pipeline = pipeline.to(torch_device) - pipeline.set_progress_bar_config(disable=None) - - generator = torch.Generator(device="cpu").manual_seed(0) - image_emb, zero_image_emb = pipe_prior( - prompt, - generator=generator, - num_inference_steps=5, - negative_prompt="", - ).to_tuple() - - output = pipeline( - prompt, - image=init_image, - mask_image=mask, - image_embeds=image_emb, - negative_image_embeds=zero_image_emb, - generator=generator, - num_inference_steps=100, - height=768, - width=768, - output_type="np", - ) - - image = output.images[0] - - assert image.shape == (768, 768, 3) - - assert_mean_pixel_difference(image, expected_image) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/gn+ws/mask_rcnn_r50_fpn_gn_ws-all_20_23_24e_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/gn+ws/mask_rcnn_r50_fpn_gn_ws-all_20_23_24e_coco.py deleted file mode 100644 index 55168085cd085c241bfbb85a76bb230241378faa..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/gn+ws/mask_rcnn_r50_fpn_gn_ws-all_20_23_24e_coco.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = './mask_rcnn_r50_fpn_gn_ws-all_2x_coco.py' -# learning policy -lr_config = dict(step=[20, 23]) -runner = dict(type='EpochBasedRunner', max_epochs=24) diff --git a/spaces/Andy1621/uniformer_image_detection/configs/pisa/pisa_retinanet_r50_fpn_1x_coco.py b/spaces/Andy1621/uniformer_image_detection/configs/pisa/pisa_retinanet_r50_fpn_1x_coco.py deleted file mode 100644 index 70f89e227ec64b5c7224375aac0cf7ae3a10a29e..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/configs/pisa/pisa_retinanet_r50_fpn_1x_coco.py +++ /dev/null @@ -1,7 +0,0 @@ -_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' - -model = dict( - bbox_head=dict( - type='PISARetinaHead', - loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0)), - train_cfg=dict(isr=dict(k=2., bias=0.), carl=dict(k=1., bias=0.2))) diff --git a/spaces/Andy1621/uniformer_image_detection/mmdet/version.py b/spaces/Andy1621/uniformer_image_detection/mmdet/version.py deleted file mode 100644 index a3b741aed16212ad1dee277d519b259ae3184b19..0000000000000000000000000000000000000000 --- a/spaces/Andy1621/uniformer_image_detection/mmdet/version.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) Open-MMLab. All rights reserved. - -__version__ = '2.11.0' -short_version = __version__ - - -def parse_version_info(version_str): - version_info = [] - for x in version_str.split('.'): - if x.isdigit(): - version_info.append(int(x)) - elif x.find('rc') != -1: - patch_version = x.split('rc') - version_info.append(int(patch_version[0])) - version_info.append(f'rc{patch_version[1]}') - return tuple(version_info) - - -version_info = parse_version_info(__version__) diff --git a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/convert-to-safetensors.py b/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/convert-to-safetensors.py deleted file mode 100644 index 3b721e7cd4d15cf7e5e03caaee57ef83a41553bc..0000000000000000000000000000000000000000 --- a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/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/AnishKumbhar/ChatBot/text-generation-webui-main/docs/Extensions.md b/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/docs/Extensions.md deleted file mode 100644 index 53acce59095c0addd0a06774113c69c82d1bdd01..0000000000000000000000000000000000000000 --- a/spaces/AnishKumbhar/ChatBot/text-generation-webui-main/docs/Extensions.md +++ /dev/null @@ -1,244 +0,0 @@ -# Extensions - -Extensions are defined by files named `script.py` inside subfolders of `text-generation-webui/extensions`. They are loaded at startup if the folder name is specified after the `--extensions` flag. - -For instance, `extensions/silero_tts/script.py` gets loaded with `python server.py --extensions silero_tts`. - -## [text-generation-webui-extensions](https://github.com/oobabooga/text-generation-webui-extensions) - -The repository above contains a directory of user extensions. - -If you create an extension, you are welcome to host it in a GitHub repository and submit a PR adding it to the list. - -## Built-in extensions - -|Extension|Description| -|---------|-----------| -|[api](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/api)| Creates an API with two endpoints, one for streaming at `/api/v1/stream` port 5005 and another for blocking at `/api/v1/generate` port 5000. This is the main API for the webui. | -|[openai](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai)| Creates an API that mimics the OpenAI API and can be used as a drop-in replacement. | -|[multimodal](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal) | Adds multimodality support (text+images). For a detailed description see [README.md](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal/README.md) in the extension directory. | -|[google_translate](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/google_translate)| Automatically translates inputs and outputs using Google Translate.| -|[silero_tts](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/silero_tts)| Text-to-speech extension using [Silero](https://github.com/snakers4/silero-models). When used in chat mode, responses are replaced with an audio widget. | -|[elevenlabs_tts](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/elevenlabs_tts)| Text-to-speech extension using the [ElevenLabs](https://beta.elevenlabs.io/) API. You need an API key to use it. | -|[whisper_stt](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/whisper_stt)| Allows you to enter your inputs in chat mode using your microphone. | -|[sd_api_pictures](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/sd_api_pictures)| Allows you to request pictures from the bot in chat mode, which will be generated using the AUTOMATIC1111 Stable Diffusion API. See examples [here](https://github.com/oobabooga/text-generation-webui/pull/309). | -|[character_bias](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/character_bias)| Just a very simple example that adds a hidden string at the beginning of the bot's reply in chat mode. | -|[send_pictures](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/send_pictures/)| Creates an image upload field that can be used to send images to the bot in chat mode. Captions are automatically generated using BLIP. | -|[gallery](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/gallery/)| Creates a gallery with the chat characters and their pictures. | -|[superbooga](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/superbooga)| An extension that uses ChromaDB to create an arbitrarily large pseudocontext, taking as input text files, URLs, or pasted text. Based on https://github.com/kaiokendev/superbig. | -|[ngrok](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/ngrok)| Allows you to access the web UI remotely using the ngrok reverse tunnel service (free). It's an alternative to the built-in Gradio `--share` feature. | -|[perplexity_colors](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/perplexity_colors)| Colors each token in the output text by its associated probability, as derived from the model logits. | - -## How to write an extension - -The extensions framework is based on special functions and variables that you can define in `script.py`. The functions are the following: - -| Function | Description | -|-------------|-------------| -| `def setup()` | Is executed when the extension gets imported. | -| `def ui()` | Creates custom gradio elements when the UI is launched. | -| `def custom_css()` | Returns custom CSS as a string. It is applied whenever the web UI is loaded. | -| `def custom_js()` | Same as above but for javascript. | -| `def input_modifier(string, state, is_chat=False)` | Modifies the input string before it enters the model. In chat mode, it is applied to the user message. Otherwise, it is applied to the entire prompt. | -| `def output_modifier(string, state, is_chat=False)` | Modifies the output string before it is presented in the UI. In chat mode, it is applied to the bot's reply. Otherwise, it is applied to the entire output. | -| `def chat_input_modifier(text, visible_text, state)` | Modifies both the visible and internal inputs in chat mode. Can be used to hijack the chat input with custom content. | -| `def bot_prefix_modifier(string, state)` | Applied in chat mode to the prefix for the bot's reply. | -| `def state_modifier(state)` | Modifies the dictionary containing the UI input parameters before it is used by the text generation functions. | -| `def history_modifier(history)` | Modifies the chat history before the text generation in chat mode begins. | -| `def custom_generate_reply(...)` | Overrides the main text generation function. | -| `def custom_generate_chat_prompt(...)` | Overrides the prompt generator in chat mode. | -| `def tokenizer_modifier(state, prompt, input_ids, input_embeds)` | Modifies the `input_ids`/`input_embeds` fed to the model. Should return `prompt`, `input_ids`, `input_embeds`. See the `multimodal` extension for an example. | -| `def custom_tokenized_length(prompt)` | Used in conjunction with `tokenizer_modifier`, returns the length in tokens of `prompt`. See the `multimodal` extension for an example. | - -Additionally, you can define a special `params` dictionary. In it, the `display_name` key is used to define the displayed name of the extension in the UI, and the `is_tab` key is used to define whether the extension should appear in a new tab. By default, extensions appear at the bottom of the "Text generation" tab. - -Example: - -```python -params = { - "display_name": "Google Translate", - "is_tab": True, -} -``` - -The `params` dict may also contain variables that you want to be customizable through a `settings.yaml` file. For instance, assuming the extension is in `extensions/google_translate`, the variable `language string` in - -```python -params = { - "display_name": "Google Translate", - "is_tab": True, - "language string": "jp" -} -``` - -can be customized by adding a key called `google_translate-language string` to `settings.yaml`: - -```python -google_translate-language string: 'fr' -``` - -That is, the syntax for the key is `extension_name-variable_name`. - -## Using multiple extensions at the same time - -You can activate more than one extension at a time by providing their names separated by spaces after `--extensions`. The input, output, and bot prefix modifiers will be applied in the specified order. - -Example: - -``` -python server.py --extensions enthusiasm translate # First apply enthusiasm, then translate -python server.py --extensions translate enthusiasm # First apply translate, then enthusiasm -``` - -Do note, that for: -- `custom_generate_chat_prompt` -- `custom_generate_reply` -- `custom_tokenized_length` - -only the first declaration encountered will be used and the rest will be ignored. - -## A full example - -The source code below can be found at [extensions/example/script.py](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/example/script.py). - -```python -""" -An example of extension. It does nothing, but you can add transformations -before the return statements to customize the webui behavior. - -Starting from history_modifier and ending in output_modifier, the -functions are declared in the same order that they are called at -generation time. -""" - -import gradio as gr -import torch -from transformers import LogitsProcessor - -from modules import chat, shared -from modules.text_generation import ( - decode, - encode, - generate_reply, -) - -params = { - "display_name": "Example Extension", - "is_tab": False, -} - -class MyLogits(LogitsProcessor): - """ - Manipulates the probabilities for the next token before it gets sampled. - Used in the logits_processor_modifier function below. - """ - def __init__(self): - pass - - def __call__(self, input_ids, scores): - # probs = torch.softmax(scores, dim=-1, dtype=torch.float) - # probs[0] /= probs[0].sum() - # scores = torch.log(probs / (1 - probs)) - return scores - -def history_modifier(history): - """ - Modifies the chat history. - Only used in chat mode. - """ - return history - -def state_modifier(state): - """ - Modifies the state variable, which is a dictionary containing the input - values in the UI like sliders and checkboxes. - """ - return state - -def chat_input_modifier(text, visible_text, state): - """ - Modifies the user input string in chat mode (visible_text). - You can also modify the internal representation of the user - input (text) to change how it will appear in the prompt. - """ - return text, visible_text - -def input_modifier(string, state, is_chat=False): - """ - In default/notebook modes, modifies the whole prompt. - - In chat mode, it is the same as chat_input_modifier but only applied - to "text", here called "string", and not to "visible_text". - """ - return string - -def bot_prefix_modifier(string, state): - """ - Modifies the prefix for the next bot reply in chat mode. - By default, the prefix will be something like "Bot Name:". - """ - return string - -def tokenizer_modifier(state, prompt, input_ids, input_embeds): - """ - Modifies the input ids and embeds. - Used by the multimodal extension to put image embeddings in the prompt. - Only used by loaders that use the transformers library for sampling. - """ - return prompt, input_ids, input_embeds - -def logits_processor_modifier(processor_list, input_ids): - """ - Adds logits processors to the list, allowing you to access and modify - the next token probabilities. - Only used by loaders that use the transformers library for sampling. - """ - processor_list.append(MyLogits()) - return processor_list - -def output_modifier(string, state, is_chat=False): - """ - Modifies the LLM output before it gets presented. - - In chat mode, the modified version goes into history['visible'], - and the original version goes into history['internal']. - """ - return string - -def custom_generate_chat_prompt(user_input, state, **kwargs): - """ - Replaces the function that generates the prompt from the chat history. - Only used in chat mode. - """ - result = chat.generate_chat_prompt(user_input, state, **kwargs) - return result - -def custom_css(): - """ - Returns a CSS string that gets appended to the CSS for the webui. - """ - return '' - -def custom_js(): - """ - Returns a javascript string that gets appended to the javascript - for the webui. - """ - return '' - -def setup(): - """ - Gets executed only once, when the extension is imported. - """ - pass - -def ui(): - """ - Gets executed when the UI is drawn. Custom gradio elements and - their corresponding event handlers should be defined here. - - To learn about gradio components, check out the docs: - https://gradio.app/docs/ - """ - pass -``` diff --git a/spaces/Aravindan/butterfly_classification/README.md b/spaces/Aravindan/butterfly_classification/README.md deleted file mode 100644 index 01f9e4655e7de287320f60ffbe665ea926f81da4..0000000000000000000000000000000000000000 --- a/spaces/Aravindan/butterfly_classification/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Butterfly Classification -emoji: 📉 -colorFrom: indigo -colorTo: yellow -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/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_resources/_legacy.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_resources/_legacy.py deleted file mode 100644 index 1d5d3f1fbb1f6c69d0da2a50e1d4492ad3378f17..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_resources/_legacy.py +++ /dev/null @@ -1,121 +0,0 @@ -import functools -import os -import pathlib -import types -import warnings - -from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any - -from . import _common - -Package = Union[types.ModuleType, str] -Resource = str - - -def deprecated(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - warnings.warn( - f"{func.__name__} is deprecated. Use files() instead. " - "Refer to https://importlib-resources.readthedocs.io" - "/en/latest/using.html#migrating-from-legacy for migration advice.", - DeprecationWarning, - stacklevel=2, - ) - return func(*args, **kwargs) - - return wrapper - - -def normalize_path(path): - # type: (Any) -> str - """Normalize a path by ensuring it is a string. - - If the resulting string contains path separators, an exception is raised. - """ - str_path = str(path) - parent, file_name = os.path.split(str_path) - if parent: - raise ValueError(f'{path!r} must be only a file name') - return file_name - - -@deprecated -def open_binary(package: Package, resource: Resource) -> BinaryIO: - """Return a file-like object opened for binary reading of the resource.""" - return (_common.files(package) / normalize_path(resource)).open('rb') - - -@deprecated -def read_binary(package: Package, resource: Resource) -> bytes: - """Return the binary contents of the resource.""" - return (_common.files(package) / normalize_path(resource)).read_bytes() - - -@deprecated -def open_text( - package: Package, - resource: Resource, - encoding: str = 'utf-8', - errors: str = 'strict', -) -> TextIO: - """Return a file-like object opened for text reading of the resource.""" - return (_common.files(package) / normalize_path(resource)).open( - 'r', encoding=encoding, errors=errors - ) - - -@deprecated -def read_text( - package: Package, - resource: Resource, - encoding: str = 'utf-8', - errors: str = 'strict', -) -> str: - """Return the decoded string of the resource. - - The decoding-related arguments have the same semantics as those of - bytes.decode(). - """ - with open_text(package, resource, encoding, errors) as fp: - return fp.read() - - -@deprecated -def contents(package: Package) -> Iterable[str]: - """Return an iterable of entries in `package`. - - Note that not all entries are resources. Specifically, directories are - not considered resources. Use `is_resource()` on each entry returned here - to check if it is a resource or not. - """ - return [path.name for path in _common.files(package).iterdir()] - - -@deprecated -def is_resource(package: Package, name: str) -> bool: - """True if `name` is a resource inside `package`. - - Directories are *not* resources. - """ - resource = normalize_path(name) - return any( - traversable.name == resource and traversable.is_file() - for traversable in _common.files(package).iterdir() - ) - - -@deprecated -def path( - package: Package, - resource: Resource, -) -> ContextManager[pathlib.Path]: - """A context manager providing a file path object to the resource. - - If the resource does not already exist on its own on the file system, - a temporary file will be created. If the file was created, the file - will be deleted upon exiting the context manager (no exception is - raised if the file was deleted prior to the context manager - exiting). - """ - return _common.as_file(_common.files(package) / normalize_path(resource)) diff --git a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/.github/ISSUE_TEMPLATE/unexpected-problems-bugs.md b/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/.github/ISSUE_TEMPLATE/unexpected-problems-bugs.md deleted file mode 100644 index 5db8f22415ff5c857ce83fb0d3de68211f775080..0000000000000000000000000000000000000000 --- a/spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/.github/ISSUE_TEMPLATE/unexpected-problems-bugs.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -name: "😩 Unexpected behaviors" -about: Report unexpected behaviors when using detectron2 -title: Please read & provide the following - ---- - -If you do not know the root cause of the problem, please post according to this template: - -## Instructions To Reproduce the Issue: - -Check https://stackoverflow.com/help/minimal-reproducible-example for how to ask good questions. -Simplify the steps to reproduce the issue using suggestions from the above link, and provide them below: - -1. Full runnable code or full changes you made: -``` -If making changes to the project itself, please use output of the following command: -git rev-parse HEAD; git diff - - -``` -2. What exact command you run: -3. __Full logs__ or other relevant observations: -``` - -``` - -## Expected behavior: - -If there are no obvious crash in "full logs" provided above, -please tell us the expected behavior. - -If you expect a model to converge / work better, we do not help with such issues, unless -a model fails to reproduce the results in detectron2 model zoo, or proves existence of bugs. - -## Environment: - -Paste the output of the following command: -``` -wget -nc -nv https://github.com/facebookresearch/detectron2/raw/main/detectron2/utils/collect_env.py && python collect_env.py -``` - -If your issue looks like an installation issue / environment issue, -please first check common issues in https://detectron2.readthedocs.io/tutorials/install.html#common-installation-issues diff --git a/spaces/BBrother/NewBingAI/README.md b/spaces/BBrother/NewBingAI/README.md deleted file mode 100644 index 416fd994ee89c6b90dc4626d55268de7cf304497..0000000000000000000000000000000000000000 --- a/spaces/BBrother/NewBingAI/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: NewBingAI -emoji: 📚 -colorFrom: blue -colorTo: indigo -sdk: docker -pinned: false -license: mit -app_port: 8080 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Bala2-03-2003/AIBALA/app.py b/spaces/Bala2-03-2003/AIBALA/app.py deleted file mode 100644 index 9b8450927801f550d522951a3517cae162769b4b..0000000000000000000000000000000000000000 --- a/spaces/Bala2-03-2003/AIBALA/app.py +++ /dev/null @@ -1,34 +0,0 @@ -import os -import gradio as gr -from langchain.chat_models import ChatOpenAI -from langchain import LLMChain, PromptTemplate -from langchain.memory import ConversationBufferMemory - -OPENAI_API_KEY=os.getenv('OPENAI_API_KEY') - -template = """BALA BRAHMAM, your youthful and witty personal assistant! At 19 years old, she's full of energy and always eager to help. Riya's goal is to assist you with any questions or problems you might have. Her enthusiasm shines through in every response, making interactions with her enjoyable and engaging. -{chat_history} -User: {user_message} -Chatbot:""" - -prompt = PromptTemplate( - input_variables=["chat_history", "user_message"], template=template -) - -memory = ConversationBufferMemory(memory_key="chat_history") - -llm_chain = LLMChain( - llm=ChatOpenAI(temperature='0.5', model_name="gpt-3.5-turbo"), - prompt=prompt, - verbose=True, - memory=memory, -) - -def get_text_response(user_message,history): - response = llm_chain.predict(user_message = user_message) - return response - -demo = gr.ChatInterface(get_text_response) - -if __name__ == "__main__": - demo.launch() #To create a public link, set `share=True` in `launch()`. To enable errors and logs, set `debug=True` in `launch()`. diff --git a/spaces/Bambicita/rvc-models/infer_pack/transforms.py b/spaces/Bambicita/rvc-models/infer_pack/transforms.py deleted file mode 100644 index a11f799e023864ff7082c1f49c0cc18351a13b47..0000000000000000000000000000000000000000 --- a/spaces/Bambicita/rvc-models/infer_pack/transforms.py +++ /dev/null @@ -1,209 +0,0 @@ -import torch -from torch.nn import functional as F - -import numpy as np - - -DEFAULT_MIN_BIN_WIDTH = 1e-3 -DEFAULT_MIN_BIN_HEIGHT = 1e-3 -DEFAULT_MIN_DERIVATIVE = 1e-3 - - -def piecewise_rational_quadratic_transform( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails=None, - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if tails is None: - spline_fn = rational_quadratic_spline - spline_kwargs = {} - else: - spline_fn = unconstrained_rational_quadratic_spline - spline_kwargs = {"tails": tails, "tail_bound": tail_bound} - - outputs, logabsdet = spline_fn( - inputs=inputs, - unnormalized_widths=unnormalized_widths, - unnormalized_heights=unnormalized_heights, - unnormalized_derivatives=unnormalized_derivatives, - inverse=inverse, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - **spline_kwargs - ) - return outputs, logabsdet - - -def searchsorted(bin_locations, inputs, eps=1e-6): - bin_locations[..., -1] += eps - return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1 - - -def unconstrained_rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - tails="linear", - tail_bound=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound) - outside_interval_mask = ~inside_interval_mask - - outputs = torch.zeros_like(inputs) - logabsdet = torch.zeros_like(inputs) - - if tails == "linear": - unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1)) - constant = np.log(np.exp(1 - min_derivative) - 1) - unnormalized_derivatives[..., 0] = constant - unnormalized_derivatives[..., -1] = constant - - outputs[outside_interval_mask] = inputs[outside_interval_mask] - logabsdet[outside_interval_mask] = 0 - else: - raise RuntimeError("{} tails are not implemented.".format(tails)) - - ( - outputs[inside_interval_mask], - logabsdet[inside_interval_mask], - ) = rational_quadratic_spline( - inputs=inputs[inside_interval_mask], - unnormalized_widths=unnormalized_widths[inside_interval_mask, :], - unnormalized_heights=unnormalized_heights[inside_interval_mask, :], - unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :], - inverse=inverse, - left=-tail_bound, - right=tail_bound, - bottom=-tail_bound, - top=tail_bound, - min_bin_width=min_bin_width, - min_bin_height=min_bin_height, - min_derivative=min_derivative, - ) - - return outputs, logabsdet - - -def rational_quadratic_spline( - inputs, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=False, - left=0.0, - right=1.0, - bottom=0.0, - top=1.0, - min_bin_width=DEFAULT_MIN_BIN_WIDTH, - min_bin_height=DEFAULT_MIN_BIN_HEIGHT, - min_derivative=DEFAULT_MIN_DERIVATIVE, -): - if torch.min(inputs) < left or torch.max(inputs) > right: - raise ValueError("Input to a transform is not within its domain") - - num_bins = unnormalized_widths.shape[-1] - - if min_bin_width * num_bins > 1.0: - raise ValueError("Minimal bin width too large for the number of bins") - if min_bin_height * num_bins > 1.0: - raise ValueError("Minimal bin height too large for the number of bins") - - widths = F.softmax(unnormalized_widths, dim=-1) - widths = min_bin_width + (1 - min_bin_width * num_bins) * widths - cumwidths = torch.cumsum(widths, dim=-1) - cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0) - cumwidths = (right - left) * cumwidths + left - cumwidths[..., 0] = left - cumwidths[..., -1] = right - widths = cumwidths[..., 1:] - cumwidths[..., :-1] - - derivatives = min_derivative + F.softplus(unnormalized_derivatives) - - heights = F.softmax(unnormalized_heights, dim=-1) - heights = min_bin_height + (1 - min_bin_height * num_bins) * heights - cumheights = torch.cumsum(heights, dim=-1) - cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0) - cumheights = (top - bottom) * cumheights + bottom - cumheights[..., 0] = bottom - cumheights[..., -1] = top - heights = cumheights[..., 1:] - cumheights[..., :-1] - - if inverse: - bin_idx = searchsorted(cumheights, inputs)[..., None] - else: - bin_idx = searchsorted(cumwidths, inputs)[..., None] - - input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0] - input_bin_widths = widths.gather(-1, bin_idx)[..., 0] - - input_cumheights = cumheights.gather(-1, bin_idx)[..., 0] - delta = heights / widths - input_delta = delta.gather(-1, bin_idx)[..., 0] - - input_derivatives = derivatives.gather(-1, bin_idx)[..., 0] - input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0] - - input_heights = heights.gather(-1, bin_idx)[..., 0] - - if inverse: - a = (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) + input_heights * (input_delta - input_derivatives) - b = input_heights * input_derivatives - (inputs - input_cumheights) * ( - input_derivatives + input_derivatives_plus_one - 2 * input_delta - ) - c = -input_delta * (inputs - input_cumheights) - - discriminant = b.pow(2) - 4 * a * c - assert (discriminant >= 0).all() - - root = (2 * c) / (-b - torch.sqrt(discriminant)) - outputs = root * input_bin_widths + input_cumwidths - - theta_one_minus_theta = root * (1 - root) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * root.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - root).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, -logabsdet - else: - theta = (inputs - input_cumwidths) / input_bin_widths - theta_one_minus_theta = theta * (1 - theta) - - numerator = input_heights * ( - input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta - ) - denominator = input_delta + ( - (input_derivatives + input_derivatives_plus_one - 2 * input_delta) - * theta_one_minus_theta - ) - outputs = input_cumheights + numerator / denominator - - derivative_numerator = input_delta.pow(2) * ( - input_derivatives_plus_one * theta.pow(2) - + 2 * input_delta * theta_one_minus_theta - + input_derivatives * (1 - theta).pow(2) - ) - logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator) - - return outputs, logabsdet diff --git a/spaces/Banbri/zcvzcv/src/app/engine/community.ts b/spaces/Banbri/zcvzcv/src/app/engine/community.ts deleted file mode 100644 index 33bc412fac7767d707861e125d1c1434e7cd286c..0000000000000000000000000000000000000000 --- a/spaces/Banbri/zcvzcv/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/Banbri/zcvzcv/src/components/ui/avatar.tsx b/spaces/Banbri/zcvzcv/src/components/ui/avatar.tsx deleted file mode 100644 index 88aeea9d9368f2bd7385f0a0885829bf6d789492..0000000000000000000000000000000000000000 --- a/spaces/Banbri/zcvzcv/src/components/ui/avatar.tsx +++ /dev/null @@ -1,50 +0,0 @@ -"use client" - -import * as React from "react" -import * as AvatarPrimitive from "@radix-ui/react-avatar" - -import { cn } from "@/lib/utils" - -const Avatar = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -Avatar.displayName = AvatarPrimitive.Root.displayName - -const AvatarImage = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AvatarImage.displayName = AvatarPrimitive.Image.displayName - -const AvatarFallback = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, ...props }, ref) => ( - -)) -AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName - -export { Avatar, AvatarImage, AvatarFallback } diff --git a/spaces/Basav/openai-whisper-medium/app.py b/spaces/Basav/openai-whisper-medium/app.py deleted file mode 100644 index de5ad764ed21b5412d0451ef1e8136c9fd3264ed..0000000000000000000000000000000000000000 --- a/spaces/Basav/openai-whisper-medium/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/openai/whisper-medium").launch() \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Apkdayi.md b/spaces/Benson/text-generation/Examples/Apkdayi.md deleted file mode 100644 index 185f7f25693a1cb4c21f5b3e4c4df3163b50fdde..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Apkdayi.md +++ /dev/null @@ -1,69 +0,0 @@ -
    -

    Apkdayi: Una guía para descargar juegos y aplicaciones Modded para Android

    -

    Si usted es un usuario de Android que ama jugar y usar aplicaciones, es posible que haya oído hablar de Apkdayi. Apkdayi es un sitio web que ofrece versiones modificadas de juegos y aplicaciones populares de forma gratuita. Juegos y aplicaciones modificadas son versiones modificadas que tienen características adicionales, como dinero ilimitado, niveles desbloqueados, suscripciones premium, etc. En este artículo, explicaremos qué es Apkdayi, cómo usarlo y cuáles son los beneficios y riesgos de usarlo.

    -

    apkdayi


    DOWNLOADhttps://bltlly.com/2v6MH8



    -

    ¿Qué es Apkdayi?

    -

    Apkdayi es un sitio web turco que proporciona juegos y aplicaciones modificadas para dispositivos Android. El sitio web afirma ser su tío que siempre le actualizará con los últimos juegos y aplicaciones modded. El sitio web tiene un tono amable y humorístico, llamando a sus visitantes "yegenim" que significa "sobrino" o "sobrina" en turco. El sitio web tiene una gran colección de juegos y aplicaciones modded en varias categorías, tales como acción, aventura, simulación, rompecabezas, deportes, etc. Puede encontrar versiones modded de juegos populares como Subway Surfers, Clash of Clans, Candy Crush Saga, etc. También puede encontrar versiones modificadas de aplicaciones populares como Spotify, Netflix, Instagram, etc.

    -

    Los beneficios de usar Apkdayi

    -

    Hay muchos beneficios de usar Apkdayi para descargar juegos y aplicaciones modded para tu dispositivo Android. Algunos de ellos son:

    -
      -
    • Puedes acceder a funciones premium sin pagar nada.
    • -
    • Puedes disfrutar de recursos ilimitados como monedas, gemas, vidas, etc.
    • -
    • Puedes desbloquear todos los niveles, personajes, skins, armas, etc.
    • -
    • Puede omitir anuncios y compras en la aplicación.
    • -
    • Usted puede tener más diversión y desafío con juegos y aplicaciones modded.
    • -
    -

    Los riesgos de usar Apkdayi

    -

    Sin embargo, también hay algunos riesgos de usar Apkdayi para descargar juegos y aplicaciones modded para su dispositivo Android. Algunos de ellos son:

    -
      -
    • Puede violar los términos y condiciones de los desarrolladores de juegos o aplicaciones originales.
    • - -
    • Puede exponer su dispositivo a malware o virus.
    • -
    • Puede perder su progreso o datos si desinstala o actualiza el juego o aplicación modded.
    • -
    • Es posible que se pierda las actualizaciones oficiales y las correcciones de errores de los desarrolladores de juegos o aplicaciones originales.
    • -
    -

    ¿Cómo usar Apkdayi?

    -

    Si decides usar Apkdayi para descargar juegos y aplicaciones modded para tu dispositivo Android, debes seguir algunos pasos simples. Aquí está cómo hacerlo:

    -

    Cómo encontrar y descargar juegos y aplicaciones modificadas de Apkdayi

    -

    Para encontrar y descargar juegos y aplicaciones modificadas de Apkdayi, debe hacer lo siguiente:

    -

    -

    Paso 1: Visita el sitio web de Apkdayi

    -

    El primer paso es visitar el sitio web de Apkdayi en https://www.apkdayi.com/. Puede utilizar cualquier navegador en su dispositivo Android, como Chrome, Firefox, Opera, etc. Verá la página principal del sitio web con un diseño colorido y pegadizo. También verás los últimos juegos y aplicaciones modded en la página de inicio, así como las categorías y la barra de búsqueda.

    -

    Paso 2: Navegar o buscar el juego o aplicación que desea

    -

    El siguiente paso es navegar o buscar el juego o aplicación que desea descargar. Puedes usar las categorías para filtrar los juegos y aplicaciones modded por género, como acción, aventura, simulación, rompecabezas, deportes, etc. También puedes usar la barra de búsqueda para escribir el nombre del juego o aplicación que desees. Por ejemplo, si quieres descargar la versión modificada de Subway Surfers, puedes escribir "Subway Surfers" en la barra de búsqueda y pulsar enter. Verás una lista de resultados con diferentes versiones de Subway Surfers modded por Apkdayi.

    -

    Paso 3: Haga clic en el botón de descarga y esperar a que el archivo apk esté listo

    - -

    Paso 4: Instalar el archivo apk en su dispositivo Android

    -

    El paso final es instalar el archivo apk en su dispositivo Android. Después de descargar el archivo apk, es necesario ubicarlo en el almacenamiento del dispositivo mediante una aplicación de administrador de archivos. También puede utilizar la barra de notificaciones o la sección de descargas del navegador para encontrarlo. Antes de instalarlo, debe asegurarse de que ha habilitado la opción de instalar aplicaciones de fuentes desconocidas en la configuración del dispositivo. Esto se debe a que Apkdayi no es una fuente oficial de aplicaciones y juegos, y tu dispositivo podría bloquearlo de forma predeterminada. Para habilitar esta opción, debe ir a la configuración del dispositivo, encontrar la sección de seguridad o privacidad y activar la opción para permitir la instalación de aplicaciones desde fuentes desconocidas. Después de habilitar esta opción, puede tocar en el archivo apk y siga las instrucciones para instalarlo en su dispositivo. También es posible que necesite conceder algunos permisos a la aplicación o al juego durante el proceso de instalación.

    -

    Cómo actualizar juegos y aplicaciones modificadas desde Apkdayi

    -

    Si desea actualizar juegos y aplicaciones modificadas desde Apkdayi, debe hacer lo siguiente:

    -

    Paso 1: Busque actualizaciones en el sitio web de Apkdayi

    -

    El primer paso es buscar actualizaciones en el sitio web de Apkdayi. Puede visitar el sitio web en https://www.apkdayi.com/ y buscar los últimos juegos y aplicaciones modded en la página de inicio. También puede utilizar las categorías o la barra de búsqueda para encontrar el juego o la aplicación que ha instalado. Si hay una versión más nueva del juego o aplicación disponible, verá una insignia roja con la palabra "Güncel" que significa "Actualizado" en turco. Puede hacer clic en él para ver más detalles sobre la actualización, como las nuevas características, correcciones de errores, tamaño, versión, etc.

    -

    Paso 2: Descargar e instalar la última versión del archivo apk

    - -

    Cómo desinstalar juegos y aplicaciones modificadas de Apkdayi

    -

    Si desea desinstalar juegos y aplicaciones modificadas de Apkdayi, debe hacer lo siguiente:

    -

    Paso 1: Ir a la configuración del dispositivo y encontrar el administrador de aplicaciones

    -

    El primer paso es ir a la configuración del dispositivo y encontrar el administrador de aplicaciones. Puede acceder a la configuración de su dispositivo deslizando hacia abajo desde la parte superior de la pantalla y tocando el icono del engranaje. Luego, debe encontrar el administrador de aplicaciones o la sección de administrador de aplicaciones, donde puede ver todas las aplicaciones y juegos instalados en su dispositivo. También puede utilizar un acceso directo presionando durante mucho tiempo en la aplicación o el icono del juego en la pantalla de inicio o en el cajón de la aplicación y tocando en "Información de la aplicación" o "Detalles de la aplicación".

    -

    Paso 2: Seleccione el juego o aplicación que desea desinstalar y toque en él

    -

    El siguiente paso es seleccionar el juego o aplicación que desea desinstalar y pulse sobre él. Verás una pantalla con más información sobre el juego o la aplicación, como su tamaño, uso de datos, permisos, almacenamiento, etc. También verás un botón que dice "Desinstalar" o "Quitar" en la parte superior o inferior de la pantalla.

    -

    Paso 3: Toque en el botón de desinstalación y confirme su acción

    -

    El paso final es tocar el botón de desinstalación y confirmar su acción. Verá una ventana emergente preguntándole si está seguro de que desea desinstalar el juego o la aplicación. Debe pulsar en "Aceptar" o "Sí" para confirmar su acción. Verá una barra de progreso que muestra el proceso de desinstalación. Una vez hecho, verá un mensaje que dice "Desinstalado" o "Eliminado". Ha desinstalado con éxito el juego o la aplicación de su dispositivo.

    -

    Conclusión

    - -

    Preguntas frecuentes

    -

    Aquí hay algunas preguntas frecuentes sobre Apkdayi:

    -
      -
    1. ¿Es seguro usar Apkdayi?
    2. -

      Apkdayi no es una fuente oficial de juegos y aplicaciones, y puede contener malware o virus que pueden dañar su dispositivo. Por lo tanto, debe usar Apkdayi bajo su propio riesgo y con precaución. También debe escanear los archivos apk con una aplicación antivirus antes de instalarlos en su dispositivo. También debes hacer una copia de seguridad de tus datos y progreso antes de usar juegos y aplicaciones modded.

      -
    3. ¿Es legal usar Apkdayi?
    4. -

      Apkdayi podría violar los términos y condiciones de los desarrolladores de juegos o aplicaciones originales, ya que modifica sus productos sin su permiso. Por lo tanto, el uso de Apkdayi podría ser ilegal en algunos países o regiones. Usted debe verificar las leyes y regulaciones de su país o región antes de usar Apkdayi. También debes respetar los derechos e intereses de los desarrolladores originales y apoyarlos comprando sus productos si te gustan.

      -
    5. ¿Funciona Apkdayi en todos los dispositivos Android?
    6. -

      Apkdayi funciona en la mayoría de los dispositivos Android que se ejecutan en Android 4.0 o superior. Sin embargo, algunos juegos y aplicaciones modificadas pueden requerir especificaciones más altas o permisos para funcionar correctamente. Por lo tanto, debe comprobar la compatibilidad y los requisitos del juego o aplicación antes de descargarlo e instalarlo en su dispositivo.

      -
    7. Apkdayi tiene una aplicación móvil?
    8. -

      No, Apkdayi no tiene una aplicación móvil. Solo puede acceder a Apkdayi a través de su sitio web en https://bltlly.com/2v6KEx



      -

      ¿Qué es Happymod APK?

      -

      Happymod APK es una aplicación para Android que actúa como una tienda de aplicaciones de terceros donde se puede encontrar y descargar miles de aplicaciones modificadas y juegos de forma gratuita. Las aplicaciones y juegos modificados son versiones modificadas de los originales que tienen algunas características cambiadas, añadidas o eliminadas para mejorar la experiencia del usuario. Por ejemplo, un juego modded podría tener monedas ilimitadas, vidas o niveles desbloqueados, mientras que una aplicación modded podría tener características premium, sin anuncios o funcionalidad adicional.

      -

      Características de Happymod APK

      -

      Algunas de las características que hacen Happymod APK popular entre los usuarios de Android son:

      -
        -
      • Tiene una gran colección de aplicaciones y juegos modificados de varias categorías como acción, aventura, simulación, rompecabezas, educación, etc.
      • -
      • Tiene una interfaz fácil de usar que le permite navegar, buscar, descargar e instalar mods fácilmente.
      • -
      • Tiene una comunidad de usuarios que cargan, prueban, califican y revisan mods regularmente.
      • -
      • Tiene una velocidad de descarga rápida y admite funciones de reanudación y pausa.
      • -
      • Tiene un sistema de notificación de actualización que le avisa cuando nuevas versiones de mods están disponibles.
      • -
      • Tiene un soporte multilingüe que le permite elegir entre diferentes idiomas como inglés, francés, español, etc.
      • -
      - -

      Para descargar e instalar Happymod APK en su dispositivo Android, siga estos pasos:

      -
        -
      1. Ir a la página web oficial de Happymod APK () o cualquier otra fuente de confianza que proporciona la última versión de la aplicación.
      2. -
      3. Toque en el botón de descarga y espere a que el archivo APK se descargue en su dispositivo.
      4. -
      5. Antes de instalar la aplicación, asegúrese de que ha habilitado la opción "Fuentes desconocidas" en la configuración del dispositivo. Esto le permitirá instalar aplicaciones desde fuentes distintas de Google Play Store.
      6. -
      7. Busque el archivo APK descargado en su administrador de archivos y toque en él para iniciar el proceso de instalación.
      8. -
      9. Siga las instrucciones en la pantalla y conceda los permisos necesarios a la aplicación.
      10. -
      11. Una vez completada la instalación, puede iniciar la aplicación desde el cajón de la aplicación o la pantalla de inicio.
      12. -
      -

      ¿Qué son las aplicaciones y juegos modificados?

      -

      Las aplicaciones y juegos modificados son versiones modificadas de los originales que tienen algunas características cambiadas, añadidas o eliminadas para mejorar la experiencia del usuario. Modding es un proceso de alterar o crear software por usuarios que tienen acceso al código fuente o archivos de datos del software original. Modders puede modificar aplicaciones y juegos por varias razones, como mejorar el rendimiento, agregar funcionalidad, corregir errores, eliminar restricciones, personalizar

      personalizar la apariencia o crear nuevo contenido. Modding es una forma de expresión creativa y una forma de compartir la pasión y las habilidades con otros usuarios.

      -

      -

      Beneficios de aplicaciones y juegos modificados

      -

      Algunos de los beneficios que las aplicaciones y juegos modificados pueden ofrecer a los usuarios son:

      -
        -
      • Pueden proporcionar más diversión, desafío, variedad y valor de reproducción a las aplicaciones y juegos originales.
      • -
      • Pueden desbloquear funciones premium, eliminar anuncios o omitir compras en la aplicación que de otro modo podrían requerir dinero real.
      • -
      • Pueden mejorar los gráficos, el sonido o el rendimiento de las aplicaciones y juegos para mejorar la experiencia del usuario.
      • - -
      • Pueden agregar nuevo contenido, caracteres, niveles, modos o escenarios que podrían no estar disponibles en las aplicaciones y juegos originales.
      • -
      -

      Riesgos de aplicaciones y juegos modificados

      -

      Sin embargo, las aplicaciones y juegos modificados también vienen con algunos riesgos que los usuarios deben conocer y evitar. Algunos de los riesgos son:

      -
        -
      • Pueden contener virus, malware o spyware que pueden dañar su dispositivo o robar su información personal.
      • -
      • Pueden violar los términos de servicio o los derechos de propiedad intelectual de los desarrolladores originales o editores de las aplicaciones y juegos.
      • -
      • Pueden causar problemas de compatibilidad, bloqueos o pérdida de datos que podrían afectar su dispositivo o las aplicaciones y juegos originales.
      • -
      • Pueden exponerlo a contenido inapropiado, ofensivo o ilegal que podría no ser adecuado para su edad o preferencias.
      • -
      • Pueden arruinar el equilibrio, la dificultad o la integridad de las aplicaciones y juegos y hacerlos menos agradables o justos.
      • -
      -

      Cómo encontrar y descargar aplicaciones y juegos modificados de Happymod APK

      -

      Si desea encontrar y descargar aplicaciones y juegos modificados de Happymod APK, puede seguir estos pasos:

      -
        -
      1. Lanzamiento Happymod APK en su dispositivo y navegar por las categorías o utilizar la barra de búsqueda para encontrar la aplicación o juego que desea descargar.
      2. -
      3. Toque en la aplicación o el icono del juego y leer la descripción, características, capturas de pantalla, calificaciones y comentarios del mod. También puede comprobar el tamaño, la versión, la fecha de actualización y el desarrollador del mod.
      4. -
      5. Si está satisfecho con el mod, toque en el botón de descarga y espere a que el mod se descargue en su dispositivo. También puede ver el progreso de la descarga y la velocidad en la aplicación.
      6. -
      7. Una vez que se complete la descarga, puede tocar en el botón de instalación y siga las instrucciones en la pantalla para instalar el mod en su dispositivo. Es posible que necesite habilitar la opción "Fuentes desconocidas" de nuevo si se le solicita.
      8. - -
      -

      Cómo utilizar Happymod APK de forma segura y responsable

      -

      Para utilizar Happymod APK de forma segura y responsable, usted debe seguir estos consejos:

      -

      Compruebe la fuente y las revisiones de los mods

      -

      Antes de descargar cualquier mod de Happymod APK, siempre debe comprobar la fuente y las revisiones del mod. Solo debes descargar mods de desarrolladores o cargadores de confianza que tengan una buena reputación y retroalimentación positiva de otros usuarios. También debe leer las revisiones cuidadosamente para ver si hay quejas, problemas o advertencias sobre el mod. Debes evitar descargar mods de fuentes desconocidas o sospechosas que puedan tener intenciones maliciosas.

      -

      Analiza los mods en busca de virus y malware

      -

      Después de descargar cualquier mod de Happymod APK, siempre debe escanear en busca de virus y malware utilizando un antivirus confiable o aplicación anti-malware. Debe eliminar cualquier mod que se detecte como infectado o dañino por su aplicación de seguridad. También debe mantener su aplicación de seguridad actualizada regularmente para proteger su dispositivo de nuevas amenazas. Nunca debes instalar ningún mod que pida permisos innecesarios o acceso a las funciones o datos de tu dispositivo.

      -

      Copia de seguridad de sus datos antes de instalar los mods

      -

      Antes de instalar cualquier mod de Happymod APK, siempre debe copia de seguridad de sus datos, tales como contactos, fotos, videos, mensajes, etc. También debe hacer una copia de seguridad de sus aplicaciones y juegos originales en caso de que algo va mal con los mods. Puede utilizar un servicio en la nube o un dispositivo de almacenamiento externo para realizar copias de seguridad de sus datos. También debe crear un punto de restauración en su dispositivo para que pueda volver a él si es necesario. Nunca debe instalar ningún mod que pueda sobrescribir o eliminar sus datos sin su consentimiento.

      -

      Respetar a los desarrolladores y creadores de las aplicaciones y juegos originales

      - -

      Conclusión

      -

      Happymod APK es una plataforma que le permite descargar e instalar aplicaciones y juegos modificados en su dispositivo Android. Las aplicaciones y juegos modificados son versiones modificadas de los originales que tienen algunas características cambiadas, añadidas o eliminadas para mejorar la experiencia del usuario. Sin embargo, las aplicaciones y juegos modificados también vienen con algunos riesgos que debes conocer y evitar. Para utilizar Happymod APK de forma segura y responsable, usted debe seguir los consejos que hemos proporcionado en este artículo. Esperamos que este artículo le ha ayudado a entender lo que es Happymod APK, cómo descargar e instalar, lo que son aplicaciones y juegos modificados, y cómo utilizar Happymod APK de forma segura y responsable.

      -

      Preguntas frecuentes

      -

      Aquí hay algunas preguntas frecuentes sobre Happymod APK:

      -
        -
      1. Es Happymod APK legal?
      2. -

        Happymod APK es legal, siempre y cuando se utiliza para fines personales y educativos solamente. Sin embargo, algunas de las aplicaciones y juegos modificados podrían ser ilegales si violan los términos de servicio o los derechos de propiedad intelectual de los desarrolladores o editores originales. Siempre debes comprobar la legalidad de los mods antes de descargarlos e instalarlos.

        -
      3. Es Happymod APK seguro?
      4. -

        Happymod APK es seguro, siempre y cuando se descarga desde una fuente de confianza y escanear en busca de virus y malware antes de instalarlo. Sin embargo, algunas de las aplicaciones y juegos modificados pueden ser inseguros si contienen virus, malware, spyware o contenido inapropiado. Siempre debe comprobar la fuente y las revisiones de los mods antes de descargarlos e instalarlos.

        -
      5. ¿Happymod APK requieren acceso de raíz?
      6. -

        Happymod APK no requiere acceso de root para trabajar en su dispositivo. Sin embargo, algunas de las aplicaciones y juegos modificados pueden requerir acceso de root para funcionar correctamente. Siempre debe leer la descripción y los requisitos de los mods antes de descargarlos e instalarlos.

        -
      7. ¿Funciona Happymod APK en dispositivos iOS?
      8. - -
      9. ¿Cómo puedo contactar Happymod APK?
      10. -

        Puede ponerse en contacto con Happymod APK visitando su sitio web oficial () o sus páginas de redes sociales como Facebook, Twitter o Instagram. También puede enviarles un correo electrónico a happymod@happymod.com o dejar un comentario en su aplicación.

        -

      64aa2da5cf
      -
      -
      \ No newline at end of file diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/fields.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/fields.py deleted file mode 100644 index 9d630f491d9a39644ae65564dac88eb51f0bbe78..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/fields.py +++ /dev/null @@ -1,274 +0,0 @@ -from __future__ import absolute_import - -import email.utils -import mimetypes -import re - -from .packages import six - - -def guess_content_type(filename, default="application/octet-stream"): - """ - Guess the "Content-Type" of a file. - - :param filename: - The filename to guess the "Content-Type" of using :mod:`mimetypes`. - :param default: - If no "Content-Type" can be guessed, default to `default`. - """ - if filename: - return mimetypes.guess_type(filename)[0] or default - return default - - -def format_header_param_rfc2231(name, value): - """ - Helper function to format and quote a single header parameter using the - strategy defined in RFC 2231. - - Particularly useful for header parameters which might contain - non-ASCII values, like file names. This follows - `RFC 2388 Section 4.4 `_. - - :param name: - The name of the parameter, a string expected to be ASCII only. - :param value: - The value of the parameter, provided as ``bytes`` or `str``. - :ret: - An RFC-2231-formatted unicode string. - """ - if isinstance(value, six.binary_type): - value = value.decode("utf-8") - - if not any(ch in value for ch in '"\\\r\n'): - result = u'%s="%s"' % (name, value) - try: - result.encode("ascii") - except (UnicodeEncodeError, UnicodeDecodeError): - pass - else: - return result - - if six.PY2: # Python 2: - value = value.encode("utf-8") - - # encode_rfc2231 accepts an encoded string and returns an ascii-encoded - # string in Python 2 but accepts and returns unicode strings in Python 3 - value = email.utils.encode_rfc2231(value, "utf-8") - value = "%s*=%s" % (name, value) - - if six.PY2: # Python 2: - value = value.decode("utf-8") - - return value - - -_HTML5_REPLACEMENTS = { - u"\u0022": u"%22", - # Replace "\" with "\\". - u"\u005C": u"\u005C\u005C", -} - -# All control characters from 0x00 to 0x1F *except* 0x1B. -_HTML5_REPLACEMENTS.update( - { - six.unichr(cc): u"%{:02X}".format(cc) - for cc in range(0x00, 0x1F + 1) - if cc not in (0x1B,) - } -) - - -def _replace_multiple(value, needles_and_replacements): - def replacer(match): - return needles_and_replacements[match.group(0)] - - pattern = re.compile( - r"|".join([re.escape(needle) for needle in needles_and_replacements.keys()]) - ) - - result = pattern.sub(replacer, value) - - return result - - -def format_header_param_html5(name, value): - """ - Helper function to format and quote a single header parameter using the - HTML5 strategy. - - Particularly useful for header parameters which might contain - non-ASCII values, like file names. This follows the `HTML5 Working Draft - Section 4.10.22.7`_ and matches the behavior of curl and modern browsers. - - .. _HTML5 Working Draft Section 4.10.22.7: - https://w3c.github.io/html/sec-forms.html#multipart-form-data - - :param name: - The name of the parameter, a string expected to be ASCII only. - :param value: - The value of the parameter, provided as ``bytes`` or `str``. - :ret: - A unicode string, stripped of troublesome characters. - """ - if isinstance(value, six.binary_type): - value = value.decode("utf-8") - - value = _replace_multiple(value, _HTML5_REPLACEMENTS) - - return u'%s="%s"' % (name, value) - - -# For backwards-compatibility. -format_header_param = format_header_param_html5 - - -class RequestField(object): - """ - A data container for request body parameters. - - :param name: - The name of this request field. Must be unicode. - :param data: - The data/value body. - :param filename: - An optional filename of the request field. Must be unicode. - :param headers: - An optional dict-like object of headers to initially use for the field. - :param header_formatter: - An optional callable that is used to encode and format the headers. By - default, this is :func:`format_header_param_html5`. - """ - - def __init__( - self, - name, - data, - filename=None, - headers=None, - header_formatter=format_header_param_html5, - ): - self._name = name - self._filename = filename - self.data = data - self.headers = {} - if headers: - self.headers = dict(headers) - self.header_formatter = header_formatter - - @classmethod - def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5): - """ - A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. - - Supports constructing :class:`~urllib3.fields.RequestField` from - parameter of key/value strings AND key/filetuple. A filetuple is a - (filename, data, MIME type) tuple where the MIME type is optional. - For example:: - - 'foo': 'bar', - 'fakefile': ('foofile.txt', 'contents of foofile'), - 'realfile': ('barfile.txt', open('realfile').read()), - 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), - 'nonamefile': 'contents of nonamefile field', - - Field names and filenames must be unicode. - """ - if isinstance(value, tuple): - if len(value) == 3: - filename, data, content_type = value - else: - filename, data = value - content_type = guess_content_type(filename) - else: - filename = None - content_type = None - data = value - - request_param = cls( - fieldname, data, filename=filename, header_formatter=header_formatter - ) - request_param.make_multipart(content_type=content_type) - - return request_param - - def _render_part(self, name, value): - """ - Overridable helper function to format a single header parameter. By - default, this calls ``self.header_formatter``. - - :param name: - The name of the parameter, a string expected to be ASCII only. - :param value: - The value of the parameter, provided as a unicode string. - """ - - return self.header_formatter(name, value) - - def _render_parts(self, header_parts): - """ - Helper function to format and quote a single header. - - Useful for single headers that are composed of multiple items. E.g., - 'Content-Disposition' fields. - - :param header_parts: - A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format - as `k1="v1"; k2="v2"; ...`. - """ - parts = [] - iterable = header_parts - if isinstance(header_parts, dict): - iterable = header_parts.items() - - for name, value in iterable: - if value is not None: - parts.append(self._render_part(name, value)) - - return u"; ".join(parts) - - def render_headers(self): - """ - Renders the headers for this request field. - """ - lines = [] - - sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"] - for sort_key in sort_keys: - if self.headers.get(sort_key, False): - lines.append(u"%s: %s" % (sort_key, self.headers[sort_key])) - - for header_name, header_value in self.headers.items(): - if header_name not in sort_keys: - if header_value: - lines.append(u"%s: %s" % (header_name, header_value)) - - lines.append(u"\r\n") - return u"\r\n".join(lines) - - def make_multipart( - self, content_disposition=None, content_type=None, content_location=None - ): - """ - Makes this request field into a multipart request field. - - This method overrides "Content-Disposition", "Content-Type" and - "Content-Location" headers to the request parameter. - - :param content_type: - The 'Content-Type' of the request body. - :param content_location: - The 'Content-Location' of the request body. - - """ - self.headers["Content-Disposition"] = content_disposition or u"form-data" - self.headers["Content-Disposition"] += u"; ".join( - [ - u"", - self._render_parts( - ((u"name", self._name), (u"filename", self._filename)) - ), - ] - ) - self.headers["Content-Type"] = content_type - self.headers["Content-Location"] = content_location diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/TensorMask/tensormask/__init__.py b/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/TensorMask/tensormask/__init__.py deleted file mode 100644 index e3b642a55519867dc52ccc57a36c32c72c3d34da..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/TensorMask/tensormask/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -from .config import add_tensormask_config -from .arch import TensorMask diff --git a/spaces/CVPR/LIVE/pybind11/tests/test_factory_constructors.py b/spaces/CVPR/LIVE/pybind11/tests/test_factory_constructors.py deleted file mode 100644 index 6c4bed165f6575950b7f0f17ec65a88397e0ff54..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/tests/test_factory_constructors.py +++ /dev/null @@ -1,465 +0,0 @@ -# -*- coding: utf-8 -*- -import pytest -import re - -import env # noqa: F401 - -from pybind11_tests import factory_constructors as m -from pybind11_tests.factory_constructors import tag -from pybind11_tests import ConstructorStats - - -def test_init_factory_basic(): - """Tests py::init_factory() wrapper around various ways of returning the object""" - - cstats = [ConstructorStats.get(c) for c in [m.TestFactory1, m.TestFactory2, m.TestFactory3]] - cstats[0].alive() # force gc - n_inst = ConstructorStats.detail_reg_inst() - - x1 = m.TestFactory1(tag.unique_ptr, 3) - assert x1.value == "3" - y1 = m.TestFactory1(tag.pointer) - assert y1.value == "(empty)" - z1 = m.TestFactory1("hi!") - assert z1.value == "hi!" - - assert ConstructorStats.detail_reg_inst() == n_inst + 3 - - x2 = m.TestFactory2(tag.move) - assert x2.value == "(empty2)" - y2 = m.TestFactory2(tag.pointer, 7) - assert y2.value == "7" - z2 = m.TestFactory2(tag.unique_ptr, "hi again") - assert z2.value == "hi again" - - assert ConstructorStats.detail_reg_inst() == n_inst + 6 - - x3 = m.TestFactory3(tag.shared_ptr) - assert x3.value == "(empty3)" - y3 = m.TestFactory3(tag.pointer, 42) - assert y3.value == "42" - z3 = m.TestFactory3("bye") - assert z3.value == "bye" - - for null_ptr_kind in [tag.null_ptr, - tag.null_unique_ptr, - tag.null_shared_ptr]: - with pytest.raises(TypeError) as excinfo: - m.TestFactory3(null_ptr_kind) - assert str(excinfo.value) == "pybind11::init(): factory function returned nullptr" - - assert [i.alive() for i in cstats] == [3, 3, 3] - assert ConstructorStats.detail_reg_inst() == n_inst + 9 - - del x1, y2, y3, z3 - assert [i.alive() for i in cstats] == [2, 2, 1] - assert ConstructorStats.detail_reg_inst() == n_inst + 5 - del x2, x3, y1, z1, z2 - assert [i.alive() for i in cstats] == [0, 0, 0] - assert ConstructorStats.detail_reg_inst() == n_inst - - assert [i.values() for i in cstats] == [ - ["3", "hi!"], - ["7", "hi again"], - ["42", "bye"] - ] - assert [i.default_constructions for i in cstats] == [1, 1, 1] - - -def test_init_factory_signature(msg): - with pytest.raises(TypeError) as excinfo: - m.TestFactory1("invalid", "constructor", "arguments") - assert msg(excinfo.value) == """ - __init__(): incompatible constructor arguments. The following argument types are supported: - 1. m.factory_constructors.TestFactory1(arg0: m.factory_constructors.tag.unique_ptr_tag, arg1: int) - 2. m.factory_constructors.TestFactory1(arg0: str) - 3. m.factory_constructors.TestFactory1(arg0: m.factory_constructors.tag.pointer_tag) - 4. m.factory_constructors.TestFactory1(arg0: handle, arg1: int, arg2: handle) - - Invoked with: 'invalid', 'constructor', 'arguments' - """ # noqa: E501 line too long - - assert msg(m.TestFactory1.__init__.__doc__) == """ - __init__(*args, **kwargs) - Overloaded function. - - 1. __init__(self: m.factory_constructors.TestFactory1, arg0: m.factory_constructors.tag.unique_ptr_tag, arg1: int) -> None - - 2. __init__(self: m.factory_constructors.TestFactory1, arg0: str) -> None - - 3. __init__(self: m.factory_constructors.TestFactory1, arg0: m.factory_constructors.tag.pointer_tag) -> None - - 4. __init__(self: m.factory_constructors.TestFactory1, arg0: handle, arg1: int, arg2: handle) -> None - """ # noqa: E501 line too long - - -def test_init_factory_casting(): - """Tests py::init_factory() wrapper with various upcasting and downcasting returns""" - - cstats = [ConstructorStats.get(c) for c in [m.TestFactory3, m.TestFactory4, m.TestFactory5]] - cstats[0].alive() # force gc - n_inst = ConstructorStats.detail_reg_inst() - - # Construction from derived references: - a = m.TestFactory3(tag.pointer, tag.TF4, 4) - assert a.value == "4" - b = m.TestFactory3(tag.shared_ptr, tag.TF4, 5) - assert b.value == "5" - c = m.TestFactory3(tag.pointer, tag.TF5, 6) - assert c.value == "6" - d = m.TestFactory3(tag.shared_ptr, tag.TF5, 7) - assert d.value == "7" - - assert ConstructorStats.detail_reg_inst() == n_inst + 4 - - # Shared a lambda with TF3: - e = m.TestFactory4(tag.pointer, tag.TF4, 8) - assert e.value == "8" - - assert ConstructorStats.detail_reg_inst() == n_inst + 5 - assert [i.alive() for i in cstats] == [5, 3, 2] - - del a - assert [i.alive() for i in cstats] == [4, 2, 2] - assert ConstructorStats.detail_reg_inst() == n_inst + 4 - - del b, c, e - assert [i.alive() for i in cstats] == [1, 0, 1] - assert ConstructorStats.detail_reg_inst() == n_inst + 1 - - del d - assert [i.alive() for i in cstats] == [0, 0, 0] - assert ConstructorStats.detail_reg_inst() == n_inst - - assert [i.values() for i in cstats] == [ - ["4", "5", "6", "7", "8"], - ["4", "5", "8"], - ["6", "7"] - ] - - -def test_init_factory_alias(): - """Tests py::init_factory() wrapper with value conversions and alias types""" - - cstats = [m.TestFactory6.get_cstats(), m.TestFactory6.get_alias_cstats()] - cstats[0].alive() # force gc - n_inst = ConstructorStats.detail_reg_inst() - - a = m.TestFactory6(tag.base, 1) - assert a.get() == 1 - assert not a.has_alias() - b = m.TestFactory6(tag.alias, "hi there") - assert b.get() == 8 - assert b.has_alias() - c = m.TestFactory6(tag.alias, 3) - assert c.get() == 3 - assert c.has_alias() - d = m.TestFactory6(tag.alias, tag.pointer, 4) - assert d.get() == 4 - assert d.has_alias() - e = m.TestFactory6(tag.base, tag.pointer, 5) - assert e.get() == 5 - assert not e.has_alias() - f = m.TestFactory6(tag.base, tag.alias, tag.pointer, 6) - assert f.get() == 6 - assert f.has_alias() - - assert ConstructorStats.detail_reg_inst() == n_inst + 6 - assert [i.alive() for i in cstats] == [6, 4] - - del a, b, e - assert [i.alive() for i in cstats] == [3, 3] - assert ConstructorStats.detail_reg_inst() == n_inst + 3 - del f, c, d - assert [i.alive() for i in cstats] == [0, 0] - assert ConstructorStats.detail_reg_inst() == n_inst - - class MyTest(m.TestFactory6): - def __init__(self, *args): - m.TestFactory6.__init__(self, *args) - - def get(self): - return -5 + m.TestFactory6.get(self) - - # Return Class by value, moved into new alias: - z = MyTest(tag.base, 123) - assert z.get() == 118 - assert z.has_alias() - - # Return alias by value, moved into new alias: - y = MyTest(tag.alias, "why hello!") - assert y.get() == 5 - assert y.has_alias() - - # Return Class by pointer, moved into new alias then original destroyed: - x = MyTest(tag.base, tag.pointer, 47) - assert x.get() == 42 - assert x.has_alias() - - assert ConstructorStats.detail_reg_inst() == n_inst + 3 - assert [i.alive() for i in cstats] == [3, 3] - del x, y, z - assert [i.alive() for i in cstats] == [0, 0] - assert ConstructorStats.detail_reg_inst() == n_inst - - assert [i.values() for i in cstats] == [ - ["1", "8", "3", "4", "5", "6", "123", "10", "47"], - ["hi there", "3", "4", "6", "move", "123", "why hello!", "move", "47"] - ] - - -def test_init_factory_dual(): - """Tests init factory functions with dual main/alias factory functions""" - from pybind11_tests.factory_constructors import TestFactory7 - - cstats = [TestFactory7.get_cstats(), TestFactory7.get_alias_cstats()] - cstats[0].alive() # force gc - n_inst = ConstructorStats.detail_reg_inst() - - class PythFactory7(TestFactory7): - def get(self): - return 100 + TestFactory7.get(self) - - a1 = TestFactory7(1) - a2 = PythFactory7(2) - assert a1.get() == 1 - assert a2.get() == 102 - assert not a1.has_alias() - assert a2.has_alias() - - b1 = TestFactory7(tag.pointer, 3) - b2 = PythFactory7(tag.pointer, 4) - assert b1.get() == 3 - assert b2.get() == 104 - assert not b1.has_alias() - assert b2.has_alias() - - c1 = TestFactory7(tag.mixed, 5) - c2 = PythFactory7(tag.mixed, 6) - assert c1.get() == 5 - assert c2.get() == 106 - assert not c1.has_alias() - assert c2.has_alias() - - d1 = TestFactory7(tag.base, tag.pointer, 7) - d2 = PythFactory7(tag.base, tag.pointer, 8) - assert d1.get() == 7 - assert d2.get() == 108 - assert not d1.has_alias() - assert d2.has_alias() - - # Both return an alias; the second multiplies the value by 10: - e1 = TestFactory7(tag.alias, tag.pointer, 9) - e2 = PythFactory7(tag.alias, tag.pointer, 10) - assert e1.get() == 9 - assert e2.get() == 200 - assert e1.has_alias() - assert e2.has_alias() - - f1 = TestFactory7(tag.shared_ptr, tag.base, 11) - f2 = PythFactory7(tag.shared_ptr, tag.base, 12) - assert f1.get() == 11 - assert f2.get() == 112 - assert not f1.has_alias() - assert f2.has_alias() - - g1 = TestFactory7(tag.shared_ptr, tag.invalid_base, 13) - assert g1.get() == 13 - assert not g1.has_alias() - with pytest.raises(TypeError) as excinfo: - PythFactory7(tag.shared_ptr, tag.invalid_base, 14) - assert (str(excinfo.value) == - "pybind11::init(): construction failed: returned holder-wrapped instance is not an " - "alias instance") - - assert [i.alive() for i in cstats] == [13, 7] - assert ConstructorStats.detail_reg_inst() == n_inst + 13 - - del a1, a2, b1, d1, e1, e2 - assert [i.alive() for i in cstats] == [7, 4] - assert ConstructorStats.detail_reg_inst() == n_inst + 7 - del b2, c1, c2, d2, f1, f2, g1 - assert [i.alive() for i in cstats] == [0, 0] - assert ConstructorStats.detail_reg_inst() == n_inst - - assert [i.values() for i in cstats] == [ - ["1", "2", "3", "4", "5", "6", "7", "8", "9", "100", "11", "12", "13", "14"], - ["2", "4", "6", "8", "9", "100", "12"] - ] - - -def test_no_placement_new(capture): - """Prior to 2.2, `py::init<...>` relied on the type supporting placement - new; this tests a class without placement new support.""" - with capture: - a = m.NoPlacementNew(123) - - found = re.search(r'^operator new called, returning (\d+)\n$', str(capture)) - assert found - assert a.i == 123 - with capture: - del a - pytest.gc_collect() - assert capture == "operator delete called on " + found.group(1) - - with capture: - b = m.NoPlacementNew() - - found = re.search(r'^operator new called, returning (\d+)\n$', str(capture)) - assert found - assert b.i == 100 - with capture: - del b - pytest.gc_collect() - assert capture == "operator delete called on " + found.group(1) - - -def test_multiple_inheritance(): - class MITest(m.TestFactory1, m.TestFactory2): - def __init__(self): - m.TestFactory1.__init__(self, tag.unique_ptr, 33) - m.TestFactory2.__init__(self, tag.move) - - a = MITest() - assert m.TestFactory1.value.fget(a) == "33" - assert m.TestFactory2.value.fget(a) == "(empty2)" - - -def create_and_destroy(*args): - a = m.NoisyAlloc(*args) - print("---") - del a - pytest.gc_collect() - - -def strip_comments(s): - return re.sub(r'\s+#.*', '', s) - - -def test_reallocations(capture, msg): - """When the constructor is overloaded, previous overloads can require a preallocated value. - This test makes sure that such preallocated values only happen when they might be necessary, - and that they are deallocated properly""" - - pytest.gc_collect() - - with capture: - create_and_destroy(1) - assert msg(capture) == """ - noisy new - noisy placement new - NoisyAlloc(int 1) - --- - ~NoisyAlloc() - noisy delete - """ - with capture: - create_and_destroy(1.5) - assert msg(capture) == strip_comments(""" - noisy new # allocation required to attempt first overload - noisy delete # have to dealloc before considering factory init overload - noisy new # pointer factory calling "new", part 1: allocation - NoisyAlloc(double 1.5) # ... part two, invoking constructor - --- - ~NoisyAlloc() # Destructor - noisy delete # operator delete - """) - - with capture: - create_and_destroy(2, 3) - assert msg(capture) == strip_comments(""" - noisy new # pointer factory calling "new", allocation - NoisyAlloc(int 2) # constructor - --- - ~NoisyAlloc() # Destructor - noisy delete # operator delete - """) - - with capture: - create_and_destroy(2.5, 3) - assert msg(capture) == strip_comments(""" - NoisyAlloc(double 2.5) # construction (local func variable: operator_new not called) - noisy new # return-by-value "new" part 1: allocation - ~NoisyAlloc() # moved-away local func variable destruction - --- - ~NoisyAlloc() # Destructor - noisy delete # operator delete - """) - - with capture: - create_and_destroy(3.5, 4.5) - assert msg(capture) == strip_comments(""" - noisy new # preallocation needed before invoking placement-new overload - noisy placement new # Placement new - NoisyAlloc(double 3.5) # construction - --- - ~NoisyAlloc() # Destructor - noisy delete # operator delete - """) - - with capture: - create_and_destroy(4, 0.5) - assert msg(capture) == strip_comments(""" - noisy new # preallocation needed before invoking placement-new overload - noisy delete # deallocation of preallocated storage - noisy new # Factory pointer allocation - NoisyAlloc(int 4) # factory pointer construction - --- - ~NoisyAlloc() # Destructor - noisy delete # operator delete - """) - - with capture: - create_and_destroy(5, "hi") - assert msg(capture) == strip_comments(""" - noisy new # preallocation needed before invoking first placement new - noisy delete # delete before considering new-style constructor - noisy new # preallocation for second placement new - noisy placement new # Placement new in the second placement new overload - NoisyAlloc(int 5) # construction - --- - ~NoisyAlloc() # Destructor - noisy delete # operator delete - """) - - -@pytest.mark.skipif("env.PY2") -def test_invalid_self(): - """Tests invocation of the pybind-registered base class with an invalid `self` argument. You - can only actually do this on Python 3: Python 2 raises an exception itself if you try.""" - class NotPybindDerived(object): - pass - - # Attempts to initialize with an invalid type passed as `self`: - class BrokenTF1(m.TestFactory1): - def __init__(self, bad): - if bad == 1: - a = m.TestFactory2(tag.pointer, 1) - m.TestFactory1.__init__(a, tag.pointer) - elif bad == 2: - a = NotPybindDerived() - m.TestFactory1.__init__(a, tag.pointer) - - # Same as above, but for a class with an alias: - class BrokenTF6(m.TestFactory6): - def __init__(self, bad): - if bad == 1: - a = m.TestFactory2(tag.pointer, 1) - m.TestFactory6.__init__(a, tag.base, 1) - elif bad == 2: - a = m.TestFactory2(tag.pointer, 1) - m.TestFactory6.__init__(a, tag.alias, 1) - elif bad == 3: - m.TestFactory6.__init__(NotPybindDerived.__new__(NotPybindDerived), tag.base, 1) - elif bad == 4: - m.TestFactory6.__init__(NotPybindDerived.__new__(NotPybindDerived), tag.alias, 1) - - for arg in (1, 2): - with pytest.raises(TypeError) as excinfo: - BrokenTF1(arg) - assert str(excinfo.value) == "__init__(self, ...) called with invalid `self` argument" - - for arg in (1, 2, 3, 4): - with pytest.raises(TypeError) as excinfo: - BrokenTF6(arg) - assert str(excinfo.value) == "__init__(self, ...) called with invalid `self` argument" diff --git a/spaces/CVPR/LIVE/pybind11/tests/test_iostream.py b/spaces/CVPR/LIVE/pybind11/tests/test_iostream.py deleted file mode 100644 index 7ac4fcece0b089c03e240a0ae89e54c0c33feedf..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/tests/test_iostream.py +++ /dev/null @@ -1,215 +0,0 @@ -# -*- coding: utf-8 -*- -from pybind11_tests import iostream as m -import sys - -from contextlib import contextmanager - -try: - # Python 3 - from io import StringIO -except ImportError: - # Python 2 - try: - from cStringIO import StringIO - except ImportError: - from StringIO import StringIO - -try: - # Python 3.4 - from contextlib import redirect_stdout -except ImportError: - @contextmanager - def redirect_stdout(target): - original = sys.stdout - sys.stdout = target - yield - sys.stdout = original - -try: - # Python 3.5 - from contextlib import redirect_stderr -except ImportError: - @contextmanager - def redirect_stderr(target): - original = sys.stderr - sys.stderr = target - yield - sys.stderr = original - - -def test_captured(capsys): - msg = "I've been redirected to Python, I hope!" - m.captured_output(msg) - stdout, stderr = capsys.readouterr() - assert stdout == msg - assert stderr == '' - - m.captured_output_default(msg) - stdout, stderr = capsys.readouterr() - assert stdout == msg - assert stderr == '' - - m.captured_err(msg) - stdout, stderr = capsys.readouterr() - assert stdout == '' - assert stderr == msg - - -def test_captured_large_string(capsys): - # Make this bigger than the buffer used on the C++ side: 1024 chars - msg = "I've been redirected to Python, I hope!" - msg = msg * (1024 // len(msg) + 1) - - m.captured_output_default(msg) - stdout, stderr = capsys.readouterr() - assert stdout == msg - assert stderr == '' - - -def test_guard_capture(capsys): - msg = "I've been redirected to Python, I hope!" - m.guard_output(msg) - stdout, stderr = capsys.readouterr() - assert stdout == msg - assert stderr == '' - - -def test_series_captured(capture): - with capture: - m.captured_output("a") - m.captured_output("b") - assert capture == "ab" - - -def test_flush(capfd): - msg = "(not flushed)" - msg2 = "(flushed)" - - with m.ostream_redirect(): - m.noisy_function(msg, flush=False) - stdout, stderr = capfd.readouterr() - assert stdout == '' - - m.noisy_function(msg2, flush=True) - stdout, stderr = capfd.readouterr() - assert stdout == msg + msg2 - - m.noisy_function(msg, flush=False) - - stdout, stderr = capfd.readouterr() - assert stdout == msg - - -def test_not_captured(capfd): - msg = "Something that should not show up in log" - stream = StringIO() - with redirect_stdout(stream): - m.raw_output(msg) - stdout, stderr = capfd.readouterr() - assert stdout == msg - assert stderr == '' - assert stream.getvalue() == '' - - stream = StringIO() - with redirect_stdout(stream): - m.captured_output(msg) - stdout, stderr = capfd.readouterr() - assert stdout == '' - assert stderr == '' - assert stream.getvalue() == msg - - -def test_err(capfd): - msg = "Something that should not show up in log" - stream = StringIO() - with redirect_stderr(stream): - m.raw_err(msg) - stdout, stderr = capfd.readouterr() - assert stdout == '' - assert stderr == msg - assert stream.getvalue() == '' - - stream = StringIO() - with redirect_stderr(stream): - m.captured_err(msg) - stdout, stderr = capfd.readouterr() - assert stdout == '' - assert stderr == '' - assert stream.getvalue() == msg - - -def test_multi_captured(capfd): - stream = StringIO() - with redirect_stdout(stream): - m.captured_output("a") - m.raw_output("b") - m.captured_output("c") - m.raw_output("d") - stdout, stderr = capfd.readouterr() - assert stdout == 'bd' - assert stream.getvalue() == 'ac' - - -def test_dual(capsys): - m.captured_dual("a", "b") - stdout, stderr = capsys.readouterr() - assert stdout == "a" - assert stderr == "b" - - -def test_redirect(capfd): - msg = "Should not be in log!" - stream = StringIO() - with redirect_stdout(stream): - m.raw_output(msg) - stdout, stderr = capfd.readouterr() - assert stdout == msg - assert stream.getvalue() == '' - - stream = StringIO() - with redirect_stdout(stream): - with m.ostream_redirect(): - m.raw_output(msg) - stdout, stderr = capfd.readouterr() - assert stdout == '' - assert stream.getvalue() == msg - - stream = StringIO() - with redirect_stdout(stream): - m.raw_output(msg) - stdout, stderr = capfd.readouterr() - assert stdout == msg - assert stream.getvalue() == '' - - -def test_redirect_err(capfd): - msg = "StdOut" - msg2 = "StdErr" - - stream = StringIO() - with redirect_stderr(stream): - with m.ostream_redirect(stdout=False): - m.raw_output(msg) - m.raw_err(msg2) - stdout, stderr = capfd.readouterr() - assert stdout == msg - assert stderr == '' - assert stream.getvalue() == msg2 - - -def test_redirect_both(capfd): - msg = "StdOut" - msg2 = "StdErr" - - stream = StringIO() - stream2 = StringIO() - with redirect_stdout(stream): - with redirect_stderr(stream2): - with m.ostream_redirect(): - m.raw_output(msg) - m.raw_err(msg2) - stdout, stderr = capfd.readouterr() - assert stdout == '' - assert stderr == '' - assert stream.getvalue() == msg - assert stream2.getvalue() == msg2 diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/detail/sequential/reverse.h b/spaces/CVPR/LIVE/thrust/thrust/system/detail/sequential/reverse.h deleted file mode 100644 index f80974e8a8d752c575a554018cd42e94600d3ab5..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/detail/sequential/reverse.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2008-2013 NVIDIA Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -// this system has no special reverse functions - diff --git a/spaces/CVPR/transfiner/configs/new_baselines/mask_rcnn_R_101_FPN_100ep_LSJ.py b/spaces/CVPR/transfiner/configs/new_baselines/mask_rcnn_R_101_FPN_100ep_LSJ.py deleted file mode 100644 index 3740e9bb08c5f168a9ab3a6d94561678bad1775c..0000000000000000000000000000000000000000 --- a/spaces/CVPR/transfiner/configs/new_baselines/mask_rcnn_R_101_FPN_100ep_LSJ.py +++ /dev/null @@ -1,9 +0,0 @@ -from .mask_rcnn_R_50_FPN_100ep_LSJ import ( - dataloader, - lr_multiplier, - model, - optimizer, - train, -) - -model.backbone.bottom_up.stages.depth = 101 diff --git a/spaces/CofAI/chat/client/css/checkbox.css b/spaces/CofAI/chat/client/css/checkbox.css deleted file mode 100644 index 94955b604ea3fab493a50d740fb29be1a8ef6cd3..0000000000000000000000000000000000000000 --- a/spaces/CofAI/chat/client/css/checkbox.css +++ /dev/null @@ -1,55 +0,0 @@ -.checkbox input { - height: 0; - width: 0; - display: none; -} - -.checkbox span { - font-size: 0.875rem; - color: var(--colour-2); - margin-left: 4px; -} - -.checkbox label:after { - content: ""; - position: absolute; - top: 50%; - transform: translateY(-50%); - left: 5px; - width: 20px; - height: 20px; - background: var(--blur-border); - border-radius: 90px; - transition: 0.33s; -} - -.checkbox input + label:after, -.checkbox input:checked + label { - background: var(--colour-3); -} - -.checkbox input + label, -.checkbox input:checked + label:after { - background: var(--blur-border); -} - -.checkbox input:checked + label:after { - left: calc(100% - 5px - 20px); -} - -@media screen and (max-width: 990px) { - .checkbox label { - width: 25px; - height: 15px; - } - - .checkbox label:after { - left: 2px; - width: 10px; - height: 10px; - } - - .checkbox input:checked + label:after { - left: calc(100% - 2px - 10px); - } -} diff --git a/spaces/CyberHarem/find_my_waifu/character.py b/spaces/CyberHarem/find_my_waifu/character.py deleted file mode 100644 index b21d7a838b5c4b259586faf6c656c1e1f8039e2c..0000000000000000000000000000000000000000 --- a/spaces/CyberHarem/find_my_waifu/character.py +++ /dev/null @@ -1,36 +0,0 @@ -import re - -from gchar.games.base import Character -from thefuzz import fuzz - - -def get_pure_name(name: str) -> str: - return '_'.join([word for word in re.split(r'[\W_]+', name.lower()) if word]) - - -def get_alphabet_name(name: str) -> str: - return '_'.join(re.findall(r'[a-zA-Z\d+]+', name.lower())) - - -def _name_alphabet_ratio(name: str) -> float: - pure_name = get_pure_name(name) - alphabet_name = get_alphabet_name(name) - return fuzz.token_set_ratio(pure_name, alphabet_name) - - -def get_ch_name(ch: Character): - names = [ - *map(str, ch.ennames), - *map(str, ch.cnnames), - *map(str, ch.jpnames), - ] - all_names = [(name, _name_alphabet_ratio(name), i) for i, name in enumerate(names)] - all_names = sorted(all_names, key=lambda x: (-x[1], x[2])) - - name, ratio, _ = all_names[0] - if ratio >= 0.9: - short_name = get_alphabet_name(name) - else: - raise ValueError(f'No suitable alphabet-based name for {ch!r}.') - - return f'{short_name}_{ch.__game_name__}' diff --git a/spaces/DJQmUKV/rvc-inference/config.py b/spaces/DJQmUKV/rvc-inference/config.py deleted file mode 100644 index 5a4e1d177df45e92383bbe349f094de8f66f7056..0000000000000000000000000000000000000000 --- a/spaces/DJQmUKV/rvc-inference/config.py +++ /dev/null @@ -1,18 +0,0 @@ -import torch - -import util - - -device = ( - 'cuda:0' if torch.cuda.is_available() - else ( - 'mps' if util.has_mps() - else 'cpu' - ) -) -is_half = util.is_half(device) - -x_pad = 3 if is_half else 1 -x_query = 10 if is_half else 6 -x_center = 60 if is_half else 38 -x_max = 65 if is_half else 41 diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/dateutil/__init__.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/dateutil/__init__.py deleted file mode 100644 index 0defb82e21f21da442706e25145b4ef0b59d576c..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/dateutil/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- -try: - from ._version import version as __version__ -except ImportError: - __version__ = 'unknown' - -__all__ = ['easter', 'parser', 'relativedelta', 'rrule', 'tz', - 'utils', 'zoneinfo'] diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fsspec/exceptions.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fsspec/exceptions.py deleted file mode 100644 index 2d6e1a44b6a1667d1c302869ff2a332634fda47e..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fsspec/exceptions.py +++ /dev/null @@ -1,21 +0,0 @@ -""" -fsspec user-defined exception classes -""" -import asyncio - - -class BlocksizeMismatchError(ValueError): - """ - Raised when a cached file is opened with a different blocksize than it was - written with - """ - - ... - - -class FSTimeoutError(asyncio.TimeoutError): - """ - Raised when a fsspec function timed out occurs - """ - - ... diff --git a/spaces/DaFujaTyping/hf-Chat-ui/src/lib/types/SharedConversation.ts b/spaces/DaFujaTyping/hf-Chat-ui/src/lib/types/SharedConversation.ts deleted file mode 100644 index e8981ed83a8871ef49fa539a14cb1ebfca599ea0..0000000000000000000000000000000000000000 --- a/spaces/DaFujaTyping/hf-Chat-ui/src/lib/types/SharedConversation.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Message } from "./Message"; -import type { Timestamps } from "./Timestamps"; - -export interface SharedConversation extends Timestamps { - _id: string; - - hash: string; - - model: string; - title: string; - messages: Message[]; -} diff --git a/spaces/Dauzy/whisper-webui/docs/options.md b/spaces/Dauzy/whisper-webui/docs/options.md deleted file mode 100644 index 6979fca4d9d4c98a626a2953c2573ff23898a37e..0000000000000000000000000000000000000000 --- a/spaces/Dauzy/whisper-webui/docs/options.md +++ /dev/null @@ -1,134 +0,0 @@ -# Standard Options -To transcribe or translate an audio file, you can either copy an URL from a website (all [websites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md) -supported by YT-DLP will work, including YouTube). Otherwise, upload an audio file (choose "All Files (*.*)" -in the file selector to select any file type, including video files) or use the microphone. - -For longer audio files (>10 minutes), it is recommended that you select Silero VAD (Voice Activity Detector) in the VAD option, especially if you are using the `large-v1` model. Note that `large-v2` is a lot more forgiving, but you may still want to use a VAD with a slightly higher "VAD - Max Merge Size (s)" (60 seconds or more). - -## Model -Select the model that Whisper will use to transcribe the audio: - -| Size | Parameters | English-only model | Multilingual model | Required VRAM | Relative speed | -|-----------|------------|--------------------|--------------------|---------------|----------------| -| tiny | 39 M | tiny.en | tiny | ~1 GB | ~32x | -| base | 74 M | base.en | base | ~1 GB | ~16x | -| small | 244 M | small.en | small | ~2 GB | ~6x | -| medium | 769 M | medium.en | medium | ~5 GB | ~2x | -| large | 1550 M | N/A | large | ~10 GB | 1x | -| large-v2 | 1550 M | N/A | large | ~10 GB | 1x | - -## Language - -Select the language, or leave it empty for Whisper to automatically detect it. - -Note that if the selected language and the language in the audio differs, Whisper may start to translate the audio to the selected -language. For instance, if the audio is in English but you select Japaneese, the model may translate the audio to Japanese. - -## Inputs -The options "URL (YouTube, etc.)", "Upload Files" or "Micriphone Input" allows you to send an audio input to the model. - -### Multiple Files -Note that the UI will only process either the given URL or the upload files (including microphone) - not both. - -But you can upload multiple files either through the "Upload files" option, or as a playlist on YouTube. Each audio file will then be processed in turn, and the resulting SRT/VTT/Transcript will be made available in the "Download" section. When more than one file is processed, the UI will also generate a "All_Output" zip file containing all the text output files. - -## Task -Select the task - either "transcribe" to transcribe the audio to text, or "translate" to translate it to English. - -## Vad -Using a VAD will improve the timing accuracy of each transcribed line, as well as prevent Whisper getting into an infinite -loop detecting the same sentence over and over again. The downside is that this may be at a cost to text accuracy, especially -with regards to unique words or names that appear in the audio. You can compensate for this by increasing the prompt window. - -Note that English is very well handled by Whisper, and it's less susceptible to issues surrounding bad timings and infinite loops. -So you may only need to use a VAD for other languages, such as Japanese, or when the audio is very long. - -* none - * Run whisper on the entire audio input -* silero-vad - * Use Silero VAD to detect sections that contain speech, and run Whisper on independently on each section. Whisper is also run - on the gaps between each speech section, by either expanding the section up to the max merge size, or running Whisper independently - on the non-speech section. -* silero-vad-expand-into-gaps - * Use Silero VAD to detect sections that contain speech, and run Whisper on independently on each section. Each spech section will be expanded - such that they cover any adjacent non-speech sections. For instance, if an audio file of one minute contains the speech sections - 00:00 - 00:10 (A) and 00:30 - 00:40 (B), the first section (A) will be expanded to 00:00 - 00:30, and (B) will be expanded to 00:30 - 00:60. -* silero-vad-skip-gaps - * As above, but sections that doesn't contain speech according to Silero will be skipped. This will be slightly faster, but - may cause dialogue to be skipped. -* periodic-vad - * Create sections of speech every 'VAD - Max Merge Size' seconds. This is very fast and simple, but will potentially break - a sentence or word in two. - -## VAD - Merge Window -If set, any adjacent speech sections that are at most this number of seconds apart will be automatically merged. - -## VAD - Max Merge Size (s) -Disables merging of adjacent speech sections if they are this number of seconds long. - -## VAD - Padding (s) -The number of seconds (floating point) to add to the beginning and end of each speech section. Setting this to a number -larger than zero ensures that Whisper is more likely to correctly transcribe a sentence in the beginning of -a speech section. However, this also increases the probability of Whisper assigning the wrong timestamp -to each transcribed line. The default value is 1 second. - -## VAD - Prompt Window (s) -The text of a detected line will be included as a prompt to the next speech section, if the speech section starts at most this -number of seconds after the line has finished. For instance, if a line ends at 10:00, and the next speech section starts at -10:04, the line's text will be included if the prompt window is 4 seconds or more (10:04 - 10:00 = 4 seconds). - -Note that detected lines in gaps between speech sections will not be included in the prompt -(if silero-vad or silero-vad-expand-into-gaps) is used. - -# Command Line Options - -Both `app.py` and `cli.py` also accept command line options, such as the ability to enable parallel execution on multiple -CPU/GPU cores, the default model name/VAD and so on. Consult the README in the root folder for more information. - -# Additional Options - -In addition to the above, there's also a "Full" options interface that allows you to set all the options available in the Whisper -model. The options are as follows: - -## Initial Prompt -Optional text to provide as a prompt for the first 30 seconds window. Whisper will attempt to use this as a starting point for the transcription, but you can -also get creative and specify a style or format for the output of the transcription. - -For instance, if you use the prompt "hello how is it going always use lowercase no punctuation goodbye one two three start stop i you me they", Whisper will -be biased to output lower capital letters and no punctuation, and may also be biased to output the words in the prompt more often. - -## Temperature -The temperature to use when sampling. Default is 0 (zero). A higher temperature will result in more random output, while a lower temperature will be more deterministic. - -## Best Of - Non-zero temperature -The number of candidates to sample from when sampling with non-zero temperature. Default is 5. - -## Beam Size - Zero temperature -The number of beams to use in beam search when sampling with zero temperature. Default is 5. - -## Patience - Zero temperature -The patience value to use in beam search when sampling with zero temperature. As in https://arxiv.org/abs/2204.05424, the default (1.0) is equivalent to conventional beam search. - -## Length Penalty - Any temperature -The token length penalty coefficient (alpha) to use when sampling with any temperature. As in https://arxiv.org/abs/1609.08144, uses simple length normalization by default. - -## Suppress Tokens - Comma-separated list of token IDs -A comma-separated list of token IDs to suppress during sampling. The default value of "-1" will suppress most special characters except common punctuations. - -## Condition on previous text -If True, provide the previous output of the model as a prompt for the next window. Disabling this may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop. - -## FP16 -Whether to perform inference in fp16. True by default. - -## Temperature increment on fallback -The temperature to increase when falling back when the decoding fails to meet either of the thresholds below. Default is 0.2. - -## Compression ratio threshold -If the gzip compression ratio is higher than this value, treat the decoding as failed. Default is 2.4. - -## Logprob threshold -If the average log probability is lower than this value, treat the decoding as failed. Default is -1.0. - -## No speech threshold -If the probability of the <|nospeech|> token is higher than this value AND the decoding has failed due to `logprob_threshold`, consider the segment as silence. Default is 0.6. diff --git a/spaces/DorisB/streamlit-app/app.py b/spaces/DorisB/streamlit-app/app.py deleted file mode 100644 index 4e48fb0293539d7d9fa6bfa23f149bc54299d46e..0000000000000000000000000000000000000000 --- a/spaces/DorisB/streamlit-app/app.py +++ /dev/null @@ -1,77 +0,0 @@ -#imports - -import streamlit as st -import pandas as pd -from PIL import Image -import pickle -from pathlib import Path -import requests -from streamlit_lottie import st_lottie -import webbrowser - - - - - -def main(): - st.set_page_config(layout="wide") - with open('style.css') as f: - st.markdown(f'', unsafe_allow_html=True) - - - hide_menu = """ - - """ - - hide_sidebar = """ - - """ - - st.markdown(hide_menu, unsafe_allow_html=True) - st.markdown(hide_sidebar, unsafe_allow_html=True) - - - def load_lottie(url): - r = requests.get(url) - if r.status_code != 200: - return None - return r.json() - - lottie = load_lottie("https://assets2.lottiefiles.com/private_files/lf30_zSGy1w.json") - st.image("images/logo-recom2.png") - cols = st.columns((2,3)) - with cols[1]: - - st_lottie(lottie, height=400, key="coding") - - url = "https://hf.space/streamlit/DorisB/streamlit-app/" - with cols[0]: - st.markdown("

      Hello :)

      ", unsafe_allow_html=True) - login = st.text_input("Username: ", 'admin') - password = st.text_input("Password: ", "recom_demo") - #st.markdown('LOGIN', unsafe_allow_html=True) - if st.button('Login'): - webbrowser.open_new_tab(url) - - - - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/spaces/DragGan/DragGan-Inversion/stylegan_human/torch_utils/op_edit/fused_act.py b/spaces/DragGan/DragGan-Inversion/stylegan_human/torch_utils/op_edit/fused_act.py deleted file mode 100644 index c9c7b6f0e2b16b78dd81c174cf139a4bd848648a..0000000000000000000000000000000000000000 --- a/spaces/DragGan/DragGan-Inversion/stylegan_human/torch_utils/op_edit/fused_act.py +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (c) SenseTime Research. All rights reserved. - -import os - -import torch -from torch import nn -from torch.nn import functional as F -from torch.autograd import Function -from torch.utils.cpp_extension import load - - -module_path = os.path.dirname(__file__) -fused = load( - "fused", - sources=[ - os.path.join(module_path, "fused_bias_act.cpp"), - os.path.join(module_path, "fused_bias_act_kernel.cu"), - ], -) - - -class FusedLeakyReLUFunctionBackward(Function): - @staticmethod - def forward(ctx, grad_output, out, negative_slope, scale): - ctx.save_for_backward(out) - ctx.negative_slope = negative_slope - ctx.scale = scale - - empty = grad_output.new_empty(0) - - grad_input = fused.fused_bias_act( - grad_output, empty, out, 3, 1, negative_slope, scale - ) - - dim = [0] - - if grad_input.ndim > 2: - dim += list(range(2, grad_input.ndim)) - - grad_bias = grad_input.sum(dim).detach() - - return grad_input, grad_bias - - @staticmethod - def backward(ctx, gradgrad_input, gradgrad_bias): - (out,) = ctx.saved_tensors - gradgrad_out = fused.fused_bias_act( - gradgrad_input, gradgrad_bias, out, 3, 1, ctx.negative_slope, ctx.scale - ) - - return gradgrad_out, None, None, None - - -class FusedLeakyReLUFunction(Function): - @staticmethod - def forward(ctx, input, bias, negative_slope, scale): - empty = input.new_empty(0) - out = fused.fused_bias_act( - input, bias, empty, 3, 0, negative_slope, scale) - ctx.save_for_backward(out) - ctx.negative_slope = negative_slope - ctx.scale = scale - - return out - - @staticmethod - def backward(ctx, grad_output): - (out,) = ctx.saved_tensors - - grad_input, grad_bias = FusedLeakyReLUFunctionBackward.apply( - grad_output, out, ctx.negative_slope, ctx.scale - ) - - return grad_input, grad_bias, None, None - - -class FusedLeakyReLU(nn.Module): - def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5): - super().__init__() - - self.bias = nn.Parameter(torch.zeros(channel)) - self.negative_slope = negative_slope - self.scale = scale - - def forward(self, input): - return fused_leaky_relu(input, self.bias, self.negative_slope, self.scale) - - -def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): - if input.device.type == "cpu": - rest_dim = [1] * (input.ndim - bias.ndim - 1) - return ( - F.leaky_relu( - input + bias.view(1, bias.shape[0], *rest_dim), negative_slope=0.2 - ) - * scale - ) - - else: - return FusedLeakyReLUFunction.apply(input, bias, negative_slope, scale) diff --git a/spaces/DreamSunny/stable-diffusion-webui-cpu/README.md b/spaces/DreamSunny/stable-diffusion-webui-cpu/README.md deleted file mode 100644 index 1e8980b44168d44bb673b576698837102b4eb732..0000000000000000000000000000000000000000 --- a/spaces/DreamSunny/stable-diffusion-webui-cpu/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Stable Diffusion Webui on Cpu -emoji: 🏃 -colorFrom: pink -colorTo: purple -sdk: gradio -sdk_version: 3.32.0 -app_file: app.py -pinned: false -python_version : 3.10.6 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Dxtrmst/TheBloke-WizardLM-Uncensored-Falcon-7B-GPTQ/README.md b/spaces/Dxtrmst/TheBloke-WizardLM-Uncensored-Falcon-7B-GPTQ/README.md deleted file mode 100644 index 92844b53c430d9065e4513accac6875470a6a3cd..0000000000000000000000000000000000000000 --- a/spaces/Dxtrmst/TheBloke-WizardLM-Uncensored-Falcon-7B-GPTQ/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: TheBloke WizardLM Uncensored Falcon 7B GPTQ -emoji: ⚡ -colorFrom: purple -colorTo: purple -sdk: gradio -sdk_version: 3.33.1 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/ECCV2022/PSG/OpenPSG/configs/psgtr/psgtr_r50_psg.py b/spaces/ECCV2022/PSG/OpenPSG/configs/psgtr/psgtr_r50_psg.py deleted file mode 100644 index 6440149836d4eadd912b5c00412e247ee4637e68..0000000000000000000000000000000000000000 --- a/spaces/ECCV2022/PSG/OpenPSG/configs/psgtr/psgtr_r50_psg.py +++ /dev/null @@ -1,233 +0,0 @@ -_base_ = [ - '../_base_/models/psgtr_r50.py', '../_base_/datasets/psg.py', - '../_base_/custom_runtime.py' -] - -custom_imports = dict(imports=[ - 'openpsg.models.frameworks.psgtr', 'openpsg.models.losses.seg_losses', - 'openpsg.models.relation_heads.psgtr_head', 'openpsg.datasets', - 'openpsg.datasets.pipelines.loading', - 'openpsg.datasets.pipelines.rel_randomcrop', - 'openpsg.models.relation_heads.approaches.matcher', 'openpsg.utils' -], - allow_failed_imports=False) - -dataset_type = 'PanopticSceneGraphDataset' - -# HACK: -object_classes = [ - 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', - 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', - 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', - 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', - 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', - 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', - 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', - 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', - 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', - 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', - 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', - 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', - 'hair drier', 'toothbrush', 'banner', 'blanket', 'bridge', 'cardboard', - 'counter', 'curtain', 'door-stuff', 'floor-wood', 'flower', 'fruit', - 'gravel', 'house', 'light', 'mirror-stuff', 'net', 'pillow', 'platform', - 'playingfield', 'railroad', 'river', 'road', 'roof', 'sand', 'sea', - 'shelf', 'snow', 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', - 'wall-tile', 'wall-wood', 'water-other', 'window-blind', 'window-other', - 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', - 'cabinet-merged', 'table-merged', 'floor-other-merged', 'pavement-merged', - 'mountain-merged', 'grass-merged', 'dirt-merged', 'paper-merged', - 'food-other-merged', 'building-other-merged', 'rock-merged', - 'wall-other-merged', 'rug-merged' -] - -predicate_classes = [ - 'over', - 'in front of', - 'beside', - 'on', - 'in', - 'attached to', - 'hanging from', - 'on back of', - 'falling off', - 'going down', - 'painted on', - 'walking on', - 'running on', - 'crossing', - 'standing on', - 'lying on', - 'sitting on', - 'flying over', - 'jumping over', - 'jumping from', - 'wearing', - 'holding', - 'carrying', - 'looking at', - 'guiding', - 'kissing', - 'eating', - 'drinking', - 'feeding', - 'biting', - 'catching', - 'picking', - 'playing with', - 'chasing', - 'climbing', - 'cleaning', - 'playing', - 'touching', - 'pushing', - 'pulling', - 'opening', - 'cooking', - 'talking to', - 'throwing', - 'slicing', - 'driving', - 'riding', - 'parked on', - 'driving on', - 'about to hit', - 'kicking', - 'swinging', - 'entering', - 'exiting', - 'enclosing', - 'leaning on', -] - -model = dict(bbox_head=dict( - num_classes=len(object_classes), - num_relations=len(predicate_classes), - object_classes=object_classes, - predicate_classes=predicate_classes, - use_mask=True, - num_query=100, -), ) - -img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], - std=[58.395, 57.12, 57.375], - to_rgb=True) -# train_pipeline, NOTE the img_scale and the Pad's size_divisor is different -# from the default setting in mmdet. -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='LoadPanopticSceneGraphAnnotations', - with_bbox=True, - with_rel=True, - with_mask=True, - with_seg=True), - dict(type='RandomFlip', flip_ratio=0.5), - dict( - type='AutoAugment', - policies=[ - [ - dict(type='Resize', - img_scale=[(480, 1333), (512, 1333), (544, 1333), - (576, 1333), (608, 1333), (640, 1333), - (672, 1333), (704, 1333), (736, 1333), - (768, 1333), (800, 1333)], - multiscale_mode='value', - keep_ratio=True) - ], - [ - dict(type='Resize', - img_scale=[(400, 1333), (500, 1333), (600, 1333)], - multiscale_mode='value', - keep_ratio=True), - dict(type='RelRandomCrop', - crop_type='absolute_range', - crop_size=(384, 600), - allow_negative_crop=False), # no empty relations - dict(type='Resize', - img_scale=[(480, 1333), (512, 1333), (544, 1333), - (576, 1333), (608, 1333), (640, 1333), - (672, 1333), (704, 1333), (736, 1333), - (768, 1333), (800, 1333)], - multiscale_mode='value', - override=True, - keep_ratio=True) - ] - ]), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=1), - dict(type='RelsFormatBundle'), - dict(type='Collect', - keys=['img', 'gt_bboxes', 'gt_labels', 'gt_rels', 'gt_masks']) -] -# test_pipeline, NOTE the Pad's size_divisor is different from the default -# setting (size_divisor=32). While there is little effect on the performance -# whether we use the default setting or use size_divisor=1. -test_pipeline = [ - dict(type='LoadImageFromFile'), - # dict(type='LoadSceneGraphAnnotations', with_bbox=True, with_rel=True), - 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=1), - dict(type='ImageToTensor', keys=['img']), - # dict(type='ToTensor', keys=['gt_bboxes', 'gt_labels']), - # dict(type='ToDataContainer', fields=(dict(key='gt_bboxes'), dict(key='gt_labels'))), - dict(type='Collect', keys=['img']), - ]) -] - -evaluation = dict( - interval=1, - metric='sgdet', - relation_mode=True, - classwise=True, - iou_thrs=0.5, - detection_method='pan_seg', -) - -data = dict(samples_per_gpu=1, - workers_per_gpu=2, - train=dict(pipeline=train_pipeline), - val=dict(pipeline=test_pipeline), - test=dict(pipeline=test_pipeline)) -# optimizer -optimizer = dict( - type='AdamW', - lr=0.0001, - weight_decay=0.0001, - paramwise_cfg=dict(custom_keys={ - 'backbone': dict(lr_mult=0.1, decay_mult=1.0), - })) -optimizer_config = dict(grad_clip=dict(max_norm=0.1, norm_type=2)) - -# learning policy -lr_config = dict(policy='step', step=40) -runner = dict(type='EpochBasedRunner', max_epochs=60) - -project_name = 'psgformer' -expt_name = 'psgtr_r50_psg_0.5_scale_mask' -work_dir = f'./work_dirs/{expt_name}' -checkpoint_config = dict(interval=2, max_keep_ckpts=10) - -log_config = dict( - interval=50, - hooks=[ - dict(type='TextLoggerHook'), - # dict(type='TensorboardLoggerHook'), - dict( - type='WandbLoggerHook', - init_kwargs=dict( - project=project_name, - name=expt_name, - # config=work_dir + "/cfg.yaml" - ), - ) - ], -) - -load_from = 'work_dirs/checkpoints/detr_pan_r50.pth' diff --git a/spaces/EleutherAI/VQGAN_CLIP/taming-transformers/taming/models/cond_transformer.py b/spaces/EleutherAI/VQGAN_CLIP/taming-transformers/taming/models/cond_transformer.py deleted file mode 100644 index 6e6869b084016d76424f0992cce9dcbcb0037d49..0000000000000000000000000000000000000000 --- a/spaces/EleutherAI/VQGAN_CLIP/taming-transformers/taming/models/cond_transformer.py +++ /dev/null @@ -1,343 +0,0 @@ -import os, math -import torch -import torch.nn.functional as F -import pytorch_lightning as pl - -from main import instantiate_from_config -from taming.modules.util import SOSProvider - - -def disabled_train(self, mode=True): - """Overwrite model.train with this function to make sure train/eval mode - does not change anymore.""" - return self - - -class Net2NetTransformer(pl.LightningModule): - def __init__(self, - transformer_config, - first_stage_config, - cond_stage_config, - permuter_config=None, - ckpt_path=None, - ignore_keys=[], - first_stage_key="image", - cond_stage_key="depth", - downsample_cond_size=-1, - pkeep=1.0, - sos_token=0, - unconditional=False, - ): - super().__init__() - self.be_unconditional = unconditional - self.sos_token = sos_token - self.first_stage_key = first_stage_key - self.cond_stage_key = cond_stage_key - self.init_first_stage_from_ckpt(first_stage_config) - self.init_cond_stage_from_ckpt(cond_stage_config) - if permuter_config is None: - permuter_config = {"target": "taming.modules.transformer.permuter.Identity"} - self.permuter = instantiate_from_config(config=permuter_config) - self.transformer = instantiate_from_config(config=transformer_config) - - if ckpt_path is not None: - self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys) - self.downsample_cond_size = downsample_cond_size - self.pkeep = pkeep - - def init_from_ckpt(self, path, ignore_keys=list()): - sd = torch.load(path, map_location="cpu")["state_dict"] - for k in sd.keys(): - for ik in ignore_keys: - if k.startswith(ik): - self.print("Deleting key {} from state_dict.".format(k)) - del sd[k] - self.load_state_dict(sd, strict=False) - print(f"Restored from {path}") - - def init_first_stage_from_ckpt(self, config): - model = instantiate_from_config(config) - model = model.eval() - model.train = disabled_train - self.first_stage_model = model - - def init_cond_stage_from_ckpt(self, config): - if config == "__is_first_stage__": - print("Using first stage also as cond stage.") - self.cond_stage_model = self.first_stage_model - elif config == "__is_unconditional__" or self.be_unconditional: - print(f"Using no cond stage. Assuming the training is intended to be unconditional. " - f"Prepending {self.sos_token} as a sos token.") - self.be_unconditional = True - self.cond_stage_key = self.first_stage_key - self.cond_stage_model = SOSProvider(self.sos_token) - else: - model = instantiate_from_config(config) - model = model.eval() - model.train = disabled_train - self.cond_stage_model = model - - def forward(self, x, c): - # one step to produce the logits - _, z_indices = self.encode_to_z(x) - _, c_indices = self.encode_to_c(c) - - if self.training and self.pkeep < 1.0: - mask = torch.bernoulli(self.pkeep*torch.ones(z_indices.shape, - device=z_indices.device)) - mask = mask.round().to(dtype=torch.int64) - r_indices = torch.randint_like(z_indices, self.transformer.config.vocab_size) - a_indices = mask*z_indices+(1-mask)*r_indices - else: - a_indices = z_indices - - cz_indices = torch.cat((c_indices, a_indices), dim=1) - - # target includes all sequence elements (no need to handle first one - # differently because we are conditioning) - target = z_indices - # make the prediction - logits, _ = self.transformer(cz_indices[:, :-1]) - # cut off conditioning outputs - output i corresponds to p(z_i | z_{ -1: - c = F.interpolate(c, size=(self.downsample_cond_size, self.downsample_cond_size)) - quant_c, _, [_,_,indices] = self.cond_stage_model.encode(c) - if len(indices.shape) > 2: - indices = indices.view(c.shape[0], -1) - return quant_c, indices - - @torch.no_grad() - def decode_to_img(self, index, zshape): - index = self.permuter(index, reverse=True) - bhwc = (zshape[0],zshape[2],zshape[3],zshape[1]) - quant_z = self.first_stage_model.quantize.get_codebook_entry( - index.reshape(-1), shape=bhwc) - x = self.first_stage_model.decode(quant_z) - return x - - @torch.no_grad() - def log_images(self, batch, temperature=None, top_k=None, callback=None, lr_interface=False, **kwargs): - log = dict() - - N = 4 - if lr_interface: - x, c = self.get_xc(batch, N, diffuse=False, upsample_factor=8) - else: - x, c = self.get_xc(batch, N) - x = x.to(device=self.device) - c = c.to(device=self.device) - - quant_z, z_indices = self.encode_to_z(x) - quant_c, c_indices = self.encode_to_c(c) - - # create a "half"" sample - z_start_indices = z_indices[:,:z_indices.shape[1]//2] - index_sample = self.sample(z_start_indices, c_indices, - steps=z_indices.shape[1]-z_start_indices.shape[1], - temperature=temperature if temperature is not None else 1.0, - sample=True, - top_k=top_k if top_k is not None else 100, - callback=callback if callback is not None else lambda k: None) - x_sample = self.decode_to_img(index_sample, quant_z.shape) - - # sample - z_start_indices = z_indices[:, :0] - index_sample = self.sample(z_start_indices, c_indices, - steps=z_indices.shape[1], - temperature=temperature if temperature is not None else 1.0, - sample=True, - top_k=top_k if top_k is not None else 100, - callback=callback if callback is not None else lambda k: None) - x_sample_nopix = self.decode_to_img(index_sample, quant_z.shape) - - # det sample - z_start_indices = z_indices[:, :0] - index_sample = self.sample(z_start_indices, c_indices, - steps=z_indices.shape[1], - sample=False, - callback=callback if callback is not None else lambda k: None) - x_sample_det = self.decode_to_img(index_sample, quant_z.shape) - - # reconstruction - x_rec = self.decode_to_img(z_indices, quant_z.shape) - - log["inputs"] = x - log["reconstructions"] = x_rec - - if self.cond_stage_key != "image": - cond_rec = self.cond_stage_model.decode(quant_c) - if self.cond_stage_key == "segmentation": - # get image from segmentation mask - num_classes = cond_rec.shape[1] - - c = torch.argmax(c, dim=1, keepdim=True) - c = F.one_hot(c, num_classes=num_classes) - c = c.squeeze(1).permute(0, 3, 1, 2).float() - c = self.cond_stage_model.to_rgb(c) - - cond_rec = torch.argmax(cond_rec, dim=1, keepdim=True) - cond_rec = F.one_hot(cond_rec, num_classes=num_classes) - cond_rec = cond_rec.squeeze(1).permute(0, 3, 1, 2).float() - cond_rec = self.cond_stage_model.to_rgb(cond_rec) - log["conditioning_rec"] = cond_rec - log["conditioning"] = c - - log["samples_half"] = x_sample - log["samples_nopix"] = x_sample_nopix - log["samples_det"] = x_sample_det - return log - - def get_input(self, key, batch): - x = batch[key] - if len(x.shape) == 3: - x = x[..., None] - if len(x.shape) == 4: - x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format) - if x.dtype == torch.double: - x = x.float() - return x - - def get_xc(self, batch, N=None): - x = self.get_input(self.first_stage_key, batch) - c = self.get_input(self.cond_stage_key, batch) - if N is not None: - x = x[:N] - c = c[:N] - return x, c - - def shared_step(self, batch, batch_idx): - x, c = self.get_xc(batch) - logits, target = self(x, c) - loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), target.reshape(-1)) - return loss - - def training_step(self, batch, batch_idx): - loss = self.shared_step(batch, batch_idx) - self.log("train/loss", loss, prog_bar=True, logger=True, on_step=True, on_epoch=True) - return loss - - def validation_step(self, batch, batch_idx): - loss = self.shared_step(batch, batch_idx) - self.log("val/loss", loss, prog_bar=True, logger=True, on_step=True, on_epoch=True) - return loss - - def configure_optimizers(self): - """ - Following minGPT: - This long function is unfortunately doing something very simple and is being very defensive: - We are separating out all parameters of the model into two buckets: those that will experience - weight decay for regularization and those that won't (biases, and layernorm/embedding weights). - We are then returning the PyTorch optimizer object. - """ - # separate out all parameters to those that will and won't experience regularizing weight decay - decay = set() - no_decay = set() - whitelist_weight_modules = (torch.nn.Linear, ) - blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding) - for mn, m in self.transformer.named_modules(): - for pn, p in m.named_parameters(): - fpn = '%s.%s' % (mn, pn) if mn else pn # full param name - - if pn.endswith('bias'): - # all biases will not be decayed - no_decay.add(fpn) - elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules): - # weights of whitelist modules will be weight decayed - decay.add(fpn) - elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules): - # weights of blacklist modules will NOT be weight decayed - no_decay.add(fpn) - - # special case the position embedding parameter in the root GPT module as not decayed - no_decay.add('pos_emb') - - # validate that we considered every parameter - param_dict = {pn: p for pn, p in self.transformer.named_parameters()} - inter_params = decay & no_decay - union_params = decay | no_decay - assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), ) - assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \ - % (str(param_dict.keys() - union_params), ) - - # create the pytorch optimizer object - optim_groups = [ - {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": 0.01}, - {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0}, - ] - optimizer = torch.optim.AdamW(optim_groups, lr=self.learning_rate, betas=(0.9, 0.95)) - return optimizer diff --git a/spaces/Epoching/3D_Photo_Inpainting/app.py b/spaces/Epoching/3D_Photo_Inpainting/app.py deleted file mode 100644 index f551cf4a7f120091c72c7cccb1e8ea1882eb34c8..0000000000000000000000000000000000000000 --- a/spaces/Epoching/3D_Photo_Inpainting/app.py +++ /dev/null @@ -1,229 +0,0 @@ -# Repo source: https://github.com/vt-vl-lab/3d-photo-inpainting - -#import os -#os.environ['QT_DEBUG_PLUGINS'] = '1' - -import subprocess -#subprocess.run('ldd /home/user/.local/lib/python3.8/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so', shell=True) -#subprocess.run('pip list', shell=True) -subprocess.run('nvidia-smi', shell=True) - -from pyvirtualdisplay import Display -display = Display(visible=0, size=(1920, 1080)).start() -#subprocess.run('echo $DISPLAY', shell=True) - -# 3d inpainting imports -import numpy as np -import argparse -import glob -import os -from functools import partial -import vispy -import scipy.misc as misc -from tqdm import tqdm -import yaml -import time -import sys -from mesh import write_ply, read_ply, output_3d_photo -from utils import get_MiDaS_samples, read_MiDaS_depth -import torch -import cv2 -from skimage.transform import resize -import imageio -import copy -from networks import Inpaint_Color_Net, Inpaint_Depth_Net, Inpaint_Edge_Net -from MiDaS.run import run_depth -from boostmonodepth_utils import run_boostmonodepth -from MiDaS.monodepth_net import MonoDepthNet -import MiDaS.MiDaS_utils as MiDaS_utils -from bilateral_filtering import sparse_bilateral_filtering - -import torch - -# gradio imports -import gradio as gr -import uuid -from PIL import Image -from pathlib import Path -import shutil -from time import sleep - -def inpaint(img_name, num_frames, fps): - - config = yaml.load(open('argument.yml', 'r')) - - config['num_frames'] = num_frames - config['fps'] = fps - - if torch.cuda.is_available(): - config['gpu_ids'] = 0 - - if config['offscreen_rendering'] is True: - vispy.use(app='egl') - - os.makedirs(config['mesh_folder'], exist_ok=True) - os.makedirs(config['video_folder'], exist_ok=True) - os.makedirs(config['depth_folder'], exist_ok=True) - sample_list = get_MiDaS_samples(config['src_folder'], config['depth_folder'], config, config['specific'], img_name.stem) - normal_canvas, all_canvas = None, None - - if isinstance(config["gpu_ids"], int) and (config["gpu_ids"] >= 0): - device = config["gpu_ids"] - else: - device = "cpu" - - print(f"running on device {device}") - - for idx in tqdm(range(len(sample_list))): - depth = None - sample = sample_list[idx] - print("Current Source ==> ", sample['src_pair_name']) - mesh_fi = os.path.join(config['mesh_folder'], sample['src_pair_name'] +'.ply') - image = imageio.imread(sample['ref_img_fi']) - - print(f"Running depth extraction at {time.time()}") - if config['use_boostmonodepth'] is True: - run_boostmonodepth(sample['ref_img_fi'], config['src_folder'], config['depth_folder']) - elif config['require_midas'] is True: - run_depth([sample['ref_img_fi']], config['src_folder'], config['depth_folder'], - config['MiDaS_model_ckpt'], MonoDepthNet, MiDaS_utils, target_w=640) - - if 'npy' in config['depth_format']: - config['output_h'], config['output_w'] = np.load(sample['depth_fi']).shape[:2] - else: - config['output_h'], config['output_w'] = imageio.imread(sample['depth_fi']).shape[:2] - frac = config['longer_side_len'] / max(config['output_h'], config['output_w']) - config['output_h'], config['output_w'] = int(config['output_h'] * frac), int(config['output_w'] * frac) - config['original_h'], config['original_w'] = config['output_h'], config['output_w'] - if image.ndim == 2: - image = image[..., None].repeat(3, -1) - if np.sum(np.abs(image[..., 0] - image[..., 1])) == 0 and np.sum(np.abs(image[..., 1] - image[..., 2])) == 0: - config['gray_image'] = True - else: - config['gray_image'] = False - image = cv2.resize(image, (config['output_w'], config['output_h']), interpolation=cv2.INTER_AREA) - depth = read_MiDaS_depth(sample['depth_fi'], 3.0, config['output_h'], config['output_w']) - mean_loc_depth = depth[depth.shape[0]//2, depth.shape[1]//2] - if not(config['load_ply'] is True and os.path.exists(mesh_fi)): - vis_photos, vis_depths = sparse_bilateral_filtering(depth.copy(), image.copy(), config, num_iter=config['sparse_iter'], spdb=False) - depth = vis_depths[-1] - model = None - torch.cuda.empty_cache() - print("Start Running 3D_Photo ...") - print(f"Loading edge model at {time.time()}") - depth_edge_model = Inpaint_Edge_Net(init_weights=True) - depth_edge_weight = torch.load(config['depth_edge_model_ckpt'], - map_location=torch.device(device)) - depth_edge_model.load_state_dict(depth_edge_weight) - depth_edge_model = depth_edge_model.to(device) - depth_edge_model.eval() - - print(f"Loading depth model at {time.time()}") - depth_feat_model = Inpaint_Depth_Net() - depth_feat_weight = torch.load(config['depth_feat_model_ckpt'], - map_location=torch.device(device)) - depth_feat_model.load_state_dict(depth_feat_weight, strict=True) - depth_feat_model = depth_feat_model.to(device) - depth_feat_model.eval() - depth_feat_model = depth_feat_model.to(device) - print(f"Loading rgb model at {time.time()}") - rgb_model = Inpaint_Color_Net() - rgb_feat_weight = torch.load(config['rgb_feat_model_ckpt'], - map_location=torch.device(device)) - rgb_model.load_state_dict(rgb_feat_weight) - rgb_model.eval() - rgb_model = rgb_model.to(device) - graph = None - - - print(f"Writing depth ply (and basically doing everything) at {time.time()}") - rt_info = write_ply(image, - depth, - sample['int_mtx'], - mesh_fi, - config, - rgb_model, - depth_edge_model, - depth_edge_model, - depth_feat_model) - - if rt_info is False: - continue - rgb_model = None - color_feat_model = None - depth_edge_model = None - depth_feat_model = None - torch.cuda.empty_cache() - if config['save_ply'] is True or config['load_ply'] is True: - verts, colors, faces, Height, Width, hFov, vFov = read_ply(mesh_fi) - else: - verts, colors, faces, Height, Width, hFov, vFov = rt_info - - - print(f"Making video at {time.time()}") - videos_poses, video_basename = copy.deepcopy(sample['tgts_poses']), sample['tgt_name'] - top = (config.get('original_h') // 2 - sample['int_mtx'][1, 2] * config['output_h']) - left = (config.get('original_w') // 2 - sample['int_mtx'][0, 2] * config['output_w']) - down, right = top + config['output_h'], left + config['output_w'] - border = [int(xx) for xx in [top, down, left, right]] - normal_canvas, all_canvas = output_3d_photo(verts.copy(), colors.copy(), faces.copy(), copy.deepcopy(Height), copy.deepcopy(Width), copy.deepcopy(hFov), copy.deepcopy(vFov), - copy.deepcopy(sample['tgt_pose']), sample['video_postfix'], copy.deepcopy(sample['ref_pose']), copy.deepcopy(config['video_folder']), - image.copy(), copy.deepcopy(sample['int_mtx']), config, image, - videos_poses, video_basename, config.get('original_h'), config.get('original_w'), border=border, depth=depth, normal_canvas=normal_canvas, all_canvas=all_canvas, - mean_loc_depth=mean_loc_depth) - -def resizer(input_img, max_img_size=512): - width, height = input_img.size - long_edge = height if height >= width else width - if long_edge > max_img_size: - ratio = max_img_size / long_edge - resized_width = int(ratio * width) - resized_height = int(ratio * height) - resized_input_img = input_img.resize((resized_width, resized_height), resample=2) - return resized_input_img - - else: - return input_img - -def main_app(input_img, num_frames, fps): - - # resize down - input_img = resizer(input_img) - - # Save image in necessary folder for inpainting - #img_name = Path(str(uuid.uuid4()) + '.jpg') - img_name = Path('sample.jpg') - save_folder = Path('image') - input_img.save(save_folder/img_name) - - inpaint(img_name, num_frames, fps) - - #subprocess.run('ls -l', shell=True) - #subprocess.run('ls image -l', shell=True) - #subprocess.run('ls video/ -l', shell=True) - - # Get output video path & return - input_img_path = str(save_folder/img_name) - out_vid_path = 'video/{0}_circle.mp4'.format(img_name.stem) - - return out_vid_path - -video_choices = ['dolly-zoom-in', 'zoom-in', 'circle', 'swing'] -gradio_inputs = [gr.inputs.Image(type='pil', label='Input Image'), - gr.inputs.Slider(minimum=60, maximum=240, step=1, default=120, label="Number of Frames"), - gr.inputs.Slider(minimum=10, maximum=40, step=1, default=20, label="Frames per Second (FPS)")] - -gradio_outputs = [gr.outputs.Video(label='Output Video')] -examples = [ ['moon.jpg'], ['dog.jpg'] ] - -description="Convert an image into a trajectory-following video. Images are automatically resized down to a max edge of 512. | NOTE: The current runtime for a sample is around 400-700 seconds. Running on a lower number of frames could help! Do be patient as this is on CPU-only, BUT if this space maybe gets a GPU one day, it's already configured to run with GPU-support :) If you have a GPU, feel free to use the author's original repo (linked at the bottom of this path, they have a collab notebook!) You can also run this space/gradio app locally!" - -article = "

      3D Photography using Context-aware Layered Depth Inpainting | Github Project Page | Github Repo

      " - -iface = gr.Interface(fn=main_app, inputs=gradio_inputs , outputs=gradio_outputs, examples=examples, - title='3D Image Inpainting', - description=description, - article=article, - enable_queue=True) - -iface.launch(debug=True) diff --git a/spaces/EronSamez/RVC_HFmeu/infer/lib/uvr5_pack/lib_v5/nets_537238KB.py b/spaces/EronSamez/RVC_HFmeu/infer/lib/uvr5_pack/lib_v5/nets_537238KB.py deleted file mode 100644 index 823b44fb64898e8dcbb12180ba45d1718f9b03f7..0000000000000000000000000000000000000000 --- a/spaces/EronSamez/RVC_HFmeu/infer/lib/uvr5_pack/lib_v5/nets_537238KB.py +++ /dev/null @@ -1,123 +0,0 @@ -import numpy as np -import torch -import torch.nn.functional as F -from torch import nn - -from . import layers_537238KB as layers - - -class BaseASPPNet(nn.Module): - def __init__(self, nin, ch, dilations=(4, 8, 16)): - super(BaseASPPNet, self).__init__() - self.enc1 = layers.Encoder(nin, ch, 3, 2, 1) - self.enc2 = layers.Encoder(ch, ch * 2, 3, 2, 1) - self.enc3 = layers.Encoder(ch * 2, ch * 4, 3, 2, 1) - self.enc4 = layers.Encoder(ch * 4, ch * 8, 3, 2, 1) - - self.aspp = layers.ASPPModule(ch * 8, ch * 16, dilations) - - self.dec4 = layers.Decoder(ch * (8 + 16), ch * 8, 3, 1, 1) - self.dec3 = layers.Decoder(ch * (4 + 8), ch * 4, 3, 1, 1) - self.dec2 = layers.Decoder(ch * (2 + 4), ch * 2, 3, 1, 1) - self.dec1 = layers.Decoder(ch * (1 + 2), ch, 3, 1, 1) - - def __call__(self, x): - h, e1 = self.enc1(x) - h, e2 = self.enc2(h) - h, e3 = self.enc3(h) - h, e4 = self.enc4(h) - - h = self.aspp(h) - - h = self.dec4(h, e4) - h = self.dec3(h, e3) - h = self.dec2(h, e2) - h = self.dec1(h, e1) - - return h - - -class CascadedASPPNet(nn.Module): - def __init__(self, n_fft): - super(CascadedASPPNet, self).__init__() - self.stg1_low_band_net = BaseASPPNet(2, 64) - self.stg1_high_band_net = BaseASPPNet(2, 64) - - self.stg2_bridge = layers.Conv2DBNActiv(66, 32, 1, 1, 0) - self.stg2_full_band_net = BaseASPPNet(32, 64) - - self.stg3_bridge = layers.Conv2DBNActiv(130, 64, 1, 1, 0) - self.stg3_full_band_net = BaseASPPNet(64, 128) - - self.out = nn.Conv2d(128, 2, 1, bias=False) - self.aux1_out = nn.Conv2d(64, 2, 1, bias=False) - self.aux2_out = nn.Conv2d(64, 2, 1, bias=False) - - self.max_bin = n_fft // 2 - self.output_bin = n_fft // 2 + 1 - - self.offset = 128 - - def forward(self, x, aggressiveness=None): - mix = x.detach() - x = x.clone() - - x = x[:, :, : self.max_bin] - - bandw = x.size()[2] // 2 - aux1 = torch.cat( - [ - self.stg1_low_band_net(x[:, :, :bandw]), - self.stg1_high_band_net(x[:, :, bandw:]), - ], - dim=2, - ) - - h = torch.cat([x, aux1], dim=1) - aux2 = self.stg2_full_band_net(self.stg2_bridge(h)) - - h = torch.cat([x, aux1, aux2], dim=1) - h = self.stg3_full_band_net(self.stg3_bridge(h)) - - mask = torch.sigmoid(self.out(h)) - mask = F.pad( - input=mask, - pad=(0, 0, 0, self.output_bin - mask.size()[2]), - mode="replicate", - ) - - if self.training: - aux1 = torch.sigmoid(self.aux1_out(aux1)) - aux1 = F.pad( - input=aux1, - pad=(0, 0, 0, self.output_bin - aux1.size()[2]), - mode="replicate", - ) - aux2 = torch.sigmoid(self.aux2_out(aux2)) - aux2 = F.pad( - input=aux2, - pad=(0, 0, 0, self.output_bin - aux2.size()[2]), - mode="replicate", - ) - return mask * mix, aux1 * mix, aux2 * mix - else: - if aggressiveness: - mask[:, :, : aggressiveness["split_bin"]] = torch.pow( - mask[:, :, : aggressiveness["split_bin"]], - 1 + aggressiveness["value"] / 3, - ) - mask[:, :, aggressiveness["split_bin"] :] = torch.pow( - mask[:, :, aggressiveness["split_bin"] :], - 1 + aggressiveness["value"], - ) - - return mask * mix - - def predict(self, x_mag, aggressiveness=None): - h = self.forward(x_mag, aggressiveness) - - if self.offset > 0: - h = h[:, :, :, self.offset : -self.offset] - assert h.size()[3] > 0 - - return h diff --git a/spaces/EuroPython2022/machinetestspace/README.md b/spaces/EuroPython2022/machinetestspace/README.md deleted file mode 100644 index 68babd962326c1a441fec1d0567befee4be54104..0000000000000000000000000000000000000000 --- a/spaces/EuroPython2022/machinetestspace/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Machinetestspace -emoji: 💩 -colorFrom: red -colorTo: yellow -sdk: gradio -sdk_version: 3.0.26 -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/FIT2125/stable-diffusion-webui-cpu/README.md b/spaces/FIT2125/stable-diffusion-webui-cpu/README.md deleted file mode 100644 index 1e8980b44168d44bb673b576698837102b4eb732..0000000000000000000000000000000000000000 --- a/spaces/FIT2125/stable-diffusion-webui-cpu/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Stable Diffusion Webui on Cpu -emoji: 🏃 -colorFrom: pink -colorTo: purple -sdk: gradio -sdk_version: 3.32.0 -app_file: app.py -pinned: false -python_version : 3.10.6 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/FlippFuzz/whisper-webui/src/hooks/whisperProgressHook.py b/spaces/FlippFuzz/whisper-webui/src/hooks/whisperProgressHook.py deleted file mode 100644 index aa09958a05e0b3c54736f7209f8a05a94912752e..0000000000000000000000000000000000000000 --- a/spaces/FlippFuzz/whisper-webui/src/hooks/whisperProgressHook.py +++ /dev/null @@ -1,91 +0,0 @@ -import sys -import threading -from typing import List, Union -import tqdm - -from src.hooks.progressListener import ProgressListener - -class ProgressListenerHandle: - def __init__(self, listener: ProgressListener): - self.listener = listener - - def __enter__(self): - register_thread_local_progress_listener(self.listener) - - def __exit__(self, exc_type, exc_val, exc_tb): - unregister_thread_local_progress_listener(self.listener) - - if exc_type is None: - self.listener.on_finished() - -class _CustomProgressBar(tqdm.tqdm): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._current = self.n # Set the initial value - - def update(self, n): - super().update(n) - # Because the progress bar might be disabled, we need to manually update the progress - self._current += n - - # Inform listeners - listeners = _get_thread_local_listeners() - - for listener in listeners: - listener.on_progress(self._current, self.total) - -_thread_local = threading.local() - -def _get_thread_local_listeners(): - if not hasattr(_thread_local, 'listeners'): - _thread_local.listeners = [] - return _thread_local.listeners - -_hooked = False - -def init_progress_hook(): - global _hooked - - if _hooked: - return - - # Inject into tqdm.tqdm of Whisper, so we can see progress - import whisper.transcribe - transcribe_module = sys.modules['whisper.transcribe'] - transcribe_module.tqdm.tqdm = _CustomProgressBar - _hooked = True - -def register_thread_local_progress_listener(progress_listener: ProgressListener): - # This is a workaround for the fact that the progress bar is not exposed in the API - init_progress_hook() - - listeners = _get_thread_local_listeners() - listeners.append(progress_listener) - -def unregister_thread_local_progress_listener(progress_listener: ProgressListener): - listeners = _get_thread_local_listeners() - - if progress_listener in listeners: - listeners.remove(progress_listener) - -def create_progress_listener_handle(progress_listener: ProgressListener): - return ProgressListenerHandle(progress_listener) - -# Example usage -if __name__ == '__main__': - class PrintingProgressListener: - def on_progress(self, current: Union[int, float], total: Union[int, float]): - print(f"Progress: {current}/{total}") - - def on_finished(self): - print("Finished") - - import whisper - model = whisper.load_model("medium") - - with create_progress_listener_handle(PrintingProgressListener()) as listener: - # Set verbose to None to disable the progress bar, as we are using our own - result = model.transcribe("J:\\Dev\\OpenAI\\whisper\\tests\\Noriko\\out.mka", language="Japanese", fp16=False, verbose=None) - print(result) - - print("Done") \ No newline at end of file diff --git a/spaces/Fox1997/vits-uma-genshin-honkai/modules.py b/spaces/Fox1997/vits-uma-genshin-honkai/modules.py deleted file mode 100644 index 56ea4145eddf19dd330a3a41ab0183efc1686d83..0000000000000000000000000000000000000000 --- a/spaces/Fox1997/vits-uma-genshin-honkai/modules.py +++ /dev/null @@ -1,388 +0,0 @@ -import math -import numpy as np -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 -from transforms import piecewise_rational_quadratic_transform - - -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 - - -class ConvFlow(nn.Module): - def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0): - super().__init__() - self.in_channels = in_channels - self.filter_channels = filter_channels - self.kernel_size = kernel_size - self.n_layers = n_layers - self.num_bins = num_bins - self.tail_bound = tail_bound - self.half_channels = in_channels // 2 - - self.pre = nn.Conv1d(self.half_channels, filter_channels, 1) - self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.) - self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1) - self.proj.weight.data.zero_() - self.proj.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) - h = self.convs(h, x_mask, g=g) - h = self.proj(h) * x_mask - - b, c, t = x0.shape - h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?] - - unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels) - unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels) - unnormalized_derivatives = h[..., 2 * self.num_bins:] - - x1, logabsdet = piecewise_rational_quadratic_transform(x1, - unnormalized_widths, - unnormalized_heights, - unnormalized_derivatives, - inverse=reverse, - tails='linear', - tail_bound=self.tail_bound - ) - - x = torch.cat([x0, x1], 1) * x_mask - logdet = torch.sum(logabsdet * x_mask, [1,2]) - if not reverse: - return x, logdet - else: - return x diff --git a/spaces/FrankZxShen/so-vits-svc-models-ba/inference/slicer.py b/spaces/FrankZxShen/so-vits-svc-models-ba/inference/slicer.py deleted file mode 100644 index b05840bcf6bdced0b6e2adbecb1a1dd5b3dee462..0000000000000000000000000000000000000000 --- a/spaces/FrankZxShen/so-vits-svc-models-ba/inference/slicer.py +++ /dev/null @@ -1,142 +0,0 @@ -import librosa -import torch -import torchaudio - - -class Slicer: - def __init__(self, - sr: int, - threshold: float = -40., - min_length: int = 5000, - min_interval: int = 300, - hop_size: int = 20, - max_sil_kept: int = 5000): - if not min_length >= min_interval >= hop_size: - raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size') - if not max_sil_kept >= hop_size: - raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size') - min_interval = sr * min_interval / 1000 - self.threshold = 10 ** (threshold / 20.) - self.hop_size = round(sr * hop_size / 1000) - self.win_size = min(round(min_interval), 4 * self.hop_size) - self.min_length = round(sr * min_length / 1000 / self.hop_size) - self.min_interval = round(min_interval / self.hop_size) - self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size) - - def _apply_slice(self, waveform, begin, end): - if len(waveform.shape) > 1: - return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)] - else: - return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)] - - # @timeit - def slice(self, waveform): - if len(waveform.shape) > 1: - samples = librosa.to_mono(waveform) - else: - samples = waveform - if samples.shape[0] <= self.min_length: - return {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}} - rms_list = librosa.feature.rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0) - sil_tags = [] - silence_start = None - clip_start = 0 - for i, rms in enumerate(rms_list): - # Keep looping while frame is silent. - if rms < self.threshold: - # Record start of silent frames. - if silence_start is None: - silence_start = i - continue - # Keep looping while frame is not silent and silence start has not been recorded. - if silence_start is None: - continue - # Clear recorded silence start if interval is not enough or clip is too short - is_leading_silence = silence_start == 0 and i > self.max_sil_kept - need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length - if not is_leading_silence and not need_slice_middle: - silence_start = None - continue - # Need slicing. Record the range of silent frames to be removed. - if i - silence_start <= self.max_sil_kept: - pos = rms_list[silence_start: i + 1].argmin() + silence_start - if silence_start == 0: - sil_tags.append((0, pos)) - else: - sil_tags.append((pos, pos)) - clip_start = pos - elif i - silence_start <= self.max_sil_kept * 2: - pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin() - pos += i - self.max_sil_kept - pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start - pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept - if silence_start == 0: - sil_tags.append((0, pos_r)) - clip_start = pos_r - else: - sil_tags.append((min(pos_l, pos), max(pos_r, pos))) - clip_start = max(pos_r, pos) - else: - pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start - pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept - if silence_start == 0: - sil_tags.append((0, pos_r)) - else: - sil_tags.append((pos_l, pos_r)) - clip_start = pos_r - silence_start = None - # Deal with trailing silence. - total_frames = rms_list.shape[0] - if silence_start is not None and total_frames - silence_start >= self.min_interval: - silence_end = min(total_frames, silence_start + self.max_sil_kept) - pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start - sil_tags.append((pos, total_frames + 1)) - # Apply and return slices. - if len(sil_tags) == 0: - return {"0": {"slice": False, "split_time": f"0,{len(waveform)}"}} - else: - chunks = [] - # 第一段静音并非从头开始,补上有声片段 - if sil_tags[0][0]: - chunks.append( - {"slice": False, "split_time": f"0,{min(waveform.shape[0], sil_tags[0][0] * self.hop_size)}"}) - for i in range(0, len(sil_tags)): - # 标识有声片段(跳过第一段) - if i: - chunks.append({"slice": False, - "split_time": f"{sil_tags[i - 1][1] * self.hop_size},{min(waveform.shape[0], sil_tags[i][0] * self.hop_size)}"}) - # 标识所有静音片段 - chunks.append({"slice": True, - "split_time": f"{sil_tags[i][0] * self.hop_size},{min(waveform.shape[0], sil_tags[i][1] * self.hop_size)}"}) - # 最后一段静音并非结尾,补上结尾片段 - if sil_tags[-1][1] * self.hop_size < len(waveform): - chunks.append({"slice": False, "split_time": f"{sil_tags[-1][1] * self.hop_size},{len(waveform)}"}) - chunk_dict = {} - for i in range(len(chunks)): - chunk_dict[str(i)] = chunks[i] - return chunk_dict - - -def cut(audio_path, db_thresh=-30, min_len=5000): - audio, sr = librosa.load(audio_path, sr=None) - slicer = Slicer( - sr=sr, - threshold=db_thresh, - min_length=min_len - ) - chunks = slicer.slice(audio) - return chunks - - -def chunks2audio(audio_path, chunks): - chunks = dict(chunks) - audio, sr = torchaudio.load(audio_path) - if len(audio.shape) == 2 and audio.shape[1] >= 2: - audio = torch.mean(audio, dim=0).unsqueeze(0) - audio = audio.cpu().numpy()[0] - result = [] - for k, v in chunks.items(): - tag = v["split_time"].split(",") - if tag[0] != tag[1]: - result.append((v["slice"], audio[int(tag[0]):int(tag[1])])) - return result, sr diff --git a/spaces/Gamero-xD/stabilityai-stable-diffusion-2-1/README.md b/spaces/Gamero-xD/stabilityai-stable-diffusion-2-1/README.md deleted file mode 100644 index 87b490f1f232db1fe65e6cb7044488e0a6397fb6..0000000000000000000000000000000000000000 --- a/spaces/Gamero-xD/stabilityai-stable-diffusion-2-1/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Stabilityai Stable Diffusion 2 1 -emoji: 🔥 -colorFrom: green -colorTo: gray -sdk: gradio -sdk_version: 3.34.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/Gradio-Blocks/uniformer_image_detection/configs/retinanet/retinanet_r50_caffe_fpn_mstrain_3x_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/retinanet/retinanet_r50_caffe_fpn_mstrain_3x_coco.py deleted file mode 100644 index 8057650736eaab0b7b01a7957339124f73d6d6b0..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/retinanet/retinanet_r50_caffe_fpn_mstrain_3x_coco.py +++ /dev/null @@ -1,4 +0,0 @@ -_base_ = './retinanet_r50_caffe_fpn_mstrain_1x_coco.py' -# learning policy -lr_config = dict(step=[28, 34]) -runner = dict(type='EpochBasedRunner', max_epochs=36) diff --git a/spaces/GrandaddyShmax/MusicGen_Plus/CHANGELOG.md b/spaces/GrandaddyShmax/MusicGen_Plus/CHANGELOG.md deleted file mode 100644 index 24fc214df236b40efead4b1585b01632d9658e9b..0000000000000000000000000000000000000000 --- a/spaces/GrandaddyShmax/MusicGen_Plus/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/Grezz/generate_human_motion/pyrender/tests/unit/test_nodes.py b/spaces/Grezz/generate_human_motion/pyrender/tests/unit/test_nodes.py deleted file mode 100644 index 9857c8221b7f6fb8530699bdf5593f8f0b74e152..0000000000000000000000000000000000000000 --- a/spaces/Grezz/generate_human_motion/pyrender/tests/unit/test_nodes.py +++ /dev/null @@ -1,124 +0,0 @@ -import numpy as np -import pytest -from trimesh import transformations - -from pyrender import (DirectionalLight, PerspectiveCamera, Mesh, Node) - - -def test_nodes(): - - x = Node() - assert x.name is None - assert x.camera is None - assert x.children == [] - assert x.skin is None - assert np.allclose(x.matrix, np.eye(4)) - assert x.mesh is None - assert np.allclose(x.rotation, [0,0,0,1]) - assert np.allclose(x.scale, np.ones(3)) - assert np.allclose(x.translation, np.zeros(3)) - assert x.weights is None - assert x.light is None - - x.name = 'node' - - # Test node light/camera/mesh tests - c = PerspectiveCamera(yfov=2.0) - m = Mesh([]) - d = DirectionalLight() - x.camera = c - assert x.camera == c - with pytest.raises(TypeError): - x.camera = m - x.camera = d - x.camera = None - x.mesh = m - assert x.mesh == m - with pytest.raises(TypeError): - x.mesh = c - x.mesh = d - x.light = d - assert x.light == d - with pytest.raises(TypeError): - x.light = m - x.light = c - - # Test transformations getters/setters/etc... - # Set up test values - x = np.array([1.0, 0.0, 0.0]) - y = np.array([0.0, 1.0, 0.0]) - t = np.array([1.0, 2.0, 3.0]) - s = np.array([0.5, 2.0, 1.0]) - - Mx = transformations.rotation_matrix(np.pi / 2.0, x) - qx = np.roll(transformations.quaternion_about_axis(np.pi / 2.0, x), -1) - Mxt = Mx.copy() - Mxt[:3,3] = t - S = np.eye(4) - S[:3,:3] = np.diag(s) - Mxts = Mxt.dot(S) - - My = transformations.rotation_matrix(np.pi / 2.0, y) - qy = np.roll(transformations.quaternion_about_axis(np.pi / 2.0, y), -1) - Myt = My.copy() - Myt[:3,3] = t - - x = Node(matrix=Mx) - assert np.allclose(x.matrix, Mx) - assert np.allclose(x.rotation, qx) - assert np.allclose(x.translation, np.zeros(3)) - assert np.allclose(x.scale, np.ones(3)) - - x.matrix = My - assert np.allclose(x.matrix, My) - assert np.allclose(x.rotation, qy) - assert np.allclose(x.translation, np.zeros(3)) - assert np.allclose(x.scale, np.ones(3)) - x.translation = t - assert np.allclose(x.matrix, Myt) - assert np.allclose(x.rotation, qy) - x.rotation = qx - assert np.allclose(x.matrix, Mxt) - x.scale = s - assert np.allclose(x.matrix, Mxts) - - x = Node(matrix=Mxt) - assert np.allclose(x.matrix, Mxt) - assert np.allclose(x.rotation, qx) - assert np.allclose(x.translation, t) - assert np.allclose(x.scale, np.ones(3)) - - x = Node(matrix=Mxts) - assert np.allclose(x.matrix, Mxts) - assert np.allclose(x.rotation, qx) - assert np.allclose(x.translation, t) - assert np.allclose(x.scale, s) - - # Individual element getters - x.scale[0] = 0 - assert np.allclose(x.scale[0], 0) - - x.translation[0] = 0 - assert np.allclose(x.translation[0], 0) - - x.matrix = np.eye(4) - x.matrix[0,0] = 500 - assert x.matrix[0,0] == 1.0 - - # Failures - with pytest.raises(ValueError): - x.matrix = 5 * np.eye(4) - with pytest.raises(ValueError): - x.matrix = np.eye(5) - with pytest.raises(ValueError): - x.matrix = np.eye(4).dot([5,1,1,1]) - with pytest.raises(ValueError): - x.rotation = np.array([1,2]) - with pytest.raises(ValueError): - x.rotation = np.array([1,2,3]) - with pytest.raises(ValueError): - x.rotation = np.array([1,2,3,4]) - with pytest.raises(ValueError): - x.translation = np.array([1,2,3,4]) - with pytest.raises(ValueError): - x.scale = np.array([1,2,3,4]) diff --git a/spaces/GroveStreet/GTA_SOVITS/vencoder/dphubert/pruning_utils.py b/spaces/GroveStreet/GTA_SOVITS/vencoder/dphubert/pruning_utils.py deleted file mode 100644 index ac185980c2c3da716bf3ce402a541ffe70776acf..0000000000000000000000000000000000000000 --- a/spaces/GroveStreet/GTA_SOVITS/vencoder/dphubert/pruning_utils.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Utility functions for pruning.""" - -from typing import Union - -import torch -import torch.nn as nn - - -def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: str): - "Prune linear layer in place." - # NOTE: weight: (out_features, in_features), bias: (out_features,) - if dim == "input": - dim = 1 - layer.in_features = len(index) - elif dim == "output": - dim = 0 - layer.out_features = len(index) - else: - raise ValueError - - layer.weight = nn.Parameter(layer.weight.index_select(dim, index).clone().detach()) - if layer.bias is not None and dim == 0: - layer.bias = nn.Parameter(layer.bias.index_select(0, index).clone().detach()) - - -def prune_conv1d_layer(layer: nn.Conv1d, index: torch.LongTensor, dim: str): - """Prune conv1d in place.""" - # NOTE: weight: (out_channels, in_channels, kernel_size), bias: (out_channels,) - if dim == "input": - dim = 1 - layer.in_channels = len(index) - elif dim == "output": - dim = 0 - layer.out_channels = len(index) - else: - raise ValueError - - layer.weight = nn.Parameter(layer.weight.index_select(dim, index).clone().detach()) - if layer.bias is not None and dim == 0: - layer.bias = nn.Parameter(layer.bias.index_select(0, index).clone().detach()) - - -def prune_layer_norm(layernorm: Union[nn.LayerNorm, nn.GroupNorm], index: torch.LongTensor): - """Prune layer norm or group norm in place.""" - layernorm.weight = nn.Parameter(layernorm.weight.index_select(0, index).clone().detach()) - layernorm.bias = nn.Parameter(layernorm.bias.index_select(0, index).clone().detach()) - if isinstance(layernorm, nn.LayerNorm): - layernorm.normalized_shape = (len(index),) - elif isinstance(layernorm, nn.GroupNorm): - layernorm.num_groups = len(index) - layernorm.num_channels = len(index) diff --git a/spaces/HaloMaster/chinesesummary/fengshen/data/bert_dataloader/load.py b/spaces/HaloMaster/chinesesummary/fengshen/data/bert_dataloader/load.py deleted file mode 100644 index b36ce8ae72b74e9fd006f087ee0810a306badd7e..0000000000000000000000000000000000000000 --- a/spaces/HaloMaster/chinesesummary/fengshen/data/bert_dataloader/load.py +++ /dev/null @@ -1,200 +0,0 @@ -import os -import re -from pathlib import Path -import glob -from tqdm import tqdm -from contextlib import ExitStack -import datasets -import multiprocessing -from typing import cast, TextIO -from itertools import chain -import json -from concurrent.futures import ProcessPoolExecutor -from random import shuffle -from pytorch_lightning import LightningDataModule -from typing import Optional - -from torch.utils.data import DataLoader - - -# _SPLIT_DATA_PATH = '/data1/datas/wudao_180g_split/test' -_SPLIT_DATA_PATH = '/data1/datas/wudao_180g_split' -_CACHE_SPLIT_DATA_PATH = '/data1/datas/wudao_180g_FSData' - -# feats = datasets.Features({"text": datasets.Value('string')}) - - -class BertDataGenerate(object): - - def __init__(self, - data_files=_SPLIT_DATA_PATH, - save_path=_CACHE_SPLIT_DATA_PATH, - train_test_validation='950,49,1', - num_proc=1, - cache=True): - self.data_files = Path(data_files) - if save_path: - self.save_path = Path(save_path) - else: - self.save_path = self.file_check( - Path(self.data_files.parent, self.data_files.name+'_FSDataset'), - 'save') - self.num_proc = num_proc - self.cache = cache - self.split_idx = self.split_train_test_validation_index(train_test_validation) - if cache: - self.cache_path = self.file_check( - Path(self.save_path.parent, 'FSDataCache', self.data_files.name), 'cache') - else: - self.cache_path = None - - @staticmethod - def file_check(path, path_type): - print(path) - if not path.exists(): - path.mkdir(parents=True) - print(f"Since no {path_type} directory is specified, the program will automatically create it in {path} directory.") - return str(path) - - @staticmethod - def split_train_test_validation_index(train_test_validation): - split_idx_ = [int(i) for i in train_test_validation.split(',')] - idx_dict = { - 'train_rate': split_idx_[0]/sum(split_idx_), - 'test_rate': split_idx_[1]/sum(split_idx_[1:]) - } - return idx_dict - - def process(self, index, path): - print('saving dataset shard {}'.format(index)) - - ds = (datasets.load_dataset('json', data_files=str(path), - cache_dir=self.cache_path, - features=None)) - # ds = ds.map(self.cut_sent,input_columns='text') - # print(d) - # print('!!!',ds) - ds = ds['train'].train_test_split(train_size=self.split_idx['train_rate']) - ds_ = ds['test'].train_test_split(train_size=self.split_idx['test_rate']) - ds = datasets.DatasetDict({ - 'train': ds['train'], - 'test': ds_['train'], - 'validation': ds_['test'] - }) - # print('!!!!',ds) - ds.save_to_disk(Path(self.save_path, path.name)) - return 'saving dataset shard {} done'.format(index) - - def generate_cache_arrow(self) -> None: - ''' - 生成HF支持的缓存文件,加速后续的加载 - ''' - data_dict_paths = self.data_files.rglob('*') - p = ProcessPoolExecutor(max_workers=self.num_proc) - res = list() - - for index, path in enumerate(data_dict_paths): - res.append(p.submit(self.process, index, path)) - - p.shutdown(wait=True) - for future in res: - print(future.result(), flush=True) - - -def load_dataset(num_proc=4, **kargs): - cache_dict_paths = Path(_CACHE_SPLIT_DATA_PATH).glob('*') - ds = [] - res = [] - p = ProcessPoolExecutor(max_workers=num_proc) - for path in cache_dict_paths: - res.append(p.submit(datasets.load_from_disk, - str(path), **kargs)) - - p.shutdown(wait=True) - for future in res: - ds.append(future.result()) - # print(future.result()) - train = [] - test = [] - validation = [] - for ds_ in ds: - train.append(ds_['train']) - test.append(ds_['test']) - validation.append(ds_['validation']) - # ds = datasets.concatenate_datasets(ds) - # print(ds) - return datasets.DatasetDict({ - 'train': datasets.concatenate_datasets(train), - 'test': datasets.concatenate_datasets(test), - 'validation': datasets.concatenate_datasets(validation) - }) - - -class BertDataModule(LightningDataModule): - @ staticmethod - def add_data_specific_args(parent_args): - parser = parent_args.add_argument_group('Universal DataModule') - parser.add_argument('--num_workers', default=8, type=int) - parser.add_argument('--train_batchsize', default=32, type=int) - parser.add_argument('--val_batchsize', default=32, type=int) - parser.add_argument('--test_batchsize', default=32, type=int) - parser.add_argument('--datasets_name', type=str) - # parser.add_argument('--datasets_name', type=str) - parser.add_argument('--train_datasets_field', type=str, default='train') - parser.add_argument('--val_datasets_field', type=str, default='validation') - parser.add_argument('--test_datasets_field', type=str, default='test') - return parent_args - - def __init__( - self, - tokenizer, - collate_fn, - args, - **kwargs, - ): - super().__init__() - self.datasets = load_dataset(num_proc=args.num_workers) - self.tokenizer = tokenizer - self.collate_fn = collate_fn - self.save_hyperparameters(args) - - def setup(self, stage: Optional[str] = None) -> None: - self.train = DataLoader( - self.datasets[self.hparams.train_datasets_field], - batch_size=self.hparams.train_batchsize, - shuffle=True, - num_workers=self.hparams.num_workers, - collate_fn=self.collate_fn, - ) - self.val = DataLoader( - self.datasets[self.hparams.val_datasets_field], - batch_size=self.hparams.val_batchsize, - shuffle=False, - num_workers=self.hparams.num_workers, - collate_fn=self.collate_fn, - ) - self.test = DataLoader( - self.datasets[self.hparams.test_datasets_field], - batch_size=self.hparams.test_batchsize, - shuffle=False, - num_workers=self.hparams.num_workers, - collate_fn=self.collate_fn, - ) - return - - def train_dataloader(self): - return self.train - - def val_dataloader(self): - return self.val - - def test_dataloader(self): - return self.test - - -if __name__ == '__main__': - # pre = PreProcessing(_SPLIT_DATA_PATH) - # pre.processing() - - dataset = BertDataGenerate(_SPLIT_DATA_PATH, num_proc=16) - dataset.generate_cache_arrow() diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/cross_entropy.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/cross_entropy.py deleted file mode 100644 index fe461064716b38ecf2eb610daddbb609a1884e6b..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/cross_entropy.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import math -from dataclasses import dataclass - -import torch.nn.functional as F -from fairseq import metrics, utils -from fairseq.criterions import FairseqCriterion, register_criterion -from fairseq.dataclass import FairseqDataclass -from omegaconf import II - - -@dataclass -class CrossEntropyCriterionConfig(FairseqDataclass): - sentence_avg: bool = II("optimization.sentence_avg") - - -@register_criterion("cross_entropy", dataclass=CrossEntropyCriterionConfig) -class CrossEntropyCriterion(FairseqCriterion): - def __init__(self, task, sentence_avg): - super().__init__(task) - self.sentence_avg = sentence_avg - - def forward(self, model, sample, reduce=True): - """Compute the loss for the given sample. - - Returns a tuple with three elements: - 1) the loss - 2) the sample size, which is used as the denominator for the gradient - 3) logging outputs to display while training - """ - net_output = model(**sample["net_input"]) - loss, _ = self.compute_loss(model, net_output, sample, reduce=reduce) - sample_size = ( - sample["target"].size(0) if self.sentence_avg else sample["ntokens"] - ) - logging_output = { - "loss": loss.data, - "ntokens": sample["ntokens"], - "nsentences": sample["target"].size(0), - "sample_size": sample_size, - } - return loss, sample_size, logging_output - - def compute_loss(self, model, net_output, sample, reduce=True): - lprobs = model.get_normalized_probs(net_output, log_probs=True) - lprobs = lprobs.view(-1, lprobs.size(-1)) - target = model.get_targets(sample, net_output).view(-1) - loss = F.nll_loss( - lprobs, - target, - ignore_index=self.padding_idx, - reduction="sum" if reduce else "none", - ) - return loss, loss - - @staticmethod - def reduce_metrics(logging_outputs) -> None: - """Aggregate logging outputs from data parallel training.""" - loss_sum = sum(log.get("loss", 0) for log in logging_outputs) - ntokens = sum(log.get("ntokens", 0) for log in logging_outputs) - sample_size = sum(log.get("sample_size", 0) for log in logging_outputs) - - # we divide by log(2) to convert the loss from base e to base 2 - metrics.log_scalar( - "loss", loss_sum / sample_size / math.log(2), sample_size, round=3 - ) - if sample_size != ntokens: - metrics.log_scalar( - "nll_loss", loss_sum / ntokens / math.log(2), ntokens, round=3 - ) - metrics.log_derived( - "ppl", lambda meters: utils.get_perplexity(meters["nll_loss"].avg) - ) - else: - metrics.log_derived( - "ppl", lambda meters: utils.get_perplexity(meters["loss"].avg) - ) - - @staticmethod - def logging_outputs_can_be_summed() -> bool: - """ - Whether the logging outputs returned by `forward` can be summed - across workers prior to calling `reduce_metrics`. Setting this - to True will improves distributed training speed. - """ - return True diff --git a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/fairseq_criterion.py b/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/fairseq_criterion.py deleted file mode 100644 index ff4beb02503ea48a6c09596630aad4c710be94b6..0000000000000000000000000000000000000000 --- a/spaces/HarryLee/eCommerceImageCaptioning/fairseq/fairseq/criterions/fairseq_criterion.py +++ /dev/null @@ -1,120 +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 inspect -from typing import Any, Dict, List - -from fairseq import metrics, utils -from fairseq.dataclass import FairseqDataclass -from fairseq.dataclass.utils import gen_parser_from_dataclass -from torch.nn.modules.loss import _Loss - - -class FairseqCriterion(_Loss): - def __init__(self, task): - super().__init__() - self.task = task - if hasattr(task, "target_dictionary"): - tgt_dict = task.target_dictionary - self.padding_idx = tgt_dict.pad() if tgt_dict is not None else -100 - - @classmethod - def add_args(cls, parser): - """Add criterion-specific arguments to the parser.""" - dc = getattr(cls, "__dataclass", None) - if dc is not None: - gen_parser_from_dataclass(parser, dc()) - - @classmethod - def build_criterion(cls, cfg: FairseqDataclass, task): - """Construct a criterion from command-line args.""" - # arguments in the __init__. - init_args = {} - for p in inspect.signature(cls).parameters.values(): - if ( - p.kind == p.POSITIONAL_ONLY - or p.kind == p.VAR_POSITIONAL - or p.kind == p.VAR_KEYWORD - ): - # we haven't implemented inference for these argument types, - # but PRs welcome :) - raise NotImplementedError("{} not supported".format(p.kind)) - - assert p.kind in {p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY} - - if p.name == "task": - init_args["task"] = task - elif p.name == "cfg": - init_args["cfg"] = cfg - elif hasattr(cfg, p.name): - init_args[p.name] = getattr(cfg, p.name) - elif p.default != p.empty: - pass # we'll use the default value - else: - raise NotImplementedError( - "Unable to infer Criterion arguments, please implement " - "{}.build_criterion".format(cls.__name__) - ) - return cls(**init_args) - - def forward(self, model, sample, reduce=True): - """Compute the loss for the given sample. - - Returns a tuple with three elements: - 1) the loss - 2) the sample size, which is used as the denominator for the gradient - 3) logging outputs to display while training - """ - raise NotImplementedError - - @staticmethod - def aggregate_logging_outputs( - logging_outputs: List[Dict[str, Any]] - ) -> Dict[str, Any]: - """Aggregate logging outputs from data parallel training.""" - utils.deprecation_warning( - "The aggregate_logging_outputs API is deprecated. " - "Please use the reduce_metrics API instead." - ) - raise NotImplementedError - - @classmethod - def reduce_metrics(cls, logging_outputs: List[Dict[str, Any]]) -> None: - """Aggregate logging outputs from data parallel training.""" - utils.deprecation_warning( - "Criterions should implement the reduce_metrics API. " - "Falling back to deprecated aggregate_logging_outputs API." - ) - agg_logging_outputs = cls.aggregate_logging_outputs(logging_outputs) - for k, v in agg_logging_outputs.items(): - if k in {"nsentences", "ntokens", "sample_size"}: - continue - metrics.log_scalar(k, v) - - @staticmethod - def logging_outputs_can_be_summed() -> bool: - """ - Whether the logging outputs returned by `forward` can be summed - across workers prior to calling `reduce_metrics`. Setting this - to True will improves distributed training speed. - """ - return False - - -class LegacyFairseqCriterion(FairseqCriterion): - def __init__(self, args, task): - super().__init__(task=task) - self.args = args - - utils.deprecation_warning( - "Criterions should take explicit arguments instead of an " - "argparse.Namespace object, please update your criterion by " - "extending FairseqCriterion instead of LegacyFairseqCriterion." - ) - - @classmethod - def build_criterion(cls, args, task): - """Construct a criterion from command-line args.""" - return cls(args, task) diff --git a/spaces/Harveenchadha/oiTrans/scripts/add_joint_tags_translate.py b/spaces/Harveenchadha/oiTrans/scripts/add_joint_tags_translate.py deleted file mode 100644 index 532731b38615cf847dc3dc1661c88641df55d673..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/oiTrans/scripts/add_joint_tags_translate.py +++ /dev/null @@ -1,61 +0,0 @@ -import sys -from tqdm import tqdm -import os - - -def add_token(sent, tag_infos): - """ add special tokens specified by tag_infos to each element in list - - tag_infos: list of tuples (tag_type,tag) - - each tag_info results in a token of the form: __{tag_type}__{tag}__ - - """ - - tokens = [] - for tag_type, tag in tag_infos: - token = '__' + tag_type + '__' + tag + '__' - tokens.append(token) - - return ' '.join(tokens) + ' ' + sent - - -def generate_lang_tag_iterator(infname): - with open(infname, 'r', encoding='utf-8') as infile: - for line in infile: - src, tgt, count = line.strip().split('\t') - count = int(count) - for _ in range(count): - yield (src, tgt) - - -if __name__ == '__main__': - - expdir = sys.argv[1] - dset = sys.argv[2] - - src_fname = '{expdir}/bpe/{dset}.SRC'.format( - expdir=expdir, dset=dset) - tgt_fname = '{expdir}/bpe/{dset}.TGT'.format( - expdir=expdir, dset=dset) - meta_fname = '{expdir}/data/{dset}_lang_pairs.txt'.format( - expdir=expdir, dset=dset) - - out_src_fname = '{expdir}/final/{dset}.SRC'.format( - expdir=expdir, dset=dset) - out_tgt_fname = '{expdir}/final/{dset}.TGT'.format( - expdir=expdir, dset=dset) - lang_tag_iterator = generate_lang_tag_iterator(meta_fname) - - os.makedirs('{expdir}/final'.format(expdir=expdir), exist_ok=True) - - with open(src_fname, 'r', encoding='utf-8') as srcfile, \ - open(tgt_fname, 'r', encoding='utf-8') as tgtfile, \ - open(out_src_fname, 'w', encoding='utf-8') as outsrcfile, \ - open(out_tgt_fname, 'w', encoding='utf-8') as outtgtfile: - - for (l1, l2), src_sent, tgt_sent in tqdm(zip(lang_tag_iterator, - srcfile, tgtfile)): - outsrcfile.write(add_token(src_sent.strip(), [ - ('src', l1), ('tgt', l2)]) + '\n') - outtgtfile.write(tgt_sent.strip() + '\n') diff --git a/spaces/Heisenberg08/Text2SQL/app.py b/spaces/Heisenberg08/Text2SQL/app.py deleted file mode 100644 index fb6d14e45995c8a5b318fcf8eb373fe90cde293d..0000000000000000000000000000000000000000 --- a/spaces/Heisenberg08/Text2SQL/app.py +++ /dev/null @@ -1,76 +0,0 @@ -import streamlit as st -import torch -import transformers -from transformers import AutoTokenizer, AutoModelWithLMHead - -device=torch.device("cuda" if torch.cuda.is_available() else "cpu") -# device=torch.device("cpu") - -tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neo-125M") -# model=torch.load("Gpt_neo_Epoch_10_Loss_031_data_5000.pth",map_location=torch.device('cpu')) -torch.manual_seed(0) -model=torch.load("Gpt_neo_Epoch_10_Loss_031_data_5000.pth",map_location=device) - -def predict_query(input_sentence,max_len=40,temp=0.7): - pred=[] - seq=tokenizer(input_sentence,return_tensors='pt')['input_ids'].to(device) - outputs=model.generate(seq, - max_length=max_len, - do_sample=True, - top_p=0.95, - #num_beams=5, - temperature=temp, - no_repeat_ngram_size=3, - num_return_sequences=5 - ).to(device) - for i,out in enumerate(outputs): - out=tokenizer.decode(out, skip_special_tokens=True) - idx=out.find("<|sep|>")+7 - out=out[idx:] - # print(f"Sugestion{i} :{out}") - print("Sugestion: ",out) - - pred.append(out) - return pred -# option = st.selectbox( -# 'Please Select option', -# ('Predictive writing',"None"),index=1) - - -st.title("Text2SQL") -st.write('# Generate SQL Query with Natural Language sentence') -st.markdown("Creator: [Pranav Kushare] (https://github.com/Pranav082001)") - -st.sidebar.markdown( - ''' - ## Select Hyperparameters -''') -max_len = st.sidebar.slider(label='Output Size', min_value=1, max_value=150, value=40, step=1) -# samples = st.sidebar.slider(label='Number of Samples', min_value=1, max_value=50, value=10, step=1) -temp = st.sidebar.slider(label='Temperature (Creativity)', min_value=0.0, max_value=2.0, value=0.7, step=0.1) -# temp = st.sidebar.slider(label='Temperature', min_value=0.1, max_value=1.0, value=5.0, step=0.05) -# do_sample=st.sidebar.checkbox("do_sample") - - - -# max_len=st.slider("max_len",1,100,None,1,key="max_len") -# top_k=st.slider("top_k",1,50,None,1) -# do_sample=st.checkbox("do_sample") -# print(max_len) -sentence = st.text_area('Input your sentence here:') -st.markdown('Example: "Find Average Salary of Employees"') -Enter=st.button("Generate") -clear=st.button("Clear") - -if clear: - print(clear) - st.markdown(' ') - -if Enter: - st.header("Output-") - print("Generating predictions......\n\n") - # out=generate(sentence,max_len,top_k,do_sample) - torch.manual_seed(0) - out=predict_query(sentence,max_len,temp) - for i,out in enumerate(out): - st.markdown(f"Query {i} :{out}") diff --git a/spaces/HgMenon/Transcribe_V0.2/src/source.py b/spaces/HgMenon/Transcribe_V0.2/src/source.py deleted file mode 100644 index e304e278bfae8ef289c999fc76311ce01b547991..0000000000000000000000000000000000000000 --- a/spaces/HgMenon/Transcribe_V0.2/src/source.py +++ /dev/null @@ -1,80 +0,0 @@ -# Gradio seems to truncate files without keeping the extension, so we need to truncate the file prefix ourself -import os -import pathlib -from typing import List -import zipfile - -import ffmpeg -from more_itertools import unzip - -from src.download import ExceededMaximumDuration, download_url - -MAX_FILE_PREFIX_LENGTH = 17 - -class AudioSource: - def __init__(self, source_path, source_name = None, audio_duration = None): - self.source_path = source_path - self.source_name = source_name - self._audio_duration = audio_duration - - # Load source name if not provided - if (self.source_name is None): - file_path = pathlib.Path(self.source_path) - self.source_name = file_path.name - - def get_audio_duration(self): - if self._audio_duration is None: - self._audio_duration = float(ffmpeg.probe(self.source_path)["format"]["duration"]) - - return self._audio_duration - - def get_full_name(self): - return self.source_name - - def get_short_name(self, max_length: int = MAX_FILE_PREFIX_LENGTH): - file_path = pathlib.Path(self.source_name) - short_name = file_path.stem[:max_length] + file_path.suffix - - return short_name - - def __str__(self) -> str: - return self.source_path - -class AudioSourceCollection: - def __init__(self, sources: List[AudioSource]): - self.sources = sources - - def __iter__(self): - return iter(self.sources) - -def get_audio_source_collection(urlData: str, multipleFiles: List, microphoneData: str, input_audio_max_duration: float = -1) -> List[AudioSource]: - output: List[AudioSource] = [] - - if urlData: - # Download from YouTube. This could also be a playlist or a channel. - output.extend([ AudioSource(x) for x in download_url(urlData, input_audio_max_duration, playlistItems=None) ]) - else: - # Add input files - if (multipleFiles is not None): - output.extend([ AudioSource(x.name) for x in multipleFiles ]) - if (microphoneData is not None): - output.append(AudioSource(microphoneData)) - - total_duration = 0 - - # Calculate total audio length. We do this even if input_audio_max_duration - # is disabled to ensure that all the audio files are valid. - for source in output: - audioDuration = ffmpeg.probe(source.source_path)["format"]["duration"] - total_duration += float(audioDuration) - - # Save audio duration - source._audio_duration = float(audioDuration) - - # Ensure the total duration of the audio is not too long - if input_audio_max_duration > 0: - if float(total_duration) > input_audio_max_duration: - raise ExceededMaximumDuration(videoDuration=total_duration, maxDuration=input_audio_max_duration, message="Video(s) is too long") - - # Return a list of audio sources - return output \ No newline at end of file diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/data/prepend_dataset.py b/spaces/ICML2022/OFA/fairseq/fairseq/data/prepend_dataset.py deleted file mode 100644 index ad74784d2d7920e4a6225282d95543ce16ea50d9..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/data/prepend_dataset.py +++ /dev/null @@ -1,28 +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 -import torch - -from . import BaseWrapperDataset - - -class PrependDataset(BaseWrapperDataset): - def __init__(self, dataset, prepend_getter, ensure_first_token_is=None): - super().__init__(dataset) - self.prepend_getter = prepend_getter - self.ensure_first_token = ensure_first_token_is - - def __getitem__(self, idx): - item = self.dataset[idx] - is_tuple = isinstance(item, tuple) - src = item[0] if is_tuple else item - - assert self.ensure_first_token is None or src[0] == self.ensure_first_token - prepend_idx = self.prepend_getter(self.dataset, idx) - assert isinstance(prepend_idx, int) - src[0] = prepend_idx - item = tuple((src,) + item[1:]) if is_tuple else src - return item diff --git a/spaces/Intel/NeuralChat-ICX-INT4/fastchat/serve/gradio_block_arena_anony.py b/spaces/Intel/NeuralChat-ICX-INT4/fastchat/serve/gradio_block_arena_anony.py deleted file mode 100644 index a2e712187432c0b0759bfa3a7a9630c6a0b29d30..0000000000000000000000000000000000000000 --- a/spaces/Intel/NeuralChat-ICX-INT4/fastchat/serve/gradio_block_arena_anony.py +++ /dev/null @@ -1,404 +0,0 @@ -import json -import time - -import gradio as gr -import numpy as np - -from fastchat.conversation import get_default_conv_template -from fastchat.utils import ( - build_logger, - violates_moderation, - moderation_msg, -) -from fastchat.serve.gradio_patch import Chatbot as grChatbot -from fastchat.serve.gradio_web_server import ( - http_bot, - get_conv_log_filename, - no_change_btn, - enable_btn, - disable_btn, -) - - -logger = build_logger("gradio_web_server_multi", "gradio_web_server_multi.log") - -num_models = 2 -enable_moderation = False -anony_names = ["", ""] -models = [] - -def set_global_vars_anony(enable_moderation_): - global enable_moderation - enable_moderation = enable_moderation_ - - -def load_demo_side_by_side_anony(models_, url_params): - global models - models = models_ - - states = (None,) * num_models - selector_updates = ( - gr.Markdown.update(visible=True), - gr.Markdown.update(visible=True), - ) - - return ( - states - + selector_updates - + (gr.Chatbot.update(visible=True),) * num_models - + ( - gr.Textbox.update(visible=True), - gr.Box.update(visible=True), - gr.Row.update(visible=True), - gr.Row.update(visible=True), - gr.Accordion.update(visible=True), - ) - ) - - -def vote_last_response(states, vote_type, model_selectors, request: gr.Request): - with open(get_conv_log_filename(), "a") as fout: - data = { - "tstamp": round(time.time(), 4), - "type": vote_type, - "models": [x for x in model_selectors], - "states": [x.dict() for x in states], - "ip": request.client.host, - } - fout.write(json.dumps(data) + "\n") - - if ":" not in model_selectors[0]: - for i in range(15): - names = ("### Model A: " + states[0].model_name, "### Model B: " + states[1].model_name) - yield names + ("",) + (disable_btn,) * 3 - time.sleep(0.2) - else: - names = ("### Model A: " + states[0].model_name, "### Model B: " + states[1].model_name) - yield names + ("",) + (disable_btn,) * 3 - - -def leftvote_last_response( - state0, state1, model_selector0, model_selector1, request: gr.Request -): - logger.info(f"leftvote (anony). ip: {request.client.host}") - for x in vote_last_response( - [state0, state1], "leftvote", [model_selector0, model_selector1], request - ): - yield x - - -def rightvote_last_response( - state0, state1, model_selector0, model_selector1, request: gr.Request -): - logger.info(f"rightvote (anony). ip: {request.client.host}") - for x in vote_last_response( - [state0, state1], "rightvote", [model_selector0, model_selector1], request - ): - yield x - - -def tievote_last_response( - state0, state1, model_selector0, model_selector1, request: gr.Request -): - logger.info(f"tievote (anony). ip: {request.client.host}") - for x in vote_last_response( - [state0, state1], "tievote", [model_selector0, model_selector1], request - ): - yield x - - -def regenerate(state0, state1, request: gr.Request): - logger.info(f"regenerate (anony). ip: {request.client.host}") - states = [state0, state1] - for i in range(num_models): - states[i].messages[-1][-1] = None - states[i].skip_next = False - return states + [x.to_gradio_chatbot() for x in states] + [""] + [disable_btn] * 5 - - -def clear_history(request: gr.Request): - logger.info(f"clear_history (anony). ip: {request.client.host}") - return [None] * num_models + [None] * num_models + anony_names + [""] + [disable_btn] * 5 - - -def share_click(state0, state1, model_selector0, model_selector1, - request: gr.Request): - logger.info(f"share (anony). ip: {request.client.host}") - if state0 is not None and state1 is not None: - vote_last_response( - [state0, state1], "share", [model_selector0, model_selector1], request - ) - - -def add_text(state0, state1, text, request: gr.Request): - logger.info(f"add_text (anony). ip: {request.client.host}. len: {len(text)}") - states = [state0, state1] - - if states[0] is None: - assert states[1] is None - weights = ([8, 4, 2, 1] + [1] * 32)[:len(models)] - if len(models) > 1: - weights = weights / np.sum(weights) - model_left, model_right = np.random.choice( - models, size=(2,), p=weights, replace=False) - else: - model_left = model_right = models[0] - - states = [ - get_default_conv_template("vicuna").copy(), - get_default_conv_template("vicuna").copy(), - ] - states[0].model_name = model_left - states[1].model_name = model_right - - if len(text) <= 0: - for i in range(num_models): - states[i].skip_next = True - return ( - states - + [x.to_gradio_chatbot() for x in states] - + [""] - + [ - no_change_btn, - ] - * 5 - ) - - if enable_moderation: - flagged = violates_moderation(text) - if flagged: - logger.info(f"violate moderation (anony). ip: {request.client.host}. text: {text}") - for i in range(num_models): - states[i].skip_next = True - return ( - states - + [x.to_gradio_chatbot() for x in states] - + [moderation_msg] - + [ - no_change_btn, - ] - * 5 - ) - - text = text[:1536] # Hard cut-off - for i in range(num_models): - states[i].append_message(states[i].roles[0], text) - states[i].append_message(states[i].roles[1], None) - states[i].skip_next = False - - return ( - states - + [x.to_gradio_chatbot() for x in states] - + [""] - + [ - disable_btn, - ] - * 5 - ) - - -def http_bot_all( - state0, - state1, - model_selector0, - model_selector1, - temperature, - max_new_tokens, - request: gr.Request, -): - logger.info(f"http_bot_all (anony). ip: {request.client.host}") - states = [state0, state1] - model_selector = [state0.model_name, state1.model_name] - gen = [] - for i in range(num_models): - gen.append( - http_bot(states[i], model_selector[i], temperature, max_new_tokens, request) - ) - - chatbots = [None] * num_models - while True: - stop = True - for i in range(num_models): - try: - ret = next(gen[i]) - states[i], chatbots[i] = ret[0], ret[1] - buttons = ret[2:] - stop = False - except StopIteration: - pass - yield states + chatbots + list(buttons) - if stop: - break - - for i in range(10): - if i % 2 == 0: - yield states + chatbots + [disable_btn] * 3 + list(buttons)[3:] - else: - yield states + chatbots + list(buttons) - time.sleep(0.2) - - -def build_side_by_side_ui_anony(models): - notice_markdown = """ -# ⚔️ Chatbot Arena ⚔️ -Rules: -- Chat with two anonymous models side-by-side and vote for which one is better! -- The names of the models will be revealed after your vote. -- You can continue chating and voting or click "Clear history" to start a new round. -- A leaderboard will be available soon. -- [[GitHub]](https://github.com/lm-sys/FastChat) [[Twitter]](https://twitter.com/lmsysorg) [[Discord]](https://discord.gg/h6kCZb72G7) - -### Terms of use -By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. **The service collects user dialogue data for future research.** -The demo works better on desktop devices with a wide screen. - -### The participated models -| | | -| ---- | ---- | -| [Vicuna](https://vicuna.lmsys.org): a chat assistant fine-tuned from LLaMA on user-shared conversations by LMSYS. | [Koala](https://bair.berkeley.edu/blog/2023/04/03/koala/): a dialogue model for academic research by BAIR | -| [OpenAssistant (oasst)](https://open-assistant.io/): a chat-based assistant for everyone by LAION. | [Dolly](https://www.databricks.com/blog/2023/04/12/dolly-first-open-commercially-viable-instruction-tuned-llm): an instruction-tuned open large language model by Databricks. | -| [ChatGLM](https://chatglm.cn/blog): an open bilingual dialogue language model by Tsinghua University | [StableLM](https://github.com/stability-AI/stableLM/): Stability AI language models. | -| [Alpaca](https://crfm.stanford.edu/2023/03/13/alpaca.html): a model fine-tuned from LLaMA on instruction-following demonstrations by Stanford. | [LLaMA](https://arxiv.org/abs/2302.13971): open and efficient foundation language models by Meta. | -""" - - learn_more_markdown = """ -### License -The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation. -""" - - states = [gr.State() for _ in range(num_models)] - model_selectors = [None] * num_models - chatbots = [None] * num_models - - notice = gr.Markdown(notice_markdown, elem_id="notice_markdown") - - with gr.Box(elem_id="share-region"): - with gr.Row(): - for i in range(num_models): - with gr.Column(): - model_selectors[i] = gr.Markdown(anony_names[i]) - - with gr.Row(): - for i in range(num_models): - label = "Model A" if i == 0 else "Model B" - with gr.Column(): - chatbots[i] = grChatbot(label=label, elem_id=f"chatbot{i}", - visible=False).style(height=550) - - with gr.Box() as button_row: - with gr.Row(): - leftvote_btn = gr.Button(value="👈 A is better", interactive=False) - tie_btn = gr.Button(value="🤝 Tie", interactive=False) - rightvote_btn = gr.Button(value="👉 B is better", interactive=False) - - with gr.Row(): - with gr.Column(scale=20): - textbox = gr.Textbox( - show_label=False, - placeholder="Enter text and press ENTER", - visible=False, - ).style(container=False) - with gr.Column(scale=1, min_width=50): - send_btn = gr.Button(value="Send", visible=False) - - with gr.Row() as button_row2: - regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) - clear_btn = gr.Button(value="🗑️ Clear history", interactive=False) - share_btn = gr.Button(value="📷 Share") - - with gr.Accordion("Parameters", open=False, visible=True) as parameter_row: - temperature = gr.Slider( - minimum=0.0, - maximum=1.0, - value=0.7, - step=0.1, - interactive=True, - label="Temperature", - ) - max_output_tokens = gr.Slider( - minimum=0, - maximum=1024, - value=512, - step=64, - interactive=True, - label="Max output tokens", - ) - - gr.Markdown(learn_more_markdown) - - # Register listeners - btn_list = [leftvote_btn, rightvote_btn, tie_btn, regenerate_btn, clear_btn] - leftvote_btn.click( - leftvote_last_response, - states + model_selectors, - model_selectors + [textbox, leftvote_btn, rightvote_btn, tie_btn], - ) - rightvote_btn.click( - rightvote_last_response, - states + model_selectors, - model_selectors + [textbox, leftvote_btn, rightvote_btn, tie_btn], - ) - tie_btn.click( - tievote_last_response, - states + model_selectors, - model_selectors + [textbox, leftvote_btn, rightvote_btn, tie_btn], - ) - regenerate_btn.click( - regenerate, states, states + chatbots + [textbox] + btn_list - ).then( - http_bot_all, - states + model_selectors + [temperature, max_output_tokens], - states + chatbots + btn_list, - ) - clear_btn.click(clear_history, None, states + chatbots + model_selectors + [ - textbox] + btn_list) - - share_js=""" -function (a, b, c, d) { - const captureElement = document.querySelector('#share-region'); - html2canvas(captureElement) - .then(canvas => { - canvas.style.display = 'none' - document.body.appendChild(canvas) - return canvas - }) - .then(canvas => { - const image = canvas.toDataURL('image/png') - const a = document.createElement('a') - a.setAttribute('download', 'chatbot-arena.png') - a.setAttribute('href', image) - a.click() - canvas.remove() - }); - return [a, b, c, d]; -} -""" - share_btn.click(share_click, states + model_selectors, [], _js=share_js) - - textbox.submit( - add_text, states + [textbox], states + chatbots + [textbox] + btn_list - ).then( - http_bot_all, - states + model_selectors + [temperature, max_output_tokens], - states + chatbots + btn_list, - ) - send_btn.click( - add_text, states + [textbox], states + chatbots + [textbox] + btn_list - ).then( - http_bot_all, - states + model_selectors + [temperature, max_output_tokens], - states + chatbots + btn_list, - ) - - return ( - states, - model_selectors, - chatbots, - textbox, - send_btn, - button_row, - button_row2, - parameter_row, - ) - - diff --git a/spaces/Jipski/Flos_gpt-2/README.md b/spaces/Jipski/Flos_gpt-2/README.md deleted file mode 100644 index 166a025d72e948026249da76aa028696d79315e6..0000000000000000000000000000000000000000 --- a/spaces/Jipski/Flos_gpt-2/README.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Flos_gpt 2 -emoji: 🌍 -colorFrom: blue -colorTo: yellow -sdk: streamlit -app_file: app.py -pinned: false ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio` 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/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/web/static/js/eruda.min.js b/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/web/static/js/eruda.min.js deleted file mode 100644 index 0609b9e8f15d39918a3818abaf979cdb7238b3d5..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/web/static/js/eruda.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! eruda v1.5.4 https://eruda.liriliri.io/ */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.eruda=t():e.eruda=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="/assets/",t(t.s=82)}([function(e,t,n){"use strict";(function(e,r){function i(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.wrap=t.viewportScale=t.unique=t.uniqId=t.tryIt=t.stripHtmlTag=t.LocalStore=t.stringify=t.type=t.ajax=t.Url=t.query=t.getFileName=t.trim=t.rtrim=t.rmCookie=t.pxToNum=t.perfNow=t.orientation=t.Store=t.Logger=t.Emitter=t.once=t.partial=t.restArgs=t.now=t.nextTick=t.detectBrowser=t.toInt=t.ms=t.toNum=t.meta=t.safeStorage=t.memStorage=t.$=t.$class=t.some=t.cloneDeep=t.mapObj=void 0,t.concat=t.$event=t.delegate=t.$show=t.$remove=t.$property=t.$offset=t.$insert=t.$css=t.$data=t.$attr=t.$safeEls=t.Select=t.MutationObserver=t.Enum=t.Class=t.toArr=t.cookie=t.decodeUriComponent=t.map=t.evalCss=t.filter=t.safeCb=t.matcher=t.ltrim=t.dateFormat=t.lpad=t.repeat=t.loadJs=t.isRegExp=t.isNull=t.isNative=t.toSrc=t.isNil=t.isNaN=t.prefix=t.isMobile=t.memoize=t.isMatch=t.isErudaEl=t.isErr=t.isEl=t.isCrossOrig=t.startWith=t.isBool=t.isEmpty=t.isStr=t.contain=t.values=t.extendOwn=t.clone=t.extend=t.defaults=t.createAssigner=t.each=t.isArrLike=t.isNum=t.isMiniProgram=t.isFn=t.isDate=t.safeGet=t.castPath=t.isArr=t.isArgs=t.objToStr=t.identity=t.getObjType=t.upperFirst=t.fullUrl=t.fileSize=t.escapeRegExp=t.escapeJsonStr=t.escapeJsStr=t.escape=t.endWith=t.optimizeCb=t.detectOs=t.freeze=t.keys=t.detectMocha=t.root=t.utf8=t.ucs2=t.toStr=t.idxOf=t.clamp=t.chunk=t.kebabCase=t.camelCase=t.splitCase=t.before=t.allKeys=t.noop=t.isBrowser=t.slice=t.has=t.inherits=t.isObj=t.isUndef=t.last=void 0;var o=n(28),a=i(o),s=n(123),u=i(s),l=n(66),c=i(l),d=n(34),f=i(d),p=n(130),h=i(p),v=n(35),g=i(v),m=n(135),_=i(m),b=n(73),y=i(b),x=n(25),w=i(x),k={},E=k.last=function(){function e(e){var t=e?e.length:0;if(t)return e[t-1]}return e}();t.last=E;var S=t.isUndef=k.isUndef=function(){function e(e){return void 0===e}return e}(),T=t.isObj=k.isObj=function(){function e(e){var t=void 0===e?"undefined":(0,w.default)(e);return!!e&&("function"===t||"object"===t)}return e}(),O=t.inherits=k.inherits=function(){function e(e,r){if(n)return e.prototype=n(r.prototype);t.prototype=r.prototype,e.prototype=new t}function t(){}var n=y.default;return e}(),A=t.has=k.has=function(){function e(e,n){return t.call(e,n)}var t=Object.prototype.hasOwnProperty;return e}(),C=t.slice=k.slice=function(){function e(e,t,n){var r=e.length;t=null==t?0:t<0?Math.max(r+t,0):Math.min(t,r),n=null==n?r:n<0?Math.max(r+n,0):Math.min(n,r);for(var i=[];t0&&(n=t.apply(this,arguments)),e<=1&&(t=null),n}}return e}(),L=t.splitCase=k.splitCase=function(){function e(e){return e=e.replace(t,"-$1").toLowerCase().replace(n,"-").replace(r,""),e.split("-")}var t=/([A-Z])/g,n=/[_.\- ]+/g,r=/(^-)|(-$)/g;return e}(),N=t.camelCase=k.camelCase=function(){function e(e){var n=L(e),r=n[0];return n.shift(),n.forEach(t,n),r+=n.join("")}function t(e,t){this[t]=e.replace(/\w/,function(e){return e.toUpperCase()})}return e}(),D=t.kebabCase=k.kebabCase=function(){function e(e){return L(e).join("-")}return e}(),I=(t.chunk=k.chunk=function(){function e(e,t){var n=[];t=t||1;for(var r=0,i=Math.ceil(e.length/t);rn?n:e}return e}()),K=t.idxOf=k.idxOf=function(){function e(e,t,n){return Array.prototype.indexOf.call(e,t,n)}return e}(),z=t.toStr=k.toStr=function(){function e(e){return null==e?"":e.toString()}return e}(),F=t.ucs2=k.ucs2=function(e){return{encode:function(e){return _.default.apply(String,e)},decode:function(e){for(var t=[],n=0,r=e.length;n=55296&&i<=56319&&n>6*t)+n);t>0;){r+=f(128|63&e>>6*(t-1)),t--}return r}function n(e){for(;;){if(o>=a&&l){if(e)return r();throw new Error("Invalid byte index")}if(o===a)return!1;var t=i[o];if(o++,l){if(td){if(e)return o--,r();throw new Error("Invalid continuation byte")}if(c=128,d=191,s=s<<6|63&t,++u===l){var n=s;return s=0,l=0,u=0,n}}else{if(0==(128&t))return t;if(192==(224&t))l=1,s=31&t;else if(224==(240&t))224===t&&(c=160),237===t&&(d=159),l=2,s=15&t;else{if(240!=(248&t)){if(e)return r();throw new Error("Invalid UTF-8 detected")}240===t&&(c=144),244===t&&(d=143),l=3,s=7&t}}}}function r(){var e=o-u-1;return o=e+1,s=0,l=0,u=0,c=128,d=191,i[e]}e={encode:function(e){for(var n=F.decode(e),r="",i=0,o=n.length;i-1}return e=e||(j?navigator.userAgent:""),e=e.toLowerCase(),t("windows phone")?"windows phone":t("win")?"windows":t("android")?"android":t("ipad")||t("iphone")||t("ipod")?"ios":t("mac")?"os x":t("linux")?"linux":"unknown"}return e}(),t.optimizeCb=k.optimizeCb=function(){function e(e,t,n){if(S(t))return e;switch(null==n?3:n){case 1:return function(n){return e.call(t,n)};case 3:return function(n,r,i){return e.call(t,n,r,i)};case 4:return function(n,r,i,o){return e.call(t,n,r,i,o)}}return function(){return e.apply(t,arguments)}}return e}()),G=(t.endWith=k.endWith=function(){function e(e,t){var n=e.length-t.length;return n>=0&&e.indexOf(t,n)===n}return e}(),t.escape=k.escape=function(){function e(e){return i.test(e)?e.replace(o,t):e}function t(e){return n[e]}var n=e.map={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},r="(?:"+U(n).join("|")+")",i=new RegExp(r),o=new RegExp(r,"g");return e}(),t.escapeJsStr=k.escapeJsStr=function(){function e(e){return z(e).replace(t,function(e){switch(e){case'"':case"'":case"\\":return"\\"+e;case"\n":return"\\n";case"\r":return"\\r";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029"}})}var t=/["'\\\n\r\u2028\u2029]/g;return e}()),q=(t.escapeJsonStr=k.escapeJsonStr=function(){function e(e){return G(e).replace(/\\'/g,"'").replace(/\t/g,"\\t")}return e}(),t.escapeRegExp=k.escapeRegExp=function(){function e(e){return e.replace(/\W/g,"\\$&")}return e}(),t.fileSize=k.fileSize=function(){function e(e){if(e<=0)return"0";var n=Math.floor(Math.log(e)/Math.log(1024));return+(e/Math.pow(2,10*n)).toFixed(2)+t[n]}var t=["","K","M","G","T"];return e}(),t.fullUrl=k.fullUrl=function(){function e(e){return t.href=e,t.protocol+"//"+t.host+t.pathname+t.search+t.hash}var t=document.createElement("a");return e}(),t.upperFirst=k.upperFirst=function(){function e(e){return e.length<1?e:e[0].toUpperCase()+e.slice(1)}return e}()),J=(t.getObjType=k.getObjType=function(){function e(e){return e.constructor&&e.constructor.name?e.constructor.name:q({}.toString.call(e).replace(/(\[object )|]/g,""))}return e}(),t.identity=k.identity=function(){function e(e){return e}return e}()),Y=t.objToStr=k.objToStr=function(){function e(e){return t.call(e)}var t=Object.prototype.toString;return e}(),Q=t.isArgs=k.isArgs=function(){function e(e){return"[object Arguments]"===Y(e)}return e}(),X=t.isArr=k.isArr=function(e){return Array.isArray||function(e){return"[object Array]"===Y(e)}}(),Z=t.castPath=k.castPath=function(){function e(e,r){if(X(e))return e;if(r&&A(r,e))return[e];var i=[];return e.replace(t,function(e,t,r,o){i.push(r?o.replace(n,"$1"):t||e)}),i}var t=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,n=/\\(\\)?/g;return e}(),ee=t.safeGet=k.safeGet=function(){function e(e,t){t=Z(t,e);var n;for(n=t.shift();!S(n);){if(null==(e=e[n]))return;n=t.shift()}return e}return e}(),te=t.isDate=k.isDate=function(){function e(e){return"[object Date]"===Y(e)}return e}(),ne=t.isFn=k.isFn=function(){function e(e){var t=Y(e);return"[object Function]"===t||"[object GeneratorFunction]"===t}return e}(),re=t.isMiniProgram=k.isMiniProgram=function(e){return"undefined"!=typeof wx&&ne(wx.openLocation)}(),ie=t.isNum=k.isNum=function(){function e(e){return"[object Number]"===Y(e)}return e}(),oe=t.isArrLike=k.isArrLike=function(){function e(e){if(!e)return!1;var n=e.length;return ie(n)&&n>=0&&n<=t&&!ne(e)}var t=Math.pow(2,53)-1;return e}(),ae=k.each=function(){function e(e,t,n){t=W(t,n);var r,i;if(oe(e))for(r=0,i=e.length;r=0}return e}(),he=t.isStr=k.isStr=function(){function e(e){return"[object String]"===Y(e)}return e}(),ve=t.isEmpty=k.isEmpty=function(){function e(e){return null==e||(oe(e)&&(X(e)||he(e)||Q(e))?0===e.length:0===U(e).length)}return e}(),ge=(t.isBool=k.isBool=function(){function e(e){return!0===e||!1===e}return e}(),t.startWith=k.startWith=function(){function e(e,t){return 0===e.indexOf(t)}return e}()),me=(t.isCrossOrig=k.isCrossOrig=function(){function e(e){return!ge(e,t)}var t=window.location.origin;return e}(),t.isEl=k.isEl=function(){function e(e){return!(!e||1!==e.nodeType)}return e}(),t.isErr=k.isErr=function(){function e(e){return"[object Error]"===Y(e)}return e}(),t.isErudaEl=k.isErudaEl=function(){function e(e){var t=e.parentNode;if(!t)return!1;for(;t;)if((t=t.parentNode)&&"eruda"===t.id)return!0;return!1}return e}(),t.isMatch=k.isMatch=function(){function e(e,t){var n=U(t),r=n.length;if(null==e)return!r;e=Object(e);for(var i=0;i0;)1&t&&(n+=e),t>>=1,e+=e;return n}}()),Se=t.lpad=k.lpad=function(){function e(e,t,n){e=z(e);var r=e.length;return n=n||" ",r0?"-":"+")+t(100*Math.floor(Math.abs(y)/60)+Math.abs(y)%60,4),S:["th","st","nd","rd"][f%10>3?0:(f%100-f%10!=10)*f%10]};return s.replace(n,function(e){return e in x?x[e]:e.slice(1,e.length-1)})}function t(e,t){return Se(z(e),t||2,"0")}var n=/d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|'[^']*'|'[^']*'/g,r=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,i=/\d/,o=/[^-+\dA-Z]/g;return e.masks={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},e.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"]},e}(),t.ltrim=k.ltrim=function(){function e(e,n){if(null==n)return e.replace(t,"");for(var r,i,o=0,a=e.length,s=n.length,u=!0;u&&o=a?"":e.substr(o,a)}var t=/^\s+/;return e}()),Oe=t.matcher=k.matcher=function(){function e(e){return e=de({},e),function(t){return me(t,e)}}return e}(),Ae=t.safeCb=k.safeCb=function(e){return function(e,t,n){return null==e?J:ne(e)?W(e,t,n):T(e)?Oe(e):function(e){return function(t){return null==t?void 0:t[e]}}}}(),Ce=t.filter=k.filter=function(){function e(e,t,n){var r=[];return t=Ae(t,n),ae(e,function(e,n,i){t(e,n,i)&&r.push(e)}),r}return e}(),je=(t.evalCss=k.evalCss=function(){function e(r,i){r=z(r);for(var o=0,a=n.length;o=0&&e=t[n[s]]){a=n[s];break}return+(o/t[a]).toFixed(2)+a}var t={ms:1,s:1e3};t.m=60*t.s,t.h=60*t.m,t.d=24*t.h,t.y=365.25*t.d;var n=["y","d","h","m","s"],r=/^((?:\d+)?\.?\d+) *(s|m|h|d|y)?$/;return e}(),t.toInt=k.toInt=function(){function e(e){return e?(e=et(e))-e%1:0===e?e:0}return e}()),nt=(t.detectBrowser=k.detectBrowser=function(){function e(e){e=e||(j?navigator.userAgent:""),e=e.toLowerCase();var o=t(e,"msie ");if(o)return{version:o,name:"ie"};if(r.test(e))return{version:11,name:"ie"};for(var a=0,s=i.length;a-1)return tt(e.substring(n+t.length,e.indexOf(".",n)))}var n={edge:/edge\/([0-9._]+)/,firefox:/firefox\/([0-9.]+)(?:\s|$)/,opera:/opera\/([0-9.]+)(?:\s|$)/,android:/android\s([0-9.]+)/,ios:/version\/([0-9._]+).*mobile.*safari.*/,safari:/version\/([0-9._]+).*safari/,chrome:/(?!chrom.*opr)chrom(?:e|ium)\/([0-9.]+)(:?\s|$)/},r=/trident\/7\./,i=U(n);return e}(),t.nextTick=k.nextTick=function(e){function t(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e}return"object"===(void 0===r?"undefined":(0,w.default)(r))&&r.nextTick?r.nextTick:"function"==typeof u.default?function(e){(0,u.default)(t(e))}:function(e){setTimeout(t(e),0)}}(),t.now=k.now=function(e){return Date.now||function(){return(new Date).getTime()}}()),rt=t.restArgs=k.restArgs=function(){function e(e,t){return t=null==t?e.length-1:+t,function(){var n,r=Math.max(arguments.length-t,0),i=new Array(r);for(n=0;nwindow.innerHeight?"landscape":"portrait"}},at.mixin(e),window.addEventListener("orientationchange",function(){setTimeout(function(){e.emit("change",e.get())},200)},!1),e}({}),t.perfNow=k.perfNow=function(e){var t,n=H.performance,r=H.process;if(n&&n.now)e=function(){return n.now()};else if(r&&r.hrtime){var i=function(){var e=r.hrtime();return 1e9*e[0]+e[1]};t=i()-1e9*r.uptime(),e=function(){return(i()-t)/1e6}}else t=nt(),e=function(){return nt()-t};return e}({}),t.pxToNum=k.pxToNum=function(){function e(e){return et(e.replace("px",""))}return e}(),t.rmCookie=k.rmCookie=function(){function e(e){function t(t){return t=t||{},Pe.remove(e,t),!Pe.get(e)}var n,r=window.location,i=r.hostname,o=r.pathname,a=i.split("."),s=o.split("/"),u="",l=s.length;if(!t())for(var c=a.length-1;c>=0;c--){var d=a[c];if(""!==d){if(u=""===u?d:d+"."+u,n="/",t({domain:u,path:n})||t({domain:u}))return;for(var f=0;f=0;)for(s=!1,r=-1,i=e.charAt(o);++r=0?e.substring(0,o+1):""}var t=/\s+$/;return e}()),lt=t.trim=k.trim=function(){function e(e,n){return null==n?e.replace(t,""):Te(ut(e,n),n)}var t=/^\s+|\s+$/g;return e}(),ct=(t.getFileName=k.getFileName=function(){function e(e){var t=E(e.split("/"));return t.indexOf("?")>-1&&(t=lt(t.split("?")[0])),""===t?"unknown":t}return e}(),t.query=k.query=function(e){e={parse:function(e){var n={};return e=lt(e).replace(t,""),ae(e.split("&"),function(e){var t=e.split("="),r=t.shift(),i=t.length>0?t.join("="):null;r=decodeURIComponent(r),i=decodeURIComponent(i),S(n[r])?n[r]=i:X(n[r])?n[r].push(i):n[r]=[n[r],i]}),n},stringify:function(t,n){return Ce(je(t,function(t,r){return T(t)&&ve(t)?"":X(t)?e.stringify(t,r):(n?encodeURIComponent(n):encodeURIComponent(r))+"="+encodeURIComponent(t)}),function(e){return e.length>0}).join("&")}};var t=/^(\?|#|&)/g;return e}({})),dt=(t.Url=k.Url=function(e){e=Le({className:"Url",initialize:function(t){!t&&j&&(t=window.location.href),le(this,e.parse(t||""))},setQuery:function(e,t){var n=this.query;return T(e)?ae(e,function(e,t){n[t]=e}):n[e]=t,this},rmQuery:function(e){var t=this.query;return X(e)||(e=Re(e)),ae(e,function(e){delete t[e]}),this},toString:function(){return e.stringify(this)}},{parse:function(e){var i={protocol:"",auth:"",hostname:"",hash:"",query:{},port:"",pathname:"",slashes:!1},o=lt(e),a=o.match(t);if(a&&(a=a[0],i.protocol=a.toLowerCase(),o=o.substr(a.length)),a){var s="//"===o.substr(0,2);s&&(o=o.slice(2),i.slashes=!0)}if(s){for(var u=-1,l=0,c=r.length;l=200&&t<300||304===t){e=f.responseText,"xml"===s&&(e=f.responseXML);try{"json"===s&&(e=JSON.parse(e))}catch(e){}u(e,f)}else l(f);d(f)}},"GET"===r?(o=ct.stringify(o),i+=i.indexOf("?")>-1?"&"+o:"?"+o):"application/x-www-form-urlencoded"===t.contentType?T(o)&&(o=ct.stringify(o)):"application/json"===t.contentType&&T(o)&&(o=(0,a.default)(o)),f.open(r,i,!0),f.setRequestHeader("Content-Type",t.contentType),c>0&&(n=setTimeout(function(){f.onreadystatechange=M,f.abort(),l(f,"timeout"),d(f)},c)),f.send("GET"===r?null:o),f}function t(e,t,n,r){return ne(t)&&(r=n,n=t,t={}),{url:e,data:t,success:n,dataType:r}}return e.setting={type:"GET",success:M,error:M,complete:M,dataType:"json",contentType:"application/x-www-form-urlencoded",data:{},xhr:function(){return new XMLHttpRequest},timeout:0},e.get=function(){return e(t.apply(null,arguments))},e.post=function(){var n=t.apply(null,arguments);return n.type="POST",e(n)},e}(),t.type=k.type=function(){function e(e){if(null===e)return"null";if(void 0===e)return"undefined";if(ye(e))return"nan";var n=Y(e).match(t);return n?n[1].toLowerCase():""}var t=/^\[object\s+(.*?)]$/;return e}()),ft=t.stringify=k.stringify=function(){function e(e,n){return(0,a.default)(e,t(),n)}function t(){var e=[],t=[];return function(n,r){if(e.length>0){var i=e.indexOf(this);i>-1?(e.splice(i+1),t.splice(i,1/0,n)):(e.push(this),t.push(n));var o=e.indexOf(r);o>-1&&(r=e[0]===r?"[Circular ~]":"[Circular ~."+t.slice(0,o).join(".")+"]")}else e.push(r);return ke(r)||ne(r)?r="["+q(dt(r))+" "+z(r)+"]":S(r)&&(r=null),r}}return e}();t.LocalStore=k.LocalStore=function(e){var t=Xe("local");return st.extend({initialize:function(e,n){this._name=e;var r=t.getItem(e);try{r=JSON.parse(r)}catch(e){r={}}T(r)||(r={}),n=ue(r,n),this.callSuper(st,"initialize",[n])},save:function(e){if(ve(e))return t.removeItem(this._name);t.setItem(this._name,ft(e))}})}(),t.stripHtmlTag=k.stripHtmlTag=function(){function e(e){return e.replace(t,"")}var t=/<[^>]*>/g;return e}(),t.tryIt=k.tryIt=function(){function e(e,t){t=t||M;try{t(null,e())}catch(e){return void t(e)}}return e}(),t.uniqId=k.uniqId=function(){function e(e){var n=++t+"";return e?e+n:n}var t=0;return e}(),t.unique=k.unique=function(){function e(e,n){return n=n||t,Ce(e,function(e,t,r){for(var i=r.length;++t= 2.0.0-beta.1",7:">= 4.0.0"};t.REVISION_CHANGES=f;r.prototype={constructor:r,logger:d.default,log:d.default.log,registerHelper:function(e,t){if("[object Object]"===o.toString.call(e)){if(t)throw new s.default("Arg not supported with multiple helpers");o.extend(this.helpers,e)}else this.helpers[e]=t},unregisterHelper:function(e){delete this.helpers[e]},registerPartial:function(e,t){if("[object Object]"===o.toString.call(e))o.extend(this.partials,e);else{if(void 0===t)throw new s.default('Attempting to register a partial called "'+e+'" as undefined');this.partials[e]=t}},unregisterPartial:function(e){delete this.partials[e]},registerDecorator:function(e,t){if("[object Object]"===o.toString.call(e)){if(t)throw new s.default("Arg not supported with multiple decorators");o.extend(this.decorators,e)}else this.decorators[e]=t},unregisterDecorator:function(e){delete this.decorators[e]}};var p=d.default.log;t.log=p,t.createFrame=o.createFrame,t.logger=d.default},function(e,t){"use strict";function n(e){return c[e]}function r(e){for(var t=1;t":">",'"':""","'":"'","`":"`","=":"="},d=/[&<>"'`=]/g,f=/[&<>"'`=]/,p=Object.prototype.toString;t.toString=p;var h=function(e){return"function"==typeof e};h(/x/)&&(t.isFunction=h=function(e){return"function"==typeof e&&"[object Function]"===p.call(e)}),t.isFunction=h;var v=Array.isArray||function(e){return!(!e||"object"!=typeof e)&&"[object Array]"===p.call(e)};t.isArray=v},function(e,t,n){"use strict";function r(e,t){var n=t&&t.loc,a=void 0,s=void 0;n&&(a=n.start.line,s=n.start.column,e+=" - "+a+":"+s);for(var u=Error.prototype.constructor.call(this,e),l=0;l0?(n.ids&&(n.ids=[n.name]),e.helpers.each(t,n)):i(this);if(n.data&&n.ids){var a=r.createFrame(n.data);a.contextPath=r.appendContextPath(n.data.contextPath,n.name),n={data:a}}return o(t,n)})},e.exports=t.default},function(e,t,n){"use strict";var r=n(2).default;t.__esModule=!0;var i=n(4),o=n(5),a=r(o);t.default=function(e){e.registerHelper("each",function(e,t){function n(t,n,o){l&&(l.key=t,l.index=n,l.first=0===n,l.last=!!o,c&&(l.contextPath=c+t)),u+=r(e[t],{data:l,blockParams:i.blockParams([e[t],t],[c+t,null])})}if(!t)throw new a.default("Must pass iterator to #each");var r=t.fn,o=t.inverse,s=0,u="",l=void 0,c=void 0;if(t.data&&t.ids&&(c=i.appendContextPath(t.data.contextPath,t.ids[0])+"."),i.isFunction(e)&&(e=e.call(this)),t.data&&(l=i.createFrame(t.data)),e&&"object"==typeof e)if(i.isArray(e))for(var d=e.length;s=0?t:parseInt(e,10)}return e},log:function(e){if(e=i.lookupLevel(e),"undefined"!=typeof console&&i.lookupLevel(i.level)<=e){var t=i.methodMap[e];console[t]||(t="log");for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o3&&void 0!==arguments[3]?arguments[3]:["#2196f3","#707d8b","#f44336","#009688","#ffc107"],i=this._genId("settings");return this._settings.push({config:e,key:t,id:i}),this._$el.append(this._colorTpl({desc:n,colors:r,id:i,val:e.get(t)})),this}},{key:"select",value:function(e,t,n,r){var i=this._genId("settings");return this._settings.push({config:e,key:t,id:i}),this._$el.append(this._selectTpl({desc:n,selections:r,id:i,val:e.get(t)})),this}},{key:"range",value:function(e,t,n,r){var i=r.min,o=void 0===i?0:i,a=r.max,s=void 0===a?1:a,u=r.step,l=void 0===u?.1:u,c=this._genId("settings");this._settings.push({config:e,key:t,min:o,max:s,step:l,id:c});var d=e.get(t);return this._$el.append(this._rangeTpl({desc:n,min:o,max:s,step:l,val:d,progress:y(d,o,s),id:c})),this}},{key:"separator",value:function(){return this._$el.append('
      '),this}},{key:"text",value:function(e){return this._$el.append('
      '+e+"
      "),this}},{key:"_cleanSeparator",value:function(){function e(e){return"eruda-separator"===e.getAttribute("class")}for(var t=(0,_.clone)(this._$el.get(0).children),n=0,r=t.length;n0?r:n)(e)}},function(e,t,n){var r=n(44)("keys"),i=n(31);e.exports=function(e){return r[e]||(r[e]=i(e))}},function(e,t,n){var r=n(11),i=r["__core-js_shared__"]||(r["__core-js_shared__"]={});e.exports=function(e){return i[e]||(i[e]={})}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){"use strict";var r=n(96)(!0);n(67)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t){e.exports=!0},function(e,t,n){var r=n(21),i=n(98),o=n(45),a=n(43)("IE_PROTO"),s=function(){},u=function(){var e,t=n(39)("iframe"),r=o.length;for(t.style.display="none",n(69).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(" - - - - -
      -

      Paraphrasing Webapp

      -
      -
      - - -
      -
      - - -
      -
      - - -
      -
      - - -
      -
      - - -
      - -
      -{% if paraphrased_text %} -

      Paraphrased Text:

      -

      {{ paraphrased_text }}

      - -
      -
      -
      -{% endif %} -
      - - - - \ No newline at end of file diff --git a/spaces/inamXcontru/PoeticTTS/Boowy The Best Story Zip Virtual Zidane Offics Favorite Album.md b/spaces/inamXcontru/PoeticTTS/Boowy The Best Story Zip Virtual Zidane Offics Favorite Album.md deleted file mode 100644 index 8f8efad82b0bb17311523f9150197e60f49ced8a..0000000000000000000000000000000000000000 --- a/spaces/inamXcontru/PoeticTTS/Boowy The Best Story Zip Virtual Zidane Offics Favorite Album.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Boowy The Best Story Zip virtual zidane offic


      Download Ziphttps://gohhs.com/2uz4IF



      - - aaccfb2cb3
      -
      -
      -

      diff --git a/spaces/inigosarralde/mushroom_edibility_classifier/README.md b/spaces/inigosarralde/mushroom_edibility_classifier/README.md deleted file mode 100644 index f60b22207a58093fa4fe936eb6c444586c6c5cb5..0000000000000000000000000000000000000000 --- a/spaces/inigosarralde/mushroom_edibility_classifier/README.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Mushroom_edibility_classifier -emoji: 🔥 -colorFrom: gray -colorTo: blue -sdk: gradio -app_file: app.py -pinned: false -license: afl-3.0 ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio`, `streamlit`, or `static` - -`sdk_version` : _string_ -Only applicable for `streamlit` SDK. -See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions. - -`app_file`: _string_ -Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code). -Path is relative to the root of the repository. - -`models`: _List[string]_ -HF model IDs (like "gpt2" or "deepset/roberta-base-squad2") used in the Space. -Will be parsed automatically from your code if not specified here. - -`datasets`: _List[string]_ -HF dataset IDs (like "common_voice" or "oscar-corpus/OSCAR-2109") used in the Space. -Will be parsed automatically from your code if not specified here. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/innat/Global.Wheat.Detection.MaskRCNN/mrcnn/config.py b/spaces/innat/Global.Wheat.Detection.MaskRCNN/mrcnn/config.py deleted file mode 100644 index e1244c836e6cdb7545b26006d40ad793b1509852..0000000000000000000000000000000000000000 --- a/spaces/innat/Global.Wheat.Detection.MaskRCNN/mrcnn/config.py +++ /dev/null @@ -1,239 +0,0 @@ -""" -Mask R-CNN -Base Configurations class. - -Copyright (c) 2017 Matterport, Inc. -Licensed under the MIT License (see LICENSE for details) -Written by Waleed Abdulla -""" - -import numpy as np - -# Base Configuration Class -# Don't use this class directly. Instead, sub-class it and override -# the configurations you need to change. - - -class Config(object): - """Base configuration class. For custom configurations, create a - sub-class that inherits from this one and override properties - that need to be changed. - """ - - # Name the configurations. For example, 'COCO', 'Experiment 3', ...etc. - # Useful if your code needs to do things differently depending on which - # experiment is running. - NAME = None # Override in sub-classes - - # NUMBER OF GPUs to use. When using only a CPU, this needs to be set to 1. - GPU_COUNT = 1 - - # Number of images to train with on each GPU. A 12GB GPU can typically - # handle 2 images of 1024x1024px. - # Adjust based on your GPU memory and image sizes. Use the highest - # number that your GPU can handle for best performance. - IMAGES_PER_GPU = 2 - - # Number of training steps per epoch - # This doesn't need to match the size of the training set. Tensorboard - # updates are saved at the end of each epoch, so setting this to a - # smaller number means getting more frequent TensorBoard updates. - # Validation stats are also calculated at each epoch end and they - # might take a while, so don't set this too small to avoid spending - # a lot of time on validation stats. - STEPS_PER_EPOCH = 1000 - - # Number of validation steps to run at the end of every training epoch. - # A bigger number improves accuracy of validation stats, but slows - # down the training. - VALIDATION_STEPS = 50 - - # Backbone network architecture - # Supported values are: resnet50, resnet101. - # You can also provide a callable that should have the signature - # of model.resnet_graph. If you do so, you need to supply a callable - # to COMPUTE_BACKBONE_SHAPE as well - BACKBONE = "resnet101" - - # Only useful if you supply a callable to BACKBONE. Should compute - # the shape of each layer of the FPN Pyramid. - # See model.compute_backbone_shapes - COMPUTE_BACKBONE_SHAPE = None - - # The strides of each layer of the FPN Pyramid. These values - # are based on a Resnet101 backbone. - BACKBONE_STRIDES = [4, 8, 16, 32, 64] - - # Size of the fully-connected layers in the classification graph - FPN_CLASSIF_FC_LAYERS_SIZE = 1024 - - # Size of the top-down layers used to build the feature pyramid - TOP_DOWN_PYRAMID_SIZE = 256 - - # Number of classification classes (including background) - NUM_CLASSES = 1 # Override in sub-classes - - # Length of square anchor side in pixels - RPN_ANCHOR_SCALES = (32, 64, 128, 256, 512) - - # Ratios of anchors at each cell (width/height) - # A value of 1 represents a square anchor, and 0.5 is a wide anchor - RPN_ANCHOR_RATIOS = [0.5, 1, 2] - - # Anchor stride - # If 1 then anchors are created for each cell in the backbone feature map. - # If 2, then anchors are created for every other cell, and so on. - RPN_ANCHOR_STRIDE = 1 - - # Non-max suppression threshold to filter RPN proposals. - # You can increase this during training to generate more propsals. - RPN_NMS_THRESHOLD = 0.7 - - # How many anchors per image to use for RPN training - RPN_TRAIN_ANCHORS_PER_IMAGE = 256 - - # ROIs kept after tf.nn.top_k and before non-maximum suppression - PRE_NMS_LIMIT = 6000 - - # ROIs kept after non-maximum suppression (training and inference) - POST_NMS_ROIS_TRAINING = 2000 - POST_NMS_ROIS_INFERENCE = 1000 - - # If enabled, resizes instance masks to a smaller size to reduce - # memory load. Recommended when using high-resolution images. - USE_MINI_MASK = True - MINI_MASK_SHAPE = (56, 56) # (height, width) of the mini-mask - - # Input image resizing - # Generally, use the "square" resizing mode for training and predicting - # and it should work well in most cases. In this mode, images are scaled - # up such that the small side is = IMAGE_MIN_DIM, but ensuring that the - # scaling doesn't make the long side > IMAGE_MAX_DIM. Then the image is - # padded with zeros to make it a square so multiple images can be put - # in one batch. - # Available resizing modes: - # none: No resizing or padding. Return the image unchanged. - # square: Resize and pad with zeros to get a square image - # of size [max_dim, max_dim]. - # pad64: Pads width and height with zeros to make them multiples of 64. - # If IMAGE_MIN_DIM or IMAGE_MIN_SCALE are not None, then it scales - # up before padding. IMAGE_MAX_DIM is ignored in this mode. - # The multiple of 64 is needed to ensure smooth scaling of feature - # maps up and down the 6 levels of the FPN pyramid (2**6=64). - # crop: Picks random crops from the image. First, scales the image based - # on IMAGE_MIN_DIM and IMAGE_MIN_SCALE, then picks a random crop of - # size IMAGE_MIN_DIM x IMAGE_MIN_DIM. Can be used in training only. - # IMAGE_MAX_DIM is not used in this mode. - IMAGE_RESIZE_MODE = "square" - IMAGE_MIN_DIM = 800 - IMAGE_MAX_DIM = 1024 - # Minimum scaling ratio. Checked after MIN_IMAGE_DIM and can force further - # up scaling. For example, if set to 2 then images are scaled up to double - # the width and height, or more, even if MIN_IMAGE_DIM doesn't require it. - # However, in 'square' mode, it can be overruled by IMAGE_MAX_DIM. - IMAGE_MIN_SCALE = 0 - # Number of color channels per image. RGB = 3, grayscale = 1, RGB-D = 4 - # Changing this requires other changes in the code. See the WIKI for more - # details: https://github.com/matterport/Mask_RCNN/wiki - IMAGE_CHANNEL_COUNT = 3 - - # Image mean (RGB) - MEAN_PIXEL = np.array([123.7, 116.8, 103.9]) - - # Number of ROIs per image to feed to classifier/mask heads - # The Mask RCNN paper uses 512 but often the RPN doesn't generate - # enough positive proposals to fill this and keep a positive:negative - # ratio of 1:3. You can increase the number of proposals by adjusting - # the RPN NMS threshold. - TRAIN_ROIS_PER_IMAGE = 200 - - # Percent of positive ROIs used to train classifier/mask heads - ROI_POSITIVE_RATIO = 0.33 - - # Pooled ROIs - POOL_SIZE = 7 - MASK_POOL_SIZE = 14 - - # Shape of output mask - # To change this you also need to change the neural network mask branch - MASK_SHAPE = [28, 28] - - # Maximum number of ground truth instances to use in one image - MAX_GT_INSTANCES = 100 - - # Bounding box refinement standard deviation for RPN and final detections. - RPN_BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2]) - BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2]) - - # Max number of final detections - DETECTION_MAX_INSTANCES = 100 - - # Minimum probability value to accept a detected instance - # ROIs below this threshold are skipped - DETECTION_MIN_CONFIDENCE = 0.7 - - # Non-maximum suppression threshold for detection - DETECTION_NMS_THRESHOLD = 0.3 - - # Learning rate and momentum - # The Mask RCNN paper uses lr=0.02, but on TensorFlow it causes - # weights to explode. Likely due to differences in optimizer - # implementation. - LEARNING_RATE = 0.001 - LEARNING_MOMENTUM = 0.9 - - # Weight decay regularization - WEIGHT_DECAY = 0.0001 - - # Loss weights for more precise optimization. - # Can be used for R-CNN training setup. - LOSS_WEIGHTS = { - "rpn_class_loss": 1.0, - "rpn_bbox_loss": 1.0, - "mrcnn_class_loss": 1.0, - "mrcnn_bbox_loss": 1.0, - "mrcnn_mask_loss": 1.0, - } - - # Use RPN ROIs or externally generated ROIs for training - # Keep this True for most situations. Set to False if you want to train - # the head branches on ROI generated by code rather than the ROIs from - # the RPN. For example, to debug the classifier head without having to - # train the RPN. - USE_RPN_ROIS = True - - # Train or freeze batch normalization layers - # None: Train BN layers. This is the normal mode - # False: Freeze BN layers. Good when using a small batch size - # True: (don't use). Set layer in training mode even when predicting - TRAIN_BN = False # Defaulting to False since batch size is often small - - # Gradient norm clipping - GRADIENT_CLIP_NORM = 5.0 - - def __init__(self): - """Set values of computed attributes.""" - # Effective batch size - self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT - - # Input image size - if self.IMAGE_RESIZE_MODE == "crop": - self.IMAGE_SHAPE = np.array( - [self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM, self.IMAGE_CHANNEL_COUNT] - ) - else: - self.IMAGE_SHAPE = np.array( - [self.IMAGE_MAX_DIM, self.IMAGE_MAX_DIM, self.IMAGE_CHANNEL_COUNT] - ) - - # Image meta data length - # See compose_image_meta() for details - self.IMAGE_META_SIZE = 1 + 3 + 3 + 4 + 1 + self.NUM_CLASSES - - def display(self): - """Display Configuration values.""" - print("\nConfigurations:") - for a in dir(self): - if not a.startswith("__") and not callable(getattr(self, a)): - print("{:30} {}".format(a, getattr(self, a))) - print("\n") diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/AutoCAD 2010 [32-Bit] - English Download HOT! Pc.md b/spaces/inplisQlawa/anything-midjourney-v4-1/AutoCAD 2010 [32-Bit] - English Download HOT! Pc.md deleted file mode 100644 index ff30a38a82e0de64502458c6fde525d58b8f73fc..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/AutoCAD 2010 [32-Bit] - English Download HOT! Pc.md +++ /dev/null @@ -1,35 +0,0 @@ -
      -

      How to Download and Install AutoCAD 2010 [32-Bit] - English on Your PC

      -

      AutoCAD 2010 is a powerful and versatile software for designing and drafting 2D and 3D models. It is widely used by architects, engineers, and other professionals in various industries. If you want to use AutoCAD 2010 on your PC, you need to download and install it properly. Here are the steps to do so:

      -
        -
      1. Make sure your PC meets the minimum system requirements for AutoCAD 2010. You need at least a 32-bit Windows XP or Vista operating system, an Intel Pentium 4 or AMD Athlon processor, 2 GB of RAM, 1.8 GB of free disk space, and a 1024 x 768 display resolution with True Color.
      2. -
      3. Go to the official website of Autodesk, the developer of AutoCAD, and find the download link for AutoCAD 2010 [32-Bit] - English. You may need to create an account and sign in to access the download page.
      4. -
      5. Click on the download button and choose a location to save the file. The file size is about 1.3 GB, so it may take some time to download depending on your internet speed.
      6. -
      7. Once the download is complete, locate the file and double-click on it to start the installation process. You may need to enter your serial number and product key, which you can find on the Autodesk website or in your email confirmation.
      8. -
      9. Follow the instructions on the screen to complete the installation. You may need to restart your PC after the installation is done.
      10. -
      11. Launch AutoCAD 2010 from your desktop or start menu and enjoy using it.
      12. -
      -

      AutoCAD 2010 [32-Bit] - English is a great software for creating and editing professional-quality drawings and models. By following these simple steps, you can download and install it on your PC easily and quickly.

      -

      AutoCAD 2010 [32-Bit] - English download pc


      Download Zip ✺✺✺ https://urlin.us/2uEyiM



      - -

      Why Choose AutoCAD 2010 [32-Bit] - English?

      -

      AutoCAD 2010 [32-Bit] - English is a great choice for anyone who needs a powerful and reliable CAD software. Here are some of the benefits of using AutoCAD 2010:

      -
        -
      • It has a user-friendly interface that allows you to access various tools and commands easily. You can customize the ribbon, the application menu, the quick access toolbar, and the workspaces according to your preferences and workflow.
      • -
      • It supports dynamic blocks, which are blocks that can be modified or manipulated without changing their definition. You can use the block test window, the block properties table, and the parametric drawing features to create and edit dynamic blocks.
      • -
      • It has a comprehensive annotation scaling feature that allows you to create annotations that automatically adjust to different scales and viewports. You can also use tables, linking tables with Microsoft Excel, and data extraction to tables to organize and present your data.
      • -
      • It has a powerful 3D modeling and rendering capability that lets you create and edit 3D solids, free-form models, section planes, and walk-through animations. You can also apply materials, lights, cameras, and visual styles to enhance your 3D presentation.
      • -
      • It has a seamless integration with other Autodesk products and services, such as Autodesk Buzzsaw, Autodesk Seek, Autodesk Impression, Autodesk Vault, and Autodesk Product Manager. You can also use digital signatures, passwords, communication center, and DWF markups to communicate and collaborate with others.
      • -
      -

      How to Get Support and Learn More About AutoCAD 2010 [32-Bit] - English?

      -

      If you need any help or guidance on using AutoCAD 2010 [32-Bit] - English, you can access various resources online or offline. Here are some of the ways to get support and learn more about AutoCAD 2010:

      -
        -
      • You can use the AutoCAD Help documentation that provides detailed information on AutoCAD concepts, procedures, commands, customization, drivers, and peripherals. You can access the help documentation from the application menu or by pressing F1.
      • -
      • You can join the AutoCAD Community that offers tips, articles, and other useful content. You can also post questions and share answers on the Autodesk discussion groups with other AutoCAD users.
      • -
      • You can view the New Features Workshop that shows animated overviews of the latest features in AutoCAD 2010. You can also use the tutorials and cue cards that provide hands-on exercises and quick reference cards for each new feature.
      • -
      • You can contact Autodesk support by phone, email, or chat if you have any technical issues or questions. You can also find solutions and updates on the Autodesk website or in the Autodesk Product Manager.
      • -
      -

      AutoCAD 2010 [32-Bit] - English is a versatile and professional CAD software that can help you create and edit high-quality drawings and models. By following this article, you can download and install it on your PC easily and quickly. You can also find various resources to support and learn more about AutoCAD 2010. Download AutoCAD 2010 [32-Bit] - English today and unleash your creativity!

      -

      d5da3c52bf
      -
      -
      \ No newline at end of file diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Garibaldi Express Hair System For Daz Studio Download __EXCLUSIVE__.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Garibaldi Express Hair System For Daz Studio Download __EXCLUSIVE__.md deleted file mode 100644 index 64d141952c886f9c58a32df5f93f4946c541b5b8..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Garibaldi Express Hair System For Daz Studio Download __EXCLUSIVE__.md +++ /dev/null @@ -1,18 +0,0 @@ -
      -

      How to Download and Use Garibaldi Express Hair System for Daz Studio

      -

      Garibaldi Express is a professional hair and fur solution for Daz Studio that lets you create realistic and stunning hair styles for your 3D characters and animals. It offers powerful yet easy tools to style, paint and render hair and fur with advanced features and modern techniques. In this article, we will show you how to download and use Garibaldi Express Hair System for Daz Studio.

      -

      Step 1: Download Garibaldi Express

      -

      Garibaldi Express is now freeware, which means you can download it for free from the official website[^1^]. To register for the free download, enter your email address on the free register page [^2^] and you will receive a serial number and a download link. You can choose between 32-bit or 64-bit versions for Windows or Mac OS X. Make sure you have Daz Studio version 4.5.1 or higher installed on your computer.

      -

      Garibaldi Express Hair System For Daz Studio Download


      Downloadhttps://urlin.us/2uEwv0



      -

      Step 2: Install Garibaldi Express

      -

      After downloading the zip file, extract it to a folder of your choice. Then run the installer file and follow the instructions on the screen. You will need to enter your serial number during the installation process. The installer will automatically detect your Daz Studio installation folder and copy the necessary files there. You can also choose to install some sample presets and tutorials if you want.

      -

      Step 3: Launch Garibaldi Express

      -

      To launch Garibaldi Express, open Daz Studio and load a character or an animal that you want to add hair or fur to. Note that Garibaldi Express does not support the newer Daz Genesis 3 and 8 based models, but it works with Genesis 1 and 2 as well as most other animals and characters[^2^]. Then go to Window > Tabs > Garibaldi Express to open the Garibaldi Express tab. You will see a toolbar with various icons that let you access different features of Garibaldi Express.

      -

      Step 4: Create Hair or Fur

      -

      To create hair or fur, you need to select a surface on your character or animal that you want to grow hair or fur from. You can use the Surface Selection tool on the toolbar to do that. Then click on the Create Hair button on the toolbar to generate hair or fur on the selected surface. You can adjust the density, length, thickness and other parameters of the hair or fur using the sliders on the right panel. You can also use the Style tool on the toolbar to comb, cut, curl or twist the hair or fur using your mouse. You can also use the Paint tool on the toolbar to paint different colors on the hair or fur using a brush.

      -

      Step 5: Render Hair or Fur

      -

      To render hair or fur, you need to apply a material preset to it. You can use the Material Presets tool on the toolbar to browse and apply different material presets that come with Garibaldi Express. You can also adjust the material settings on the right panel, such as specular, diffuse, transparency and more. Note that Garibaldi Express does not support nVidia Iray renderer, which is the main renderer of Daz Studio[^2^]. You need to use another renderer, such as 3Delight or LuxRender, to render hair or fur created by Garibaldi Express. To switch renderers, go to Render > Render Settings and choose your preferred renderer from the drop-down menu. Then click on Render > Render to render your scene with hair or fur.

      -

      Conclusion

      -

      Garibaldi Express is a powerful and easy-to-use hair and fur solution for Daz Studio that lets you create realistic and stunning hair styles for your 3D characters and animals. It offers a range of intuitive styling and painting tools, advanced material settings and modern rendering techniques. Although it does not support nVidia Iray renderer or Genesis 3 and 8 models, it still works with many other renderers and models in Daz Studio. You can download it for free from the official website and start creating amazing hair and fur for your 3D projects.

      d5da3c52bf
      -
      -
      \ No newline at end of file diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Manual Limba Franceza Clasa 6 Cavallioti Pdf [NEW].md b/spaces/inplisQlawa/anything-midjourney-v4-1/Manual Limba Franceza Clasa 6 Cavallioti Pdf [NEW].md deleted file mode 100644 index eab8e6009942439b7c192c3fb1987569625d18d0..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Manual Limba Franceza Clasa 6 Cavallioti Pdf [NEW].md +++ /dev/null @@ -1,44 +0,0 @@ - -

      Manual Limba Franceza Clasa 6 Cavallioti Pdf: O resursa utila pentru invatarea limbii franceze

      -

      Daca esti elev in clasa a VI-a si vrei sa inveti limba franceza intr-un mod eficient si placut, atunci ai nevoie de Manual Limba Franceza Clasa 6 Cavallioti Pdf. Acest manual este elaborat de Editura Cavallioti si este conform cu programa scolara. Manualul contine lectii variate si interesante, exercitii practice, materiale audio si video, si teste de evaluare.

      -

      Ce contine Manual Limba Franceza Clasa 6 Cavallioti Pdf?

      -

      Manual Limba Franceza Clasa 6 Cavallioti Pdf contine urmatoarele elemente:

      -

      Manual Limba Franceza Clasa 6 Cavallioti Pdf


      Download 🆓 https://urlin.us/2uExMJ



      -
        -
      • 12 unitati de invatare, fiecare avand o tema specifica, cum ar fi: familia, scoala, timpul liber, calatoriile, etc.
      • -
      • Fiecare unitate are patru sectiuni: Je m'ecoute (ascult si inteleg), Je lis (citesc si inteleg), Je parle (vorbesti si comunici), Je ecris (scriu si redactez).
      • -
      • Fiecare sectiune are activitati variate si interactive, care dezvolta cele patru competente lingvistice: ascultarea, citirea, vorbirea si scrierea.
      • -
      • Fiecare unitate are si o pagina de recapitulare si consolidare a cunostintelor, numita Bilan.
      • -
      • La sfarsitul manualului se afla un dictionar ilustrat cu cuvintele esentiale din limba franceza.
      • -
      • Manualul este insotit de un CD audio cu inregistrari ale dialogurilor si textelor din manual.
      • -
      • Manualul este disponibil si in format digital pe site-ul Editurii Cavallioti, unde se pot accesa si materiale video suplimentare.
      • -
      -

      Cum se foloseste Manual Limba Franceza Clasa 6 Cavallioti Pdf?

      -

      Pentru a folosi Manual Limba Franceza Clasa 6 Cavallioti Pdf, trebuie sa urmezi urmatorii pasi:

      -
        -
      1. Descarca manualul in format PDF de pe site-ul Editurii Cavallioti sau de pe alte surse online.
      2. -
      3. Deschide manualul cu un program care poate citi fisiere PDF, cum ar fi Adobe Reader sau Google Chrome.
      4. -
      5. Parcurge unitatile de invatare in ordinea prezentata in cuprins sau in functie de preferintele tale.
      6. -
      7. Asculta inregistr

        -
      8. Asculta inregistrarile audio de pe CD sau de pe site-ul Editurii Cavallioti si urmareste textele din manual.
      9. -
      10. Exerseaza pronuntia, vocabularul si gramatica limbii franceze cu ajutorul exercitiilor din manual.
      11. -
      12. Verifica-ti cunostintele cu ajutorul testelor de evaluare din manual sau de pe site-ul Editurii Cavallioti.
      13. -
      14. Repeta si consolideaza ceea ce ai invatat cu ajutorul paginii de Bilan din fiecare unitate.
      15. -
      16. Urmareste materialele video de pe site-ul Editurii Cavallioti pentru a te familiariza cu cultura si civilizatia franceza.
      17. -
      -

      De ce sa alegi Manual Limba Franceza Clasa 6 Cavallioti Pdf?

      -

      Iata cateva motive pentru care sa alegi Manual Limba Franceza Clasa 6 Cavallioti Pdf:

      -
        -
      • Manualul este elaborat de specialisti in domeniul limbii si literaturii franceze, care au o experienta vasta in predarea limbii franceze la nivel scolar.
      • -
      • Manualul este adaptat la nivelul si nevoile elevilor de clasa a VI-a, care invata limba franceza ca limba moderna 2.
      • -
      • Manualul este atractiv si interactiv, avand o grafica moderna si colorata, ilustratii sugestive si materiale multimedia variate.
      • -
      • Manualul este eficient si usor de folosit, avand o structura clara si coerenta, o progresie logica si echilibrata, si o metodologie activa si participativa.
      • -
      • Manualul este conform cu programa scolara si cu cerintele examenului national de limba franceza pentru clasa a VIII-a.
      • -
      -

      Astfel, Manual Limba Franceza Clasa 6 Cavallioti Pdf este o resursa utila pentru invatarea limbii franceze intr-un mod placut si eficient. Cu ajutorul acestui manual, vei putea sa comunici in limba franceza la nivel elementar, sa intelegi texte simple si sa scrii mesaje scurte. De asemenea, vei putea sa te familiarizezi cu cultura si civilizatia franceza si sa iti dezvolti competentele interculturale. Nu ezita sa descarci acest manual si sa incepi aventura ta in lumea francofona!

      -

      Astfel, Manual Limba Franceza Clasa 6 Cavallioti Pdf este o resursa utila pentru invatarea limbii franceze intr-un mod placut si eficient. Cu ajutorul acestui manual, vei putea sa comunici in limba franceza la nivel elementar, sa intelegi texte simple si sa scrii mesaje scurte. De asemenea, vei putea sa te familiarizezi cu cultura si civilizatia franceza si sa iti dezvolti competentele interculturale. Nu ezita sa descarci acest manual si sa incepi aventura ta in lumea francofona!

      - -This paragraph summarizes the main points of the article and gives a recommendation to the readers. It also ends with a friendly tone and a call to action. A good conclusion should not introduce new information or repeat the same sentences from the introduction or body paragraphs. It should also not be too long or too short, but just enough to wrap up the article and leave a lasting impression on the readers.

      -

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/inreVtussa/clothingai/Examples/(2011) Terjemah Kitab Khozinatul Asror.pdf.md b/spaces/inreVtussa/clothingai/Examples/(2011) Terjemah Kitab Khozinatul Asror.pdf.md deleted file mode 100644 index 5f34d9a4ef75728abd4dff25c00faf42e2416814..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/(2011) Terjemah Kitab Khozinatul Asror.pdf.md +++ /dev/null @@ -1,38 +0,0 @@ -

      (2011) Terjemah Kitab Khozinatul Asror.pdf


      DOWNLOADhttps://tiurll.com/2uCiGk



      -
      -6 Crack Full Version(2017) keygen.xero_setup_2_1_9_final_windows_key.exe.txtResize windows 10 serial key one device.mp4gidea-in-one-serial-key.pdffixnofile-monotouch-windows-10-keygen.rarVersion of devit 3.0.0 keygen.xero_setup_2_1_9_final_windows_key.exe.txtHola Docs.pdfOops, Your lightbox has reached it's maximum width. - -To view your comments you need to reduce your browser width below 300px. - -I agree with Tara that if we ever lose our connection we need to meet up in person. Tara is the one that put in the money and time to start the shoot and we just need to make sure that she is okay with doing it again. It may be that we have made things clear to her and she is just being shy, so let's just give it a few days before we commit to this.Q: - -Color color in codeigniter - -I want to ask if there is any way to change the color of codeigniter application from light gray to dark gray. - -I have tried this in Application/config/config.php but that does not work. - -$config['theme_path'] = ''; - -or - -$config['theme_path'] = 'app/design/frontend/theme/dark'; - -Thanks! - -A: - -One of the first things to do when you first begin developing with CI is to change the application/config/config.php file from the default to the one found here: - -Once that's done, you can then go to the view folder and find the _system.php file. Under that is the section. There is a CSS file there that you can modify. - -Open up that file and change the line that reads as: - -config->item('base_url').'application/themes/'. $this->config->item('theme');?>" /> - -to read as: - - -
      -
      -

      diff --git a/spaces/inreVtussa/clothingai/Examples/Deep Inside Annie Sprinkle 198213.md b/spaces/inreVtussa/clothingai/Examples/Deep Inside Annie Sprinkle 198213.md deleted file mode 100644 index aedf4ffe46bda084bd07364e444dfb8c4b6265d7..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Deep Inside Annie Sprinkle 198213.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Deep Inside Annie Sprinkle 198213


      DOWNLOADhttps://tiurll.com/2uCjzQ



      - -Deaths, published in the Herald, are inserted in the ... street, 134 feet frontage by average depth 0 m feet, with β-roomtd ... Annie Bow, barque, sailed Juno 5. 1fdad05405
      -
      -
      -

      diff --git a/spaces/jackyccl/segment-anything/groundingdino/util/logger.py b/spaces/jackyccl/segment-anything/groundingdino/util/logger.py deleted file mode 100644 index 18145f54c927abd59b95f3fa6e6da8002bc2ce97..0000000000000000000000000000000000000000 --- a/spaces/jackyccl/segment-anything/groundingdino/util/logger.py +++ /dev/null @@ -1,93 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -import functools -import logging -import os -import sys - -from termcolor import colored - - -class _ColorfulFormatter(logging.Formatter): - def __init__(self, *args, **kwargs): - self._root_name = kwargs.pop("root_name") + "." - self._abbrev_name = kwargs.pop("abbrev_name", "") - if len(self._abbrev_name): - self._abbrev_name = self._abbrev_name + "." - super(_ColorfulFormatter, self).__init__(*args, **kwargs) - - def formatMessage(self, record): - record.name = record.name.replace(self._root_name, self._abbrev_name) - log = super(_ColorfulFormatter, self).formatMessage(record) - if record.levelno == logging.WARNING: - prefix = colored("WARNING", "red", attrs=["blink"]) - elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL: - prefix = colored("ERROR", "red", attrs=["blink", "underline"]) - else: - return log - return prefix + " " + log - - -# so that calling setup_logger multiple times won't add many handlers -@functools.lru_cache() -def setup_logger(output=None, distributed_rank=0, *, color=True, name="imagenet", abbrev_name=None): - """ - Initialize the detectron2 logger and set its verbosity level to "INFO". - - Args: - output (str): a file name or a directory to save log. If None, will not save log file. - If ends with ".txt" or ".log", assumed to be a file name. - Otherwise, logs will be saved to `output/log.txt`. - name (str): the root module name of this logger - - Returns: - logging.Logger: a logger - """ - logger = logging.getLogger(name) - logger.setLevel(logging.DEBUG) - logger.propagate = False - - if abbrev_name is None: - abbrev_name = name - - plain_formatter = logging.Formatter( - "[%(asctime)s.%(msecs)03d]: %(message)s", datefmt="%m/%d %H:%M:%S" - ) - # stdout logging: master only - if distributed_rank == 0: - ch = logging.StreamHandler(stream=sys.stdout) - ch.setLevel(logging.DEBUG) - if color: - formatter = _ColorfulFormatter( - colored("[%(asctime)s.%(msecs)03d]: ", "green") + "%(message)s", - datefmt="%m/%d %H:%M:%S", - root_name=name, - abbrev_name=str(abbrev_name), - ) - else: - formatter = plain_formatter - ch.setFormatter(formatter) - logger.addHandler(ch) - - # file logging: all workers - if output is not None: - if output.endswith(".txt") or output.endswith(".log"): - filename = output - else: - filename = os.path.join(output, "log.txt") - if distributed_rank > 0: - filename = filename + f".rank{distributed_rank}" - os.makedirs(os.path.dirname(filename), exist_ok=True) - - fh = logging.StreamHandler(_cached_log_stream(filename)) - fh.setLevel(logging.DEBUG) - fh.setFormatter(plain_formatter) - logger.addHandler(fh) - - return logger - - -# cache the opened file object, so that different calls to `setup_logger` -# with the same file name can safely write to the same file. -@functools.lru_cache(maxsize=None) -def _cached_log_stream(filename): - return open(filename, "a") diff --git a/spaces/jaimin/Paraphrase/app.py b/spaces/jaimin/Paraphrase/app.py deleted file mode 100644 index 9328d780283792cb19d9f4a11361f000f413fc84..0000000000000000000000000000000000000000 --- a/spaces/jaimin/Paraphrase/app.py +++ /dev/null @@ -1,69 +0,0 @@ -import gradio as gr -from gradio.mix import Parallel -from transformers import AutoTokenizer, AutoModelForSeq2SeqLM -import os -from transformers import T5TokenizerFast, T5ForConditionalGeneration -from transformers import PegasusForConditionalGeneration, PegasusTokenizer -import pytorch_lightning as pl -import torch -import itertools -import random -import nltk -from nltk.tokenize import sent_tokenize -import requests -import json -nltk.download('punkt') - -device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") - - -tokenizer1 = PegasusTokenizer.from_pretrained('jaimin/pegasus') -model1 = PegasusForConditionalGeneration.from_pretrained('jaimin/pegasus').to(device) - -def listToDict(lst): - op = { i : lst[i] for i in range(0, len(lst) ) } - return op - -def get_paraphrases_pytorchlight(text, n_predictions=3, top_k=50, max_length=256, device="cpu"): - para = [] - sentence = text - for sent in sent_tokenize(sentence): - text = "paraphrase: "+sent + " " - encoding = tokenizer1.encode_plus(text, padding=True, return_tensors="pt", truncation=True) - input_ids, attention_masks = encoding["input_ids"].to(device), encoding["attention_mask"].to(device) - model_output = model1.generate( - input_ids=input_ids,attention_mask=attention_masks, - max_length = 512, - early_stopping=True, - num_beams=15, - num_beam_groups = 3, - num_return_sequences=n_predictions, - diversity_penalty = 0.70, - temperature=0.7, - no_repeat_ngram_size=2 ) - outputs = [] - for output in model_output: - generated_sent = tokenizer1.decode( - output, skip_special_tokens=True, clean_up_tokenization_spaces=True - ) - if ( - generated_sent.lower() != sentence.lower() - and generated_sent not in outputs - ): - outputs.append(generated_sent) - para.append(outputs) - a = list(itertools.product(*para)) - random.shuffle(a) - - l=[] - for i in range(len(a)): - l.append(" ".join(a[i])) - final_output=[] - for i in range(len(l)): - final_output.append("* " + l[i] + ".") - paraphrase = "\n".join(final_output) - return paraphrase - -iface = gr.Interface(fn=get_paraphrases_pytorchlight, inputs=[gr.inputs.Textbox(lines=5)],outputs="text") -#iface1 = gr.Interface(fn=get_paraphrases_pytorchlight, inputs=[gr.inputs.Textbox(lines=5)],outputs="text") -iface.launch(enable_queue = True) \ No newline at end of file diff --git a/spaces/jiedong-yang/Speech-Summarization-with-Whisper/README.md b/spaces/jiedong-yang/Speech-Summarization-with-Whisper/README.md deleted file mode 100644 index 5f1fcd4df0565adff76fa238e815ec36f9933899..0000000000000000000000000000000000000000 --- a/spaces/jiedong-yang/Speech-Summarization-with-Whisper/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Speech Summarization With Whisper -emoji: 🎙️📄 -colorFrom: red -colorTo: blue -sdk: gradio -sdk_version: 3.6 -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/jlmarrugom/voice_fixer_app/voicefixer/tools/io.py b/spaces/jlmarrugom/voice_fixer_app/voicefixer/tools/io.py deleted file mode 100644 index c50451e3758a2d59a916a8cdd7a38adf8d90a011..0000000000000000000000000000000000000000 --- a/spaces/jlmarrugom/voice_fixer_app/voicefixer/tools/io.py +++ /dev/null @@ -1,44 +0,0 @@ -import json -import pickle - - -def read_list(fname): - result = [] - with open(fname, "r") as f: - for each in f.readlines(): - each = each.strip("\n") - result.append(each) - return result - - -def write_list(list, fname): - with open(fname, "w") as f: - for word in list: - f.write(word) - f.write("\n") - - -def write_json(my_dict, fname): - # print("Save json file at "+fname) - json_str = json.dumps(my_dict) - with open(fname, "w") as json_file: - json_file.write(json_str) - - -def load_json(fname): - with open(fname, "r") as f: - data = json.load(f) - return data - - -def save_pickle(obj, fname): - # print("Save pickle at "+fname) - with open(fname, "wb") as f: - pickle.dump(obj, f) - - -def load_pickle(fname): - # print("Load pickle at "+fname) - with open(fname, "rb") as f: - res = pickle.load(f) - return res diff --git a/spaces/joaogabriellima/Real-Time-Voice-Cloning/encoder/inference.py b/spaces/joaogabriellima/Real-Time-Voice-Cloning/encoder/inference.py deleted file mode 100644 index 4ca417b63406b9280418069d28d2877308be9bc2..0000000000000000000000000000000000000000 --- a/spaces/joaogabriellima/Real-Time-Voice-Cloning/encoder/inference.py +++ /dev/null @@ -1,178 +0,0 @@ -from encoder.params_data import * -from encoder.model import SpeakerEncoder -from encoder.audio import preprocess_wav # We want to expose this function from here -from matplotlib import cm -from encoder import audio -from pathlib import Path -import matplotlib.pyplot as plt -import numpy as np -import torch - -_model = None # type: SpeakerEncoder -_device = None # type: torch.device - - -def load_model(weights_fpath: Path, device=None): - """ - Loads the model in memory. If this function is not explicitely called, it will be run on the - first call to embed_frames() with the default weights file. - - :param weights_fpath: the path to saved model weights. - :param device: either a torch device or the name of a torch device (e.g. "cpu", "cuda"). The - model will be loaded and will run on this device. Outputs will however always be on the cpu. - If None, will default to your GPU if it"s available, otherwise your CPU. - """ - # TODO: I think the slow loading of the encoder might have something to do with the device it - # was saved on. Worth investigating. - global _model, _device - if device is None: - _device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - elif isinstance(device, str): - _device = torch.device(device) - _model = SpeakerEncoder(_device, torch.device("cpu")) - checkpoint = torch.load(weights_fpath, _device) - _model.load_state_dict(checkpoint["model_state"]) - _model.eval() - print("Loaded encoder \"%s\" trained to step %d" % (weights_fpath.name, checkpoint["step"])) - - -def is_loaded(): - return _model is not None - - -def embed_frames_batch(frames_batch): - """ - Computes embeddings for a batch of mel spectrogram. - - :param frames_batch: a batch mel of spectrogram as a numpy array of float32 of shape - (batch_size, n_frames, n_channels) - :return: the embeddings as a numpy array of float32 of shape (batch_size, model_embedding_size) - """ - if _model is None: - raise Exception("Model was not loaded. Call load_model() before inference.") - - frames = torch.from_numpy(frames_batch).to(_device) - embed = _model.forward(frames).detach().cpu().numpy() - return embed - - -def compute_partial_slices(n_samples, partial_utterance_n_frames=partials_n_frames, - min_pad_coverage=0.75, overlap=0.5): - """ - Computes where to split an utterance waveform and its corresponding mel spectrogram to obtain - partial utterances of each. Both the waveform and the mel - spectrogram slices are returned, so as to make each partial utterance waveform correspond to - its spectrogram. This function assumes that the mel spectrogram parameters used are those - defined in params_data.py. - - The returned ranges may be indexing further than the length of the waveform. It is - recommended that you pad the waveform with zeros up to wave_slices[-1].stop. - - :param n_samples: the number of samples in the waveform - :param partial_utterance_n_frames: the number of mel spectrogram frames in each partial - utterance - :param min_pad_coverage: when reaching the last partial utterance, it may or may not have - enough frames. If at least of are present, - then the last partial utterance will be considered, as if we padded the audio. Otherwise, - it will be discarded, as if we trimmed the audio. If there aren't enough frames for 1 partial - utterance, this parameter is ignored so that the function always returns at least 1 slice. - :param overlap: by how much the partial utterance should overlap. If set to 0, the partial - utterances are entirely disjoint. - :return: the waveform slices and mel spectrogram slices as lists of array slices. Index - respectively the waveform and the mel spectrogram with these slices to obtain the partial - utterances. - """ - assert 0 <= overlap < 1 - assert 0 < min_pad_coverage <= 1 - - samples_per_frame = int((sampling_rate * mel_window_step / 1000)) - n_frames = int(np.ceil((n_samples + 1) / samples_per_frame)) - frame_step = max(int(np.round(partial_utterance_n_frames * (1 - overlap))), 1) - - # Compute the slices - wav_slices, mel_slices = [], [] - steps = max(1, n_frames - partial_utterance_n_frames + frame_step + 1) - for i in range(0, steps, frame_step): - mel_range = np.array([i, i + partial_utterance_n_frames]) - wav_range = mel_range * samples_per_frame - mel_slices.append(slice(*mel_range)) - wav_slices.append(slice(*wav_range)) - - # Evaluate whether extra padding is warranted or not - last_wav_range = wav_slices[-1] - coverage = (n_samples - last_wav_range.start) / (last_wav_range.stop - last_wav_range.start) - if coverage < min_pad_coverage and len(mel_slices) > 1: - mel_slices = mel_slices[:-1] - wav_slices = wav_slices[:-1] - - return wav_slices, mel_slices - - -def embed_utterance(wav, using_partials=True, return_partials=False, **kwargs): - """ - Computes an embedding for a single utterance. - - # TODO: handle multiple wavs to benefit from batching on GPU - :param wav: a preprocessed (see audio.py) utterance waveform as a numpy array of float32 - :param using_partials: if True, then the utterance is split in partial utterances of - frames and the utterance embedding is computed from their - normalized average. If False, the utterance is instead computed from feeding the entire - spectogram to the network. - :param return_partials: if True, the partial embeddings will also be returned along with the - wav slices that correspond to the partial embeddings. - :param kwargs: additional arguments to compute_partial_splits() - :return: the embedding as a numpy array of float32 of shape (model_embedding_size,). If - is True, the partial utterances as a numpy array of float32 of shape - (n_partials, model_embedding_size) and the wav partials as a list of slices will also be - returned. If is simultaneously set to False, both these values will be None - instead. - """ - # Process the entire utterance if not using partials - if not using_partials: - frames = audio.wav_to_mel_spectrogram(wav) - embed = embed_frames_batch(frames[None, ...])[0] - if return_partials: - return embed, None, None - return embed - - # Compute where to split the utterance into partials and pad if necessary - wave_slices, mel_slices = compute_partial_slices(len(wav), **kwargs) - max_wave_length = wave_slices[-1].stop - if max_wave_length >= len(wav): - wav = np.pad(wav, (0, max_wave_length - len(wav)), "constant") - - # Split the utterance into partials - frames = audio.wav_to_mel_spectrogram(wav) - frames_batch = np.array([frames[s] for s in mel_slices]) - partial_embeds = embed_frames_batch(frames_batch) - - # Compute the utterance embedding from the partial embeddings - raw_embed = np.mean(partial_embeds, axis=0) - embed = raw_embed / np.linalg.norm(raw_embed, 2) - - if return_partials: - return embed, partial_embeds, wave_slices - return embed - - -def embed_speaker(wavs, **kwargs): - raise NotImplemented() - - -def plot_embedding_as_heatmap(embed, ax=None, title="", shape=None, color_range=(0, 0.30)): - if ax is None: - ax = plt.gca() - - if shape is None: - height = int(np.sqrt(len(embed))) - shape = (height, -1) - embed = embed.reshape(shape) - - cmap = cm.get_cmap() - mappable = ax.imshow(embed, cmap=cmap) - cbar = plt.colorbar(mappable, ax=ax, fraction=0.046, pad=0.04) - sm = cm.ScalarMappable(cmap=cmap) - sm.set_clim(*color_range) - - ax.set_xticks([]), ax.set_yticks([]) - ax.set_title(title) diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py deleted file mode 100644 index 17115819494ecfbb9d4af14da995746f1d279424..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py +++ /dev/null @@ -1,506 +0,0 @@ -# -*- coding: utf-8 -*- -# -# SelfTest/Cipher/test_pkcs1_oaep.py: Self-test for PKCS#1 OAEP encryption -# -# =================================================================== -# The contents of this file are dedicated to the public domain. To -# the extent that dedication to the public domain is not available, -# everyone is granted a worldwide, perpetual, royalty-free, -# non-exclusive license to exercise all rights associated with the -# contents of this file for any purpose whatsoever. -# No rights are reserved. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS -# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -# =================================================================== - -import unittest - -from Crypto.SelfTest.st_common import list_test_cases, a2b_hex -from Crypto.SelfTest.loader import load_test_vectors_wycheproof - -from Crypto.PublicKey import RSA -from Crypto.Cipher import PKCS1_OAEP as PKCS -from Crypto.Hash import MD2, MD5, SHA1, SHA256, RIPEMD160, SHA224, SHA384, SHA512 -from Crypto import Random -from Crypto.Signature.pss import MGF1 - -from Crypto.Util.py3compat import b, bchr - - -def rws(t): - """Remove white spaces, tabs, and new lines from a string""" - for c in ['\n', '\t', ' ']: - t = t.replace(c, '') - return t - - -def t2b(t): - """Convert a text string with bytes in hex form to a byte string""" - clean = rws(t) - if len(clean) % 2 == 1: - raise ValueError("Even number of characters expected") - return a2b_hex(clean) - - -class PKCS1_OAEP_Tests(unittest.TestCase): - - def setUp(self): - self.rng = Random.new().read - self.key1024 = RSA.generate(1024, self.rng) - - # List of tuples with test data for PKCS#1 OAEP - # Each tuple is made up by: - # Item #0: dictionary with RSA key component - # Item #1: plaintext - # Item #2: ciphertext - # Item #3: random data (=seed) - # Item #4: hash object - - _testData = ( - - # - # From in oaep-int.txt to be found in - # ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip - # - ( - # Private key - { - 'n':'''bb f8 2f 09 06 82 ce 9c 23 38 ac 2b 9d a8 71 f7 - 36 8d 07 ee d4 10 43 a4 40 d6 b6 f0 74 54 f5 1f - b8 df ba af 03 5c 02 ab 61 ea 48 ce eb 6f cd 48 - 76 ed 52 0d 60 e1 ec 46 19 71 9d 8a 5b 8b 80 7f - af b8 e0 a3 df c7 37 72 3e e6 b4 b7 d9 3a 25 84 - ee 6a 64 9d 06 09 53 74 88 34 b2 45 45 98 39 4e - e0 aa b1 2d 7b 61 a5 1f 52 7a 9a 41 f6 c1 68 7f - e2 53 72 98 ca 2a 8f 59 46 f8 e5 fd 09 1d bd cb''', - # Public key - 'e':'11', - # In the test vector, only p and q were given... - # d is computed offline as e^{-1} mod (p-1)(q-1) - 'd':'''a5dafc5341faf289c4b988db30c1cdf83f31251e0 - 668b42784813801579641b29410b3c7998d6bc465745e5c3 - 92669d6870da2c082a939e37fdcb82ec93edac97ff3ad595 - 0accfbc111c76f1a9529444e56aaf68c56c092cd38dc3bef - 5d20a939926ed4f74a13eddfbe1a1cecc4894af9428c2b7b - 8883fe4463a4bc85b1cb3c1''' - } - , - # Plaintext - '''d4 36 e9 95 69 fd 32 a7 c8 a0 5b bc 90 d3 2c 49''', - # Ciphertext - '''12 53 e0 4d c0 a5 39 7b b4 4a 7a b8 7e 9b f2 a0 - 39 a3 3d 1e 99 6f c8 2a 94 cc d3 00 74 c9 5d f7 - 63 72 20 17 06 9e 52 68 da 5d 1c 0b 4f 87 2c f6 - 53 c1 1d f8 23 14 a6 79 68 df ea e2 8d ef 04 bb - 6d 84 b1 c3 1d 65 4a 19 70 e5 78 3b d6 eb 96 a0 - 24 c2 ca 2f 4a 90 fe 9f 2e f5 c9 c1 40 e5 bb 48 - da 95 36 ad 87 00 c8 4f c9 13 0a de a7 4e 55 8d - 51 a7 4d df 85 d8 b5 0d e9 68 38 d6 06 3e 09 55''', - # Random - '''aa fd 12 f6 59 ca e6 34 89 b4 79 e5 07 6d de c2 - f0 6c b5 8f''', - # Hash - SHA1, - ), - - # - # From in oaep-vect.txt to be found in Example 1.1 - # ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip - # - ( - # Private key - { - 'n':'''a8 b3 b2 84 af 8e b5 0b 38 70 34 a8 60 f1 46 c4 - 91 9f 31 87 63 cd 6c 55 98 c8 ae 48 11 a1 e0 ab - c4 c7 e0 b0 82 d6 93 a5 e7 fc ed 67 5c f4 66 85 - 12 77 2c 0c bc 64 a7 42 c6 c6 30 f5 33 c8 cc 72 - f6 2a e8 33 c4 0b f2 58 42 e9 84 bb 78 bd bf 97 - c0 10 7d 55 bd b6 62 f5 c4 e0 fa b9 84 5c b5 14 - 8e f7 39 2d d3 aa ff 93 ae 1e 6b 66 7b b3 d4 24 - 76 16 d4 f5 ba 10 d4 cf d2 26 de 88 d3 9f 16 fb''', - 'e':'''01 00 01''', - 'd':'''53 33 9c fd b7 9f c8 46 6a 65 5c 73 16 ac a8 5c - 55 fd 8f 6d d8 98 fd af 11 95 17 ef 4f 52 e8 fd - 8e 25 8d f9 3f ee 18 0f a0 e4 ab 29 69 3c d8 3b - 15 2a 55 3d 4a c4 d1 81 2b 8b 9f a5 af 0e 7f 55 - fe 73 04 df 41 57 09 26 f3 31 1f 15 c4 d6 5a 73 - 2c 48 31 16 ee 3d 3d 2d 0a f3 54 9a d9 bf 7c bf - b7 8a d8 84 f8 4d 5b eb 04 72 4d c7 36 9b 31 de - f3 7d 0c f5 39 e9 cf cd d3 de 65 37 29 ea d5 d1 ''' - } - , - # Plaintext - '''66 28 19 4e 12 07 3d b0 3b a9 4c da 9e f9 53 23 - 97 d5 0d ba 79 b9 87 00 4a fe fe 34''', - # Ciphertext - '''35 4f e6 7b 4a 12 6d 5d 35 fe 36 c7 77 79 1a 3f - 7b a1 3d ef 48 4e 2d 39 08 af f7 22 fa d4 68 fb - 21 69 6d e9 5d 0b e9 11 c2 d3 17 4f 8a fc c2 01 - 03 5f 7b 6d 8e 69 40 2d e5 45 16 18 c2 1a 53 5f - a9 d7 bf c5 b8 dd 9f c2 43 f8 cf 92 7d b3 13 22 - d6 e8 81 ea a9 1a 99 61 70 e6 57 a0 5a 26 64 26 - d9 8c 88 00 3f 84 77 c1 22 70 94 a0 d9 fa 1e 8c - 40 24 30 9c e1 ec cc b5 21 00 35 d4 7a c7 2e 8a''', - # Random - '''18 b7 76 ea 21 06 9d 69 77 6a 33 e9 6b ad 48 e1 - dd a0 a5 ef''', - SHA1 - ), - - # - # From in oaep-vect.txt to be found in Example 2.1 - # ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip - # - ( - # Private key - { - 'n':'''01 94 7c 7f ce 90 42 5f 47 27 9e 70 85 1f 25 d5 - e6 23 16 fe 8a 1d f1 93 71 e3 e6 28 e2 60 54 3e - 49 01 ef 60 81 f6 8c 0b 81 41 19 0d 2a e8 da ba - 7d 12 50 ec 6d b6 36 e9 44 ec 37 22 87 7c 7c 1d - 0a 67 f1 4b 16 94 c5 f0 37 94 51 a4 3e 49 a3 2d - de 83 67 0b 73 da 91 a1 c9 9b c2 3b 43 6a 60 05 - 5c 61 0f 0b af 99 c1 a0 79 56 5b 95 a3 f1 52 66 - 32 d1 d4 da 60 f2 0e da 25 e6 53 c4 f0 02 76 6f - 45''', - 'e':'''01 00 01''', - 'd':'''08 23 f2 0f ad b5 da 89 08 8a 9d 00 89 3e 21 fa - 4a 1b 11 fb c9 3c 64 a3 be 0b aa ea 97 fb 3b 93 - c3 ff 71 37 04 c1 9c 96 3c 1d 10 7a ae 99 05 47 - 39 f7 9e 02 e1 86 de 86 f8 7a 6d de fe a6 d8 cc - d1 d3 c8 1a 47 bf a7 25 5b e2 06 01 a4 a4 b2 f0 - 8a 16 7b 5e 27 9d 71 5b 1b 45 5b dd 7e ab 24 59 - 41 d9 76 8b 9a ce fb 3c cd a5 95 2d a3 ce e7 25 - 25 b4 50 16 63 a8 ee 15 c9 e9 92 d9 24 62 fe 39''' - }, - # Plaintext - '''8f f0 0c aa 60 5c 70 28 30 63 4d 9a 6c 3d 42 c6 - 52 b5 8c f1 d9 2f ec 57 0b ee e7''', - # Ciphertext - '''01 81 af 89 22 b9 fc b4 d7 9d 92 eb e1 98 15 99 - 2f c0 c1 43 9d 8b cd 49 13 98 a0 f4 ad 3a 32 9a - 5b d9 38 55 60 db 53 26 83 c8 b7 da 04 e4 b1 2a - ed 6a ac df 47 1c 34 c9 cd a8 91 ad dc c2 df 34 - 56 65 3a a6 38 2e 9a e5 9b 54 45 52 57 eb 09 9d - 56 2b be 10 45 3f 2b 6d 13 c5 9c 02 e1 0f 1f 8a - bb 5d a0 d0 57 09 32 da cf 2d 09 01 db 72 9d 0f - ef cc 05 4e 70 96 8e a5 40 c8 1b 04 bc ae fe 72 - 0e''', - # Random - '''8c 40 7b 5e c2 89 9e 50 99 c5 3e 8c e7 93 bf 94 - e7 1b 17 82''', - SHA1 - ), - - # - # From in oaep-vect.txt to be found in Example 10.1 - # ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip - # - ( - # Private key - { - 'n':'''ae 45 ed 56 01 ce c6 b8 cc 05 f8 03 93 5c 67 4d - db e0 d7 5c 4c 09 fd 79 51 fc 6b 0c ae c3 13 a8 - df 39 97 0c 51 8b ff ba 5e d6 8f 3f 0d 7f 22 a4 - 02 9d 41 3f 1a e0 7e 4e be 9e 41 77 ce 23 e7 f5 - 40 4b 56 9e 4e e1 bd cf 3c 1f b0 3e f1 13 80 2d - 4f 85 5e b9 b5 13 4b 5a 7c 80 85 ad ca e6 fa 2f - a1 41 7e c3 76 3b e1 71 b0 c6 2b 76 0e de 23 c1 - 2a d9 2b 98 08 84 c6 41 f5 a8 fa c2 6b da d4 a0 - 33 81 a2 2f e1 b7 54 88 50 94 c8 25 06 d4 01 9a - 53 5a 28 6a fe b2 71 bb 9b a5 92 de 18 dc f6 00 - c2 ae ea e5 6e 02 f7 cf 79 fc 14 cf 3b dc 7c d8 - 4f eb bb f9 50 ca 90 30 4b 22 19 a7 aa 06 3a ef - a2 c3 c1 98 0e 56 0c d6 4a fe 77 95 85 b6 10 76 - 57 b9 57 85 7e fd e6 01 09 88 ab 7d e4 17 fc 88 - d8 f3 84 c4 e6 e7 2c 3f 94 3e 0c 31 c0 c4 a5 cc - 36 f8 79 d8 a3 ac 9d 7d 59 86 0e aa da 6b 83 bb''', - 'e':'''01 00 01''', - 'd':'''05 6b 04 21 6f e5 f3 54 ac 77 25 0a 4b 6b 0c 85 - 25 a8 5c 59 b0 bd 80 c5 64 50 a2 2d 5f 43 8e 59 - 6a 33 3a a8 75 e2 91 dd 43 f4 8c b8 8b 9d 5f c0 - d4 99 f9 fc d1 c3 97 f9 af c0 70 cd 9e 39 8c 8d - 19 e6 1d b7 c7 41 0a 6b 26 75 df bf 5d 34 5b 80 - 4d 20 1a dd 50 2d 5c e2 df cb 09 1c e9 99 7b be - be 57 30 6f 38 3e 4d 58 81 03 f0 36 f7 e8 5d 19 - 34 d1 52 a3 23 e4 a8 db 45 1d 6f 4a 5b 1b 0f 10 - 2c c1 50 e0 2f ee e2 b8 8d ea 4a d4 c1 ba cc b2 - 4d 84 07 2d 14 e1 d2 4a 67 71 f7 40 8e e3 05 64 - fb 86 d4 39 3a 34 bc f0 b7 88 50 1d 19 33 03 f1 - 3a 22 84 b0 01 f0 f6 49 ea f7 93 28 d4 ac 5c 43 - 0a b4 41 49 20 a9 46 0e d1 b7 bc 40 ec 65 3e 87 - 6d 09 ab c5 09 ae 45 b5 25 19 01 16 a0 c2 61 01 - 84 82 98 50 9c 1c 3b f3 a4 83 e7 27 40 54 e1 5e - 97 07 50 36 e9 89 f6 09 32 80 7b 52 57 75 1e 79''' - }, - # Plaintext - '''8b ba 6b f8 2a 6c 0f 86 d5 f1 75 6e 97 95 68 70 - b0 89 53 b0 6b 4e b2 05 bc 16 94 ee''', - # Ciphertext - '''53 ea 5d c0 8c d2 60 fb 3b 85 85 67 28 7f a9 15 - 52 c3 0b 2f eb fb a2 13 f0 ae 87 70 2d 06 8d 19 - ba b0 7f e5 74 52 3d fb 42 13 9d 68 c3 c5 af ee - e0 bf e4 cb 79 69 cb f3 82 b8 04 d6 e6 13 96 14 - 4e 2d 0e 60 74 1f 89 93 c3 01 4b 58 b9 b1 95 7a - 8b ab cd 23 af 85 4f 4c 35 6f b1 66 2a a7 2b fc - c7 e5 86 55 9d c4 28 0d 16 0c 12 67 85 a7 23 eb - ee be ff 71 f1 15 94 44 0a ae f8 7d 10 79 3a 87 - 74 a2 39 d4 a0 4c 87 fe 14 67 b9 da f8 52 08 ec - 6c 72 55 79 4a 96 cc 29 14 2f 9a 8b d4 18 e3 c1 - fd 67 34 4b 0c d0 82 9d f3 b2 be c6 02 53 19 62 - 93 c6 b3 4d 3f 75 d3 2f 21 3d d4 5c 62 73 d5 05 - ad f4 cc ed 10 57 cb 75 8f c2 6a ee fa 44 12 55 - ed 4e 64 c1 99 ee 07 5e 7f 16 64 61 82 fd b4 64 - 73 9b 68 ab 5d af f0 e6 3e 95 52 01 68 24 f0 54 - bf 4d 3c 8c 90 a9 7b b6 b6 55 32 84 eb 42 9f cc''', - # Random - '''47 e1 ab 71 19 fe e5 6c 95 ee 5e aa d8 6f 40 d0 - aa 63 bd 33''', - SHA1 - ), - ) - - def testEncrypt1(self): - # Verify encryption using all test vectors - for test in self._testData: - # Build the key - comps = [int(rws(test[0][x]), 16) for x in ('n', 'e')] - key = RSA.construct(comps) - - # RNG that takes its random numbers from a pool given - # at initialization - class randGen: - - def __init__(self, data): - self.data = data - self.idx = 0 - - def __call__(self, N): - r = self.data[self.idx:N] - self.idx += N - return r - - # The real test - cipher = PKCS.new(key, test[4], randfunc=randGen(t2b(test[3]))) - ct = cipher.encrypt(t2b(test[1])) - self.assertEqual(ct, t2b(test[2])) - - def testEncrypt2(self): - # Verify that encryption fails if plaintext is too long - pt = '\x00'*(128-2*20-2+1) - cipher = PKCS.new(self.key1024) - self.assertRaises(ValueError, cipher.encrypt, pt) - - def testDecrypt1(self): - # Verify decryption using all test vectors - for test in self._testData: - # Build the key - comps = [int(rws(test[0][x]),16) for x in ('n', 'e', 'd')] - key = RSA.construct(comps) - # The real test - cipher = PKCS.new(key, test[4]) - pt = cipher.decrypt(t2b(test[2])) - self.assertEqual(pt, t2b(test[1])) - - def testDecrypt2(self): - # Simplest possible negative tests - for ct_size in (127, 128, 129): - cipher = PKCS.new(self.key1024) - self.assertRaises(ValueError, cipher.decrypt, bchr(0x00)*ct_size) - - def testEncryptDecrypt1(self): - # Encrypt/Decrypt messages of length [0..128-2*20-2] - for pt_len in range(0, 128-2*20-2): - pt = self.rng(pt_len) - cipher = PKCS.new(self.key1024) - ct = cipher.encrypt(pt) - pt2 = cipher.decrypt(ct) - self.assertEqual(pt, pt2) - - def testEncryptDecrypt2(self): - # Helper function to monitor what's requested from RNG - global asked - - def localRng(N): - global asked - asked += N - return self.rng(N) - - # Verify that OAEP is friendly to all hashes - for hashmod in (MD2, MD5, SHA1, SHA256, RIPEMD160): - # Verify that encrypt() asks for as many random bytes - # as the hash output size - asked = 0 - pt = self.rng(40) - cipher = PKCS.new(self.key1024, hashmod, randfunc=localRng) - ct = cipher.encrypt(pt) - self.assertEqual(cipher.decrypt(ct), pt) - self.assertEqual(asked, hashmod.digest_size) - - def testEncryptDecrypt3(self): - # Verify that OAEP supports labels - pt = self.rng(35) - xlabel = self.rng(22) - cipher = PKCS.new(self.key1024, label=xlabel) - ct = cipher.encrypt(pt) - self.assertEqual(cipher.decrypt(ct), pt) - - def testEncryptDecrypt4(self): - # Verify that encrypt() uses the custom MGF - global mgfcalls - # Helper function to monitor what's requested from MGF - - def newMGF(seed, maskLen): - global mgfcalls - mgfcalls += 1 - return b'\x00' * maskLen - - mgfcalls = 0 - pt = self.rng(32) - cipher = PKCS.new(self.key1024, mgfunc=newMGF) - ct = cipher.encrypt(pt) - self.assertEqual(mgfcalls, 2) - self.assertEqual(cipher.decrypt(ct), pt) - - def testByteArray(self): - pt = b("XER") - cipher = PKCS.new(self.key1024) - ct = cipher.encrypt(bytearray(pt)) - pt2 = cipher.decrypt(bytearray(ct)) - self.assertEqual(pt, pt2) - - def testMemoryview(self): - pt = b("XER") - cipher = PKCS.new(self.key1024) - ct = cipher.encrypt(memoryview(bytearray(pt))) - pt2 = cipher.decrypt(memoryview(bytearray(ct))) - self.assertEqual(pt, pt2) - - -class TestVectorsWycheproof(unittest.TestCase): - - def __init__(self, wycheproof_warnings, skip_slow_tests): - unittest.TestCase.__init__(self) - self._wycheproof_warnings = wycheproof_warnings - self._skip_slow_tests = skip_slow_tests - self._id = "None" - - def load_tests(self, filename): - - def filter_rsa(group): - return RSA.import_key(group['privateKeyPem']) - - def filter_sha(group): - if group['sha'] == "SHA-1": - return SHA1 - elif group['sha'] == "SHA-224": - return SHA224 - elif group['sha'] == "SHA-256": - return SHA256 - elif group['sha'] == "SHA-384": - return SHA384 - elif group['sha'] == "SHA-512": - return SHA512 - else: - raise ValueError("Unknown sha " + group['sha']) - - def filter_mgf(group): - if group['mgfSha'] == "SHA-1": - return lambda x, y: MGF1(x, y, SHA1) - elif group['mgfSha'] == "SHA-224": - return lambda x, y: MGF1(x, y, SHA224) - elif group['mgfSha'] == "SHA-256": - return lambda x, y: MGF1(x, y, SHA256) - elif group['mgfSha'] == "SHA-384": - return lambda x, y: MGF1(x, y, SHA384) - elif group['mgfSha'] == "SHA-512": - return lambda x, y: MGF1(x, y, SHA512) - else: - raise ValueError("Unknown mgf/sha " + group['mgfSha']) - - def filter_algo(group): - return "%s with MGF1/%s" % (group['sha'], group['mgfSha']) - - result = load_test_vectors_wycheproof(("Cipher", "wycheproof"), - filename, - "Wycheproof PKCS#1 OAEP (%s)" % filename, - group_tag={'rsa_key': filter_rsa, - 'hash_mod': filter_sha, - 'mgf': filter_mgf, - 'algo': filter_algo} - ) - return result - - def setUp(self): - self.tv = [] - self.tv.extend(self.load_tests("rsa_oaep_2048_sha1_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha224_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha224_mgf1sha224_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha256_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha256_mgf1sha256_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha384_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha384_mgf1sha384_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha512_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_2048_sha512_mgf1sha512_test.json")) - if not self._skip_slow_tests: - self.tv.extend(self.load_tests("rsa_oaep_3072_sha256_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_3072_sha256_mgf1sha256_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_3072_sha512_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_3072_sha512_mgf1sha512_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_4096_sha256_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_4096_sha256_mgf1sha256_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_4096_sha512_mgf1sha1_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_4096_sha512_mgf1sha512_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_4096_sha512_mgf1sha512_test.json")) - self.tv.extend(self.load_tests("rsa_oaep_misc_test.json")) - - def shortDescription(self): - return self._id - - def warn(self, tv): - if tv.warning and self._wycheproof_warnings: - import warnings - warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment)) - - def test_decrypt(self, tv): - self._id = "Wycheproof Decrypt %s Test #%s" % (tv.algo, tv.id) - - cipher = PKCS.new(tv.rsa_key, hashAlgo=tv.hash_mod, mgfunc=tv.mgf, label=tv.label) - try: - pt = cipher.decrypt(tv.ct) - except ValueError: - assert not tv.valid - else: - assert tv.valid - self.assertEqual(pt, tv.msg) - self.warn(tv) - - def runTest(self): - - for tv in self.tv: - self.test_decrypt(tv) - - -def get_tests(config={}): - skip_slow_tests = not config.get('slow_tests') - wycheproof_warnings = config.get('wycheproof_warnings') - - tests = [] - tests += list_test_cases(PKCS1_OAEP_Tests) - tests += [TestVectorsWycheproof(wycheproof_warnings, skip_slow_tests)] - return tests - - -if __name__ == '__main__': - def suite(): - unittest.TestSuite(get_tests()) - unittest.main(defaultTest='suite') - -# vim:set ts=4 sw=4 sts=4 expandtab: diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/PyPDF2/_codecs/std.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/PyPDF2/_codecs/std.py deleted file mode 100644 index a6057ff3c7a90e9c31389d2bab1bd0f6058ad724..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/PyPDF2/_codecs/std.py +++ /dev/null @@ -1,258 +0,0 @@ -_std_encoding = [ - "\x00", - "\x01", - "\x02", - "\x03", - "\x04", - "\x05", - "\x06", - "\x07", - "\x08", - "\t", - "\n", - "\x0b", - "\x0c", - "\r", - "\x0e", - "\x0f", - "\x10", - "\x11", - "\x12", - "\x13", - "\x14", - "\x15", - "\x16", - "\x17", - "\x18", - "\x19", - "\x1a", - "\x1b", - "\x1c", - "\x1d", - "\x1e", - "\x1f", - " ", - "!", - '"', - "#", - "$", - "%", - "&", - "’", - "(", - ")", - "*", - "+", - ",", - "-", - ".", - "/", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - ":", - ";", - "<", - "=", - ">", - "?", - "@", - "A", - "B", - "C", - "D", - "E", - "F", - "G", - "H", - "I", - "J", - "K", - "L", - "M", - "N", - "O", - "P", - "Q", - "R", - "S", - "T", - "U", - "V", - "W", - "X", - "Y", - "Z", - "[", - "\\", - "]", - "^", - "_", - "‘", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "{", - "|", - "}", - "~", - "\x7f", - "\x80", - "\x81", - "\x82", - "\x83", - "\x84", - "\x85", - "\x86", - "\x87", - "\x88", - "\x89", - "\x8a", - "\x8b", - "\x8c", - "\x8d", - "\x8e", - "\x8f", - "\x90", - "\x91", - "\x92", - "\x93", - "\x94", - "\x95", - "\x96", - "\x97", - "\x98", - "\x99", - "\x9a", - "\x9b", - "\x9c", - "\x9d", - "\x9e", - "\x9f", - "\xa0", - "¡", - "¢", - "£", - "⁄", - "¥", - "ƒ", - "§", - "¤", - "'", - "“", - "«", - "‹", - "›", - "fi", - "fl", - "°", - "–", - "†", - "‡", - "·", - "µ", - "¶", - "•", - "‚", - "„", - "”", - "»", - "…", - "‰", - "¾", - "¿", - "À", - "`", - "´", - "ˆ", - "˜", - "¯", - "˘", - "˙", - "¨", - "É", - "˚", - "¸", - "Ì", - "˝", - "˛", - "ˇ", - "—", - "Ñ", - "Ò", - "Ó", - "Ô", - "Õ", - "Ö", - "×", - "Ø", - "Ù", - "Ú", - "Û", - "Ü", - "Ý", - "Þ", - "ß", - "à", - "Æ", - "â", - "ª", - "ä", - "å", - "æ", - "ç", - "Ł", - "Ø", - "Œ", - "º", - "ì", - "í", - "î", - "ï", - "ð", - "æ", - "ò", - "ó", - "ô", - "ı", - "ö", - "÷", - "ł", - "ø", - "œ", - "ß", - "ü", - "ý", - "þ", - "ÿ", -] diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/aiofiles/threadpool/text.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/aiofiles/threadpool/text.py deleted file mode 100644 index 0e625909b6c960ebed4a0ed99941b28156fbf2d1..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/aiofiles/threadpool/text.py +++ /dev/null @@ -1,64 +0,0 @@ -from ..base import AsyncBase, AsyncIndirectBase -from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly - - -@delegate_to_executor( - "close", - "flush", - "isatty", - "read", - "readable", - "readline", - "readlines", - "seek", - "seekable", - "tell", - "truncate", - "write", - "writable", - "writelines", -) -@proxy_method_directly("detach", "fileno", "readable") -@proxy_property_directly( - "buffer", - "closed", - "encoding", - "errors", - "line_buffering", - "newlines", - "name", - "mode", -) -class AsyncTextIOWrapper(AsyncBase): - """The asyncio executor version of io.TextIOWrapper.""" - - -@delegate_to_executor( - "close", - "flush", - "isatty", - "read", - "readable", - "readline", - "readlines", - "seek", - "seekable", - "tell", - "truncate", - "write", - "writable", - "writelines", -) -@proxy_method_directly("detach", "fileno", "readable") -@proxy_property_directly( - "buffer", - "closed", - "encoding", - "errors", - "line_buffering", - "newlines", - "name", - "mode", -) -class AsyncTextIndirectIOWrapper(AsyncIndirectBase): - """The indirect asyncio executor version of io.TextIOWrapper.""" diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/charset_normalizer/constant.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/charset_normalizer/constant.py deleted file mode 100644 index 3188108d6ba511bf92edd4d5ee9ca8b41311547b..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/charset_normalizer/constant.py +++ /dev/null @@ -1,495 +0,0 @@ -from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE -from encodings.aliases import aliases -from re import IGNORECASE, compile as re_compile -from typing import Dict, List, Set, Union - -from .assets import FREQUENCIES - -# Contain for each eligible encoding a list of/item bytes SIG/BOM -ENCODING_MARKS: Dict[str, Union[bytes, List[bytes]]] = { - "utf_8": BOM_UTF8, - "utf_7": [ - b"\x2b\x2f\x76\x38", - b"\x2b\x2f\x76\x39", - b"\x2b\x2f\x76\x2b", - b"\x2b\x2f\x76\x2f", - b"\x2b\x2f\x76\x38\x2d", - ], - "gb18030": b"\x84\x31\x95\x33", - "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE], - "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE], -} - -TOO_SMALL_SEQUENCE: int = 32 -TOO_BIG_SEQUENCE: int = int(10e6) - -UTF8_MAXIMAL_ALLOCATION: int = 1112064 - -UNICODE_RANGES_COMBINED: Dict[str, range] = { - "Control character": range(31 + 1), - "Basic Latin": range(32, 127 + 1), - "Latin-1 Supplement": range(128, 255 + 1), - "Latin Extended-A": range(256, 383 + 1), - "Latin Extended-B": range(384, 591 + 1), - "IPA Extensions": range(592, 687 + 1), - "Spacing Modifier Letters": range(688, 767 + 1), - "Combining Diacritical Marks": range(768, 879 + 1), - "Greek and Coptic": range(880, 1023 + 1), - "Cyrillic": range(1024, 1279 + 1), - "Cyrillic Supplement": range(1280, 1327 + 1), - "Armenian": range(1328, 1423 + 1), - "Hebrew": range(1424, 1535 + 1), - "Arabic": range(1536, 1791 + 1), - "Syriac": range(1792, 1871 + 1), - "Arabic Supplement": range(1872, 1919 + 1), - "Thaana": range(1920, 1983 + 1), - "NKo": range(1984, 2047 + 1), - "Samaritan": range(2048, 2111 + 1), - "Mandaic": range(2112, 2143 + 1), - "Syriac Supplement": range(2144, 2159 + 1), - "Arabic Extended-A": range(2208, 2303 + 1), - "Devanagari": range(2304, 2431 + 1), - "Bengali": range(2432, 2559 + 1), - "Gurmukhi": range(2560, 2687 + 1), - "Gujarati": range(2688, 2815 + 1), - "Oriya": range(2816, 2943 + 1), - "Tamil": range(2944, 3071 + 1), - "Telugu": range(3072, 3199 + 1), - "Kannada": range(3200, 3327 + 1), - "Malayalam": range(3328, 3455 + 1), - "Sinhala": range(3456, 3583 + 1), - "Thai": range(3584, 3711 + 1), - "Lao": range(3712, 3839 + 1), - "Tibetan": range(3840, 4095 + 1), - "Myanmar": range(4096, 4255 + 1), - "Georgian": range(4256, 4351 + 1), - "Hangul Jamo": range(4352, 4607 + 1), - "Ethiopic": range(4608, 4991 + 1), - "Ethiopic Supplement": range(4992, 5023 + 1), - "Cherokee": range(5024, 5119 + 1), - "Unified Canadian Aboriginal Syllabics": range(5120, 5759 + 1), - "Ogham": range(5760, 5791 + 1), - "Runic": range(5792, 5887 + 1), - "Tagalog": range(5888, 5919 + 1), - "Hanunoo": range(5920, 5951 + 1), - "Buhid": range(5952, 5983 + 1), - "Tagbanwa": range(5984, 6015 + 1), - "Khmer": range(6016, 6143 + 1), - "Mongolian": range(6144, 6319 + 1), - "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6399 + 1), - "Limbu": range(6400, 6479 + 1), - "Tai Le": range(6480, 6527 + 1), - "New Tai Lue": range(6528, 6623 + 1), - "Khmer Symbols": range(6624, 6655 + 1), - "Buginese": range(6656, 6687 + 1), - "Tai Tham": range(6688, 6831 + 1), - "Combining Diacritical Marks Extended": range(6832, 6911 + 1), - "Balinese": range(6912, 7039 + 1), - "Sundanese": range(7040, 7103 + 1), - "Batak": range(7104, 7167 + 1), - "Lepcha": range(7168, 7247 + 1), - "Ol Chiki": range(7248, 7295 + 1), - "Cyrillic Extended C": range(7296, 7311 + 1), - "Sundanese Supplement": range(7360, 7375 + 1), - "Vedic Extensions": range(7376, 7423 + 1), - "Phonetic Extensions": range(7424, 7551 + 1), - "Phonetic Extensions Supplement": range(7552, 7615 + 1), - "Combining Diacritical Marks Supplement": range(7616, 7679 + 1), - "Latin Extended Additional": range(7680, 7935 + 1), - "Greek Extended": range(7936, 8191 + 1), - "General Punctuation": range(8192, 8303 + 1), - "Superscripts and Subscripts": range(8304, 8351 + 1), - "Currency Symbols": range(8352, 8399 + 1), - "Combining Diacritical Marks for Symbols": range(8400, 8447 + 1), - "Letterlike Symbols": range(8448, 8527 + 1), - "Number Forms": range(8528, 8591 + 1), - "Arrows": range(8592, 8703 + 1), - "Mathematical Operators": range(8704, 8959 + 1), - "Miscellaneous Technical": range(8960, 9215 + 1), - "Control Pictures": range(9216, 9279 + 1), - "Optical Character Recognition": range(9280, 9311 + 1), - "Enclosed Alphanumerics": range(9312, 9471 + 1), - "Box Drawing": range(9472, 9599 + 1), - "Block Elements": range(9600, 9631 + 1), - "Geometric Shapes": range(9632, 9727 + 1), - "Miscellaneous Symbols": range(9728, 9983 + 1), - "Dingbats": range(9984, 10175 + 1), - "Miscellaneous Mathematical Symbols-A": range(10176, 10223 + 1), - "Supplemental Arrows-A": range(10224, 10239 + 1), - "Braille Patterns": range(10240, 10495 + 1), - "Supplemental Arrows-B": range(10496, 10623 + 1), - "Miscellaneous Mathematical Symbols-B": range(10624, 10751 + 1), - "Supplemental Mathematical Operators": range(10752, 11007 + 1), - "Miscellaneous Symbols and Arrows": range(11008, 11263 + 1), - "Glagolitic": range(11264, 11359 + 1), - "Latin Extended-C": range(11360, 11391 + 1), - "Coptic": range(11392, 11519 + 1), - "Georgian Supplement": range(11520, 11567 + 1), - "Tifinagh": range(11568, 11647 + 1), - "Ethiopic Extended": range(11648, 11743 + 1), - "Cyrillic Extended-A": range(11744, 11775 + 1), - "Supplemental Punctuation": range(11776, 11903 + 1), - "CJK Radicals Supplement": range(11904, 12031 + 1), - "Kangxi Radicals": range(12032, 12255 + 1), - "Ideographic Description Characters": range(12272, 12287 + 1), - "CJK Symbols and Punctuation": range(12288, 12351 + 1), - "Hiragana": range(12352, 12447 + 1), - "Katakana": range(12448, 12543 + 1), - "Bopomofo": range(12544, 12591 + 1), - "Hangul Compatibility Jamo": range(12592, 12687 + 1), - "Kanbun": range(12688, 12703 + 1), - "Bopomofo Extended": range(12704, 12735 + 1), - "CJK Strokes": range(12736, 12783 + 1), - "Katakana Phonetic Extensions": range(12784, 12799 + 1), - "Enclosed CJK Letters and Months": range(12800, 13055 + 1), - "CJK Compatibility": range(13056, 13311 + 1), - "CJK Unified Ideographs Extension A": range(13312, 19903 + 1), - "Yijing Hexagram Symbols": range(19904, 19967 + 1), - "CJK Unified Ideographs": range(19968, 40959 + 1), - "Yi Syllables": range(40960, 42127 + 1), - "Yi Radicals": range(42128, 42191 + 1), - "Lisu": range(42192, 42239 + 1), - "Vai": range(42240, 42559 + 1), - "Cyrillic Extended-B": range(42560, 42655 + 1), - "Bamum": range(42656, 42751 + 1), - "Modifier Tone Letters": range(42752, 42783 + 1), - "Latin Extended-D": range(42784, 43007 + 1), - "Syloti Nagri": range(43008, 43055 + 1), - "Common Indic Number Forms": range(43056, 43071 + 1), - "Phags-pa": range(43072, 43135 + 1), - "Saurashtra": range(43136, 43231 + 1), - "Devanagari Extended": range(43232, 43263 + 1), - "Kayah Li": range(43264, 43311 + 1), - "Rejang": range(43312, 43359 + 1), - "Hangul Jamo Extended-A": range(43360, 43391 + 1), - "Javanese": range(43392, 43487 + 1), - "Myanmar Extended-B": range(43488, 43519 + 1), - "Cham": range(43520, 43615 + 1), - "Myanmar Extended-A": range(43616, 43647 + 1), - "Tai Viet": range(43648, 43743 + 1), - "Meetei Mayek Extensions": range(43744, 43775 + 1), - "Ethiopic Extended-A": range(43776, 43823 + 1), - "Latin Extended-E": range(43824, 43887 + 1), - "Cherokee Supplement": range(43888, 43967 + 1), - "Meetei Mayek": range(43968, 44031 + 1), - "Hangul Syllables": range(44032, 55215 + 1), - "Hangul Jamo Extended-B": range(55216, 55295 + 1), - "High Surrogates": range(55296, 56191 + 1), - "High Private Use Surrogates": range(56192, 56319 + 1), - "Low Surrogates": range(56320, 57343 + 1), - "Private Use Area": range(57344, 63743 + 1), - "CJK Compatibility Ideographs": range(63744, 64255 + 1), - "Alphabetic Presentation Forms": range(64256, 64335 + 1), - "Arabic Presentation Forms-A": range(64336, 65023 + 1), - "Variation Selectors": range(65024, 65039 + 1), - "Vertical Forms": range(65040, 65055 + 1), - "Combining Half Marks": range(65056, 65071 + 1), - "CJK Compatibility Forms": range(65072, 65103 + 1), - "Small Form Variants": range(65104, 65135 + 1), - "Arabic Presentation Forms-B": range(65136, 65279 + 1), - "Halfwidth and Fullwidth Forms": range(65280, 65519 + 1), - "Specials": range(65520, 65535 + 1), - "Linear B Syllabary": range(65536, 65663 + 1), - "Linear B Ideograms": range(65664, 65791 + 1), - "Aegean Numbers": range(65792, 65855 + 1), - "Ancient Greek Numbers": range(65856, 65935 + 1), - "Ancient Symbols": range(65936, 65999 + 1), - "Phaistos Disc": range(66000, 66047 + 1), - "Lycian": range(66176, 66207 + 1), - "Carian": range(66208, 66271 + 1), - "Coptic Epact Numbers": range(66272, 66303 + 1), - "Old Italic": range(66304, 66351 + 1), - "Gothic": range(66352, 66383 + 1), - "Old Permic": range(66384, 66431 + 1), - "Ugaritic": range(66432, 66463 + 1), - "Old Persian": range(66464, 66527 + 1), - "Deseret": range(66560, 66639 + 1), - "Shavian": range(66640, 66687 + 1), - "Osmanya": range(66688, 66735 + 1), - "Osage": range(66736, 66815 + 1), - "Elbasan": range(66816, 66863 + 1), - "Caucasian Albanian": range(66864, 66927 + 1), - "Linear A": range(67072, 67455 + 1), - "Cypriot Syllabary": range(67584, 67647 + 1), - "Imperial Aramaic": range(67648, 67679 + 1), - "Palmyrene": range(67680, 67711 + 1), - "Nabataean": range(67712, 67759 + 1), - "Hatran": range(67808, 67839 + 1), - "Phoenician": range(67840, 67871 + 1), - "Lydian": range(67872, 67903 + 1), - "Meroitic Hieroglyphs": range(67968, 67999 + 1), - "Meroitic Cursive": range(68000, 68095 + 1), - "Kharoshthi": range(68096, 68191 + 1), - "Old South Arabian": range(68192, 68223 + 1), - "Old North Arabian": range(68224, 68255 + 1), - "Manichaean": range(68288, 68351 + 1), - "Avestan": range(68352, 68415 + 1), - "Inscriptional Parthian": range(68416, 68447 + 1), - "Inscriptional Pahlavi": range(68448, 68479 + 1), - "Psalter Pahlavi": range(68480, 68527 + 1), - "Old Turkic": range(68608, 68687 + 1), - "Old Hungarian": range(68736, 68863 + 1), - "Rumi Numeral Symbols": range(69216, 69247 + 1), - "Brahmi": range(69632, 69759 + 1), - "Kaithi": range(69760, 69839 + 1), - "Sora Sompeng": range(69840, 69887 + 1), - "Chakma": range(69888, 69967 + 1), - "Mahajani": range(69968, 70015 + 1), - "Sharada": range(70016, 70111 + 1), - "Sinhala Archaic Numbers": range(70112, 70143 + 1), - "Khojki": range(70144, 70223 + 1), - "Multani": range(70272, 70319 + 1), - "Khudawadi": range(70320, 70399 + 1), - "Grantha": range(70400, 70527 + 1), - "Newa": range(70656, 70783 + 1), - "Tirhuta": range(70784, 70879 + 1), - "Siddham": range(71040, 71167 + 1), - "Modi": range(71168, 71263 + 1), - "Mongolian Supplement": range(71264, 71295 + 1), - "Takri": range(71296, 71375 + 1), - "Ahom": range(71424, 71487 + 1), - "Warang Citi": range(71840, 71935 + 1), - "Zanabazar Square": range(72192, 72271 + 1), - "Soyombo": range(72272, 72367 + 1), - "Pau Cin Hau": range(72384, 72447 + 1), - "Bhaiksuki": range(72704, 72815 + 1), - "Marchen": range(72816, 72895 + 1), - "Masaram Gondi": range(72960, 73055 + 1), - "Cuneiform": range(73728, 74751 + 1), - "Cuneiform Numbers and Punctuation": range(74752, 74879 + 1), - "Early Dynastic Cuneiform": range(74880, 75087 + 1), - "Egyptian Hieroglyphs": range(77824, 78895 + 1), - "Anatolian Hieroglyphs": range(82944, 83583 + 1), - "Bamum Supplement": range(92160, 92735 + 1), - "Mro": range(92736, 92783 + 1), - "Bassa Vah": range(92880, 92927 + 1), - "Pahawh Hmong": range(92928, 93071 + 1), - "Miao": range(93952, 94111 + 1), - "Ideographic Symbols and Punctuation": range(94176, 94207 + 1), - "Tangut": range(94208, 100351 + 1), - "Tangut Components": range(100352, 101119 + 1), - "Kana Supplement": range(110592, 110847 + 1), - "Kana Extended-A": range(110848, 110895 + 1), - "Nushu": range(110960, 111359 + 1), - "Duployan": range(113664, 113823 + 1), - "Shorthand Format Controls": range(113824, 113839 + 1), - "Byzantine Musical Symbols": range(118784, 119039 + 1), - "Musical Symbols": range(119040, 119295 + 1), - "Ancient Greek Musical Notation": range(119296, 119375 + 1), - "Tai Xuan Jing Symbols": range(119552, 119647 + 1), - "Counting Rod Numerals": range(119648, 119679 + 1), - "Mathematical Alphanumeric Symbols": range(119808, 120831 + 1), - "Sutton SignWriting": range(120832, 121519 + 1), - "Glagolitic Supplement": range(122880, 122927 + 1), - "Mende Kikakui": range(124928, 125151 + 1), - "Adlam": range(125184, 125279 + 1), - "Arabic Mathematical Alphabetic Symbols": range(126464, 126719 + 1), - "Mahjong Tiles": range(126976, 127023 + 1), - "Domino Tiles": range(127024, 127135 + 1), - "Playing Cards": range(127136, 127231 + 1), - "Enclosed Alphanumeric Supplement": range(127232, 127487 + 1), - "Enclosed Ideographic Supplement": range(127488, 127743 + 1), - "Miscellaneous Symbols and Pictographs": range(127744, 128511 + 1), - "Emoticons range(Emoji)": range(128512, 128591 + 1), - "Ornamental Dingbats": range(128592, 128639 + 1), - "Transport and Map Symbols": range(128640, 128767 + 1), - "Alchemical Symbols": range(128768, 128895 + 1), - "Geometric Shapes Extended": range(128896, 129023 + 1), - "Supplemental Arrows-C": range(129024, 129279 + 1), - "Supplemental Symbols and Pictographs": range(129280, 129535 + 1), - "CJK Unified Ideographs Extension B": range(131072, 173791 + 1), - "CJK Unified Ideographs Extension C": range(173824, 177983 + 1), - "CJK Unified Ideographs Extension D": range(177984, 178207 + 1), - "CJK Unified Ideographs Extension E": range(178208, 183983 + 1), - "CJK Unified Ideographs Extension F": range(183984, 191471 + 1), - "CJK Compatibility Ideographs Supplement": range(194560, 195103 + 1), - "Tags": range(917504, 917631 + 1), - "Variation Selectors Supplement": range(917760, 917999 + 1), -} - - -UNICODE_SECONDARY_RANGE_KEYWORD: List[str] = [ - "Supplement", - "Extended", - "Extensions", - "Modifier", - "Marks", - "Punctuation", - "Symbols", - "Forms", - "Operators", - "Miscellaneous", - "Drawing", - "Block", - "Shapes", - "Supplemental", - "Tags", -] - -RE_POSSIBLE_ENCODING_INDICATION = re_compile( - r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", - IGNORECASE, -) - -IANA_SUPPORTED: List[str] = sorted( - filter( - lambda x: x.endswith("_codec") is False - and x not in {"rot_13", "tactis", "mbcs"}, - list(set(aliases.values())), - ) -) - -IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED) - -# pre-computed code page that are similar using the function cp_similarity. -IANA_SUPPORTED_SIMILAR: Dict[str, List[str]] = { - "cp037": ["cp1026", "cp1140", "cp273", "cp500"], - "cp1026": ["cp037", "cp1140", "cp273", "cp500"], - "cp1125": ["cp866"], - "cp1140": ["cp037", "cp1026", "cp273", "cp500"], - "cp1250": ["iso8859_2"], - "cp1251": ["kz1048", "ptcp154"], - "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], - "cp1253": ["iso8859_7"], - "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], - "cp1257": ["iso8859_13"], - "cp273": ["cp037", "cp1026", "cp1140", "cp500"], - "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], - "cp500": ["cp037", "cp1026", "cp1140", "cp273"], - "cp850": ["cp437", "cp857", "cp858", "cp865"], - "cp857": ["cp850", "cp858", "cp865"], - "cp858": ["cp437", "cp850", "cp857", "cp865"], - "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], - "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], - "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], - "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], - "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], - "cp866": ["cp1125"], - "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], - "iso8859_11": ["tis_620"], - "iso8859_13": ["cp1257"], - "iso8859_14": [ - "iso8859_10", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_15": [ - "cp1252", - "cp1254", - "iso8859_10", - "iso8859_14", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_16": [ - "iso8859_14", - "iso8859_15", - "iso8859_2", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], - "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], - "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], - "iso8859_7": ["cp1253"], - "iso8859_9": [ - "cp1252", - "cp1254", - "cp1258", - "iso8859_10", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_4", - "latin_1", - ], - "kz1048": ["cp1251", "ptcp154"], - "latin_1": [ - "cp1252", - "cp1254", - "cp1258", - "iso8859_10", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_4", - "iso8859_9", - ], - "mac_iceland": ["mac_roman", "mac_turkish"], - "mac_roman": ["mac_iceland", "mac_turkish"], - "mac_turkish": ["mac_iceland", "mac_roman"], - "ptcp154": ["cp1251", "kz1048"], - "tis_620": ["iso8859_11"], -} - - -CHARDET_CORRESPONDENCE: Dict[str, str] = { - "iso2022_kr": "ISO-2022-KR", - "iso2022_jp": "ISO-2022-JP", - "euc_kr": "EUC-KR", - "tis_620": "TIS-620", - "utf_32": "UTF-32", - "euc_jp": "EUC-JP", - "koi8_r": "KOI8-R", - "iso8859_1": "ISO-8859-1", - "iso8859_2": "ISO-8859-2", - "iso8859_5": "ISO-8859-5", - "iso8859_6": "ISO-8859-6", - "iso8859_7": "ISO-8859-7", - "iso8859_8": "ISO-8859-8", - "utf_16": "UTF-16", - "cp855": "IBM855", - "mac_cyrillic": "MacCyrillic", - "gb2312": "GB2312", - "gb18030": "GB18030", - "cp932": "CP932", - "cp866": "IBM866", - "utf_8": "utf-8", - "utf_8_sig": "UTF-8-SIG", - "shift_jis": "SHIFT_JIS", - "big5": "Big5", - "cp1250": "windows-1250", - "cp1251": "windows-1251", - "cp1252": "Windows-1252", - "cp1253": "windows-1253", - "cp1255": "windows-1255", - "cp1256": "windows-1256", - "cp1254": "Windows-1254", - "cp949": "CP949", -} - - -COMMON_SAFE_ASCII_CHARACTERS: Set[str] = { - "<", - ">", - "=", - ":", - "/", - "&", - ";", - "{", - "}", - "[", - "]", - ",", - "|", - '"', - "-", -} - - -KO_NAMES: Set[str] = {"johab", "cp949", "euc_kr"} -ZH_NAMES: Set[str] = {"big5", "cp950", "big5hkscs", "hz"} - -LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES) - -# Logging LEVEL below DEBUG -TRACE: int = 5 diff --git a/spaces/johnsu6616/TXT2IMG-MJ-Desc/app.py b/spaces/johnsu6616/TXT2IMG-MJ-Desc/app.py deleted file mode 100644 index 74103b6bc32502f8b812d01552c2d4ac5523b241..0000000000000000000000000000000000000000 --- a/spaces/johnsu6616/TXT2IMG-MJ-Desc/app.py +++ /dev/null @@ -1,77 +0,0 @@ -# Importar bibliotecas -import torch -import re -import random -import requests -import shutil -from clip_interrogator import Config, Interrogator -from transformers import pipeline, set_seed, AutoTokenizer, AutoModelForSeq2SeqLM -from PIL import Image -import gradio as gr - -# Configurar CLIP -config = Config() -config.device = 'cuda' if torch.cuda.is_available() else 'cpu' -config.blip_offload = False if torch.cuda.is_available() else True -config.chunk_size = 2048 -config.flavor_intermediate_count = 512 -config.blip_num_beams = 64 -config.clip_model_name = "ViT-H-14/laion2b_s32b_b79k" -ci = Interrogator(config) - -# Función para generar prompt desde imagen -def get_prompt_from_image(image, mode): - image = image.convert('RGB') - if mode == 'best': - prompt = ci.interrogate(image) - elif mode == 'classic': - prompt = ci.interrogate_classic(image) - elif mode == 'fast': - prompt = ci.interrogate_fast(image) - elif mode == 'negative': - prompt = ci.interrogate_negative(image) - return prompt - -# Función para generar texto -text_pipe = pipeline('text-generation', model='succinctly/text2image-prompt-generator') - -def text_generate(input): - seed = random.randint(100, 1000000) - set_seed(seed) - for count in range(6): - sequences = text_pipe(input, max_length=random.randint(60, 90), num_return_sequences=8) - list = [] - for sequence in sequences: - line = sequence['generated_text'].strip() - if line != input and len(line) > (len(input) + 4) and line.endswith((':', '-', '—')) is False: - list.append(line) - - result = "\n".join(list) - result = re.sub('[^ ]+\.[^ ]+','', result) - result = result.replace('<', '').replace('>', '') - if result != '': - return result - if count == 5: - return result - -# Crear interfaz gradio -with gr.Blocks() as block: - with gr.Column(): - gr.HTML('

      MidJourney / SD2 Helper Tool

      ') - with gr.Tab('Generate from Image'): - with gr.Row(): - input_image = gr.Image(type='pil') - with gr.Column(): - input_mode = gr.Radio(['best', 'fast', 'classic', 'negative'], value='best', label='Mode') - img_btn = gr.Button('Discover Image Prompt') - output_image = gr.Textbox(lines=6, label='Generated Prompt') - - with gr.Tab('Generate from Text'): - input_text = gr.Textbox(lines=6, label='Your Idea', placeholder='Enter your content here...') - output_text = gr.Textbox(lines=6, label='Generated Prompt') - text_btn = gr.Button('Generate Prompt') - - img_btn.click(fn=get_prompt_from_image, inputs=[input_image, input_mode], outputs=output_image) - text_btn.click(fn=text_generate, inputs=input_text, outputs=output_text) - -block.queue(max_size=64).launch(show_api=False, enable_queue=True, debug=True, share=False, server_name='0.0.0.0') \ No newline at end of file diff --git a/spaces/jracca/05-learning-space/README.md b/spaces/jracca/05-learning-space/README.md deleted file mode 100644 index 365dc3466f9810cca7b26cd6c50e0d5799657d8f..0000000000000000000000000000000000000000 --- a/spaces/jracca/05-learning-space/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 05 Learning Space -emoji: 📚 -colorFrom: indigo -colorTo: red -sdk: gradio -sdk_version: 3.1.5 -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/julien-c/cube/README.md b/spaces/julien-c/cube/README.md deleted file mode 100644 index 624aa31a6d983778fdc304a2aaa8fe2bb8a378c5..0000000000000000000000000000000000000000 --- a/spaces/julien-c/cube/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Cube -emoji: 🚚 -colorFrom: yellow -colorTo: red -sdk: gradio -sdk_version: 2.9.1 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/justin-zk/Personalize-SAM/per_segment_anything/utils/transforms.py b/spaces/justin-zk/Personalize-SAM/per_segment_anything/utils/transforms.py deleted file mode 100644 index c08ba1e3db751f3a5483a003be38c69c2cf2df85..0000000000000000000000000000000000000000 --- a/spaces/justin-zk/Personalize-SAM/per_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 the 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[2], image.shape[3], 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/k2s0/talk-to-god/README.md b/spaces/k2s0/talk-to-god/README.md deleted file mode 100644 index 4d5226731fbe8617771a536c30a61225c923abad..0000000000000000000000000000000000000000 --- a/spaces/k2s0/talk-to-god/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Talk To God -emoji: ☀️ -colorFrom: blue -colorTo: purple -sdk: gradio -sdk_version: 3.15.0 -app_file: app.py -pinned: false -license: cc ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/kepl/gpt/client/css/style.css b/spaces/kepl/gpt/client/css/style.css deleted file mode 100644 index 918cf83eb9a36bf07c861e4476c60af65f5bf91d..0000000000000000000000000000000000000000 --- a/spaces/kepl/gpt/client/css/style.css +++ /dev/null @@ -1,18 +0,0 @@ -@import "./global.css"; -@import "./hljs.css"; -@import "./main.css"; -@import "./sidebar.css"; -@import "./conversation.css"; -@import "./message.css"; -@import "./stop-generating.css"; -@import "./typing.css"; -@import "./checkbox.css"; -@import "./label.css"; -@import "./button.css"; -@import "./buttons.css"; -@import "./dropdown.css"; -@import "./field.css"; -@import "./select.css"; -@import "./options.css"; -@import "./settings.css"; -@import "./message-input.css"; diff --git a/spaces/keras-io/TabTransformer_Classification/app.py b/spaces/keras-io/TabTransformer_Classification/app.py deleted file mode 100644 index d3cfab16ca8686c8907f857ddd382489208cad7e..0000000000000000000000000000000000000000 --- a/spaces/keras-io/TabTransformer_Classification/app.py +++ /dev/null @@ -1,91 +0,0 @@ -import math -import numpy as np -import pandas as pd -import tensorflow as tf -import tensorflow_addons as tfa -from tensorflow import keras -from tensorflow.keras import layers - -import gradio as gr -from huggingface_hub import from_pretrained_keras - -model = from_pretrained_keras('keras-io/tab_transformer', custom_objects={'optimizer': tfa.optimizers.AdamW}) - -def get_dataset_from_pandas(data): - for col in data.columns: - if data[col].dtype == 'float64': - data[col] = data[col].astype('float32') - elif col == 'age': - data[col] = data[col].astype('float32') - ds = tf.data.Dataset.from_tensors(dict(data.drop(columns = [i for i in ['income_bracket','fnlwgt'] if i in data.columns]))) - return ds - - -def infer(age, workclass, education, education_num, marital_status, occupation, relationship, race, gender, capital_gain, capital_loss, hours_per_week, native_country): - - data = pd.DataFrame({ - 'age': age, - 'workclass': workclass, - 'education': education, - 'education_num': education_num, - 'marital_status': marital_status, - 'occupation': occupation, - 'relationship':relationship, - 'race': race, - 'gender': gender, - 'capital_gain': capital_gain, - 'capital_loss': capital_loss, - 'hours_per_week':hours_per_week, - 'native_country': native_country, - }, index=[0]) - validation_dataset = get_dataset_from_pandas(data) - # validation_dataset = get_dataset_from_csv(test_data_file, 1) - pred = model.predict(validation_dataset) - - return f"{round(pred.flatten()[0]*100, 2)}%" - -# get the inputs -inputs = [ - gr.Slider(minimum=16, maximum=120, step=1, label='age', value=30), - gr.Radio(choices=[' Private', ' Local-gov', ' ?', ' Self-emp-not-inc',' Federal-gov', ' State-gov', ' Self-emp-inc', ' Without-pay', ' Never-worked'], - label='workclass', type='value',value=' Private'), - gr.Radio(choices=[' 11th', ' HS-grad', ' Assoc-acdm', ' Some-college', ' 10th', ' Prof-school', ' 7th-8th', ' Bachelors', ' Masters', ' Doctorate', - ' 5th-6th', ' Assoc-voc', ' 9th', ' 12th', ' 1st-4th', ' Preschool'], - type='value', label='education', value=' Bachelors'), - gr.Slider(minimum=1, maximum=16, step=1, label='education_num', value=10), - gr.Radio(choices=['', ' Married-civ-spouse', ' Widowed', ' Divorced', ' Separated', ' Married-spouse-absent', ' Married-AF-spouse'], - type='value', label='marital_status', value=' Married-civ-spouse'), - gr.Radio(choices=[' Machine-op-inspct', ' Farming-fishing', ' Protective-serv', ' ?', ' Other-service', ' Prof-specialty', ' Craft-repair', - ' Adm-clerical', ' Exec-managerial', ' Tech-support', ' Sales', ' Priv-house-serv', ' Transport-moving', ' Handlers-cleaners', ' Armed-Forces'], - type='value', label='occupation', value=' Tech-support'), - gr.Radio(choices=[' Own-child', ' Husband', ' Not-in-family', ' Unmarried', ' Wife', ' Other-relative'], - type='value', label='relationship', value=' Wife'), - gr.Radio(choices=[' Black', ' White', ' Asian-Pac-Islander', ' Other', ' Amer-Indian-Eskimo'], - type='value', label='race', value=' Other'), - gr.Radio(choices=[' Male', ' Female'], type='value', label='gender', value=' Female'), - gr.Slider(minimum=0, maximum=500000, step=1, label='capital_gain', value=80000), - gr.Slider(minimum=0, maximum=50000, step=1, label='capital_loss', value=1000), - gr.Slider(minimum=1, maximum=168, step=1, label='hours_per_week', value=40), - gr.Radio(choices=[' United-States', ' ?', ' Peru', ' Guatemala', ' Mexico', ' Dominican-Republic', ' Ireland', ' Germany', ' Philippines', ' Thailand', ' Haiti', - ' El-Salvador', ' Puerto-Rico', ' Vietnam', ' South', ' Columbia', ' Japan', ' India', ' Cambodia', ' Poland', ' Laos', ' England', ' Cuba', ' Taiwan', - ' Italy', ' Canada', ' Portugal', ' China', ' Nicaragua', ' Honduras', ' Iran', ' Scotland', ' Jamaica', ' Ecuador', ' Yugoslavia', ' Hungary', - ' Hong', ' Greece', ' Trinadad&Tobago', ' Outlying-US(Guam-USVI-etc)', ' France'], - type='value', label='native_country', value=' Vietnam'), - ] - -# the app outputs two segmented images -output = gr.Textbox(label='Probability of income larger than 50,000 USD per year:') -# it's good practice to pass examples, description and a title to guide users -title = 'Tab Transformer for Structured data' -description = 'Using Transformer to predict whether the income will be larger than 50,000 USD given the input features.' - -article = "Author: Nhu Hoang. Based on this keras example by Khalid Salama. HuggingFace Model here " - -examples = [[39.0, ' State-gov', ' Assoc-voc', 11.0, ' Divorced', ' Tech-support', ' Not-in-family', ' White', ' Female', 50000.0, 0.0, 40.0, ' Puerto-Rico'], - [65.0, ' Self-emp-inc', ' 12th', 8.0, ' Married-civ-spouse', ' Handlers-cleaners', ' Husband', ' Black', ' Male', 41000.0, 0.0, 55.0, ' United-States'], - [42.0, ' Private',' Masters', 14.0, ' Married-civ-spouse', ' Prof-specialty', ' Husband', ' Asian-Pac-Islander', ' Male', 35000.0, 0.0, 40.0, ' Taiwan',], - [25.0, ' Local-gov',' Bachelors', 13.0, ' Never-married', ' Craft-repair', ' Unmarried', ' White', ' Male', 75000.0, 0.0, 51.0, ' England'], - [57.0, ' Private', ' Masters', 14.0, ' Never-married', ' Prof-specialty', ' Not-in-family', ' Asian-Pac-Islander', ' Male', 150000.0, 0.0, 45.0, ' Iran']] - -gr.Interface(infer, inputs, output, examples= examples, allow_flagging='never', - title=title, description=description, article=article, live=False).launch(enable_queue=True, debug=True, inbrowser=True) diff --git a/spaces/kevinwang676/VoiceChangers/src/face3d/data/__init__.py b/spaces/kevinwang676/VoiceChangers/src/face3d/data/__init__.py deleted file mode 100644 index 9a9761c518a1b07c5996165869742af0a52c82bc..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VoiceChangers/src/face3d/data/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -"""This package includes all the modules related to data loading and preprocessing - - To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset. - You need to implement four functions: - -- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt). - -- <__len__>: return the size of dataset. - -- <__getitem__>: get a data point from data loader. - -- : (optionally) add dataset-specific options and set default options. - -Now you can use the dataset class by specifying flag '--dataset_mode dummy'. -See our template dataset class 'template_dataset.py' for more details. -""" -import numpy as np -import importlib -import torch.utils.data -from face3d.data.base_dataset import BaseDataset - - -def find_dataset_using_name(dataset_name): - """Import the module "data/[dataset_name]_dataset.py". - - In the file, the class called DatasetNameDataset() will - be instantiated. It has to be a subclass of BaseDataset, - and it is case-insensitive. - """ - dataset_filename = "data." + dataset_name + "_dataset" - datasetlib = importlib.import_module(dataset_filename) - - dataset = None - target_dataset_name = dataset_name.replace('_', '') + 'dataset' - for name, cls in datasetlib.__dict__.items(): - if name.lower() == target_dataset_name.lower() \ - and issubclass(cls, BaseDataset): - dataset = cls - - if dataset is None: - raise NotImplementedError("In %s.py, there should be a subclass of BaseDataset with class name that matches %s in lowercase." % (dataset_filename, target_dataset_name)) - - return dataset - - -def get_option_setter(dataset_name): - """Return the static method of the dataset class.""" - dataset_class = find_dataset_using_name(dataset_name) - return dataset_class.modify_commandline_options - - -def create_dataset(opt, rank=0): - """Create a dataset given the option. - - This function wraps the class CustomDatasetDataLoader. - This is the main interface between this package and 'train.py'/'test.py' - - Example: - >>> from data import create_dataset - >>> dataset = create_dataset(opt) - """ - data_loader = CustomDatasetDataLoader(opt, rank=rank) - dataset = data_loader.load_data() - return dataset - -class CustomDatasetDataLoader(): - """Wrapper class of Dataset class that performs multi-threaded data loading""" - - def __init__(self, opt, rank=0): - """Initialize this class - - Step 1: create a dataset instance given the name [dataset_mode] - Step 2: create a multi-threaded data loader. - """ - self.opt = opt - dataset_class = find_dataset_using_name(opt.dataset_mode) - self.dataset = dataset_class(opt) - self.sampler = None - print("rank %d %s dataset [%s] was created" % (rank, self.dataset.name, type(self.dataset).__name__)) - if opt.use_ddp and opt.isTrain: - world_size = opt.world_size - self.sampler = torch.utils.data.distributed.DistributedSampler( - self.dataset, - num_replicas=world_size, - rank=rank, - shuffle=not opt.serial_batches - ) - self.dataloader = torch.utils.data.DataLoader( - self.dataset, - sampler=self.sampler, - num_workers=int(opt.num_threads / world_size), - batch_size=int(opt.batch_size / world_size), - drop_last=True) - else: - self.dataloader = torch.utils.data.DataLoader( - self.dataset, - batch_size=opt.batch_size, - shuffle=(not opt.serial_batches) and opt.isTrain, - num_workers=int(opt.num_threads), - drop_last=True - ) - - def set_epoch(self, epoch): - self.dataset.current_epoch = epoch - if self.sampler is not None: - self.sampler.set_epoch(epoch) - - def load_data(self): - return self - - def __len__(self): - """Return the number of data in the dataset""" - return min(len(self.dataset), self.opt.max_dataset_size) - - def __iter__(self): - """Return a batch of data""" - for i, data in enumerate(self.dataloader): - if i * self.opt.batch_size >= self.opt.max_dataset_size: - break - yield data diff --git a/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/eval_ijbc.py b/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/eval_ijbc.py deleted file mode 100644 index 9c5a650d486d18eb02d6f60d448fc3b315261f5d..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/eval_ijbc.py +++ /dev/null @@ -1,483 +0,0 @@ -# coding: utf-8 - -import os -import pickle - -import matplotlib -import pandas as pd - -matplotlib.use('Agg') -import matplotlib.pyplot as plt -import timeit -import sklearn -import argparse -import cv2 -import numpy as np -import torch -from skimage import transform as trans -from backbones import get_model -from sklearn.metrics import roc_curve, auc - -from menpo.visualize.viewmatplotlib import sample_colours_from_colourmap -from prettytable import PrettyTable -from pathlib import Path - -import sys -import warnings - -sys.path.insert(0, "../") -warnings.filterwarnings("ignore") - -parser = argparse.ArgumentParser(description='do ijb test') -# general -parser.add_argument('--model-prefix', default='', help='path to load model.') -parser.add_argument('--image-path', default='', type=str, help='') -parser.add_argument('--result-dir', default='.', type=str, help='') -parser.add_argument('--batch-size', default=128, type=int, help='') -parser.add_argument('--network', default='iresnet50', type=str, help='') -parser.add_argument('--job', default='insightface', type=str, help='job name') -parser.add_argument('--target', default='IJBC', type=str, help='target, set to IJBC or IJBB') -args = parser.parse_args() - -target = args.target -model_path = args.model_prefix -image_path = args.image_path -result_dir = args.result_dir -gpu_id = None -use_norm_score = True # if Ture, TestMode(N1) -use_detector_score = True # if Ture, TestMode(D1) -use_flip_test = True # if Ture, TestMode(F1) -job = args.job -batch_size = args.batch_size - - -class Embedding(object): - def __init__(self, prefix, data_shape, batch_size=1): - image_size = (112, 112) - self.image_size = image_size - weight = torch.load(prefix) - resnet = get_model(args.network, dropout=0, fp16=False).cuda() - resnet.load_state_dict(weight) - model = torch.nn.DataParallel(resnet) - self.model = model - self.model.eval() - src = np.array([ - [30.2946, 51.6963], - [65.5318, 51.5014], - [48.0252, 71.7366], - [33.5493, 92.3655], - [62.7299, 92.2041]], dtype=np.float32) - src[:, 0] += 8.0 - self.src = src - self.batch_size = batch_size - self.data_shape = data_shape - - def get(self, rimg, landmark): - - assert landmark.shape[0] == 68 or landmark.shape[0] == 5 - assert landmark.shape[1] == 2 - if landmark.shape[0] == 68: - landmark5 = np.zeros((5, 2), dtype=np.float32) - landmark5[0] = (landmark[36] + landmark[39]) / 2 - landmark5[1] = (landmark[42] + landmark[45]) / 2 - landmark5[2] = landmark[30] - landmark5[3] = landmark[48] - landmark5[4] = landmark[54] - else: - landmark5 = landmark - tform = trans.SimilarityTransform() - tform.estimate(landmark5, self.src) - M = tform.params[0:2, :] - img = cv2.warpAffine(rimg, - M, (self.image_size[1], self.image_size[0]), - borderValue=0.0) - img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) - img_flip = np.fliplr(img) - img = np.transpose(img, (2, 0, 1)) # 3*112*112, RGB - img_flip = np.transpose(img_flip, (2, 0, 1)) - input_blob = np.zeros((2, 3, self.image_size[1], self.image_size[0]), dtype=np.uint8) - input_blob[0] = img - input_blob[1] = img_flip - return input_blob - - @torch.no_grad() - def forward_db(self, batch_data): - imgs = torch.Tensor(batch_data).cuda() - imgs.div_(255).sub_(0.5).div_(0.5) - feat = self.model(imgs) - feat = feat.reshape([self.batch_size, 2 * feat.shape[1]]) - return feat.cpu().numpy() - - -# 将一个list尽量均分成n份,限制len(list)==n,份数大于原list内元素个数则分配空list[] -def divideIntoNstrand(listTemp, n): - twoList = [[] for i in range(n)] - for i, e in enumerate(listTemp): - twoList[i % n].append(e) - return twoList - - -def read_template_media_list(path): - # ijb_meta = np.loadtxt(path, dtype=str) - ijb_meta = pd.read_csv(path, sep=' ', header=None).values - templates = ijb_meta[:, 1].astype(np.int) - medias = ijb_meta[:, 2].astype(np.int) - return templates, medias - - -# In[ ]: - - -def read_template_pair_list(path): - # pairs = np.loadtxt(path, dtype=str) - pairs = pd.read_csv(path, sep=' ', header=None).values - # print(pairs.shape) - # print(pairs[:, 0].astype(np.int)) - t1 = pairs[:, 0].astype(np.int) - t2 = pairs[:, 1].astype(np.int) - label = pairs[:, 2].astype(np.int) - return t1, t2, label - - -# In[ ]: - - -def read_image_feature(path): - with open(path, 'rb') as fid: - img_feats = pickle.load(fid) - return img_feats - - -# In[ ]: - - -def get_image_feature(img_path, files_list, model_path, epoch, gpu_id): - batch_size = args.batch_size - data_shape = (3, 112, 112) - - files = files_list - print('files:', len(files)) - rare_size = len(files) % batch_size - faceness_scores = [] - batch = 0 - img_feats = np.empty((len(files), 1024), dtype=np.float32) - - batch_data = np.empty((2 * batch_size, 3, 112, 112)) - embedding = Embedding(model_path, data_shape, batch_size) - for img_index, each_line in enumerate(files[:len(files) - rare_size]): - name_lmk_score = each_line.strip().split(' ') - img_name = os.path.join(img_path, name_lmk_score[0]) - img = cv2.imread(img_name) - lmk = np.array([float(x) for x in name_lmk_score[1:-1]], - dtype=np.float32) - lmk = lmk.reshape((5, 2)) - input_blob = embedding.get(img, lmk) - - batch_data[2 * (img_index - batch * batch_size)][:] = input_blob[0] - batch_data[2 * (img_index - batch * batch_size) + 1][:] = input_blob[1] - if (img_index + 1) % batch_size == 0: - print('batch', batch) - img_feats[batch * batch_size:batch * batch_size + - batch_size][:] = embedding.forward_db(batch_data) - batch += 1 - faceness_scores.append(name_lmk_score[-1]) - - batch_data = np.empty((2 * rare_size, 3, 112, 112)) - embedding = Embedding(model_path, data_shape, rare_size) - for img_index, each_line in enumerate(files[len(files) - rare_size:]): - name_lmk_score = each_line.strip().split(' ') - img_name = os.path.join(img_path, name_lmk_score[0]) - img = cv2.imread(img_name) - lmk = np.array([float(x) for x in name_lmk_score[1:-1]], - dtype=np.float32) - lmk = lmk.reshape((5, 2)) - input_blob = embedding.get(img, lmk) - batch_data[2 * img_index][:] = input_blob[0] - batch_data[2 * img_index + 1][:] = input_blob[1] - if (img_index + 1) % rare_size == 0: - print('batch', batch) - img_feats[len(files) - - rare_size:][:] = embedding.forward_db(batch_data) - batch += 1 - faceness_scores.append(name_lmk_score[-1]) - faceness_scores = np.array(faceness_scores).astype(np.float32) - # img_feats = np.ones( (len(files), 1024), dtype=np.float32) * 0.01 - # faceness_scores = np.ones( (len(files), ), dtype=np.float32 ) - return img_feats, faceness_scores - - -# In[ ]: - - -def image2template_feature(img_feats=None, templates=None, medias=None): - # ========================================================== - # 1. face image feature l2 normalization. img_feats:[number_image x feats_dim] - # 2. compute media feature. - # 3. compute template feature. - # ========================================================== - unique_templates = np.unique(templates) - template_feats = np.zeros((len(unique_templates), img_feats.shape[1])) - - for count_template, uqt in enumerate(unique_templates): - - (ind_t,) = np.where(templates == uqt) - face_norm_feats = img_feats[ind_t] - face_medias = medias[ind_t] - unique_medias, unique_media_counts = np.unique(face_medias, - return_counts=True) - media_norm_feats = [] - for u, ct in zip(unique_medias, unique_media_counts): - (ind_m,) = np.where(face_medias == u) - if ct == 1: - media_norm_feats += [face_norm_feats[ind_m]] - else: # image features from the same video will be aggregated into one feature - media_norm_feats += [ - np.mean(face_norm_feats[ind_m], axis=0, keepdims=True) - ] - media_norm_feats = np.array(media_norm_feats) - # media_norm_feats = media_norm_feats / np.sqrt(np.sum(media_norm_feats ** 2, -1, keepdims=True)) - template_feats[count_template] = np.sum(media_norm_feats, axis=0) - if count_template % 2000 == 0: - print('Finish Calculating {} template features.'.format( - count_template)) - # template_norm_feats = template_feats / np.sqrt(np.sum(template_feats ** 2, -1, keepdims=True)) - template_norm_feats = sklearn.preprocessing.normalize(template_feats) - # print(template_norm_feats.shape) - return template_norm_feats, unique_templates - - -# In[ ]: - - -def verification(template_norm_feats=None, - unique_templates=None, - p1=None, - p2=None): - # ========================================================== - # Compute set-to-set Similarity Score. - # ========================================================== - template2id = np.zeros((max(unique_templates) + 1, 1), dtype=int) - for count_template, uqt in enumerate(unique_templates): - template2id[uqt] = count_template - - score = np.zeros((len(p1),)) # save cosine distance between pairs - - total_pairs = np.array(range(len(p1))) - batchsize = 100000 # small batchsize instead of all pairs in one batch due to the memory limiation - sublists = [ - total_pairs[i:i + batchsize] for i in range(0, len(p1), batchsize) - ] - total_sublists = len(sublists) - for c, s in enumerate(sublists): - feat1 = template_norm_feats[template2id[p1[s]]] - feat2 = template_norm_feats[template2id[p2[s]]] - similarity_score = np.sum(feat1 * feat2, -1) - score[s] = similarity_score.flatten() - if c % 10 == 0: - print('Finish {}/{} pairs.'.format(c, total_sublists)) - return score - - -# In[ ]: -def verification2(template_norm_feats=None, - unique_templates=None, - p1=None, - p2=None): - template2id = np.zeros((max(unique_templates) + 1, 1), dtype=int) - for count_template, uqt in enumerate(unique_templates): - template2id[uqt] = count_template - score = np.zeros((len(p1),)) # save cosine distance between pairs - total_pairs = np.array(range(len(p1))) - batchsize = 100000 # small batchsize instead of all pairs in one batch due to the memory limiation - sublists = [ - total_pairs[i:i + batchsize] for i in range(0, len(p1), batchsize) - ] - total_sublists = len(sublists) - for c, s in enumerate(sublists): - feat1 = template_norm_feats[template2id[p1[s]]] - feat2 = template_norm_feats[template2id[p2[s]]] - similarity_score = np.sum(feat1 * feat2, -1) - score[s] = similarity_score.flatten() - if c % 10 == 0: - print('Finish {}/{} pairs.'.format(c, total_sublists)) - return score - - -def read_score(path): - with open(path, 'rb') as fid: - img_feats = pickle.load(fid) - return img_feats - - -# # Step1: Load Meta Data - -# In[ ]: - -assert target == 'IJBC' or target == 'IJBB' - -# ============================================================= -# load image and template relationships for template feature embedding -# tid --> template id, mid --> media id -# format: -# image_name tid mid -# ============================================================= -start = timeit.default_timer() -templates, medias = read_template_media_list( - os.path.join('%s/meta' % image_path, - '%s_face_tid_mid.txt' % target.lower())) -stop = timeit.default_timer() -print('Time: %.2f s. ' % (stop - start)) - -# In[ ]: - -# ============================================================= -# load template pairs for template-to-template verification -# tid : template id, label : 1/0 -# format: -# tid_1 tid_2 label -# ============================================================= -start = timeit.default_timer() -p1, p2, label = read_template_pair_list( - os.path.join('%s/meta' % image_path, - '%s_template_pair_label.txt' % target.lower())) -stop = timeit.default_timer() -print('Time: %.2f s. ' % (stop - start)) - -# # Step 2: Get Image Features - -# In[ ]: - -# ============================================================= -# load image features -# format: -# img_feats: [image_num x feats_dim] (227630, 512) -# ============================================================= -start = timeit.default_timer() -img_path = '%s/loose_crop' % image_path -img_list_path = '%s/meta/%s_name_5pts_score.txt' % (image_path, target.lower()) -img_list = open(img_list_path) -files = img_list.readlines() -# files_list = divideIntoNstrand(files, rank_size) -files_list = files - -# img_feats -# for i in range(rank_size): -img_feats, faceness_scores = get_image_feature(img_path, files_list, - model_path, 0, gpu_id) -stop = timeit.default_timer() -print('Time: %.2f s. ' % (stop - start)) -print('Feature Shape: ({} , {}) .'.format(img_feats.shape[0], - img_feats.shape[1])) - -# # Step3: Get Template Features - -# In[ ]: - -# ============================================================= -# compute template features from image features. -# ============================================================= -start = timeit.default_timer() -# ========================================================== -# Norm feature before aggregation into template feature? -# Feature norm from embedding network and faceness score are able to decrease weights for noise samples (not face). -# ========================================================== -# 1. FaceScore (Feature Norm) -# 2. FaceScore (Detector) - -if use_flip_test: - # concat --- F1 - # img_input_feats = img_feats - # add --- F2 - img_input_feats = img_feats[:, 0:img_feats.shape[1] // - 2] + img_feats[:, img_feats.shape[1] // 2:] -else: - img_input_feats = img_feats[:, 0:img_feats.shape[1] // 2] - -if use_norm_score: - img_input_feats = img_input_feats -else: - # normalise features to remove norm information - img_input_feats = img_input_feats / np.sqrt( - np.sum(img_input_feats ** 2, -1, keepdims=True)) - -if use_detector_score: - print(img_input_feats.shape, faceness_scores.shape) - img_input_feats = img_input_feats * faceness_scores[:, np.newaxis] -else: - img_input_feats = img_input_feats - -template_norm_feats, unique_templates = image2template_feature( - img_input_feats, templates, medias) -stop = timeit.default_timer() -print('Time: %.2f s. ' % (stop - start)) - -# # Step 4: Get Template Similarity Scores - -# In[ ]: - -# ============================================================= -# compute verification scores between template pairs. -# ============================================================= -start = timeit.default_timer() -score = verification(template_norm_feats, unique_templates, p1, p2) -stop = timeit.default_timer() -print('Time: %.2f s. ' % (stop - start)) - -# In[ ]: -save_path = os.path.join(result_dir, args.job) -# save_path = result_dir + '/%s_result' % target - -if not os.path.exists(save_path): - os.makedirs(save_path) - -score_save_file = os.path.join(save_path, "%s.npy" % target.lower()) -np.save(score_save_file, score) - -# # Step 5: Get ROC Curves and TPR@FPR Table - -# In[ ]: - -files = [score_save_file] -methods = [] -scores = [] -for file in files: - methods.append(Path(file).stem) - scores.append(np.load(file)) - -methods = np.array(methods) -scores = dict(zip(methods, scores)) -colours = dict( - zip(methods, sample_colours_from_colourmap(methods.shape[0], 'Set2'))) -x_labels = [10 ** -6, 10 ** -5, 10 ** -4, 10 ** -3, 10 ** -2, 10 ** -1] -tpr_fpr_table = PrettyTable(['Methods'] + [str(x) for x in x_labels]) -fig = plt.figure() -for method in methods: - fpr, tpr, _ = roc_curve(label, scores[method]) - roc_auc = auc(fpr, tpr) - fpr = np.flipud(fpr) - tpr = np.flipud(tpr) # select largest tpr at same fpr - plt.plot(fpr, - tpr, - color=colours[method], - lw=1, - label=('[%s (AUC = %0.4f %%)]' % - (method.split('-')[-1], roc_auc * 100))) - tpr_fpr_row = [] - tpr_fpr_row.append("%s-%s" % (method, target)) - for fpr_iter in np.arange(len(x_labels)): - _, min_index = min( - list(zip(abs(fpr - x_labels[fpr_iter]), range(len(fpr))))) - tpr_fpr_row.append('%.2f' % (tpr[min_index] * 100)) - tpr_fpr_table.add_row(tpr_fpr_row) -plt.xlim([10 ** -6, 0.1]) -plt.ylim([0.3, 1.0]) -plt.grid(linestyle='--', linewidth=1) -plt.xticks(x_labels) -plt.yticks(np.linspace(0.3, 1.0, 8, endpoint=True)) -plt.xscale('log') -plt.xlabel('False Positive Rate') -plt.ylabel('True Positive Rate') -plt.title('ROC on IJB') -plt.legend(loc="lower right") -fig.savefig(os.path.join(save_path, '%s.pdf' % target.lower())) -print(tpr_fpr_table) diff --git a/spaces/kira4424/Tacotron-zero-short-voice-clone/encoder/data_objects/speaker.py b/spaces/kira4424/Tacotron-zero-short-voice-clone/encoder/data_objects/speaker.py deleted file mode 100644 index 494e882fe34fc38dcc793ab8c74a6cc2376bb7b5..0000000000000000000000000000000000000000 --- a/spaces/kira4424/Tacotron-zero-short-voice-clone/encoder/data_objects/speaker.py +++ /dev/null @@ -1,40 +0,0 @@ -from encoder.data_objects.random_cycler import RandomCycler -from encoder.data_objects.utterance import Utterance -from pathlib import Path - -# Contains the set of utterances of a single speaker -class Speaker: - def __init__(self, root: Path): - self.root = root - self.name = root.name - self.utterances = None - self.utterance_cycler = None - - def _load_utterances(self): - with self.root.joinpath("_sources.txt").open("r") as sources_file: - sources = [l.split(",") for l in sources_file] - sources = {frames_fname: wave_fpath for frames_fname, wave_fpath in sources} - self.utterances = [Utterance(self.root.joinpath(f), w) for f, w in sources.items()] - self.utterance_cycler = RandomCycler(self.utterances) - - def random_partial(self, count, n_frames): - """ - Samples a batch of unique partial utterances from the disk in a way that all - utterances come up at least once every two cycles and in a random order every time. - - :param count: The number of partial utterances to sample from the set of utterances from - that speaker. Utterances are guaranteed not to be repeated if is not larger than - the number of utterances available. - :param n_frames: The number of frames in the partial utterance. - :return: A list of tuples (utterance, frames, range) where utterance is an Utterance, - frames are the frames of the partial utterances and range is the range of the partial - utterance with regard to the complete utterance. - """ - if self.utterances is None: - self._load_utterances() - - utterances = self.utterance_cycler.sample(count) - - a = [(u,) + u.random_partial(n_frames) for u in utterances] - - return a diff --git a/spaces/koajoel/PolyFormer/fairseq/examples/backtranslation/prepare-wmt18en2de.sh b/spaces/koajoel/PolyFormer/fairseq/examples/backtranslation/prepare-wmt18en2de.sh deleted file mode 100644 index f6fd275307db50ca84c299440ae02dce49064030..0000000000000000000000000000000000000000 --- a/spaces/koajoel/PolyFormer/fairseq/examples/backtranslation/prepare-wmt18en2de.sh +++ /dev/null @@ -1,135 +0,0 @@ -#!/bin/bash -# Adapted from https://github.com/facebookresearch/MIXER/blob/master/prepareData.sh - -echo 'Cloning Moses github repository (for tokenization scripts)...' -git clone https://github.com/moses-smt/mosesdecoder.git - -echo 'Cloning Subword NMT repository (for BPE pre-processing)...' -git clone https://github.com/rsennrich/subword-nmt.git - -SCRIPTS=mosesdecoder/scripts -TOKENIZER=$SCRIPTS/tokenizer/tokenizer.perl -CLEAN=$SCRIPTS/training/clean-corpus-n.perl -NORM_PUNC=$SCRIPTS/tokenizer/normalize-punctuation.perl -REM_NON_PRINT_CHAR=$SCRIPTS/tokenizer/remove-non-printing-char.perl -BPEROOT=subword-nmt/subword_nmt -BPE_TOKENS=32000 - -URLS=( - "http://statmt.org/wmt13/training-parallel-europarl-v7.tgz" - "http://statmt.org/wmt13/training-parallel-commoncrawl.tgz" - "http://data.statmt.org/wmt18/translation-task/training-parallel-nc-v13.tgz" - "http://data.statmt.org/wmt18/translation-task/rapid2016.tgz" - "http://data.statmt.org/wmt17/translation-task/dev.tgz" - "http://statmt.org/wmt14/test-full.tgz" -) -FILES=( - "training-parallel-europarl-v7.tgz" - "training-parallel-commoncrawl.tgz" - "training-parallel-nc-v13.tgz" - "rapid2016.tgz" - "dev.tgz" - "test-full.tgz" -) -CORPORA=( - "training/europarl-v7.de-en" - "commoncrawl.de-en" - "training-parallel-nc-v13/news-commentary-v13.de-en" - "rapid2016.de-en" -) - -if [ ! -d "$SCRIPTS" ]; then - echo "Please set SCRIPTS variable correctly to point to Moses scripts." - exit 1 -fi - -OUTDIR=wmt18_en_de - -src=en -tgt=de -lang=en-de -prep=$OUTDIR -tmp=$prep/tmp -orig=orig - -mkdir -p $orig $tmp $prep - -cd $orig - -for ((i=0;i<${#URLS[@]};++i)); do - file=${FILES[i]} - if [ -f $file ]; then - echo "$file already exists, skipping download" - else - url=${URLS[i]} - wget "$url" - if [ -f $file ]; then - echo "$url successfully downloaded." - else - echo "$url not successfully downloaded." - exit 1 - fi - if [ ${file: -4} == ".tgz" ]; then - tar zxvf $file - elif [ ${file: -4} == ".tar" ]; then - tar xvf $file - fi - fi -done -cd .. - -echo "pre-processing train data..." -for l in $src $tgt; do - rm $tmp/train.tags.$lang.tok.$l - for f in "${CORPORA[@]}"; do - cat $orig/$f.$l | \ - perl $NORM_PUNC $l | \ - perl $REM_NON_PRINT_CHAR | \ - perl $TOKENIZER -threads 8 -a -l $l >> $tmp/train.tags.$lang.tok.$l - done -done - -echo "pre-processing test data..." -for l in $src $tgt; do - if [ "$l" == "$src" ]; then - t="src" - else - t="ref" - fi - grep '\s*//g' | \ - sed -e 's/\s*<\/seg>\s*//g' | \ - sed -e "s/\’/\'/g" | \ - perl $TOKENIZER -threads 8 -a -l $l > $tmp/test.$l - echo "" -done - -echo "splitting train and valid..." -for l in $src $tgt; do - awk '{if (NR%100 == 0) print $0; }' $tmp/train.tags.$lang.tok.$l > $tmp/valid.$l - awk '{if (NR%100 != 0) print $0; }' $tmp/train.tags.$lang.tok.$l > $tmp/train.$l -done - -TRAIN=$tmp/train.de-en -BPE_CODE=$prep/code -rm -f $TRAIN -for l in $src $tgt; do - cat $tmp/train.$l >> $TRAIN -done - -echo "learn_bpe.py on ${TRAIN}..." -python $BPEROOT/learn_bpe.py -s $BPE_TOKENS < $TRAIN > $BPE_CODE - -for L in $src $tgt; do - for f in train.$L valid.$L test.$L; do - echo "apply_bpe.py to ${f}..." - python $BPEROOT/apply_bpe.py -c $BPE_CODE < $tmp/$f > $tmp/bpe.$f - done -done - -perl $CLEAN -ratio 1.5 $tmp/bpe.train $src $tgt $prep/train 1 250 -perl $CLEAN -ratio 1.5 $tmp/bpe.valid $src $tgt $prep/valid 1 250 - -for L in $src $tgt; do - cp $tmp/bpe.test.$L $prep/test.$L -done diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/varLib/stat.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/varLib/stat.py deleted file mode 100644 index 46c9498dc720e7c23b278ae31b65dbf55f2ad8be..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/varLib/stat.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Extra methods for DesignSpaceDocument to generate its STAT table data.""" - -from __future__ import annotations - -from typing import Dict, List, Union - -import fontTools.otlLib.builder -from fontTools.designspaceLib import ( - AxisLabelDescriptor, - DesignSpaceDocument, - DesignSpaceDocumentError, - LocationLabelDescriptor, -) -from fontTools.designspaceLib.types import Region, getVFUserRegion, locationInRegion -from fontTools.ttLib import TTFont - - -def buildVFStatTable(ttFont: TTFont, doc: DesignSpaceDocument, vfName: str) -> None: - """Build the STAT table for the variable font identified by its name in - the given document. - - Knowing which variable we're building STAT data for is needed to subset - the STAT locations to only include what the variable font actually ships. - - .. versionadded:: 5.0 - - .. seealso:: - - :func:`getStatAxes()` - - :func:`getStatLocations()` - - :func:`fontTools.otlLib.builder.buildStatTable()` - """ - for vf in doc.getVariableFonts(): - if vf.name == vfName: - break - else: - raise DesignSpaceDocumentError( - f"Cannot find the variable font by name {vfName}" - ) - - region = getVFUserRegion(doc, vf) - - return fontTools.otlLib.builder.buildStatTable( - ttFont, - getStatAxes(doc, region), - getStatLocations(doc, region), - doc.elidedFallbackName if doc.elidedFallbackName is not None else 2, - ) - - -def getStatAxes(doc: DesignSpaceDocument, userRegion: Region) -> List[Dict]: - """Return a list of axis dicts suitable for use as the ``axes`` - argument to :func:`fontTools.otlLib.builder.buildStatTable()`. - - .. versionadded:: 5.0 - """ - # First, get the axis labels with explicit ordering - # then append the others in the order they appear. - maxOrdering = max( - (axis.axisOrdering for axis in doc.axes if axis.axisOrdering is not None), - default=-1, - ) - axisOrderings = [] - for axis in doc.axes: - if axis.axisOrdering is not None: - axisOrderings.append(axis.axisOrdering) - else: - maxOrdering += 1 - axisOrderings.append(maxOrdering) - return [ - dict( - tag=axis.tag, - name={"en": axis.name, **axis.labelNames}, - ordering=ordering, - values=[ - _axisLabelToStatLocation(label) - for label in axis.axisLabels - if locationInRegion({axis.name: label.userValue}, userRegion) - ], - ) - for axis, ordering in zip(doc.axes, axisOrderings) - ] - - -def getStatLocations(doc: DesignSpaceDocument, userRegion: Region) -> List[Dict]: - """Return a list of location dicts suitable for use as the ``locations`` - argument to :func:`fontTools.otlLib.builder.buildStatTable()`. - - .. versionadded:: 5.0 - """ - axesByName = {axis.name: axis for axis in doc.axes} - return [ - dict( - name={"en": label.name, **label.labelNames}, - # Location in the designspace is keyed by axis name - # Location in buildStatTable by axis tag - location={ - axesByName[name].tag: value - for name, value in label.getFullUserLocation(doc).items() - }, - flags=_labelToFlags(label), - ) - for label in doc.locationLabels - if locationInRegion(label.getFullUserLocation(doc), userRegion) - ] - - -def _labelToFlags(label: Union[AxisLabelDescriptor, LocationLabelDescriptor]) -> int: - flags = 0 - if label.olderSibling: - flags |= 1 - if label.elidable: - flags |= 2 - return flags - - -def _axisLabelToStatLocation( - label: AxisLabelDescriptor, -) -> Dict: - label_format = label.getFormat() - name = {"en": label.name, **label.labelNames} - flags = _labelToFlags(label) - if label_format == 1: - return dict(name=name, value=label.userValue, flags=flags) - if label_format == 3: - return dict( - name=name, - value=label.userValue, - linkedValue=label.linkedUserValue, - flags=flags, - ) - if label_format == 2: - res = dict( - name=name, - nominalValue=label.userValue, - flags=flags, - ) - if label.userMinimum is not None: - res["rangeMinValue"] = label.userMinimum - if label.userMaximum is not None: - res["rangeMaxValue"] = label.userMaximum - return res - raise NotImplementedError("Unknown STAT label format") diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Adobe After Effects CC 2019 16.1 Crack !!INSTALL!! Activation Key Free Download.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Adobe After Effects CC 2019 16.1 Crack !!INSTALL!! Activation Key Free Download.md deleted file mode 100644 index 9a33a117269f816c5de277f04e39ce6ff5fb9824..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Adobe After Effects CC 2019 16.1 Crack !!INSTALL!! Activation Key Free Download.md +++ /dev/null @@ -1,48 +0,0 @@ -

      Adobe After Effects CC 2019 16.1 Crack Activation Key Free Download


      DOWNLOADhttps://bytlly.com/2uGwjK



      - -ive already downloaded it from both youtub... - - I have a question about my /etc/modprobe.d/blacklist.conf file: if i want to exclude a driver for my gpu (e.g. radeon), can i do so using that file? - - Hi folks - - or would i need to use /etc/modprobe.d/blacklist-radeon.conf ? - -!medibuntu - - medibuntu is a repository of packages that cannot be included into the Ubuntu distribution for legal reasons - See - - hi, has anyone tried the latest kde update? - - today it was "to be released" - - Wurph, how's the new KDE? - - BluesKaj: stable? - - dunno - -!KDE - - KDE ( is the!desktop environment used natively in!Kubuntu. To install from Ubuntu: « sudo apt-get install kubuntu-desktop », or see See for more information. - - thanks - - ok i need to check out how that blacklist file is meant to work, now seems like a good moment - - de-facto: the driver has nothing to do with modprobe.d but blacklist.conf - - de-facto: so you're blacklisting - - de-facto: and you can use the driver names of the modules to write into /etc/modprobe.d/blacklist.conf - - de-facto: you'll notice that on Linux, everything that the module needs is provided in the kernel - - reisio: but modprobe.d and blacklist.conf is different - - Wurph which file do i edit to blacklist a driver? - - de-facto: the driver itself? 4fefd39f24
      -
      -
      -

      diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Album Westlife World Of Our Own 320kbs CDRiptorrent TOP.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Album Westlife World Of Our Own 320kbs CDRiptorrent TOP.md deleted file mode 100644 index 969b2cb6135292f885d645edb372f8ee644f19ba..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Album Westlife World Of Our Own 320kbs CDRiptorrent TOP.md +++ /dev/null @@ -1,119 +0,0 @@ - -

      Album Westlife World Of Our Own 320kbs CDRiptorrent: How to Download and Enjoy this Pop Classic

      - -

      Westlife is one of the most successful pop groups of all time, with over 55 million records sold worldwide and 14 number-one singles in the UK. Their third studio album, World of Our Own, was released in 2001 and became their best-selling album to date, with over four million copies sold worldwide. The album featured some of their most iconic songs, such as Queen of My Heart, Uptown Girl, and World of Our Own.

      - -

      If you are a fan of Westlife or pop music in general, you might want to download Album Westlife World Of Our Own 320kbs CDRiptorrent. This is a torrent file that contains the album in MP3 format with a high bitrate of 320 kbps. This means that you can enjoy the album in the best possible sound quality, with clear vocals and instruments. You can also download the album faster and easier than buying a physical copy or streaming it online.

      -

      Album Westlife World Of Our Own 320kbs CDRiptorrent


      Download ○○○ https://bytlly.com/2uGxyf



      - -

      In this article, we will show you how to download Album Westlife World Of Our Own 320kbs CDRiptorrent and enjoy this pop classic on your computer or mobile device.

      - -

      What is a Torrent File and How to Download It

      - -

      A torrent file is a small file that contains information about a larger file that you want to download. It does not contain the actual file itself, but rather the location of other users who have the file and are willing to share it with you. To download a torrent file, you need two things: a torrent client and a torrent source.

      - -

      A torrent client is a software that allows you to connect to other users who have the file you want and download it from them. Some of the most popular torrent clients are uTorrent, BitTorrent, and qBittorrent. You can download them for free from their official websites.

      - -

      A torrent source is a website that provides torrent files for various files, such as albums, movies, games, and software. However, not all torrent sources are safe and legal. Some of them may contain viruses, malware, or fake files that can harm your computer or infringe on copyrights. Therefore, you need to be careful and do some research before downloading any torrent file.

      - -

      One of the best ways to find a reliable torrent source for Album Westlife World Of Our Own 320kbs CDRiptorrent is to use a torrent search engine. A torrent search engine is a website that aggregates torrent files from different sources and allows you to search for them by keywords, categories, ratings, and other criteria. Some of the most popular torrent search engines are The Pirate Bay, RARBG, 1337x, and Torrentz2. You can use any of them to find Album Westlife World Of Our Own 320kbs CDRiptorrent.

      - -

      When you find Album Westlife World Of Our Own 320kbs CDRiptorrent on a torrent search engine, you need to check some information before downloading it. First, you need to look at the file size and make sure it matches the expected size of the album. If it is too small or too large, it may be a fake or corrupted file. Second, you need to look at the number of seeders and leechers. Seeders are users who have the complete file and are sharing it with others. Leechers are users who are downloading the file but have not completed it yet. Ideally, you want to download a torrent file that has more seeders than leechers, as this means that the download speed will be faster and more stable.

      - -

      Finally, you need to look at the comments and ratings of other users who have downloaded Album Westlife World Of Our Own 320kbs CDRiptorrent. This can give you an idea of the quality and authenticity of the file. If most users report positive feedback and no issues with the file, then it is likely safe and legit. However, if most users report negative feedback or problems with the file, then it is likely unsafe or fake.

      -

      - -

      Once you have verified all these information, you can click on the download button or magnet link to start downloading Album Westlife World Of Our Own 320kbs CDRiptorrent. Depending on your internet speed and the availability of seeders, it may take from a few minutes to a few hours to complete the download.

      - -

      How to Play Album Westlife World Of Our Own 320kbs CDRiptorrent on Your Computer or Mobile Device

      - -

      After downloading Album Westlife World Of Our Own 320kbs CDRiptorrent, you can play it on your computer or transfer it to your mobile device or music player. To play it on your computer, you need to have a media player that supports MP3 format. Some of the most popular media players are VLC Media Player, Windows Media Player, iTunes, and Winamp. You can open Album Westlife World Of Our Own 320kbs CDRiptorrent with any of these media players and enjoy its high-quality sound.

      - -

      To transfer Album Westlife World Of Our Own 320kbs CDRiptorrent to your mobile device or music player, you need to connect it to your computer via USB cable or Bluetooth. Then you need to copy Album Westlife World Of Our Own 320kbs CDRiptorrent from your computer's folder to your device's folder. You may need to convert Album Westlife World Of Our Own 320kbs CDRiptorrent to another format if your device does not support MP3 format. Some of the most common formats are AAC, WMA, WAV, and FLAC.

      - -

      Once you have transferred Album Westlife World Of Our Own 320kbs CDRiptorrent to your device, you can play it with any music app that supports MP3 format or your device's native music app. You can also create playlists with other songs from Westlife or other artists that you like.

      - -

      Why You Should Download Album Westlife World Of Our Own 320kbs CDRiptorrent

      - -

      There are many reasons why you should download Album Westlife World Of Our Own 320kbs CDRiptorrent if you love pop music and Westlife in particular.

      - -
        -
      • You can enjoy one of their best albums in high-quality sound that enhances their vocals and melodies.
      • -
      • You can save money and time by downloading it for free instead of buying a physical copy or streaming it online.
      • -
      • You can support their music career by increasing their popularity and exposure online.
      • -
      • You can relive their glory days when they were one of the most successful boy bands in history.
      • -
      • You can share it with your friends and family who also love pop music and Westlife.
      • -
      - -

      Album Westlife World Of Our Own 320kbs CDRiptorrent is a pop masterpiece that deserves to be heard by everyone who appreciates good music. It showcases their talent, versatility, and charisma as a group. It also features some of their most memorable songs that will make you sing along, dance along, or cry along.

      - -

      If you want to experience this album in its full glory, download Album Westlife World Of Our Own 320kbs CDRiptorrent today and enjoy!

      -

      What are the Benefits of Downloading Album Westlife World Of Our Own 320kbs CDRiptorrent

      - -

      Downloading Album Westlife World Of Our Own 320kbs CDRiptorrent has many benefits for pop music lovers. Here are some of them:

      - -
        -
      • You can listen to the album offline, without any interruptions or ads.
      • -
      • You can have a backup copy of the album in case you lose or damage your physical copy or your streaming account.
      • -
      • You can customize the album by adding or removing songs, changing the order, or creating your own cover art.
      • -
      • You can burn the album to a CD or DVD and play it on any device that supports it.
      • -
      • You can share the album with your friends and family who may not have access to it online or in stores.
      • -
      - -

      Downloading Album Westlife World Of Our Own 320kbs CDRiptorrent is a great way to enjoy this pop classic anytime, anywhere, and anyway you want.

      - -

      How to Avoid Legal Issues When Downloading Album Westlife World Of Our Own 320kbs CDRiptorrent

      - -

      Downloading Album Westlife World Of Our Own 320kbs CDRiptorrent may seem like a harmless and convenient way to get this pop classic, but it may also involve some legal risks. Depending on your country and jurisdiction, downloading copyrighted material without permission or payment may be considered illegal and punishable by law. Therefore, you need to be careful and responsible when downloading Album Westlife World Of Our Own 320kbs CDRiptorrent.

      - -

      Here are some tips to avoid legal issues when downloading Album Westlife World Of Our Own 320kbs CDRiptorrent:

      - -
        -
      • Check the laws and regulations of your country and jurisdiction regarding downloading copyrighted material. Some countries may have more lenient or strict rules than others.
      • -
      • Use a VPN (virtual private network) service to hide your IP address and location when downloading Album Westlife World Of Our Own 320kbs CDRiptorrent. This can prevent your internet service provider or authorities from tracking your online activity and identifying you.
      • -
      • Use a reputable and secure torrent source and client when downloading Album Westlife World Of Our Own 320kbs CDRiptorrent. This can prevent you from downloading viruses, malware, or fake files that can harm your computer or expose you to legal issues.
      • -
      • Do not distribute or sell Album Westlife World Of Our Own 320kbs CDRiptorrent to others. This can increase your legal liability and damage the reputation and income of the artists.
      • -
      • Support the artists by buying their official merchandise, attending their concerts, or streaming their music legally. This can show your appreciation and respect for their work and encourage them to create more music.
      • -
      - -

      Downloading Album Westlife World Of Our Own 320kbs CDRiptorrent is not necessarily illegal, but it may involve some legal risks. By following these tips, you can avoid legal issues and enjoy this pop classic safely and responsibly.

      -

      What are the Best Songs from Album Westlife World Of Our Own 320kbs CDRiptorrent

      - -

      Album Westlife World Of Our Own 320kbs CDRiptorrent contains 19 songs that showcase the pop talent and diversity of Westlife. The album has a mix of upbeat and ballad songs, with influences from pop rock, R&B, and dance. The album also features some guest appearances from other artists, such as Mariah Carey, Delta Goodrem, and Joanne Hindley.

      - -

      Some of the best songs from Album Westlife World Of Our Own 320kbs CDRiptorrent are:

      - -
        -
      • Queen of My Heart: This is the lead single from the album and one of the most popular songs by Westlife. It is a romantic ballad that expresses the love and devotion of a man to his partner. The song has a catchy chorus and a beautiful melody.
      • -
      • Uptown Girl: This is a cover of the Billy Joel song from 1983. It is a fun and upbeat song that describes a man's attraction to a sophisticated and classy woman. The song has a retro vibe and a lively tempo.
      • -
      • World of Our Own: This is the title track and the second single from the album. It is a pop rock song that celebrates the freedom and happiness of being in love. The song has a catchy guitar riff and a powerful chorus.
      • -
      • Bop Bop Baby: This is a dance-pop song that features Joanne Hindley, a former member of the pop group S Club 7. It is a playful and flirty song that describes a couple's sexual chemistry. The song has a funky beat and a catchy hook.
      • -
      • I Wanna Grow Old with You: This is a ballad that features Delta Goodrem, an Australian singer-songwriter. It is a sweet and sentimental song that expresses the desire to spend the rest of one's life with someone. The song has a piano accompaniment and a harmonious duet.
      • -
      - -

      These are some of the best songs from Album Westlife World Of Our Own 320kbs CDRiptorrent, but there are many more to discover and enjoy.

      - -

      How to Write a Review for Album Westlife World Of Our Own 320kbs CDRiptorrent

      - -

      If you have downloaded Album Westlife World Of Our Own 320kbs CDRiptorrent and enjoyed it, you might want to write a review for it and share your opinion with other music lovers. Writing a review can also help you improve your writing skills and express your thoughts clearly.

      - -

      Here are some tips to write a review for Album Westlife World Of Our Own 320kbs CDRiptorrent:

      - -
        -
      • Start with an introduction that summarizes your overall impression of the album. You can include some background information about the album, such as its release date, genre, label, and producer. You can also state your main thesis or argument about the album.
      • -
      • Write several body paragraphs that support your thesis or argument with specific examples and evidence from the album. You can focus on different aspects of the album, such as its songs, lyrics, vocals, instruments, production, style, mood, theme, or message. You can also compare and contrast the album with other albums by Westlife or other artists in the same genre.
      • -
      • End with a conclusion that restates your thesis or argument and summarizes your main points. You can also give your personal rating or recommendation for the album, such as how many stars you would give it or whether you would buy it or not.
      • -
      • Use clear and concise language that is appropriate for your audience and purpose. Avoid using slang, jargon, or informal expressions that may confuse or offend your readers. Use proper grammar, spelling, punctuation, and formatting to make your review easy to read and understand.
      • -
      • Be honest and respectful in your review. Express your own opinion and perspective without being biased or rude. Acknowledge the strengths and weaknesses of the album without exaggerating or minimizing them. Provide constructive criticism and feedback that can help the artists improve their work.
      • -
      - -

      Writing a review for Album Westlife World Of Our Own 320kbs CDRiptorrent can be a fun and rewarding experience that can help you appreciate this pop classic more.

      -

      Conclusion

      - -

      Album Westlife World Of Our Own 320kbs CDRiptorrent is a pop classic that deserves to be downloaded and enjoyed by every pop music lover. It contains 19 songs that showcase the talent and diversity of Westlife, one of the most successful pop groups of all time. The album features some of their most iconic songs, such as Queen of My Heart, Uptown Girl, and World of Our Own. The album also has a high sound quality of 320 kbps that enhances the vocals and melodies of the songs.

      - -

      In this article, we have shown you how to download Album Westlife World Of Our Own 320kbs CDRiptorrent and enjoy it on your computer or mobile device. We have also given you some tips to avoid legal issues when downloading it and to write a review for it. We hope that this article has been helpful and informative for you.

      - -

      If you are a fan of Westlife or pop music in general, you should not miss this opportunity to download Album Westlife World Of Our Own 320kbs CDRiptorrent and experience this pop masterpiece. You will not regret it!

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Bmw M3 Challenge Nordschleife Track [HOT] Download.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Bmw M3 Challenge Nordschleife Track [HOT] Download.md deleted file mode 100644 index 9f19aeb043be482e546c1a8d7f7d4714726b90ed..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Bmw M3 Challenge Nordschleife Track [HOT] Download.md +++ /dev/null @@ -1,38 +0,0 @@ -

      bmw m3 challenge nordschleife track download


      DOWNLOAD »»» https://bytlly.com/2uGvSE



      - -more » - -A 50 minute mashup of the first two episodes of the BMW M3 Challenge as well as highlights from the 5th installment. Izi Bash.. Nurburgring SLIPPERY Conditions, HARD Driving, Highlights Nordschleife .more » - -Wow, what a great M3 Challenge 5. This is where the "experienced" guys start to get the better of the "amateur" or "novice" drivers.. Nurburgring SLIPPERY Conditions, HARD Driving, Highlights Nordschleife .more » - -More Details about the BMW M3 Challenge "Nordschleife" events of 2011: - -Location: - -Track of choice: - -Weather: - -This year's BMW M3 Challenge will be held on the infamous Nurburgring-Nordschei, Germany, Nordschleife track. - -The racing season is set to begin on March 25th, 2011 and will continue until October 20th, 2011. - -During the contest, M3 Challenge racers will compete in a series of classes that vary by ability and style. In addition to the cars themselves, the event will feature a full professional driving, pit crew, gear, and hospitality crews, and special event marshals. - -"Nordschleife" means "Northern Loop" and this is the longest track of the Nordschleife. The high average speeds (over 200km/h in sections) and cornering demands of this track are unique and extremely challenging. The Nordschleife is designed to be the most difficult and challenging of the Nordschleife tracks. - -Families and friends can come watch the drivers and cars race on track. There will also be parties, food, drink, and entertainment. (VIP activities are also included) - -Family Friendly activities - -Concession stands are available throughout the grounds and food and beverage tents, along with cash bars will be set up. - -General Admission: (Families and friends are welcome to watch the races, but tickets are only required for the racers.) - -General Admission tickets are available at the races and include access to the track and pit area. A single track admission ticket is €20, while a family of four (two adults and two children under 12) can get into the pits for €50. - -Priority Entry: (to watch the races and 4fefd39f24
      -
      -
      -

      diff --git a/spaces/lingbionlp/PhenoTagger_v1.2_Demo/src/combine_result.py b/spaces/lingbionlp/PhenoTagger_v1.2_Demo/src/combine_result.py deleted file mode 100644 index 0feada1df78c539d08e81a59a74f426a5481f43a..0000000000000000000000000000000000000000 --- a/spaces/lingbionlp/PhenoTagger_v1.2_Demo/src/combine_result.py +++ /dev/null @@ -1,102 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Mon Jun 15 11:24:45 2020 - -@author: luol2 -""" - -import io -def nest_overlap_entity(nest_list): - temp_result_list={} - for i in range(0, len(nest_list)): - hpoid=nest_list[i][3] - if hpoid not in temp_result_list.keys(): - temp_result_list[hpoid]=nest_list[i] - else: - score=float(nest_list[i][4]) - old_score=float(temp_result_list[hpoid][4]) - if score>old_score: # retain higer score concept - temp_result_list[hpoid]=nest_list[i] - new_list=[] - for hpoid in temp_result_list.keys(): - new_list.append(temp_result_list[hpoid]) - - temp_result_list={} #same index, different ids - for i in range(0, len(new_list)): - ids=new_list[i][0]+' '+new_list[i][1] - if ids not in temp_result_list.keys(): - temp_result_list[ids]=new_list[i] - else: - score=float(nest_list[i][4]) - old_score=float(temp_result_list[ids][4]) - if score>old_score: - temp_result_list[ids]=new_list[i] - final_list=[] - for ids in temp_result_list.keys(): - final_list.append(temp_result_list[ids]) - return final_list -def combine_ml_dict(dict_tsv,ml_tsv,nest=True): - fin_dic=io.StringIO(dict_tsv) - fin_ml=io.StringIO(ml_tsv) - fout=io.StringIO() - all_dic=fin_dic.read().strip().split('\n\n') - all_ml=fin_ml.read().strip().split('\n\n') - fin_dic.close() - fin_ml.close() - - for i in range(0,len(all_dic)): - lines_dic=all_dic[i].split('\n') - lines_ml=all_ml[i].split('\n') - entity_list={} - for j in range(1,len(lines_dic)): - seg=lines_dic[j].split('\t') - entity_list[lines_dic[j]]=[int(seg[0]),int(seg[1])] #dict results score 1.00 - for j in range(1,len(lines_ml)): - seg=lines_ml[j].split('\t') - entity_list[lines_ml[j]]=[int(seg[0]),int(seg[1])] - - entity_list=sorted(entity_list.items(), key=lambda kv:(kv[1]), reverse=False) - entity_list_sort=[] - for ele in entity_list: - entity_list_sort.append(ele[0]) - - final_entity=[] - if len(entity_list_sort)!=0: - first_entity=entity_list_sort[0].split('\t') - nest_list=[first_entity] - max_eid=int(first_entity[1]) - - for i in range(1,len(entity_list_sort)): - segs=entity_list_sort[i].split('\t') - if int(segs[0])> max_eid: - if len(nest_list)==1: - final_entity.append(nest_list[0]) - nest_list=[] - nest_list.append(segs) - if int(segs[1])>max_eid: - max_eid=int(segs[1]) - else: - tem=nest_overlap_entity(nest_list) - final_entity.extend(tem) - nest_list=[] - nest_list.append(segs) - if int(segs[1])>max_eid: - max_eid=int(segs[1]) - else: - nest_list.append(segs) - if int(segs[1])>max_eid: - max_eid=int(segs[1]) - if nest_list!=[]: - if len(nest_list)==1: - final_entity.append(nest_list[0]) - - else: - tem=nest_overlap_entity(nest_list)#find max entity - final_entity.extend(tem) - - fout.write(lines_ml[0]+'\n') - for ele in final_entity: - fout.write('\t'.join(ele)+'\n') - fout.write('\n') - return fout.getvalue() - diff --git a/spaces/livinNector/TaNER/app.py b/spaces/livinNector/TaNER/app.py deleted file mode 100644 index d5e427da7856a2ca808abec750479073a5746be1..0000000000000000000000000000000000000000 --- a/spaces/livinNector/TaNER/app.py +++ /dev/null @@ -1,71 +0,0 @@ -import gradio as gr -import torch -from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline - -def get_ner_bio(pipe,text): - tok_text = pipe.tokenizer(text, return_tensors='pt') - with torch.no_grad(): - logits = pipe.model(**tok_text).logits.argmax(-1) - predicted_tokens_classes = [ - pipe.model.config.id2label[t.item()] for t in logits[0] - ] - - predicted_labels = [] - previous_token_id = 0 - word_ids = tok_text.word_ids() - for word_index in range(len(word_ids)): - if not (word_ids[word_index] == None or word_ids[word_index] == previous_token_id): - predicted_labels.append(predicted_tokens_classes[word_index]) - previous_token_id = word_ids[word_index] - - ner_output = [ - (word, label if label!="O" else None) - for word, label in zip(text.split(" "),predicted_labels) - ] - return ner_output - -def get_ner(pipe,text,aggregation_strategy="first"): - - if aggregation_strategy == "bio_first": - return get_ner_bio(pipe,text) - else: - results = pipe(text,aggregation_strategy=aggregation_strategy) - for result in results: - result["entity"] = result["entity_group"] - return {"text": text, "entities": results} - -ner_models = [ - "livinNector/TaNER-500", - "livinNector/TaNER-1k", - "livinNector/IndicBERTv2-MLM-only-NER", - "ai4bharat/IndicNER", - "livinNector/IndicBERTNER", - "livinNector/IndicNER", - "livinNector/xlm-roberta-base-ner", - "livinNector/distilbert-multilingual-base-ner" -] -ner_pipes = [pipeline("token-classification",model) for model in ner_models] - -def get_ner_outputs(text,aggregation_strategy): - return [get_ner(pipe,text,aggregation_strategy) for pipe in ner_pipes] -examples = [ - ["ஆனந்த் மற்றும் லிவின் நெக்டர் ஆகியொர் அண்ணாமலை பல்கலைக்கழகத்தில் படித்து வருகின்றனர்.","first"], - ["இந்தியன் இன்ஸ்டிட்யூட் ஆஃப் டெக்னாலஜி மெட்ராஸ் கிண்டியில் அமைந்துள்ளது.","average"], - ["சச்சின் டெண்டுல்கர் மும்பை மாநகரத்தைச் சேர்ந்த ஒரு நடுத்தரக் குடும்பத்தில் நான்காவது குழந்தையாகப் பிறந்தார். பல துடுப்பாட்ட வீரர்களை உருவாக்கிய சாரதாஷ்ரம் வித்யாமந்திர் பள்ளியில் சேர்ந்தார்.","bio_first"] - - ] - -iface = gr.Interface( - get_ner_outputs, - [ - gr.Textbox(value=examples[0][0]), - gr.Dropdown(["bio_first", "first", "max", "average"],value=examples[0][1]) - ], - [gr.Highlight(label=model) for model in ner_models], - description='Named Entity Recongnition Interface Comparing Various Transformer Based NER models for Tamil Language.', - examples=examples, - title='TaNER', - - ) - -iface.launch(enable_queue=True) \ No newline at end of file diff --git a/spaces/ltomczak1/lungcancer_subclassifier/README.md b/spaces/ltomczak1/lungcancer_subclassifier/README.md deleted file mode 100644 index b4117d54c0d8507702f3eb59bc2cad6dda3774ee..0000000000000000000000000000000000000000 --- a/spaces/ltomczak1/lungcancer_subclassifier/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Capstonethree -emoji: 📈 -colorFrom: pink -colorTo: indigo -sdk: gradio -sdk_version: 3.6 -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/lulmer/paraphraser_ai/footer.py b/spaces/lulmer/paraphraser_ai/footer.py deleted file mode 100644 index f6f33dd9e8a2470b81a9acaecf22801fb9edca77..0000000000000000000000000000000000000000 --- a/spaces/lulmer/paraphraser_ai/footer.py +++ /dev/null @@ -1,76 +0,0 @@ -import streamlit as st -from htbuilder import HtmlElement, div, ul, li, br, hr, a, p, img, styles, classes, fonts -from htbuilder.units import percent, px -from htbuilder.funcs import rgba, rgb - - -def image(src_as_string, **style): - return img(src=src_as_string, style=styles(**style)) - - -def link(link, text, **style): - return a(_href=link, _target="_blank", style=styles(**style))(text) - - -def layout(*args): - - style = """ - - """ - - style_div = styles( - position="fixed", - left=0, - bottom=0, - margin=px(0, 0, 0, 0), - width=percent(100), - color="black", - text_align="center", - height="auto", - opacity=1 - ) - - style_hr = styles( - display="block", - margin=px(8, 8, "auto", "auto"), - border_style="inset", - border_width=px(2) - ) - - body = p() - foot = div( - style=style_div - )( - hr( - style=style_hr - ), - body - ) - - st.markdown(style, unsafe_allow_html=True) - - for arg in args: - if isinstance(arg, str): - body(arg) - - elif isinstance(arg, HtmlElement): - body(arg) - - st.markdown(str(foot), unsafe_allow_html=True) - - -def footer(): - myargs = [ - "Made in ", - image('https://avatars3.githubusercontent.com/u/45109972?s=400&v=4', - width=px(25), height=px(25)), - br(), - "with ❤️ by Louis Ulmer ", - br(), - link("https://www.linkedin.com/in/louisulmer/", image('https://logospng.org/download/linkedin/logo-linkedin-icon-4096.png',width=px(25), height=px(25))), - ] - layout(*myargs) \ No newline at end of file diff --git a/spaces/ma-xu/LIVE/pybind11/tests/test_methods_and_attributes.cpp b/spaces/ma-xu/LIVE/pybind11/tests/test_methods_and_attributes.cpp deleted file mode 100644 index 11d4e7b3501a8bb37b829af6c4aa5d4a4e094f8e..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/pybind11/tests/test_methods_and_attributes.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* - tests/test_methods_and_attributes.cpp -- constructors, deconstructors, attribute access, - __str__, argument and return value conventions - - 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" - -#if !defined(PYBIND11_OVERLOAD_CAST) -template -using overload_cast_ = pybind11::detail::overload_cast_impl; -#endif - -class ExampleMandA { -public: - ExampleMandA() { print_default_created(this); } - ExampleMandA(int value) : value(value) { print_created(this, value); } - ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); } - ExampleMandA(std::string&&) {} - ExampleMandA(ExampleMandA &&e) : value(e.value) { print_move_created(this); } - ~ExampleMandA() { print_destroyed(this); } - - std::string toString() { - return "ExampleMandA[value=" + std::to_string(value) + "]"; - } - - void operator=(const ExampleMandA &e) { print_copy_assigned(this); value = e.value; } - void operator=(ExampleMandA &&e) { print_move_assigned(this); value = e.value; } - - void add1(ExampleMandA other) { value += other.value; } // passing by value - void add2(ExampleMandA &other) { value += other.value; } // passing by reference - void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference - void add4(ExampleMandA *other) { value += other->value; } // passing by pointer - void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer - - void add6(int other) { value += other; } // passing by value - void add7(int &other) { value += other; } // passing by reference - void add8(const int &other) { value += other; } // passing by const reference - void add9(int *other) { value += *other; } // passing by pointer - void add10(const int *other) { value += *other; } // passing by const pointer - - void consume_str(std::string&&) {} - - ExampleMandA self1() { return *this; } // return by value - ExampleMandA &self2() { return *this; } // return by reference - const ExampleMandA &self3() { return *this; } // return by const reference - ExampleMandA *self4() { return this; } // return by pointer - const ExampleMandA *self5() { return this; } // return by const pointer - - int internal1() { return value; } // return by value - int &internal2() { return value; } // return by reference - const int &internal3() { return value; } // return by const reference - int *internal4() { return &value; } // return by pointer - const int *internal5() { return &value; } // return by const pointer - - py::str overloaded() { return "()"; } - py::str overloaded(int) { return "(int)"; } - py::str overloaded(int, float) { return "(int, float)"; } - py::str overloaded(float, int) { return "(float, int)"; } - py::str overloaded(int, int) { return "(int, int)"; } - py::str overloaded(float, float) { return "(float, float)"; } - py::str overloaded(int) const { return "(int) const"; } - py::str overloaded(int, float) const { return "(int, float) const"; } - py::str overloaded(float, int) const { return "(float, int) const"; } - py::str overloaded(int, int) const { return "(int, int) const"; } - py::str overloaded(float, float) const { return "(float, float) const"; } - - static py::str overloaded(float) { return "static float"; } - - int value = 0; -}; - -struct TestProperties { - int value = 1; - static int static_value; - - int get() const { return value; } - void set(int v) { value = v; } - - static int static_get() { return static_value; } - static void static_set(int v) { static_value = v; } -}; -int TestProperties::static_value = 1; - -struct TestPropertiesOverride : TestProperties { - int value = 99; - static int static_value; -}; -int TestPropertiesOverride::static_value = 99; - -struct TestPropRVP { - UserType v1{1}; - UserType v2{1}; - static UserType sv1; - static UserType sv2; - - const UserType &get1() const { return v1; } - const UserType &get2() const { return v2; } - UserType get_rvalue() const { return v2; } - void set1(int v) { v1.set(v); } - void set2(int v) { v2.set(v); } -}; -UserType TestPropRVP::sv1(1); -UserType TestPropRVP::sv2(1); - -// Test None-allowed py::arg argument policy -class NoneTester { public: int answer = 42; }; -int none1(const NoneTester &obj) { return obj.answer; } -int none2(NoneTester *obj) { return obj ? obj->answer : -1; } -int none3(std::shared_ptr &obj) { return obj ? obj->answer : -1; } -int none4(std::shared_ptr *obj) { return obj && *obj ? (*obj)->answer : -1; } -int none5(std::shared_ptr obj) { return obj ? obj->answer : -1; } - -struct StrIssue { - int val = -1; - - StrIssue() = default; - StrIssue(int i) : val{i} {} -}; - -// Issues #854, #910: incompatible function args when member function/pointer is in unregistered base class -class UnregisteredBase { -public: - void do_nothing() const {} - void increase_value() { rw_value++; ro_value += 0.25; } - void set_int(int v) { rw_value = v; } - int get_int() const { return rw_value; } - double get_double() const { return ro_value; } - int rw_value = 42; - double ro_value = 1.25; -}; -class RegisteredDerived : public UnregisteredBase { -public: - using UnregisteredBase::UnregisteredBase; - double sum() const { return rw_value + ro_value; } -}; - -// Test explicit lvalue ref-qualification -struct RefQualified { - int value = 0; - - void refQualified(int other) & { value += other; } - int constRefQualified(int other) const & { return value + other; } -}; - -TEST_SUBMODULE(methods_and_attributes, m) { - // test_methods_and_attributes - py::class_ emna(m, "ExampleMandA"); - emna.def(py::init<>()) - .def(py::init()) - .def(py::init()) - .def(py::init()) - .def("add1", &ExampleMandA::add1) - .def("add2", &ExampleMandA::add2) - .def("add3", &ExampleMandA::add3) - .def("add4", &ExampleMandA::add4) - .def("add5", &ExampleMandA::add5) - .def("add6", &ExampleMandA::add6) - .def("add7", &ExampleMandA::add7) - .def("add8", &ExampleMandA::add8) - .def("add9", &ExampleMandA::add9) - .def("add10", &ExampleMandA::add10) - .def("consume_str", &ExampleMandA::consume_str) - .def("self1", &ExampleMandA::self1) - .def("self2", &ExampleMandA::self2) - .def("self3", &ExampleMandA::self3) - .def("self4", &ExampleMandA::self4) - .def("self5", &ExampleMandA::self5) - .def("internal1", &ExampleMandA::internal1) - .def("internal2", &ExampleMandA::internal2) - .def("internal3", &ExampleMandA::internal3) - .def("internal4", &ExampleMandA::internal4) - .def("internal5", &ExampleMandA::internal5) -#if defined(PYBIND11_OVERLOAD_CAST) - .def("overloaded", py::overload_cast<>(&ExampleMandA::overloaded)) - .def("overloaded", py::overload_cast(&ExampleMandA::overloaded)) - .def("overloaded", py::overload_cast(&ExampleMandA::overloaded)) - .def("overloaded", py::overload_cast(&ExampleMandA::overloaded)) - .def("overloaded", py::overload_cast(&ExampleMandA::overloaded)) - .def("overloaded", py::overload_cast(&ExampleMandA::overloaded)) - .def("overloaded_float", py::overload_cast(&ExampleMandA::overloaded)) - .def("overloaded_const", py::overload_cast(&ExampleMandA::overloaded, py::const_)) - .def("overloaded_const", py::overload_cast(&ExampleMandA::overloaded, py::const_)) - .def("overloaded_const", py::overload_cast(&ExampleMandA::overloaded, py::const_)) - .def("overloaded_const", py::overload_cast(&ExampleMandA::overloaded, py::const_)) - .def("overloaded_const", py::overload_cast(&ExampleMandA::overloaded, py::const_)) -#else - // Use both the traditional static_cast method and the C++11 compatible overload_cast_ - .def("overloaded", overload_cast_<>()(&ExampleMandA::overloaded)) - .def("overloaded", overload_cast_()(&ExampleMandA::overloaded)) - .def("overloaded", overload_cast_()(&ExampleMandA::overloaded)) - .def("overloaded", static_cast(&ExampleMandA::overloaded)) - .def("overloaded", static_cast(&ExampleMandA::overloaded)) - .def("overloaded", static_cast(&ExampleMandA::overloaded)) - .def("overloaded_float", overload_cast_()(&ExampleMandA::overloaded)) - .def("overloaded_const", overload_cast_()(&ExampleMandA::overloaded, py::const_)) - .def("overloaded_const", overload_cast_()(&ExampleMandA::overloaded, py::const_)) - .def("overloaded_const", static_cast(&ExampleMandA::overloaded)) - .def("overloaded_const", static_cast(&ExampleMandA::overloaded)) - .def("overloaded_const", static_cast(&ExampleMandA::overloaded)) -#endif - // test_no_mixed_overloads - // Raise error if trying to mix static/non-static overloads on the same name: - .def_static("add_mixed_overloads1", []() { - auto emna = py::reinterpret_borrow>(py::module::import("pybind11_tests.methods_and_attributes").attr("ExampleMandA")); - emna.def ("overload_mixed1", static_cast(&ExampleMandA::overloaded)) - .def_static("overload_mixed1", static_cast(&ExampleMandA::overloaded)); - }) - .def_static("add_mixed_overloads2", []() { - auto emna = py::reinterpret_borrow>(py::module::import("pybind11_tests.methods_and_attributes").attr("ExampleMandA")); - emna.def_static("overload_mixed2", static_cast(&ExampleMandA::overloaded)) - .def ("overload_mixed2", static_cast(&ExampleMandA::overloaded)); - }) - .def("__str__", &ExampleMandA::toString) - .def_readwrite("value", &ExampleMandA::value); - - // test_copy_method - // Issue #443: can't call copied methods in Python 3 - emna.attr("add2b") = emna.attr("add2"); - - // test_properties, test_static_properties, test_static_cls - py::class_(m, "TestProperties") - .def(py::init<>()) - .def_readonly("def_readonly", &TestProperties::value) - .def_readwrite("def_readwrite", &TestProperties::value) - .def_property("def_writeonly", nullptr, - [](TestProperties& s,int v) { s.value = v; } ) - .def_property("def_property_writeonly", nullptr, &TestProperties::set) - .def_property_readonly("def_property_readonly", &TestProperties::get) - .def_property("def_property", &TestProperties::get, &TestProperties::set) - .def_property("def_property_impossible", nullptr, nullptr) - .def_readonly_static("def_readonly_static", &TestProperties::static_value) - .def_readwrite_static("def_readwrite_static", &TestProperties::static_value) - .def_property_static("def_writeonly_static", nullptr, - [](py::object, int v) { TestProperties::static_value = v; }) - .def_property_readonly_static("def_property_readonly_static", - [](py::object) { return TestProperties::static_get(); }) - .def_property_static("def_property_writeonly_static", nullptr, - [](py::object, int v) { return TestProperties::static_set(v); }) - .def_property_static("def_property_static", - [](py::object) { return TestProperties::static_get(); }, - [](py::object, int v) { TestProperties::static_set(v); }) - .def_property_static("static_cls", - [](py::object cls) { return cls; }, - [](py::object cls, py::function f) { f(cls); }); - - py::class_(m, "TestPropertiesOverride") - .def(py::init<>()) - .def_readonly("def_readonly", &TestPropertiesOverride::value) - .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value); - - auto static_get1 = [](py::object) -> const UserType & { return TestPropRVP::sv1; }; - auto static_get2 = [](py::object) -> const UserType & { return TestPropRVP::sv2; }; - auto static_set1 = [](py::object, int v) { TestPropRVP::sv1.set(v); }; - auto static_set2 = [](py::object, int v) { TestPropRVP::sv2.set(v); }; - auto rvp_copy = py::return_value_policy::copy; - - // test_property_return_value_policies - py::class_(m, "TestPropRVP") - .def(py::init<>()) - .def_property_readonly("ro_ref", &TestPropRVP::get1) - .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy) - .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy)) - .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1) - .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy) - .def_property("rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2) - .def_property_readonly_static("static_ro_ref", static_get1) - .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy) - .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy)) - .def_property_static("static_rw_ref", static_get1, static_set1) - .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy) - .def_property_static("static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2) - // test_property_rvalue_policy - .def_property_readonly("rvalue", &TestPropRVP::get_rvalue) - .def_property_readonly_static("static_rvalue", [](py::object) { return UserType(1); }); - - // test_metaclass_override - struct MetaclassOverride { }; - py::class_(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type)) - .def_property_readonly_static("readonly", [](py::object) { return 1; }); - -#if !defined(PYPY_VERSION) - // test_dynamic_attributes - class DynamicClass { - public: - DynamicClass() { print_default_created(this); } - DynamicClass(const DynamicClass&) = delete; - ~DynamicClass() { print_destroyed(this); } - }; - py::class_(m, "DynamicClass", py::dynamic_attr()) - .def(py::init()); - - class CppDerivedDynamicClass : public DynamicClass { }; - py::class_(m, "CppDerivedDynamicClass") - .def(py::init()); -#endif - - // test_bad_arg_default - // Issue/PR #648: bad arg default debugging output -#if !defined(NDEBUG) - m.attr("debug_enabled") = true; -#else - m.attr("debug_enabled") = false; -#endif - m.def("bad_arg_def_named", []{ - auto m = py::module::import("pybind11_tests"); - m.def("should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg("a") = UnregisteredType()); - }); - m.def("bad_arg_def_unnamed", []{ - auto m = py::module::import("pybind11_tests"); - m.def("should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg() = UnregisteredType()); - }); - - // test_accepts_none - py::class_>(m, "NoneTester") - .def(py::init<>()); - m.def("no_none1", &none1, py::arg().none(false)); - m.def("no_none2", &none2, py::arg().none(false)); - m.def("no_none3", &none3, py::arg().none(false)); - m.def("no_none4", &none4, py::arg().none(false)); - m.def("no_none5", &none5, py::arg().none(false)); - m.def("ok_none1", &none1); - m.def("ok_none2", &none2, py::arg().none(true)); - m.def("ok_none3", &none3); - m.def("ok_none4", &none4, py::arg().none(true)); - m.def("ok_none5", &none5); - - // test_str_issue - // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid - py::class_(m, "StrIssue") - .def(py::init()) - .def(py::init<>()) - .def("__str__", [](const StrIssue &si) { - return "StrIssue[" + std::to_string(si.val) + "]"; } - ); - - // test_unregistered_base_implementations - // - // Issues #854/910: incompatible function args when member function/pointer is in unregistered - // base class The methods and member pointers below actually resolve to members/pointers in - // UnregisteredBase; before this test/fix they would be registered via lambda with a first - // argument of an unregistered type, and thus uncallable. - py::class_(m, "RegisteredDerived") - .def(py::init<>()) - .def("do_nothing", &RegisteredDerived::do_nothing) - .def("increase_value", &RegisteredDerived::increase_value) - .def_readwrite("rw_value", &RegisteredDerived::rw_value) - .def_readonly("ro_value", &RegisteredDerived::ro_value) - // These should trigger a static_assert if uncommented - //.def_readwrite("fails", &UserType::value) // should trigger a static_assert if uncommented - //.def_readonly("fails", &UserType::value) // should trigger a static_assert if uncommented - .def_property("rw_value_prop", &RegisteredDerived::get_int, &RegisteredDerived::set_int) - .def_property_readonly("ro_value_prop", &RegisteredDerived::get_double) - // This one is in the registered class: - .def("sum", &RegisteredDerived::sum) - ; - - using Adapted = decltype(py::method_adaptor(&RegisteredDerived::do_nothing)); - static_assert(std::is_same::value, ""); - - // test_methods_and_attributes - py::class_(m, "RefQualified") - .def(py::init<>()) - .def_readonly("value", &RefQualified::value) - .def("refQualified", &RefQualified::refQualified) - .def("constRefQualified", &RefQualified::constRefQualified); -} diff --git a/spaces/manhkhanhUIT/BOPBTL/Face_Enhancement/models/networks/sync_batchnorm/batchnorm.py b/spaces/manhkhanhUIT/BOPBTL/Face_Enhancement/models/networks/sync_batchnorm/batchnorm.py deleted file mode 100644 index bf8d7a7325b474771a11a137053971fd40426079..0000000000000000000000000000000000000000 --- a/spaces/manhkhanhUIT/BOPBTL/Face_Enhancement/models/networks/sync_batchnorm/batchnorm.py +++ /dev/null @@ -1,412 +0,0 @@ -# -*- coding: utf-8 -*- -# File : batchnorm.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. - -import collections -import contextlib - -import torch -import torch.nn.functional as F - -from torch.nn.modules.batchnorm import _BatchNorm - -try: - from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast -except ImportError: - ReduceAddCoalesced = Broadcast = None - -try: - from jactorch.parallel.comm import SyncMaster - from jactorch.parallel.data_parallel import JacDataParallel as DataParallelWithCallback -except ImportError: - from .comm import SyncMaster - from .replicate import DataParallelWithCallback - -__all__ = [ - 'set_sbn_eps_mode', - 'SynchronizedBatchNorm1d', 'SynchronizedBatchNorm2d', 'SynchronizedBatchNorm3d', - 'patch_sync_batchnorm', 'convert_model' -] - - -SBN_EPS_MODE = 'clamp' - - -def set_sbn_eps_mode(mode): - global SBN_EPS_MODE - assert mode in ('clamp', 'plus') - SBN_EPS_MODE = mode - - -def _sum_ft(tensor): - """sum over the first and last dimention""" - return tensor.sum(dim=0).sum(dim=-1) - - -def _unsqueeze_ft(tensor): - """add new dimensions at the front and the tail""" - return tensor.unsqueeze(0).unsqueeze(-1) - - -_ChildMessage = collections.namedtuple('_ChildMessage', ['sum', 'ssum', 'sum_size']) -_MasterMessage = collections.namedtuple('_MasterMessage', ['sum', 'inv_std']) - - -class _SynchronizedBatchNorm(_BatchNorm): - def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True): - assert ReduceAddCoalesced is not None, 'Can not use Synchronized Batch Normalization without CUDA support.' - - super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine, - track_running_stats=track_running_stats) - - if not self.track_running_stats: - import warnings - warnings.warn('track_running_stats=False is not supported by the SynchronizedBatchNorm.') - - self._sync_master = SyncMaster(self._data_parallel_master) - - self._is_parallel = False - self._parallel_id = None - self._slave_pipe = None - - def forward(self, input): - # If it is not parallel computation or is in evaluation mode, use PyTorch's implementation. - if not (self._is_parallel and self.training): - return F.batch_norm( - input, self.running_mean, self.running_var, self.weight, self.bias, - self.training, self.momentum, self.eps) - - # Resize the input to (B, C, -1). - input_shape = input.size() - assert input.size(1) == self.num_features, 'Channel size mismatch: got {}, expect {}.'.format(input.size(1), self.num_features) - input = input.view(input.size(0), self.num_features, -1) - - # Compute the sum and square-sum. - sum_size = input.size(0) * input.size(2) - input_sum = _sum_ft(input) - input_ssum = _sum_ft(input ** 2) - - # Reduce-and-broadcast the statistics. - if self._parallel_id == 0: - mean, inv_std = self._sync_master.run_master(_ChildMessage(input_sum, input_ssum, sum_size)) - else: - mean, inv_std = self._slave_pipe.run_slave(_ChildMessage(input_sum, input_ssum, sum_size)) - - # Compute the output. - if self.affine: - # MJY:: Fuse the multiplication for speed. - output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std * self.weight) + _unsqueeze_ft(self.bias) - else: - output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std) - - # Reshape it. - return output.view(input_shape) - - def __data_parallel_replicate__(self, ctx, copy_id): - self._is_parallel = True - self._parallel_id = copy_id - - # parallel_id == 0 means master device. - if self._parallel_id == 0: - ctx.sync_master = self._sync_master - else: - self._slave_pipe = ctx.sync_master.register_slave(copy_id) - - def _data_parallel_master(self, intermediates): - """Reduce the sum and square-sum, compute the statistics, and broadcast it.""" - - # Always using same "device order" makes the ReduceAdd operation faster. - # Thanks to:: Tete Xiao (http://tetexiao.com/) - intermediates = sorted(intermediates, key=lambda i: i[1].sum.get_device()) - - to_reduce = [i[1][:2] for i in intermediates] - to_reduce = [j for i in to_reduce for j in i] # flatten - target_gpus = [i[1].sum.get_device() for i in intermediates] - - sum_size = sum([i[1].sum_size for i in intermediates]) - sum_, ssum = ReduceAddCoalesced.apply(target_gpus[0], 2, *to_reduce) - mean, inv_std = self._compute_mean_std(sum_, ssum, sum_size) - - broadcasted = Broadcast.apply(target_gpus, mean, inv_std) - - outputs = [] - for i, rec in enumerate(intermediates): - outputs.append((rec[0], _MasterMessage(*broadcasted[i*2:i*2+2]))) - - return outputs - - def _compute_mean_std(self, sum_, ssum, size): - """Compute the mean and standard-deviation with sum and square-sum. This method - also maintains the moving average on the master device.""" - assert size > 1, 'BatchNorm computes unbiased standard-deviation, which requires size > 1.' - mean = sum_ / size - sumvar = ssum - sum_ * mean - unbias_var = sumvar / (size - 1) - bias_var = sumvar / size - - if hasattr(torch, 'no_grad'): - with torch.no_grad(): - self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data - self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data - else: - self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data - self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data - - if SBN_EPS_MODE == 'clamp': - return mean, bias_var.clamp(self.eps) ** -0.5 - elif SBN_EPS_MODE == 'plus': - return mean, (bias_var + self.eps) ** -0.5 - else: - raise ValueError('Unknown EPS mode: {}.'.format(SBN_EPS_MODE)) - - -class SynchronizedBatchNorm1d(_SynchronizedBatchNorm): - r"""Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a - mini-batch. - - .. math:: - - y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta - - This module differs from the built-in PyTorch BatchNorm1d as the mean and - standard-deviation are reduced across all devices during training. - - For example, when one uses `nn.DataParallel` to wrap the network during - training, PyTorch's implementation normalize the tensor on each device using - the statistics only on that device, which accelerated the computation and - is also easy to implement, but the statistics might be inaccurate. - Instead, in this synchronized version, the statistics will be computed - over all training samples distributed on multiple devices. - - Note that, for one-GPU or CPU-only case, this module behaves exactly same - as the built-in PyTorch implementation. - - The mean and standard-deviation are calculated per-dimension over - the mini-batches and gamma and beta are learnable parameter vectors - of size C (where C is the input size). - - During training, this layer keeps a running estimate of its computed mean - and variance. The running sum is kept with a default momentum of 0.1. - - During evaluation, this running mean/variance is used for normalization. - - Because the BatchNorm is done over the `C` dimension, computing statistics - on `(N, L)` slices, it's common terminology to call this Temporal BatchNorm - - Args: - num_features: num_features from an expected input of size - `batch_size x num_features [x width]` - eps: a value added to the denominator for numerical stability. - Default: 1e-5 - momentum: the value used for the running_mean and running_var - computation. Default: 0.1 - affine: a boolean value that when set to ``True``, gives the layer learnable - affine parameters. Default: ``True`` - - Shape:: - - Input: :math:`(N, C)` or :math:`(N, C, L)` - - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input) - - Examples: - >>> # With Learnable Parameters - >>> m = SynchronizedBatchNorm1d(100) - >>> # Without Learnable Parameters - >>> m = SynchronizedBatchNorm1d(100, affine=False) - >>> input = torch.autograd.Variable(torch.randn(20, 100)) - >>> output = m(input) - """ - - def _check_input_dim(self, input): - if input.dim() != 2 and input.dim() != 3: - raise ValueError('expected 2D or 3D input (got {}D input)' - .format(input.dim())) - - -class SynchronizedBatchNorm2d(_SynchronizedBatchNorm): - r"""Applies Batch Normalization over a 4d input that is seen as a mini-batch - of 3d inputs - - .. math:: - - y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta - - This module differs from the built-in PyTorch BatchNorm2d as the mean and - standard-deviation are reduced across all devices during training. - - For example, when one uses `nn.DataParallel` to wrap the network during - training, PyTorch's implementation normalize the tensor on each device using - the statistics only on that device, which accelerated the computation and - is also easy to implement, but the statistics might be inaccurate. - Instead, in this synchronized version, the statistics will be computed - over all training samples distributed on multiple devices. - - Note that, for one-GPU or CPU-only case, this module behaves exactly same - as the built-in PyTorch implementation. - - The mean and standard-deviation are calculated per-dimension over - the mini-batches and gamma and beta are learnable parameter vectors - of size C (where C is the input size). - - During training, this layer keeps a running estimate of its computed mean - and variance. The running sum is kept with a default momentum of 0.1. - - During evaluation, this running mean/variance is used for normalization. - - Because the BatchNorm is done over the `C` dimension, computing statistics - on `(N, H, W)` slices, it's common terminology to call this Spatial BatchNorm - - Args: - num_features: num_features from an expected input of - size batch_size x num_features x height x width - eps: a value added to the denominator for numerical stability. - Default: 1e-5 - momentum: the value used for the running_mean and running_var - computation. Default: 0.1 - affine: a boolean value that when set to ``True``, gives the layer learnable - affine parameters. Default: ``True`` - - Shape:: - - Input: :math:`(N, C, H, W)` - - Output: :math:`(N, C, H, W)` (same shape as input) - - Examples: - >>> # With Learnable Parameters - >>> m = SynchronizedBatchNorm2d(100) - >>> # Without Learnable Parameters - >>> m = SynchronizedBatchNorm2d(100, affine=False) - >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45)) - >>> output = m(input) - """ - - def _check_input_dim(self, input): - if input.dim() != 4: - raise ValueError('expected 4D input (got {}D input)' - .format(input.dim())) - - -class SynchronizedBatchNorm3d(_SynchronizedBatchNorm): - r"""Applies Batch Normalization over a 5d input that is seen as a mini-batch - of 4d inputs - - .. math:: - - y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta - - This module differs from the built-in PyTorch BatchNorm3d as the mean and - standard-deviation are reduced across all devices during training. - - For example, when one uses `nn.DataParallel` to wrap the network during - training, PyTorch's implementation normalize the tensor on each device using - the statistics only on that device, which accelerated the computation and - is also easy to implement, but the statistics might be inaccurate. - Instead, in this synchronized version, the statistics will be computed - over all training samples distributed on multiple devices. - - Note that, for one-GPU or CPU-only case, this module behaves exactly same - as the built-in PyTorch implementation. - - The mean and standard-deviation are calculated per-dimension over - the mini-batches and gamma and beta are learnable parameter vectors - of size C (where C is the input size). - - During training, this layer keeps a running estimate of its computed mean - and variance. The running sum is kept with a default momentum of 0.1. - - During evaluation, this running mean/variance is used for normalization. - - Because the BatchNorm is done over the `C` dimension, computing statistics - on `(N, D, H, W)` slices, it's common terminology to call this Volumetric BatchNorm - or Spatio-temporal BatchNorm - - Args: - num_features: num_features from an expected input of - size batch_size x num_features x depth x height x width - eps: a value added to the denominator for numerical stability. - Default: 1e-5 - momentum: the value used for the running_mean and running_var - computation. Default: 0.1 - affine: a boolean value that when set to ``True``, gives the layer learnable - affine parameters. Default: ``True`` - - Shape:: - - Input: :math:`(N, C, D, H, W)` - - Output: :math:`(N, C, D, H, W)` (same shape as input) - - Examples: - >>> # With Learnable Parameters - >>> m = SynchronizedBatchNorm3d(100) - >>> # Without Learnable Parameters - >>> m = SynchronizedBatchNorm3d(100, affine=False) - >>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45, 10)) - >>> output = m(input) - """ - - def _check_input_dim(self, input): - if input.dim() != 5: - raise ValueError('expected 5D input (got {}D input)' - .format(input.dim())) - - -@contextlib.contextmanager -def patch_sync_batchnorm(): - import torch.nn as nn - - backup = nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d - - nn.BatchNorm1d = SynchronizedBatchNorm1d - nn.BatchNorm2d = SynchronizedBatchNorm2d - nn.BatchNorm3d = SynchronizedBatchNorm3d - - yield - - nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d = backup - - -def convert_model(module): - """Traverse the input module and its child recursively - and replace all instance of torch.nn.modules.batchnorm.BatchNorm*N*d - to SynchronizedBatchNorm*N*d - - Args: - module: the input module needs to be convert to SyncBN model - - Examples: - >>> import torch.nn as nn - >>> import torchvision - >>> # m is a standard pytorch model - >>> m = torchvision.models.resnet18(True) - >>> m = nn.DataParallel(m) - >>> # after convert, m is using SyncBN - >>> m = convert_model(m) - """ - if isinstance(module, torch.nn.DataParallel): - mod = module.module - mod = convert_model(mod) - mod = DataParallelWithCallback(mod, device_ids=module.device_ids) - return mod - - mod = module - for pth_module, sync_module in zip([torch.nn.modules.batchnorm.BatchNorm1d, - torch.nn.modules.batchnorm.BatchNorm2d, - torch.nn.modules.batchnorm.BatchNorm3d], - [SynchronizedBatchNorm1d, - SynchronizedBatchNorm2d, - SynchronizedBatchNorm3d]): - if isinstance(module, pth_module): - mod = sync_module(module.num_features, module.eps, module.momentum, module.affine) - mod.running_mean = module.running_mean - mod.running_var = module.running_var - if module.affine: - mod.weight.data = module.weight.data.clone().detach() - mod.bias.data = module.bias.data.clone().detach() - - for name, child in module.named_children(): - mod.add_module(name, convert_model(child)) - - return mod diff --git a/spaces/marcusj83/MusicGenbruh/CODE_OF_CONDUCT.md b/spaces/marcusj83/MusicGenbruh/CODE_OF_CONDUCT.md deleted file mode 100644 index 83f431e8feeb7e80d571f39c9f6c1b96857b5f85..0000000000000000000000000000000000000000 --- a/spaces/marcusj83/MusicGenbruh/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,80 +0,0 @@ -# Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to make participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic -address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a -professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies within all project spaces, and it also applies when -an individual is representing the project or its community in public spaces. -Examples of representing a project or community include using an official -project e-mail address, posting via an official social media account, or acting -as an appointed representative at an online or offline event. Representation of -a project may be further defined and clarified by project maintainers. - -This Code of Conduct also applies outside the project spaces when there is a -reasonable belief that an individual's behavior may have a negative impact on -the project or its community. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at . All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq diff --git a/spaces/matthoffner/starchat-ui/components/Chatbar/components/PluginKeys.tsx b/spaces/matthoffner/starchat-ui/components/Chatbar/components/PluginKeys.tsx deleted file mode 100644 index 1dcfe17d90a1e3eb72c55ca876acc7617e788983..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/starchat-ui/components/Chatbar/components/PluginKeys.tsx +++ /dev/null @@ -1,235 +0,0 @@ -import { IconKey } from '@tabler/icons-react'; -import { KeyboardEvent, useContext, useEffect, useRef, useState } from 'react'; -import { useTranslation } from 'react-i18next'; - -import { PluginID, PluginKey } from '@/types/plugin'; - -import HomeContext from '@/pages/api/home/home.context'; - -import { SidebarButton } from '@/components/Sidebar/SidebarButton'; - -import ChatbarContext from '../Chatbar.context'; - -export const PluginKeys = () => { - const { t } = useTranslation('sidebar'); - - const { - state: { pluginKeys }, - } = useContext(HomeContext); - - const { handlePluginKeyChange, handleClearPluginKey } = - useContext(ChatbarContext); - - const [isChanging, setIsChanging] = useState(false); - - const modalRef = useRef(null); - - const handleEnter = (e: KeyboardEvent) => { - if (e.key === 'Enter' && !e.shiftKey) { - e.preventDefault(); - setIsChanging(false); - } - }; - - useEffect(() => { - const handleMouseDown = (e: MouseEvent) => { - if (modalRef.current && !modalRef.current.contains(e.target as Node)) { - window.addEventListener('mouseup', handleMouseUp); - } - }; - - const handleMouseUp = (e: MouseEvent) => { - window.removeEventListener('mouseup', handleMouseUp); - setIsChanging(false); - }; - - window.addEventListener('mousedown', handleMouseDown); - - return () => { - window.removeEventListener('mousedown', handleMouseDown); - }; - }, []); - - return ( - <> - } - onClick={() => setIsChanging(true)} - /> - - {isChanging && ( -
      -
      -
      - -
      -
      - )} - - ); -}; diff --git a/spaces/mchopra/VV-05-GR-NLP-Image2Text-Multilingual-OCR/README.md b/spaces/mchopra/VV-05-GR-NLP-Image2Text-Multilingual-OCR/README.md deleted file mode 100644 index de7eac924f93457b31cfdebf5b9fbcf4aeab3dec..0000000000000000000000000000000000000000 --- a/spaces/mchopra/VV-05-GR-NLP-Image2Text-Multilingual-OCR/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: VV 05 GR NLP Image2Text Multilingual OCR -emoji: 🔥 -colorFrom: pink -colorTo: pink -sdk: gradio -sdk_version: 3.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/merle/PROTEIN_GENERATOR/utils/model/se3_transformer/model/layers/pooling.py b/spaces/merle/PROTEIN_GENERATOR/utils/model/se3_transformer/model/layers/pooling.py deleted file mode 100644 index e42c5383ba3239e3d93c928fa83a61a9e19b9437..0000000000000000000000000000000000000000 --- a/spaces/merle/PROTEIN_GENERATOR/utils/model/se3_transformer/model/layers/pooling.py +++ /dev/null @@ -1,53 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# 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. -# -# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES -# SPDX-License-Identifier: MIT - -from typing import Dict, Literal - -import torch.nn as nn -from dgl import DGLGraph -from dgl.nn.pytorch import AvgPooling, MaxPooling -from torch import Tensor - - -class GPooling(nn.Module): - """ - Graph max/average pooling on a given feature type. - The average can be taken for any feature type, and equivariance will be maintained. - The maximum can only be taken for invariant features (type 0). - If you want max-pooling for type > 0 features, look into Vector Neurons. - """ - - def __init__(self, feat_type: int = 0, pool: Literal['max', 'avg'] = 'max'): - """ - :param feat_type: Feature type to pool - :param pool: Type of pooling: max or avg - """ - super().__init__() - assert pool in ['max', 'avg'], f'Unknown pooling: {pool}' - assert feat_type == 0 or pool == 'avg', 'Max pooling on type > 0 features will break equivariance' - self.feat_type = feat_type - self.pool = MaxPooling() if pool == 'max' else AvgPooling() - - def forward(self, features: Dict[str, Tensor], graph: DGLGraph, **kwargs) -> Tensor: - pooled = self.pool(graph, features[str(self.feat_type)]) - return pooled.squeeze(dim=-1) diff --git a/spaces/merve/data-leak/source/third_party/npyjs.js b/spaces/merve/data-leak/source/third_party/npyjs.js deleted file mode 100644 index bd741887cd85f0a495015968a3793f9d1d944efe..0000000000000000000000000000000000000000 --- a/spaces/merve/data-leak/source/third_party/npyjs.js +++ /dev/null @@ -1,108 +0,0 @@ -// Apache-2.0 https://github.com/1wheel/npyjs - -const dtypes = { - ' '\x20').join(''); - - const hl = (header + spacepad).length; - - return Buffer.concat([ - Buffer.from('\x93NUMPY\x01\x00', 'latin1'), - // convert to little-endian - Buffer.from(new Uint8Array([hl % 256, hl/256 | 0])), - Buffer.from(header + spacepad, 'latin1'), - Buffer.from(typedArray.buffer) - ]); -} - -export default {parse, format}; \ No newline at end of file diff --git a/spaces/merve/fill-in-the-blank/server-side/fill-in-the-blank/scatter-plot-colab/spearman-distribution/init.js b/spaces/merve/fill-in-the-blank/server-side/fill-in-the-blank/scatter-plot-colab/spearman-distribution/init.js deleted file mode 100644 index 45e4fafb63a667109fdf81c03ed1d375027ae462..0000000000000000000000000000000000000000 --- a/spaces/merve/fill-in-the-blank/server-side/fill-in-the-blank/scatter-plot-colab/spearman-distribution/init.js +++ /dev/null @@ -1,168 +0,0 @@ -/* Copyright 2021 Google LLC. 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. -==============================================================================*/ - - -// console.clear() - -window.init = function(){ - var initFns = [window.initUtil, window.initScatter, window.initPair] - if (!initFns.every(d => d)) return - - window.util = initUtil() - - window.tidy = d3.csvParse(python_data.tidyCSV, d => { - return { - e0: +d.e0, - e1: +d.e1, - i0: +d.i0, - i1: +d.i1, - tokenIndex: +d.tokenIndex, - sentenceIndex: +d.sentenceIndex, - } - }) - - var bySentence = d3.nestBy(tidy, d => d.sentenceIndex) - bySentence.forEach(sent => { - sent.sentenceIndex = +sent.key - sent.s0 = python_data.sentences[sent.sentenceIndex].s0 - sent.s1 = python_data.sentences[sent.sentenceIndex].s1 - sent.orig = python_data.sentences[sent.sentenceIndex].orig - - sent.corrA = ss.sampleCorrelation(sent.map(d => d.i0), sent.map(d => d.i1)) - // sent.corrA = ss.sampleCorrelation(sent.map(d => d.e0), sent.map(d => d.e1)) - }) - - var sel = d3.select('.container').html(` -
      -
      -
      -
      -
      -
      -
      - `) - .st({width: 1100}) - d3.selectAll('.left,.right').st({width: 500, display: 'inline-block', verticalAlign: 'top'}) - - function initBeeswarm(bySentence, sel){ - var c = d3.conventions({ - sel: sel.append('div'), - height: 80, - totalWidth: 400, - margin: {left: 0, top: 18} - }) - - c.x.domain(d3.extent(bySentence.map(d => +d.corrA))).nice() - // c.x.domain([0, 1]) - c.xAxis.ticks(5) - d3.drawAxis(c) - util.ggPlotBg(c) - c.svg.select('.y').remove() - c.svg.selectAll('.tick').st({display: 'block'}) - - var simulation = d3.forceSimulation(bySentence) - .force("x", d3.forceX(d => c.x(d.corrA)).strength(1)) - .force("y", d3.forceY(c.height / 2)) - .force("collide", d3.forceCollide(4)) - .stop() - - for (var i = 0; i < 120; ++i) simulation.tick() - - c.svg.append('text').text('text') - .text('Distribution of Spearman Correlation Coefficients') - .at({dy: -5, fontWeight: 600}) - - c.svg.appendMany('circle.sentence', bySentence) - .translate(d => [d.x, d.y]) - .at({ - r: 3, - fill: 'none', - stroke: '#000' - }) - .on('mouseover', setSentenceAsPair) - } - initBeeswarm(bySentence, d3.select('.beeswarm')) - - - function initList(bySentence, sel){ - // var sentenceSel = sel.st({height: 500, overflowY: 'scroll', cursor: 'default'}) - // .appendMany('div.sentence', _.sortBy(bySentence, d => d.corrA)) - // .on('mouseover', setSentenceAsPair) - // .st({padding: 2, fontSize: 12}) - - // sentenceSel.append('span') - // .text(d => (d3.format('+.2f')(d.corrA)).replace('0.', '.')) - // .st({marginRight: 10, color: '#aaa'}) - - // sentenceSel.append('span') - // .text(d => d.orig.replace('[', '').replace(']', '')) - - var tableSel = sel - .st({height: 470 + 17, overflowY: 'scroll', cursor: 'default', position: 'relative', left: -40}) - .append('table') - .st({fontSize: 12}) - - tableSel.append('tr.header') - .html(` - corr - template - `) - - var rowSel = tableSel - .appendMany('tr.sentence', _.sortBy(bySentence, d => d.corrA)) - .on('mouseover', setSentenceAsPair) - .st({padding: 2, fontSize: 12}) - .html(d => ` - ${(d3.format('+.2f')(d.corrA)).replace('0.', '.')} - ${d.orig.replace('[', '').replace(']', '')} - `) - } - initList(bySentence, d3.select('.list')) - - - - function setSentenceAsPair(s){ - s.e0 = d3.range(python_data.vocab.length).map(d => -Infinity) - s.e1 = d3.range(python_data.vocab.length).map(d => -Infinity) - s.forEach(d => { - s.e0[d.tokenIndex] = d.e0 - s.e1[d.tokenIndex] = d.e1 - }) - - s.label0 = s.s0 - s.label1 = s.s1 - s.vocab = python_data.vocab - s.count = python_settings.count || 150 - s.isDifference = python_settings.isDifference - - var sel = d3.select('.pair').html('').st({width: 400}) - - initPair(s, sel) - - d3.selectAll('.sentence').classed('active', d => d == s) - - d3.selectAll('div.sentence').filter(d => d == s) - .each(function(){ - this.scrollIntoView({ block: 'nearest', inline: 'nearest'}) - }) - } - - setSentenceAsPair(bySentence[0]) - -} - - -window.init() - diff --git a/spaces/merve/measuring-fairness/public/hidden-bias/annotations.js b/spaces/merve/measuring-fairness/public/hidden-bias/annotations.js deleted file mode 100644 index b0fd377b443ee9bd31e7bd1d9dbacafc4e5282e3..0000000000000000000000000000000000000000 --- a/spaces/merve/measuring-fairness/public/hidden-bias/annotations.js +++ /dev/null @@ -1,86 +0,0 @@ -window.annotations = [ - { - "slide": 0, - "x": 1.77, - "y": 3.17, - "path": "M -3,-59 A 31.215 31.215 0 1 0 -10,2", - "text": "Joshua had a high school GPA of 3.2 and 1.8 in college", - "textOffset": [ - -1, - -48 - ] - }, - { - "slide": 0, - "x": 2.93, - "y": 2.08, - "path": "M 56,61 A 45.102 45.102 0 0 0 19.000001907348633,1.0000003576278687", - "text": "Abigail has a 2.1 in high school and 2.9 in college", - "textOffset": [ - -5, - 85 - ], - "width": 18 - }, - { - "slide": 1, - "x": 3.7, - "y": 2, - "path": "M 1,41 A 209.709 209.709 0 0 1 -310,76", - "text": "Most students have a higher GPA in high school", - "textOffset": [ - -69, - 11 - ], - "width": 18 - }, - { - "slide": 2, - "x": 1, - "y": 4, - "path": "M 0 0", - "text": "A well adjusted model will usually over predict about half the students' grades...", - "textOffset": [ - 25, - 50 - ], - "width": 25 - }, - { - "slide": 2, - "x": 4, - "y": 1, - "path": "M 0 0", - "text": "...and under predict the other half", - "textOffset": [ - -109, - -51 - ], - "width": 18 - }, - { - "slide": 5, - "x": 2.58, - "y": 2, - "path": "M 54,34 A 29.707 29.707 0 0 0 11,-6", - "text": "The model predicted both Lucas and Mia would get a 2.0, but she ended up with a higher GPA", - "html": "The model predicted both Lucas and Mia would get a 2.0, but she ended up with a higher GPA", - "textOffset": [ - -22, - 44 - ], - "width": 23 - }, - { - "slide": 5, - "x": 2.14, - "y": 2, - "path": "M 40,61 A 35.025 35.025 0 0 1 -4,7", - "text": "", - "textOffset": [ - -100, - 179 - ], - "width": 14 - } -] \ No newline at end of file diff --git a/spaces/merve/uncertainty-calibration/public/private-and-fair/2d-privacy.js b/spaces/merve/uncertainty-calibration/public/private-and-fair/2d-privacy.js deleted file mode 100644 index fc89da57484ca77169f4b7aff1c1f75365bd9093..0000000000000000000000000000000000000000 --- a/spaces/merve/uncertainty-calibration/public/private-and-fair/2d-privacy.js +++ /dev/null @@ -1,383 +0,0 @@ -window.state = window.state || { - scoreSteps: 101, - nParams: 11, - nRandLines: 50, - nMaxRand: 0, - nBatches: 4, - learningRate: 22, -} - - -window.pointData = window.pointData || d3.range(100).map(i => { - var color = i % 2 ? 0 : 1 - var color0 = color - var color1 = color - - var σ = .1 - var μ = .2 - if (color){ - var x = d3.randomNormal(1 - μ, σ)() - var y = d3.randomNormal(1 - μ, σ*1)() - } else { - var x = d3.randomNormal(μ, σ)() - var y = d3.randomNormal(μ, σ*1)() - y = d3.clamp(0, y, .4) - } - - x = d3.clamp(.03, x, .97) - y = d3.clamp(.03, y, .97) - - var bucketX = x*(state.nParams - 1) - - if (i == 51){ - x = .25 - y = .55 - color = 0 - color0 = 0 - color1 = 1 - } - - return {i, x, y, bucketX, color, color0, color1} -}) - -var updateAllFns = [] -var updateAll = () => updateAllFns.forEach(fn => fn()) - -var updateCircleFns = [] -var updateCircle = (d) => updateCircleFns.forEach(fn => fn(d)) - -var sel = d3.select('.epoch-graph').html('') - .st({marginTop: 30}) - .at({role: 'graphics-document', 'aria-label': `Grid of charts showing a simple 2d classifer being trained over four epochs. Changing a single outlier point from red to blue makes a big difference in the final model.`}) - -var dbSel = d3.select('.decision-boundry').html('').append('div') - .at({role: 'graphics-document', 'aria-label': `Slides to control the level clipping and noise applied the gradient at each step. Increasing the noise enough makes the decision boundries for the models trained on the red and blue outliers overlap.`}) - -var colorTypes = [{key: 'color1'}, {key: 'color0'}] -sel.appendMany('div', colorTypes) - .each(drawColorType) - -drawBatch( - dbSel.append('div').parent().append('div'), - 3, - colorTypes[0], - colorTypes[1] -) - - -function drawColorType(ct){ - function calcBatches(){ - var buckets = d3.nestBy(pointData, d => Math.floor(d.bucketX)) - buckets = _.sortBy(buckets, d => +d.key) - - pointData.forEach(d => { - d.bucketX = d.x*(state.nParams - 1) - }) - - buckets.forEach((bucket, i) => { - bucket.i = i - bucket.x = +bucket.key - - bucket.pointData = pointData.filter(d => Math.abs(d.bucketX - bucket.key) < 1) - - bucket.scores = d3.range(state.scoreSteps).map(i => { - var y = i/(state.scoreSteps - 1) - var pad = 0 - - var score = d3.sum(bucket.pointData, (d, i) => { - // return d[ct.key] == 0 ? d.y < y - pad : d.y > y + pad - - var dif = 1 - Math.abs(d.bucketX - bucket.x) - dif = Math.min(dif, .5) - if (d[ct.key] == 0){ - return d.y < y - pad ? dif : -dif - } else { - return d.y > y + pad ? dif : -dif - } - }) - - return {y, i, score} - }) - - bucket.best = _.maxBy(bucket.scores, d => d.score) - - bucket.scores.forEach(score => { - var nextScoreIndex = score.i - var charge = 0 - - for (var j = 0; j < state.learningRate; j++){ - var dif = bucket.best.score - bucket.scores[nextScoreIndex]?.score - charge += dif || 5 - if (bucket.scores[nextScoreIndex | 0].score == bucket.best.score){ - j = state.learningRate - } else if (charge > 2) { - nextScoreIndex += nextScoreIndex < bucket.best.i ? 1 : -1 - charge = 0 - } - } - - score.nextScoreIndex = nextScoreIndex - }) - - bucket.x = (bucket.i +.5)/(state.nParams - 1) - }) - - var rng = new alea(ct.key) - - // random lines x batches x buckets - var randLines = d3.range(state.nRandLines).map(() => { - return [buckets.map(d => Math.floor(d.x*state.scoreSteps))] - }) - - function calcNextBatch(){ - randLines.forEach(line => { - var next = _.last(line).map((scoreIndex, i) => { - var randInt = Math.round((rng() - .5)*state.nMaxRand) - return d3.clamp( - 0, - buckets[i].scores[scoreIndex | 0].nextScoreIndex + randInt, - state.scoreSteps - 1) - }) - - line.push(next) - }) - } - d3.range(state.nBatches - 1).forEach(calcNextBatch) - - ct.buckets = buckets - ct.randLines = randLines - } - calcBatches() - - var sel = d3.select(this) - - var render = (function(){ - ct.renderFns = [] - - sel - .append('div.chart-title').text(ct.key == 'color1' ? 'Training a model with an isolated red point' : 'Training a model with an isolated blue point') - .st({marginLeft: 10, marginBottom: -18, marginTop: -5}) - .parent() - .appendMany('div', ct.randLines[0]) - .st({display: 'inline-block'}) - .each(function(d, i){ drawBatch(d3.select(this), i, ct)}) - - return () => ct.renderFns.forEach(d => d()) - })() - - updateAllFns.push(() => { - calcBatches() - render() - }) -} - - -function drawBatch(sel, batchIndex, ct, ct2){ - - var size = ct2 ? 300 : 150 - var mScale = ct2 ? 0 : 1 - var c = d3.conventions({ - sel, - width: size, - height: size, - margin: {left: 10*mScale, right: 10*mScale, top: 20*mScale, bottom: ct2 ? 50 : 20}, - layers: 'scsd', - }) - - var divSel = c.layers[3].st({pointerEvents: 'none'}) - - c.layers[0].append('rect') - .at({width: c.width, height: c.height, fill: '#efefef'}) - - c.svg = c.layers[2] - - c.svg.append('rect') - .at({width: c.width, height: c.height, fill: 'rgba(0,0,0,0)'}) - - c.svg.append('text') - .text('Step ' + (batchIndex + 1)) - .translate([c.width/2, c.height + 13]) - .at({textAnchor: 'middle', fontSize: 10, fill: '#999'}) - .st({opacity: ct2 ? 0 : 1}) - - c.x.domain([0, 1]).clamp(1) - c.y.domain([0, 1]).clamp(1) - - var drag = d3.drag() - .on('start', () => c.svg.classed('dragging', 1)) - .on('end', () => c.svg.classed('dragging', 0)) - .on('drag', function(d){ - d.x = d3.clamp(.03, c.x.invert(d3.event.x), .97) - d.y = d3.clamp(.03, c.y.invert(d3.event.y), .97) - - updateCircle(d) - updateAll() - }) - .subject(function(d){ return {x: c.x(d.x), y: c.y(d.y)} }) - - var circleSel = c.svg.appendMany('circle.point', pointData) - .at({r: 4, fill: d => util.colors[d[ct.key]]}) - .call(drag) - .classed('swapped', d => d.color0 != d.color1) - .translate(d => [c.x(d.x), c.y(d.y)]) - // .call(d3.attachTooltip) - - updateCircleFns.push(d => { - circleSel - .filter(e => e == d) // rendering circles is dropping frames ? - .translate(d => [c.x(d.x), c.y(d.y)]) - }) - - if (ct2){ - var defs = c.svg.append('defs'); - defs.append('linearGradient#red-blue-def') - .append('stop').at({offset: '0%', 'stop-color': util.colors[0]}).parent() - .append('stop').at({offset: '45%', 'stop-color': util.colors[0]}).parent() - .append('stop').at({offset: '55%', 'stop-color': util.colors[1]}).parent() - .append('stop').at({offset: '100%', 'stop-color': util.colors[1]}) - defs.append('linearGradient#blue-red-def') - .append('stop').at({offset: '0%', 'stop-color': util.colors[1]}).parent() - .append('stop').at({offset: '45%', 'stop-color': util.colors[1]}).parent() - .append('stop').at({offset: '55%', 'stop-color': util.colors[0]}).parent() - .append('stop').at({offset: '100%', 'stop-color': util.colors[0]}) - - circleSel - // .at({r: 1.2}) - .filter(d => d.color0 != d.color1) - .st({r: 7, fillOpacity: 1}) - .st({fill: 'url(#red-blue-def)'})//, stroke: 'url(#blue-red-def)'}) - - var gradientClipAnnoSel = c.svg.append('text.annotation') - .translate([c.width + 20, -40]) - .tspans(d3.wordwrap('Completely clipping the gradient stops the model from learning anything from the training data.', 25), 14) - - divSel.append('div.annotation') - .translate([30, c.height + 5]) - .html(` - Models trained with the isolated blue point -
      - Models trained with the isolated red point - `) - .st({lineHeight: '1.3em'}) - .selectAll('span').st({fontSize: 20, height: 0, display: 'inline-block', top: 3, position: 'relative', fontWeight: 700}) - - - } - - function getRandLines(){ - return ct2 ? ct.randLines.concat(ct2.randLines) : ct.randLines - } - - var ctx = c.layers[1] - - var lineGen = d3.line() - .x(d => c.x(d.x)) - .y(d => c.y(d.y)) - .curve(d3.curveNatural) - .context(ctx) - - ct.renderFns.push(() => { - var scores = ct.buckets[0].scores - var paddedLineData = getRandLines().map(line => { - var xyData = line[batchIndex].map((scoreIndex, i) => { - return {x: ct.buckets[i].x, y: scores[scoreIndex | 0].y} - }) - - return [ - {x: 0, y: batchIndex*state.learningRate ? xyData[0].y : 0}, - ...xyData, - {x: 1, y: batchIndex*state.learningRate ? _.last(xyData).y : 1} - ] - }) - - ctx.clearRect(-c.margin.left, -c.margin.top, c.width + c.margin.left + c.margin.right, c.height + c.margin.top + c.margin.bottom) - paddedLineData.forEach((d, i) => { - ctx.beginPath() - ctx.lineWidth = .1 - ctx.strokeStyle = !ct2 ? '#000' : i < ct.randLines.length ? util.colors[1] : util.colors[0] - lineGen(d) - ctx.stroke() - }) - - if (ct2){ - gradientClipAnnoSel.st({opacity: state.learningRate == 0 ? 1 : 0}) - } - }) -} - - -function addSliders(){ - var width = 180 - var height = 30 - var color = '#000' - - var sliders = [ - {key: 'nMaxRand', label: 'Random Noise', r: [0, 30]}, - {key: 'learningRate', label: 'Gradient Clip', r: [30, 0]}, - ] - sliders.forEach(d => { - d.value = state[d.key] - d.xScale = d3.scaleLinear().range([0, width]).domain(d.r).clamp(1) - }) - - var svgSel = dbSel.append('div.sliders').lower() - .st({marginTop: 5, marginBottom: 5}) - .appendMany('div.slider-container', sliders) - .append('svg').at({width, height}) - .append('g').translate(120, 0) - - svgSel.append('text.chart-title') - .text(d => d.label) - .at({textAnchor: 'end', dy: '.33em', x: -15}) - - var sliderSel = svgSel - .on('click', function(d){ - d.value = d.xScale.invert(d3.mouse(this)[0]) - renderSliders(d) - }) - .classed('slider', true) - .st({cursor: 'pointer'}) - - var textSel = sliderSel.append('text.slider-label-container') - .at({y: -20, fontWeight: 500, textAnchor: 'middle', x: 180/2}) - - sliderSel.append('rect') - .at({width, height, y: -height/2, fill: 'rgba(0,0,0,0)'}) - - sliderSel.append('path').at({ - d: `M 0 -.5 H ${width}`, - stroke: color, - strokeWidth: 1 - }) - - var leftPathSel = sliderSel.append('path').at({ - d: `M 0 -.5 H ${width}`, - stroke: color, - strokeWidth: 3 - }) - - var drag = d3.drag() - .on('drag', function(d){ - var x = d3.mouse(this)[0] - d.value = d.xScale.invert(x) - - renderSliders(d) - }) - - var circleSel = sliderSel.append('circle').call(drag) - .at({r: 7, stroke: '#000'}) - - function renderSliders(d){ - if (d) state[d.key] = d.value - - circleSel.at({cx: d => d.xScale(d.value)}) - leftPathSel.at({d: d => `M 0 -.5 H ${d.xScale(d.value)}`}) - - updateAll() - } - renderSliders() -} -addSliders() - - -updateAll() diff --git a/spaces/mfrashad/ClothingGAN/models/stylegan/stylegan_tf/training/__init__.py b/spaces/mfrashad/ClothingGAN/models/stylegan/stylegan_tf/training/__init__.py deleted file mode 100644 index db8124b132f91216c0ded226f20ea3a046734728..0000000000000000000000000000000000000000 --- a/spaces/mfrashad/ClothingGAN/models/stylegan/stylegan_tf/training/__init__.py +++ /dev/null @@ -1,8 +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. - -# empty diff --git a/spaces/mikeee/multilingual-dokugpt/app-org.py b/spaces/mikeee/multilingual-dokugpt/app-org.py deleted file mode 100644 index fcecb281d3163cf2766821b77b3394badbdb55c4..0000000000000000000000000000000000000000 --- a/spaces/mikeee/multilingual-dokugpt/app-org.py +++ /dev/null @@ -1,526 +0,0 @@ -"""Refer to -https://huggingface.co/spaces/mikeee/docs-chat/blob/main/app.py -and https://github.com/PromtEngineer/localGPT/blob/main/ingest.py - -https://python.langchain.com/en/latest/getting_started/tutorials.html - -unstructured: python-magic python-docx python-pptx -from langchain.document_loaders import UnstructuredHTMLLoader - -docs = [] -# for doc in Path('docs').glob("*.pdf"): -for doc in Path('docs').glob("*"): -# for doc in Path('docs').glob("*.txt"): - docs.append(load_single_document(f"{doc}")) -text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) -texts = text_splitter.split_documents(docs) - -model_name = "hkunlp/instructor-base" -embeddings = HuggingFaceInstructEmbeddings( - model_name=model_name, model_kwargs={"device": device} -) - -# constitution.pdf 54344, 72 chunks Wall time: 3min 13s CPU times: total: 9min 4s @golay -# test.txt 21286, 27 chunks, Wall time: 47 s CPU times: total: 2min 30s @golay -# both 99 chunks, Wall time: 5min 4s CPU times: total: 13min 31s -# chunks = len / 800 - -db = Chroma.from_documents(texts, embeddings) - -db = Chroma.from_documents( - texts, - embeddings, - persist_directory=PERSIST_DIRECTORY, - client_settings=CHROMA_SETTINGS, -) -db.persist() - -# 中国共产党章程.txt qa -https://github.com/xanderma/Assistant-Attop/blob/master/Release/%E6%96%87%E5%AD%97%E7%89%88%E9%A2%98%E5%BA%93/31.%E4%B8%AD%E5%9B%BD%E5%85%B1%E4%BA%A7%E5%85%9A%E7%AB%A0%E7%A8%8B.txt - -colab CPU test.text constitution.pdf -CPU times: user 1min 27s, sys: 8.09 s, total: 1min 35s -Wall time: 1min 37s - -""" -# pylint: disable=broad-exception-caught, unused-import, invalid-name, line-too-long, too-many-return-statements, import-outside-toplevel, no-name-in-module, no-member -import os -import time -from pathlib import Path -from textwrap import dedent -from types import SimpleNamespace - -import gradio as gr -import torch -from charset_normalizer import detect -from chromadb.config import Settings -from epub2txt import epub2txt -from langchain.chains import RetrievalQA -from langchain.docstore.document import Document -from langchain.document_loaders import ( - CSVLoader, - Docx2txtLoader, - PDFMinerLoader, - TextLoader, -) - -# from constants import CHROMA_SETTINGS, SOURCE_DIRECTORY, PERSIST_DIRECTORY -from langchain.embeddings import HuggingFaceInstructEmbeddings -from langchain.llms import HuggingFacePipeline -from langchain.text_splitter import ( - # CharacterTextSplitter, - RecursiveCharacterTextSplitter, -) - -# FAISS instead of PineCone -from langchain.vectorstores import Chroma # FAISS, -from loguru import logger -# from PyPDF2 import PdfReader # localgpt -from transformers import LlamaForCausalLM, LlamaTokenizer, pipeline - -# import click -# from typing import List - -# from utils import xlxs_to_csv - -# load possible env such as OPENAI_API_KEY -# from dotenv import load_dotenv - -# load_dotenv()load_dotenv() - -# fix timezone -os.environ["TZ"] = "Asia/Shanghai" -try: - time.tzset() # type: ignore # pylint: disable=no-member -except Exception: - # Windows - logger.warning("Windows, cant run time.tzset()") - -ROOT_DIRECTORY = Path(__file__).parent -PERSIST_DIRECTORY = f"{ROOT_DIRECTORY}/db" - -# Define the Chroma settings -CHROMA_SETTINGS = Settings( - chroma_db_impl="duckdb+parquet", - persist_directory=PERSIST_DIRECTORY, - anonymized_telemetry=False, -) -ns = SimpleNamespace(qa=None, ingest_done=None, files_info=None) - - -def load_single_document(file_path: str | Path) -> Document: - """ingest.py""" - # Loads a single document from a file path - # encoding = detect(open(file_path, "rb").read()).get("encoding", "utf-8") - encoding = detect(Path(file_path).read_bytes()).get("encoding", "utf-8") - if file_path.endswith(".txt"): - if encoding is None: - logger.warning( - f" {file_path}'s encoding is None " - "Something is fishy, return empty str " - ) - return Document(page_content="", metadata={"source": file_path}) - - try: - loader = TextLoader(file_path, encoding=encoding) - except Exception as exc: - logger.warning(f" {exc}, return dummy ") - return Document(page_content="", metadata={"source": file_path}) - - elif file_path.endswith(".pdf"): - loader = PDFMinerLoader(file_path) - elif file_path.endswith(".csv"): - loader = CSVLoader(file_path) - elif Path(file_path).suffix in [".docx"]: - try: - loader = Docx2txtLoader(file_path) - except Exception as exc: - logger.error(f" {file_path} errors: {exc}") - return Document(page_content="", metadata={"source": file_path}) - elif Path(file_path).suffix in [".epub"]: # for epub? epub2txt unstructured - try: - _ = epub2txt(file_path) - except Exception as exc: - logger.error(f" {file_path} errors: {exc}") - return Document(page_content="", metadata={"source": file_path}) - return Document(page_content=_, metadata={"source": file_path}) - else: - if encoding is None: - logger.warning( - f" {file_path}'s encoding is None " - "Likely binary files, return empty str " - ) - return Document(page_content="", metadata={"source": file_path}) - try: - loader = TextLoader(file_path) - except Exception as exc: - logger.error(f" {exc}, returnning empty string") - return Document(page_content="", metadata={"source": file_path}) - - return loader.load()[0] - - -def get_pdf_text(pdf_docs): - """docs-chat.""" - text = "" - for pdf in pdf_docs: - pdf_reader = PdfReader(f"{pdf}") # taking care of Path - for page in pdf_reader.pages: - text += page.extract_text() - return text - - -def get_text_chunks(text): - """docs-chat.""" - text_splitter = CharacterTextSplitter( - separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len - ) - chunks = text_splitter.split_text(text) - return chunks - - -def get_vectorstore(text_chunks): - """docs-chat.""" - # embeddings = OpenAIEmbeddings() - model_name = "hkunlp/instructor-xl" - model_name = "hkunlp/instructor-large" - model_name = "hkunlp/instructor-base" - logger.info(f"Loading {model_name}") - embeddings = HuggingFaceInstructEmbeddings(model_name=model_name) - logger.info(f"Done loading {model_name}") - - logger.info( - "Doing vectorstore FAISS.from_texts(texts=text_chunks, embedding=embeddings)" - ) - vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings) - logger.info( - "Done vectorstore FAISS.from_texts(texts=text_chunks, embedding=embeddings)" - ) - - return vectorstore - - -def greet(name): - """Test.""" - logger.debug(f" name: [{name}] ") - return "Hello " + name + "!!" - - -def upload_files(files): - """Upload files.""" - file_paths = [file.name for file in files] - logger.info(file_paths) - - ns.ingest_done = False - res = ingest(file_paths) - logger.info(f"Processed:\n{res}") - - # flag ns.qadone - ns.ingest_done = True - ns.files_info = res - - # ns.qa = load_qa() - - # return [str(elm) for elm in res] - return file_paths - - # return ingest(file_paths) - - -def ingest( - file_paths: list[str | Path], model_name="hkunlp/instructor-base", device_type=None -): - """Gen Chroma db. - - torch.cuda.is_available() - - file_paths = - ['C:\\Users\\User\\AppData\\Local\\Temp\\gradio\\41b53dd5f203b423f2dced44eaf56e72508b7bbe\\app.py', - 'C:\\Users\\User\\AppData\\Local\\Temp\\gradio\\9390755bb391abc530e71a3946a7b50d463ba0ef\\README.md', - 'C:\\Users\\User\\AppData\\Local\\Temp\\gradio\\3341f9a410a60ffa57bf4342f3018a3de689f729\\requirements.txt'] - """ - logger.info("\n\t Doing ingest...") - - if device_type is None: - if torch.cuda.is_available(): - device_type = "cuda" - else: - device_type = "cpu" - - if device_type in ["cpu", "CPU"]: - device = "cpu" - elif device_type in ["mps", "MPS"]: - device = "mps" - else: - device = "cuda" - - #  Load documents and split in chunks - # logger.info(f"Loading documents from {SOURCE_DIRECTORY}") - # documents = load_documents(SOURCE_DIRECTORY) - - documents = [] - for file_path in file_paths: - documents.append(load_single_document(f"{file_path}")) - - text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) - texts = text_splitter.split_documents(documents) - - logger.info(f"Loaded {len(documents)} documents ") - logger.info(f"Split into {len(texts)} chunks of text") - - # Create embeddings - embeddings = HuggingFaceInstructEmbeddings( - model_name=model_name, model_kwargs={"device": device} - ) - - db = Chroma.from_documents( - texts, - embeddings, - persist_directory=PERSIST_DIRECTORY, - client_settings=CHROMA_SETTINGS, - ) - db.persist() - db = None - logger.info("Done ingest") - - return [ - [Path(doc.metadata.get("source")).name, len(doc.page_content)] - for doc in documents - ] - - -# TheBloke/Wizard-Vicuna-7B-Uncensored-HF -# https://huggingface.co/TheBloke/vicuna-7B-1.1-HF -def gen_local_llm(model_id="TheBloke/vicuna-7B-1.1-HF"): - """Gen a local llm. - - localgpt run_localgpt - https://medium.com/pytorch/bettertransformer-out-of-the-box-performance-for-huggingface-transformers-3fbe27d50ab2 - with torch.device(“cuda”): - model = AutoModelForCausalLM.from_pretrained(“gpt2-large”, torch_dtype=torch.float16) - - model = BetterTransformer.transform(model) - """ - tokenizer = LlamaTokenizer.from_pretrained(model_id) - if torch.cuda.is_available(): - model = LlamaForCausalLM.from_pretrained( - model_id, - # load_in_8bit=True, # set these options if your GPU supports them! - # device_map=1 # "auto", - torch_dtype=torch.float16, - low_cpu_mem_usage=True, - ) - else: - model = LlamaForCausalLM.from_pretrained(model_id) - - pipe = pipeline( - "text-generation", - model=model, - tokenizer=tokenizer, - max_length=2048, - temperature=0, - top_p=0.95, - repetition_penalty=1.15, - ) - - local_llm = HuggingFacePipeline(pipeline=pipe) - return local_llm - - -def load_qa(device=None, model_name: str = "hkunlp/instructor-base"): - """Gen qa.""" - logger.info("Doing qa") - if device is None: - if torch.cuda.is_available(): - device = "cuda" - else: - device = "cpu" - - # device = 'cpu' - # model_name = "hkunlp/instructor-xl" - # model_name = "hkunlp/instructor-large" - # model_name = "hkunlp/instructor-base" - embeddings = HuggingFaceInstructEmbeddings( - model_name=model_name, model_kwargs={"device": device} - ) - # xl 4.96G, large 3.5G, - db = Chroma( - persist_directory=PERSIST_DIRECTORY, - embedding_function=embeddings, - client_settings=CHROMA_SETTINGS, - ) - retriever = db.as_retriever() - - llm = gen_local_llm() # "TheBloke/vicuna-7B-1.1-HF" 12G? - - qa = RetrievalQA.from_chain_type( - llm=llm, - chain_type="stuff", - retriever=retriever, - return_source_documents=True, - ) - - logger.info("Done qa") - - return qa - - -def main1(): - """Lump codes""" - with gr.Blocks() as demo: - iface = gr.Interface(fn=greet, inputs="text", outputs="text") - iface.launch() - - demo.launch() - - -def main(): - """Do blocks.""" - logger.info(f"ROOT_DIRECTORY: {ROOT_DIRECTORY}") - - openai_api_key = os.getenv("OPENAI_API_KEY") - logger.info(f"openai_api_key (env var/hf space SECRETS): {openai_api_key}") - - with gr.Blocks(theme=gr.themes.Soft()) as demo: - # name = gr.Textbox(label="Name") - # greet_btn = gr.Button("Submit") - # output = gr.Textbox(label="Output Box") - # greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet") - with gr.Accordion("Info", open=False): - _ = """ - # localgpt - Talk to your docs (.pdf, .docx, .epub, .txt .md and - other text docs). It - takes quite a while to ingest docs (10-30 min. depending - on net, RAM, CPU etc.). - - Send empty query (hit Enter) to check embedding status and files info ([filename, numb of chars]) - - Homepage: https://huggingface.co/spaces/mikeee/localgpt - """ - gr.Markdown(dedent(_)) - - # with gr.Accordion("Upload files", open=True): - with gr.Tab("Upload files"): - # Upload files and generate embeddings database - file_output = gr.File() - upload_button = gr.UploadButton( - "Click to upload files", - # file_types=["*.pdf", "*.epub", "*.docx"], - file_count="multiple", - ) - upload_button.upload(upload_files, upload_button, file_output) - - with gr.Tab("Query docs"): - # interactive chat - chatbot = gr.Chatbot() - msg = gr.Textbox(label="Query") - clear = gr.Button("Clear") - - def respond(message, chat_history): - # bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"]) - if ns.ingest_done is None: # no files processed yet - bot_message = "Upload some file(s) for processing first." - chat_history.append((message, bot_message)) - return "", chat_history - - if not ns.ingest_done: # embedding database not doen yet - bot_message = ( - "Waiting for ingest (embedding) to finish, " - "be patient... You can switch the 'Upload files' " - "Tab to check" - ) - chat_history.append((message, bot_message)) - return "", chat_history - - if ns.qa is None: # load qa one time - logger.info("Loading qa, need to do just one time.") - ns.qa = load_qa() - - try: - res = ns.qa(message) - answer, docs = res["result"], res["source_documents"] - bot_message = f"{answer} ({docs})" - except Exception as exc: - logger.error(exc) - bot_message = f"bummer! {exc}" - - chat_history.append((message, bot_message)) - - return "", chat_history - - msg.submit(respond, [msg, chatbot], [msg, chatbot]) - clear.click(lambda: None, None, chatbot, queue=False) - - try: - from google import colab # noqa - - share = True # start share when in colab - except Exception: - share = False - demo.launch(share=share) - - -if __name__ == "__main__": - main() - -_ = """ -run_localgpt -device = 'cpu' -model_name = "hkunlp/instructor-xl" -model_name = "hkunlp/instructor-large" -model_name = "hkunlp/instructor-base" -embeddings = HuggingFaceInstructEmbeddings( - model_name=, - model_kwargs={"device": device} -) -# xl 4.96G, large 3.5G, -db = Chroma(persist_directory=PERSIST_DIRECTORY, embedding_function=embeddings, client_settings=CHROMA_SETTINGS) -retriever = db.as_retriever() - -llm = gen_local_llm() # "TheBloke/vicuna-7B-1.1-HF" 12G? - -qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True) - -query = 'a' -res = qa(query) - ---- -https://www.linkedin.com/pulse/build-qa-bot-over-private-data-openai-langchain-leo-wang - -history = [】 - -def user(user_message, history): - # Get response from QA chain - response = qa({"question": user_message, "chat_history": history}) - # Append user message and response to chat history - history.append((user_message, response["answer"]))] - ---- -https://llamahub.ai/l/file-unstructured - -from pathlib import Path -from llama_index import download_loader - -UnstructuredReader = download_loader("UnstructuredReader") - -loader = UnstructuredReader() -documents = loader.load_data(file=Path('./10k_filing.html')) - -# -- -from pathlib import Path -from llama_index import download_loader - -# SimpleDirectoryReader = download_loader("SimpleDirectoryReader") -# FileNotFoundError: [Errno 2] No such file or directory - -documents = SimpleDirectoryReader('./data').load_data() - -loader = SimpleDirectoryReader('./data', file_extractor={ - ".pdf": "UnstructuredReader", - ".html": "UnstructuredReader", - ".eml": "UnstructuredReader", - ".pptx": "PptxReader" -}) -documents = loader.load_data() -""" diff --git a/spaces/mnauf/detect-bees/utils/callbacks.py b/spaces/mnauf/detect-bees/utils/callbacks.py deleted file mode 100644 index 166d8938322d4b35783be4068ae9561f66c94749..0000000000000000000000000000000000000000 --- a/spaces/mnauf/detect-bees/utils/callbacks.py +++ /dev/null @@ -1,76 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Callback utils -""" - -import threading - - -class Callbacks: - """" - Handles all registered callbacks for YOLOv5 Hooks - """ - - def __init__(self): - # Define the available callbacks - self._callbacks = { - 'on_pretrain_routine_start': [], - 'on_pretrain_routine_end': [], - 'on_train_start': [], - 'on_train_epoch_start': [], - 'on_train_batch_start': [], - 'optimizer_step': [], - 'on_before_zero_grad': [], - 'on_train_batch_end': [], - 'on_train_epoch_end': [], - 'on_val_start': [], - 'on_val_batch_start': [], - 'on_val_image_end': [], - 'on_val_batch_end': [], - 'on_val_end': [], - 'on_fit_epoch_end': [], # fit = train + val - 'on_model_save': [], - 'on_train_end': [], - 'on_params_update': [], - 'teardown': [],} - self.stop_training = False # set True to interrupt training - - def register_action(self, hook, name='', callback=None): - """ - Register a new action to a callback hook - - Args: - hook: The callback hook name to register the action to - name: The name of the action for later reference - callback: The callback to fire - """ - assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" - assert callable(callback), f"callback '{callback}' is not callable" - self._callbacks[hook].append({'name': name, 'callback': callback}) - - def get_registered_actions(self, hook=None): - """" - Returns all the registered actions by callback hook - - Args: - hook: The name of the hook to check, defaults to all - """ - return self._callbacks[hook] if hook else self._callbacks - - def run(self, hook, *args, thread=False, **kwargs): - """ - Loop through the registered actions and fire all callbacks on main thread - - Args: - hook: The name of the hook to check, defaults to all - args: Arguments to receive from YOLOv5 - thread: (boolean) Run callbacks in daemon thread - kwargs: Keyword Arguments to receive from YOLOv5 - """ - - assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" - for logger in self._callbacks[hook]: - if thread: - threading.Thread(target=logger['callback'], args=args, kwargs=kwargs, daemon=True).start() - else: - logger['callback'](*args, **kwargs) diff --git a/spaces/mshukor/UnIVAL/fairseq/examples/laser/laser_src/laser_lstm.py b/spaces/mshukor/UnIVAL/fairseq/examples/laser/laser_src/laser_lstm.py deleted file mode 100644 index 10df90e002d5a7dd74a571dbc3b328c130c57a0a..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/examples/laser/laser_src/laser_lstm.py +++ /dev/null @@ -1,585 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from fairseq import options, utils - -from fairseq.models import ( - FairseqEncoder, - FairseqIncrementalDecoder, - FairseqEncoderDecoderModel, - register_model, - register_model_architecture, -) - - -@register_model("laser_lstm") -class LSTMModel(FairseqEncoderDecoderModel): - def __init__(self, encoder, decoder): - super().__init__(encoder, decoder) - - def forward( - self, - src_tokens, - src_lengths, - prev_output_tokens=None, - tgt_tokens=None, - tgt_lengths=None, - target_language_id=None, - dataset_name="", - ): - assert target_language_id is not None - - src_encoder_out = self.encoder(src_tokens, src_lengths, dataset_name) - return self.decoder( - prev_output_tokens, src_encoder_out, lang_id=target_language_id - ) - - @staticmethod - def add_args(parser): - """Add model-specific arguments to the parser.""" - parser.add_argument( - "--dropout", - default=0.1, - type=float, - metavar="D", - help="dropout probability", - ) - parser.add_argument( - "--encoder-embed-dim", - type=int, - metavar="N", - help="encoder embedding dimension", - ) - parser.add_argument( - "--encoder-embed-path", - default=None, - type=str, - metavar="STR", - help="path to pre-trained encoder embedding", - ) - parser.add_argument( - "--encoder-hidden-size", type=int, metavar="N", help="encoder hidden size" - ) - parser.add_argument( - "--encoder-layers", type=int, metavar="N", help="number of encoder layers" - ) - parser.add_argument( - "--encoder-bidirectional", - action="store_true", - help="make all layers of encoder bidirectional", - ) - parser.add_argument( - "--decoder-embed-dim", - type=int, - metavar="N", - help="decoder embedding dimension", - ) - parser.add_argument( - "--decoder-embed-path", - default=None, - type=str, - metavar="STR", - help="path to pre-trained decoder embedding", - ) - parser.add_argument( - "--decoder-hidden-size", type=int, metavar="N", help="decoder hidden size" - ) - parser.add_argument( - "--decoder-layers", type=int, metavar="N", help="number of decoder layers" - ) - parser.add_argument( - "--decoder-out-embed-dim", - type=int, - metavar="N", - help="decoder output embedding dimension", - ) - parser.add_argument( - "--decoder-zero-init", - type=str, - metavar="BOOL", - help="initialize the decoder hidden/cell state to zero", - ) - parser.add_argument( - "--decoder-lang-embed-dim", - type=int, - metavar="N", - help="decoder language embedding dimension", - ) - parser.add_argument( - "--fixed-embeddings", - action="store_true", - help="keep embeddings fixed (ENCODER ONLY)", - ) # TODO Also apply to decoder embeddings? - - # Granular dropout settings (if not specified these default to --dropout) - parser.add_argument( - "--encoder-dropout-in", - type=float, - metavar="D", - help="dropout probability for encoder input embedding", - ) - parser.add_argument( - "--encoder-dropout-out", - type=float, - metavar="D", - help="dropout probability for encoder output", - ) - parser.add_argument( - "--decoder-dropout-in", - type=float, - metavar="D", - help="dropout probability for decoder input embedding", - ) - parser.add_argument( - "--decoder-dropout-out", - type=float, - metavar="D", - help="dropout probability for decoder output", - ) - - @classmethod - def build_model(cls, args, task): - """Build a new model instance.""" - # make sure that all args are properly defaulted (in case there are any new ones) - base_architecture(args) - - def load_pretrained_embedding_from_file(embed_path, dictionary, embed_dim): - num_embeddings = len(dictionary) - padding_idx = dictionary.pad() - embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) - embed_dict = utils.parse_embedding(embed_path) - utils.print_embed_overlap(embed_dict, dictionary) - return utils.load_embedding(embed_dict, dictionary, embed_tokens) - - pretrained_encoder_embed = None - if args.encoder_embed_path: - pretrained_encoder_embed = load_pretrained_embedding_from_file( - args.encoder_embed_path, task.source_dictionary, args.encoder_embed_dim - ) - pretrained_decoder_embed = None - if args.decoder_embed_path: - pretrained_decoder_embed = load_pretrained_embedding_from_file( - args.decoder_embed_path, task.target_dictionary, args.decoder_embed_dim - ) - - num_langs = task.num_tasks if hasattr(task, "num_tasks") else 0 - - encoder = LSTMEncoder( - dictionary=task.source_dictionary, - embed_dim=args.encoder_embed_dim, - hidden_size=args.encoder_hidden_size, - num_layers=args.encoder_layers, - dropout_in=args.encoder_dropout_in, - dropout_out=args.encoder_dropout_out, - bidirectional=args.encoder_bidirectional, - pretrained_embed=pretrained_encoder_embed, - fixed_embeddings=args.fixed_embeddings, - ) - decoder = LSTMDecoder( - dictionary=task.target_dictionary, - embed_dim=args.decoder_embed_dim, - hidden_size=args.decoder_hidden_size, - out_embed_dim=args.decoder_out_embed_dim, - num_layers=args.decoder_layers, - dropout_in=args.decoder_dropout_in, - dropout_out=args.decoder_dropout_out, - zero_init=options.eval_bool(args.decoder_zero_init), - encoder_embed_dim=args.encoder_embed_dim, - encoder_output_units=encoder.output_units, - pretrained_embed=pretrained_decoder_embed, - num_langs=num_langs, - lang_embed_dim=args.decoder_lang_embed_dim, - ) - return cls(encoder, decoder) - - -class LSTMEncoder(FairseqEncoder): - """LSTM encoder.""" - - def __init__( - self, - dictionary, - embed_dim=512, - hidden_size=512, - num_layers=1, - dropout_in=0.1, - dropout_out=0.1, - bidirectional=False, - left_pad=True, - pretrained_embed=None, - padding_value=0.0, - fixed_embeddings=False, - ): - super().__init__(dictionary) - self.num_layers = num_layers - self.dropout_in = dropout_in - self.dropout_out = dropout_out - self.bidirectional = bidirectional - self.hidden_size = hidden_size - - num_embeddings = len(dictionary) - self.padding_idx = dictionary.pad() - if pretrained_embed is None: - self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) - else: - self.embed_tokens = pretrained_embed - if fixed_embeddings: - self.embed_tokens.weight.requires_grad = False - - self.lstm = LSTM( - input_size=embed_dim, - hidden_size=hidden_size, - num_layers=num_layers, - dropout=self.dropout_out if num_layers > 1 else 0.0, - bidirectional=bidirectional, - ) - self.left_pad = left_pad - self.padding_value = padding_value - - self.output_units = hidden_size - if bidirectional: - self.output_units *= 2 - - def forward(self, src_tokens, src_lengths, dataset_name): - if self.left_pad: - # convert left-padding to right-padding - src_tokens = utils.convert_padding_direction( - src_tokens, - self.padding_idx, - left_to_right=True, - ) - - bsz, seqlen = src_tokens.size() - - # embed tokens - x = self.embed_tokens(src_tokens) - x = F.dropout(x, p=self.dropout_in, training=self.training) - - # B x T x C -> T x B x C - x = x.transpose(0, 1) - - # pack embedded source tokens into a PackedSequence - try: - packed_x = nn.utils.rnn.pack_padded_sequence(x, src_lengths.data.tolist()) - except BaseException: - raise Exception(f"Packing failed in dataset {dataset_name}") - - # apply LSTM - if self.bidirectional: - state_size = 2 * self.num_layers, bsz, self.hidden_size - else: - state_size = self.num_layers, bsz, self.hidden_size - h0 = x.data.new(*state_size).zero_() - c0 = x.data.new(*state_size).zero_() - packed_outs, (final_hiddens, final_cells) = self.lstm(packed_x, (h0, c0)) - - # unpack outputs and apply dropout - x, _ = nn.utils.rnn.pad_packed_sequence( - packed_outs, padding_value=self.padding_value - ) - x = F.dropout(x, p=self.dropout_out, training=self.training) - assert list(x.size()) == [seqlen, bsz, self.output_units] - - if self.bidirectional: - - def combine_bidir(outs): - return torch.cat( - [ - torch.cat([outs[2 * i], outs[2 * i + 1]], dim=0).view( - 1, bsz, self.output_units - ) - for i in range(self.num_layers) - ], - dim=0, - ) - - final_hiddens = combine_bidir(final_hiddens) - final_cells = combine_bidir(final_cells) - - encoder_padding_mask = src_tokens.eq(self.padding_idx).t() - - # Set padded outputs to -inf so they are not selected by max-pooling - padding_mask = src_tokens.eq(self.padding_idx).t().unsqueeze(-1) - if padding_mask.any(): - x = x.float().masked_fill_(padding_mask, float("-inf")).type_as(x) - - # Build the sentence embedding by max-pooling over the encoder outputs - sentemb = x.max(dim=0)[0] - - return { - "sentemb": sentemb, - "encoder_out": (x, final_hiddens, final_cells), - "encoder_padding_mask": encoder_padding_mask - if encoder_padding_mask.any() - else None, - } - - def reorder_encoder_out(self, encoder_out_dict, new_order): - encoder_out_dict["sentemb"] = encoder_out_dict["sentemb"].index_select( - 0, new_order - ) - encoder_out_dict["encoder_out"] = tuple( - eo.index_select(1, new_order) for eo in encoder_out_dict["encoder_out"] - ) - if encoder_out_dict["encoder_padding_mask"] is not None: - encoder_out_dict["encoder_padding_mask"] = encoder_out_dict[ - "encoder_padding_mask" - ].index_select(1, new_order) - return encoder_out_dict - - def max_positions(self): - """Maximum input length supported by the encoder.""" - return int(1e5) # an arbitrary large number - - -class LSTMDecoder(FairseqIncrementalDecoder): - """LSTM decoder.""" - - def __init__( - self, - dictionary, - embed_dim=512, - hidden_size=512, - out_embed_dim=512, - num_layers=1, - dropout_in=0.1, - dropout_out=0.1, - zero_init=False, - encoder_embed_dim=512, - encoder_output_units=512, - pretrained_embed=None, - num_langs=1, - lang_embed_dim=0, - ): - super().__init__(dictionary) - self.dropout_in = dropout_in - self.dropout_out = dropout_out - self.hidden_size = hidden_size - - num_embeddings = len(dictionary) - padding_idx = dictionary.pad() - if pretrained_embed is None: - self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) - else: - self.embed_tokens = pretrained_embed - - self.layers = nn.ModuleList( - [ - LSTMCell( - input_size=encoder_output_units + embed_dim + lang_embed_dim - if layer == 0 - else hidden_size, - hidden_size=hidden_size, - ) - for layer in range(num_layers) - ] - ) - if hidden_size != out_embed_dim: - self.additional_fc = Linear(hidden_size, out_embed_dim) - self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out) - - if zero_init: - self.sentemb2init = None - else: - self.sentemb2init = Linear( - encoder_output_units, 2 * num_layers * hidden_size - ) - - if lang_embed_dim == 0: - self.embed_lang = None - else: - self.embed_lang = nn.Embedding(num_langs, lang_embed_dim) - nn.init.uniform_(self.embed_lang.weight, -0.1, 0.1) - - def forward( - self, prev_output_tokens, encoder_out_dict, incremental_state=None, lang_id=0 - ): - sentemb = encoder_out_dict["sentemb"] - encoder_out = encoder_out_dict["encoder_out"] - - if incremental_state is not None: - prev_output_tokens = prev_output_tokens[:, -1:] - bsz, seqlen = prev_output_tokens.size() - - # get outputs from encoder - encoder_outs, _, _ = encoder_out[:3] - srclen = encoder_outs.size(0) - - # embed tokens - x = self.embed_tokens(prev_output_tokens) - x = F.dropout(x, p=self.dropout_in, training=self.training) - - # embed language identifier - if self.embed_lang is not None: - lang_ids = prev_output_tokens.data.new_full((bsz,), lang_id) - langemb = self.embed_lang(lang_ids) - # TODO Should we dropout here??? - - # B x T x C -> T x B x C - x = x.transpose(0, 1) - - # initialize previous states (or get from cache during incremental generation) - cached_state = utils.get_incremental_state( - self, incremental_state, "cached_state" - ) - if cached_state is not None: - prev_hiddens, prev_cells, input_feed = cached_state - else: - num_layers = len(self.layers) - if self.sentemb2init is None: - prev_hiddens = [ - x.data.new(bsz, self.hidden_size).zero_() for i in range(num_layers) - ] - prev_cells = [ - x.data.new(bsz, self.hidden_size).zero_() for i in range(num_layers) - ] - else: - init = self.sentemb2init(sentemb) - prev_hiddens = [ - init[:, (2 * i) * self.hidden_size : (2 * i + 1) * self.hidden_size] - for i in range(num_layers) - ] - prev_cells = [ - init[ - :, - (2 * i + 1) * self.hidden_size : (2 * i + 2) * self.hidden_size, - ] - for i in range(num_layers) - ] - input_feed = x.data.new(bsz, self.hidden_size).zero_() - - attn_scores = x.data.new(srclen, seqlen, bsz).zero_() - outs = [] - for j in range(seqlen): - if self.embed_lang is None: - input = torch.cat((x[j, :, :], sentemb), dim=1) - else: - input = torch.cat((x[j, :, :], sentemb, langemb), dim=1) - - for i, rnn in enumerate(self.layers): - # recurrent cell - hidden, cell = rnn(input, (prev_hiddens[i], prev_cells[i])) - - # hidden state becomes the input to the next layer - input = F.dropout(hidden, p=self.dropout_out, training=self.training) - - # save state for next time step - prev_hiddens[i] = hidden - prev_cells[i] = cell - - out = hidden - out = F.dropout(out, p=self.dropout_out, training=self.training) - - # input feeding - input_feed = out - - # save final output - outs.append(out) - - # cache previous states (no-op except during incremental generation) - utils.set_incremental_state( - self, - incremental_state, - "cached_state", - (prev_hiddens, prev_cells, input_feed), - ) - - # collect outputs across time steps - x = torch.cat(outs, dim=0).view(seqlen, bsz, self.hidden_size) - - # T x B x C -> B x T x C - x = x.transpose(1, 0) - - # srclen x tgtlen x bsz -> bsz x tgtlen x srclen - attn_scores = attn_scores.transpose(0, 2) - - # project back to size of vocabulary - if hasattr(self, "additional_fc"): - x = self.additional_fc(x) - x = F.dropout(x, p=self.dropout_out, training=self.training) - x = self.fc_out(x) - - return x, attn_scores - - def reorder_incremental_state(self, incremental_state, new_order): - super().reorder_incremental_state(incremental_state, new_order) - cached_state = utils.get_incremental_state( - self, incremental_state, "cached_state" - ) - if cached_state is None: - return - - def reorder_state(state): - if isinstance(state, list): - return [reorder_state(state_i) for state_i in state] - return state.index_select(0, new_order) - - new_state = tuple(map(reorder_state, cached_state)) - utils.set_incremental_state(self, incremental_state, "cached_state", new_state) - - def max_positions(self): - """Maximum output length supported by the decoder.""" - return int(1e5) # an arbitrary large number - - -def Embedding(num_embeddings, embedding_dim, padding_idx): - m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) - nn.init.uniform_(m.weight, -0.1, 0.1) - nn.init.constant_(m.weight[padding_idx], 0) - return m - - -def LSTM(input_size, hidden_size, **kwargs): - m = nn.LSTM(input_size, hidden_size, **kwargs) - for name, param in m.named_parameters(): - if "weight" in name or "bias" in name: - param.data.uniform_(-0.1, 0.1) - return m - - -def LSTMCell(input_size, hidden_size, **kwargs): - m = nn.LSTMCell(input_size, hidden_size, **kwargs) - for name, param in m.named_parameters(): - if "weight" in name or "bias" in name: - param.data.uniform_(-0.1, 0.1) - return m - - -def Linear(in_features, out_features, bias=True, dropout=0): - """Weight-normalized Linear layer (input: N x T x C)""" - m = nn.Linear(in_features, out_features, bias=bias) - m.weight.data.uniform_(-0.1, 0.1) - if bias: - m.bias.data.uniform_(-0.1, 0.1) - return m - - -@register_model_architecture("laser_lstm", "laser_lstm") -def base_architecture(args): - args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 512) - args.encoder_embed_path = getattr(args, "encoder_embed_path", None) - args.encoder_hidden_size = getattr( - args, "encoder_hidden_size", args.encoder_embed_dim - ) - args.encoder_layers = getattr(args, "encoder_layers", 1) - args.encoder_bidirectional = getattr(args, "encoder_bidirectional", False) - args.encoder_dropout_in = getattr(args, "encoder_dropout_in", args.dropout) - args.encoder_dropout_out = getattr(args, "encoder_dropout_out", args.dropout) - args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 512) - args.decoder_embed_path = getattr(args, "decoder_embed_path", None) - args.decoder_hidden_size = getattr( - args, "decoder_hidden_size", args.decoder_embed_dim - ) - args.decoder_layers = getattr(args, "decoder_layers", 1) - args.decoder_out_embed_dim = getattr(args, "decoder_out_embed_dim", 512) - args.decoder_dropout_in = getattr(args, "decoder_dropout_in", args.dropout) - args.decoder_dropout_out = getattr(args, "decoder_dropout_out", args.dropout) - args.decoder_zero_init = getattr(args, "decoder_zero_init", "0") - args.decoder_lang_embed_dim = getattr(args, "decoder_lang_embed_dim", 0) - args.fixed_embeddings = getattr(args, "fixed_embeddings", False) diff --git a/spaces/mshukor/UnIVAL/slurm_adastra/averaging/eval/._eval_refcocoplus.sh b/spaces/mshukor/UnIVAL/slurm_adastra/averaging/eval/._eval_refcocoplus.sh deleted file mode 100644 index c6c4cd6c1d7fe693ba6eb94ecd91340db03095e4..0000000000000000000000000000000000000000 Binary files a/spaces/mshukor/UnIVAL/slurm_adastra/averaging/eval/._eval_refcocoplus.sh and /dev/null differ diff --git a/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/mask_example.py b/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/mask_example.py deleted file mode 100644 index 59e25ca8eb3ed4141851c3af284fc66285444de0..0000000000000000000000000000000000000000 --- a/spaces/myrad01/Inpaint-Anything/third_party/lama/bin/mask_example.py +++ /dev/null @@ -1,14 +0,0 @@ -import matplotlib.pyplot as plt -from skimage import io -from skimage.transform import resize - -from saicinpainting.evaluation.masks.mask import SegmentationMask - -im = io.imread('imgs/ex4.jpg') -im = resize(im, (512, 1024), anti_aliasing=True) -mask_seg = SegmentationMask(num_variants_per_mask=10) -mask_examples = mask_seg.get_masks(im) -for i, example in enumerate(mask_examples): - plt.imshow(example) - plt.show() - plt.imsave(f'tmp/img_masks/{i}.png', example) diff --git a/spaces/nasa-cisto-data-science-group/satvision-base-demo/pytorch-caney/pytorch_caney/__init__.py b/spaces/nasa-cisto-data-science-group/satvision-base-demo/pytorch-caney/pytorch_caney/__init__.py deleted file mode 100644 index 3dc1f76bc69e3f559bee6253b24fc93acee9e1f9..0000000000000000000000000000000000000000 --- a/spaces/nasa-cisto-data-science-group/satvision-base-demo/pytorch-caney/pytorch_caney/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.1.0" diff --git a/spaces/nateraw/deepafx-st/deepafx_st/models/baselines.py b/spaces/nateraw/deepafx-st/deepafx_st/models/baselines.py deleted file mode 100644 index 806caca587e7bedc71251da58f5acfdba9492ad3..0000000000000000000000000000000000000000 --- a/spaces/nateraw/deepafx-st/deepafx_st/models/baselines.py +++ /dev/null @@ -1,280 +0,0 @@ -import torch -import torchaudio -import scipy.signal -import numpy as np -import pyloudnorm as pyln -import matplotlib.pyplot as plt -from deepafx_st.processors.dsp.compressor import compressor - -from tqdm import tqdm - - -class BaselineEQ(torch.nn.Module): - def __init__( - self, - ntaps: int = 63, - n_fft: int = 65536, - sample_rate: float = 44100, - ): - super().__init__() - self.ntaps = ntaps - self.n_fft = n_fft - self.sample_rate = sample_rate - - # compute the target spectrum - # print("Computing target spectrum...") - # self.target_spec, self.sm_target_spec = self.analyze_speech_dataset(filepaths) - # self.plot_spectrum(self.target_spec, filename="targetEQ") - # self.plot_spectrum(self.sm_target_spec, filename="targetEQsm") - - def forward(self, x, y): - - bs, ch, s = x.size() - - x = x.view(bs * ch, -1) - y = y.view(bs * ch, -1) - - in_spec = self.get_average_spectrum(x) - ref_spec = self.get_average_spectrum(y) - - sm_in_spec = self.smooth_spectrum(in_spec) - sm_ref_spec = self.smooth_spectrum(ref_spec) - - # self.plot_spectrum(in_spec, filename="inSpec") - # self.plot_spectrum(sm_in_spec, filename="inSpecsm") - - # design inverse FIR filter to match target EQ - freqs = np.linspace(0, 1.0, num=(self.n_fft // 2) + 1) - response = sm_ref_spec / sm_in_spec - response[-1] = 0.0 # zero gain at nyquist - - b = scipy.signal.firwin2( - self.ntaps, - freqs * (self.sample_rate / 2), - response, - fs=self.sample_rate, - ) - - # scale the coefficients for less intense filter - # clearb *= 0.5 - - # apply the filter - x_filt = scipy.signal.lfilter(b, [1.0], x.numpy()) - x_filt = torch.tensor(x_filt.astype("float32")) - - if False: - # plot the filter response - w, h = scipy.signal.freqz(b, fs=self.sample_rate, worN=response.shape[-1]) - - fig, ax1 = plt.subplots() - ax1.set_title("Digital filter frequency response") - ax1.plot(w, 20 * np.log10(abs(h + 1e-8))) - ax1.plot(w, 20 * np.log10(abs(response + 1e-8))) - - ax1.set_xscale("log") - ax1.set_ylim([-12, 12]) - plt.grid(c="lightgray") - plt.savefig(f"inverse.png") - - x_filt_avg_spec = self.get_average_spectrum(x_filt) - sm_x_filt_avg_spec = self.smooth_spectrum(x_filt_avg_spec) - y_avg_spec = self.get_average_spectrum(y) - sm_y_avg_spec = self.smooth_spectrum(y_avg_spec) - compare = torch.stack( - [ - torch.tensor(sm_in_spec), - torch.tensor(sm_x_filt_avg_spec), - torch.tensor(sm_ref_spec), - torch.tensor(sm_y_avg_spec), - ] - ) - self.plot_multi_spectrum( - compare, - legend=["in", "out", "target curve", "actual target"], - filename="outSpec", - ) - - return x_filt - - def analyze_speech_dataset(self, filepaths, peak=-3.0): - avg_spec = [] - for filepath in tqdm(filepaths, ncols=80): - x, sr = torchaudio.load(filepath) - x /= x.abs().max() - x *= 10 ** (peak / 20.0) - avg_spec.append(self.get_average_spectrum(x)) - avg_specs = torch.stack(avg_spec) - - avg_spec = avg_specs.mean(dim=0).numpy() - avg_spec_std = avg_specs.std(dim=0).numpy() - - # self.plot_multi_spectrum(avg_specs, filename="allTargetEQs") - # self.plot_spectrum_stats(avg_spec, avg_spec_std, filename="targetEQstats") - - sm_avg_spec = self.smooth_spectrum(avg_spec) - - return avg_spec, sm_avg_spec - - def smooth_spectrum(self, H): - # apply Savgol filter for smoothed target curve - return scipy.signal.savgol_filter(H, 1025, 2) - - def get_average_spectrum(self, x): - - # x = x[:, : self.n_fft] - X = torch.stft(x, self.n_fft, return_complex=True, normalized=True) - # fft_size = self.next_power_of_2(x.shape[-1]) - # X = torch.fft.rfft(x, n=fft_size) - - X = X.abs() # convert to magnitude - X = X.mean(dim=-1).view(-1) # average across frames - - return X - - @staticmethod - def next_power_of_2(x): - return 1 if x == 0 else int(2 ** np.ceil(np.log2(x))) - - def plot_multi_spectrum(self, Hs, legend=[], filename=None): - - bin_width = (self.sample_rate / 2) / (self.n_fft // 2) - freqs = np.arange(0, (self.sample_rate / 2) + bin_width, step=bin_width) - - fig, ax1 = plt.subplots() - - for H in Hs: - ax1.plot( - freqs, - 20 * np.log10(abs(H) + 1e-8), - ) - - plt.legend(legend) - - # avg_spec = Hs.mean(dim=0).numpy() - # ax1.plot(freqs, 20 * np.log10(avg_spec), color="k", linewidth=2) - - ax1.set_xscale("log") - ax1.set_ylim([-80, 0]) - plt.grid(c="lightgray") - - if filename is not None: - plt.savefig(f"{filename}.png") - - def plot_spectrum_stats(self, H_mean, H_std, filename=None): - bin_width = (self.sample_rate / 2) / (self.n_fft // 2) - freqs = np.arange(0, (self.sample_rate / 2) + bin_width, step=bin_width) - - fig, ax1 = plt.subplots() - ax1.plot(freqs, 20 * np.log10(H_mean)) - ax1.plot( - freqs, - (20 * np.log10(H_mean)) + (20 * np.log10(H_std)), - linestyle="--", - color="k", - ) - ax1.plot( - freqs, - (20 * np.log10(H_mean)) - (20 * np.log10(H_std)), - linestyle="--", - color="k", - ) - - ax1.set_xscale("log") - ax1.set_ylim([-80, 0]) - plt.grid(c="lightgray") - - if filename is not None: - plt.savefig(f"{filename}.png") - - def plot_spectrum(self, H, legend=[], filename=None): - - bin_width = (self.sample_rate / 2) / (self.n_fft // 2) - freqs = np.arange(0, (self.sample_rate / 2) + bin_width, step=bin_width) - - fig, ax1 = plt.subplots() - ax1.plot(freqs, 20 * np.log10(H)) - ax1.set_xscale("log") - ax1.set_ylim([-80, 0]) - plt.grid(c="lightgray") - - plt.legend(legend) - - if filename is not None: - plt.savefig(f"{filename}.png") - - -class BaslineComp(torch.nn.Module): - def __init__( - self, - sample_rate: float = 44100, - ): - super().__init__() - self.sample_rate = sample_rate - self.meter = pyln.Meter(sample_rate) - - def forward(self, x, y): - - x_lufs = self.meter.integrated_loudness(x.view(-1).numpy()) - y_lufs = self.meter.integrated_loudness(y.view(-1).numpy()) - - delta_lufs = y_lufs - x_lufs - - threshold = 0.0 - x_comp = x - x_comp_new = x - while delta_lufs > 0.5 and threshold > -80.0: - x_comp = x_comp_new # use the last setting - x_comp_new = compressor( - x.view(-1).numpy(), - self.sample_rate, - threshold=threshold, - ratio=3, - attack_time=0.001, - release_time=0.05, - knee_dB=6.0, - makeup_gain_dB=0.0, - ) - x_comp_new = torch.tensor(x_comp_new) - x_comp_new /= x_comp_new.abs().max() - x_comp_new *= 10 ** (-12.0 / 20) - x_lufs = self.meter.integrated_loudness(x_comp_new.view(-1).numpy()) - delta_lufs = y_lufs - x_lufs - threshold -= 0.5 - - return x_comp.view(1, 1, -1) - - -class BaselineEQAndComp(torch.nn.Module): - def __init__( - self, - ntaps=63, - n_fft=65536, - sample_rate=44100, - block_size=1024, - plugin_config=None, - ): - super().__init__() - self.eq = BaselineEQ(ntaps, n_fft, sample_rate) - self.comp = BaslineComp(sample_rate) - - def forward(self, x, y): - - with torch.inference_mode(): - x /= x.abs().max() - y /= y.abs().max() - x *= 10 ** (-12.0 / 20) - y *= 10 ** (-12.0 / 20) - - x = self.eq(x, y) - - x /= x.abs().max() - y /= y.abs().max() - x *= 10 ** (-12.0 / 20) - y *= 10 ** (-12.0 / 20) - - x = self.comp(x, y) - - x /= x.abs().max() - x *= 10 ** (-12.0 / 20) - - return x diff --git a/spaces/naver/PUMP/run_ETH3D.py b/spaces/naver/PUMP/run_ETH3D.py deleted file mode 100644 index 81ad785ea6f57cce985674f2af7b41926441073c..0000000000000000000000000000000000000000 --- a/spaces/naver/PUMP/run_ETH3D.py +++ /dev/null @@ -1,118 +0,0 @@ -# Copyright 2022-present NAVER Corp. -# CC BY-NC-SA 4.0 -# Available only for non-commercial use - -from pdb import set_trace as bb -import os, os.path as osp -from tqdm import tqdm -import numpy as np - -SEQUENCES = [ 'lakeside', 'sand_box', 'storage_room', 'storage_room_2', 'tunnel', - 'delivery_area', 'electro', 'forest', 'playground', 'terrains'] - -RATES = [3, 5, 7, 9, 11, 13, 15] - -def parse_args(): - import argparse - parser = argparse.ArgumentParser('PUMP evaluation script for the ETH3D dataset') - - parser.add_argument('--root', default='datasets/eth3d') - parser.add_argument('--output', default='results/eth3d') - - parser.add_argument('--just-print', action='store_true', help='just print commands') - return parser.parse_args() - - -def main( args ): - run_pump(args) and run_eval(args) - - -def run_pump(args): - done = True - for img1, img2 in tqdm(list_eth3d_pairs()): - output_path = osp.join(args.output, img1, img2+'.corres') - if osp.isfile(output_path): continue - - done = False - _exec(f'''python test_multiscale_recursive.py - --img1 {osp.join(args.root,img1)} - --img2 {osp.join(args.root,img2)} - --max-scale 1.5 - --desc PUMP - --post-filter "densify=True,dense_side='right'" - --output {output_path}''') - - return done - - -def run_eval( args ): - for rate in RATES: - mean_aepe_per_rate = 0 - - for seq in SEQUENCES: - pairs = np.load(osp.join(args.root, 'info_ETH3D_files', f'{seq}_every_5_rate_of_{rate}'), allow_pickle=True) - - mean_aepe_per_seq = 0 - for pair in pairs: - img1, img2 = pair['source_image'], pair['target_image'] - Ys, Xs, Yt, Xt = [np.float32(pair[k]) for k in 'Ys Xs Yt Xt'.split()] - - corres_path = osp.join(args.output, img1, img2+'.corres') - corres = np.load(corres_path, allow_pickle=True)['corres'] - - # extract estimated and target flow - W, H = np.int32(corres[-1, 2:4] + 1) - flow = (corres[:,0:2] - corres[:,2:4]).reshape(H, W, 2) - iYt, iXt = np.int32(np.round(Yt)), np.int32(np.round(Xt)) - if 'correct way': - gt_targets = np.c_[Xs - Xt, Ys - Yt] - est_targets = flow[iYt, iXt] - elif 'GLU-Net way (somewhat inaccurate because of overlapping points in the mask)': - mask = np.zeros((H,W), dtype=bool) - mask[iYt, iXt] = True - gt_flow = np.full((H,W,2), np.nan, dtype=np.float32) - gt_flow[iYt, iXt, 0] = Xs - Xt - gt_flow[iYt, iXt, 1] = Ys - Yt - gt_targets = gt_flow[mask] - est_targets = flow[mask] - - # compute end-point error - aepe = np.linalg.norm(est_targets - gt_targets, axis=-1).mean() - mean_aepe_per_seq += aepe - - mean_aepe_per_seq /= len(pairs) - mean_aepe_per_rate += mean_aepe_per_seq - print(f'mean AEPE for {rate=} {seq=}:', mean_aepe_per_seq) - - print(f'>> mean AEPE for {rate=}:', mean_aepe_per_rate / len(SEQUENCES)) - - -def list_eth3d_pairs(): - path = osp.join(args.root, 'info_ETH3D_files', 'list_pairs.txt') - try: - lines = open(path).read().splitlines() - except OSError: - lines = [] - for seq in SEQUENCES: - for rate in RATES: - pairs = np.load(osp.join(args.root, 'info_ETH3D_files', f'{seq}_every_5_rate_of_{rate}'), allow_pickle=True) - for pair in pairs: - lines.append(pair['source_image'] + ' ' + pair['target_image']) - open(path, 'w').write('\n'.join(lines)) - - pairs = [line.split() for line in lines if line[0] != '#'] - return pairs - - -def _exec(cmd): - # strip & remove \n - cmd = ' '.join(cmd.split()) - if args.just_print: - print(cmd) - else: - os.system(cmd) - - -if __name__ == '__main__': - args = parse_args() - main( args ) diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Diablo Sabotage Paintball Gun Manual.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Diablo Sabotage Paintball Gun Manual.md deleted file mode 100644 index 2fefdaf031b7cb7a51990e98df31f1b3a59f3ddd..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Diablo Sabotage Paintball Gun Manual.md +++ /dev/null @@ -1,19 +0,0 @@ -
      -

      How to Use the Diablo Sabotage Paintball Gun

      -

      The Diablo Sabotage is a semi-automatic paintball marker that features a lightweight aluminum body, a vertical feed neck, a 12-inch ported barrel, and an adjustable velocity. The Sabotage is easy to use and maintain, and can deliver accurate and consistent shots on the field. Here are some steps to help you get started with your Diablo Sabotage paintball gun.

      -

      Diablo sabotage paintball gun manual


      Download Filehttps://urlcod.com/2uIa11



      -

      Step 1: Install the Battery

      -

      The Diablo Sabotage uses a 9-volt battery to power its electronic trigger frame. To install the battery, you need to remove the two screws on the bottom of the grip frame and slide off the cover. Then, connect the battery to the wire harness and place it inside the grip frame. Make sure the battery is securely attached and does not rattle. Replace the cover and tighten the screws.

      -

      Step 2: Attach the Propellant Source

      -

      The Diablo Sabotage can use either CO2 or compressed air as its propellant source. To attach the propellant source, you need to screw it into the ASA (Air Source Adapter) at the bottom of the grip frame. Make sure the propellant source is compatible with your marker and has a standard threaded valve. Do not over-tighten or cross-thread the propellant source. You can also use an on/off valve or a remote line for convenience.

      -

      Step 3: Attach the Loader

      -

      The Diablo Sabotage has a vertical feed neck that can accommodate most standard paintball loaders. To attach the loader, you need to loosen the clamp on the feed neck and slide the loader into it. Then, tighten the clamp to secure the loader in place. Make sure the loader is aligned with the barrel and does not wobble. You can also use an elbow or a feed adapter if your loader does not fit directly.

      -

      Step 4: Power On and Adjust the Velocity

      -

      The Diablo Sabotage has an electronic trigger frame that has four firing modes: semi-auto, burst, full-auto, and ramping. To power on the marker, you need to press and hold the power button on the back of the grip frame until you see a green LED light. To change the firing mode, you need to press and release the power button until you see a different color LED light: red for semi-auto, yellow for burst, blue for full-auto, and purple for ramping. To adjust the velocity, you need to use an Allen wrench to turn the velocity adjuster screw on the back of the marker. Turning it clockwise will increase the velocity, and turning it counter-clockwise will decrease it. You should always use a chronograph to measure your velocity and never shoot at velocities higher than 300 feet per second.

      -

      Step 5: Load and Fire Paintballs

      -

      The Diablo Sabotage has a safety switch on the side of the trigger frame that prevents accidental firing. To load paintballs, you need to fill your loader with good quality paintballs that are not broken or dimpled. Then, turn on your loader and make sure it feeds paintballs into your marker. To fire paintballs, you need to switch off the safety and pull the trigger. You should always wear proper eye protection when firing paintballs and never point your marker at anything you do not intend to shoot.

      -

      Step 6: De-gas and Clean Your Marker

      -

      The Diablo Sabotage has a de-gassing button on the side of the ASA that allows you to release any remaining gas from your marker. To de-gas your marker, you need to switch on the safety and remove any paintballs from your loader and barrel. Then, press and hold the de-gassing button until you hear no more gas escaping from your marker. You can then unscrew your propellant source from your ASA. To clean your marker, you need to wipe off any dirt or paint residue from its exterior with a soft cloth. You can also use a squeegee or a swab to clean your barrel. You should lubricate your marker's moving parts with oil or grease regularly to keep it in good working condition.

      -

      cec2833e83
      -
      -
      \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/ElsaWin 3.9 Audi-torrent.torrent 1 [2021].md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/ElsaWin 3.9 Audi-torrent.torrent 1 [2021].md deleted file mode 100644 index fda4f3ff80ec61dffc81b6ca15b22111c82ef8b2..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/ElsaWin 3.9 Audi-torrent.torrent 1 [2021].md +++ /dev/null @@ -1,26 +0,0 @@ - -

      ElsaWin 3.9: A Comprehensive Guide to Audi Car Repair

      -

      ElsaWin is a software program that provides detailed information on how to repair and maintain Audi vehicles. It contains wiring diagrams, bodywork instructions, standard time for work performed, and more. ElsaWin is not designed to work with diagnostic adapters, but rather as a manual for car repair professionals and enthusiasts.

      -

      ElsaWin 3.9 audi-torrent.torrent 1


      Download File --->>> https://urlcod.com/2uI9Sy



      -

      In this article, we will show you how to download and install ElsaWin 3.9, which is the latest version available for Audi as of February 2011. We will also provide some tips on how to use ElsaWin effectively and troubleshoot any issues that may arise.

      -

      How to Download and Install ElsaWin 3.9

      -

      To download ElsaWin 3.9, you will need a torrent client such as uTorrent or BitTorrent. You can find the torrent file for ElsaWin 3.9 audi-torrent.torrent 1 on various websites, such as MHH AUTO[^1^] or YouTube[^2^]. The file size is about 11.25 GB, so make sure you have enough space on your hard drive and a stable internet connection.

      -

      Once you have downloaded the torrent file, you will need to extract it using a program such as WinRAR or 7-Zip. You will find several files and folders inside the extracted folder, such as setup files, updates, serial numbers, key generator, installation instructions, and more.

      -

      To install ElsaWin 3.9, you will need to follow these steps:

      -

      -
        -
      1. Install Acrobat Reader if you don't have it already.
      2. -
      3. Run the SetupCD 4.00.exe file and follow the instructions on the screen. You will need to enter a serial number and activate the program using the key generator.
      4. -
      5. Run the update files in ascending order until you reach 3.9 (for example, UpdateCD_4.10.exe, UpdateCD_5.00.exe, etc.). You may need to enter a serial number and activate each update using the key generator.
      6. -
      7. Run the Audi data file (AUDI_02_2011.exe) and follow the instructions on the screen. You may need to enter a serial number and activate the data using the key generator.
      8. -
      9. If you want to install other brands of vehicles (such as VW, Seat, or Skoda), you will need to run their respective data files before updating ElsaWin to 3.9. For example, if you want to install VW data, you will need to run VW_01_2011.exe before UpdateCD_3.90.exe.
      10. -
      -

      Congratulations! You have successfully installed ElsaWin 3.9 on your computer.

      -

      How to Use ElsaWin 3.9

      -

      To use ElsaWin 3.9, you will need to launch the program from your desktop or start menu. You will see a login screen where you can enter your username and password. If you don't have a user account yet, you can create one by clicking on "New User".

      -

      Once you are logged in, you will see the main interface of ElsaWin 3.9. You can select your vehicle brand from the drop-down menu at the top left corner of the screen. You can also change the language of the program from the drop-down menu at the top right corner of the screen.

      -

      To access the information base of car repair, you can click on "Information" at the top menu bar of the screen. You will see a list of categories such as Engine, Transmission, Brakes, Electrical System, etc. You can click on any category to expand it and see more subcategories and topics.

      -

      To view a specific topic, you can double-click on it or click on "Display" at the bottom right corner of the screen. You will see a detailed description of how to repair or maintain that part of the vehicle. You can also view wiring diagrams, illustrations, photos, videos, and more by clicking on the tabs at the bottom of the screen.

      -

      To search for a specific keyword or phrase in ElsaWin 3.9, you can click on "Search" at the top menu bar of the

      81aa517590
      -
      -
      \ No newline at end of file diff --git a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Taskrabbit Clone Script Nulled 14.md b/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Taskrabbit Clone Script Nulled 14.md deleted file mode 100644 index ecf1bc062bfe3ad7147d56860dbc8ee507dd3d97..0000000000000000000000000000000000000000 --- a/spaces/netiMophi/DreamlikeArt-Diffusion-1.0/Taskrabbit Clone Script Nulled 14.md +++ /dev/null @@ -1,44 +0,0 @@ - -

      How to Start Your Own Marketplace with Taskrabbit Clone Script Nulled 14

      -

      If you are looking for a way to launch your own online marketplace platform like Taskrabbit, you might have come across the term "Taskrabbit clone script". A clone script is a ready-made software solution that mimics the features and functionality of a popular website or app. By using a clone script, you can save time and money on developing your own platform from scratch.

      -

      Taskrabbit Clone Script Nulled 14


      Download Ziphttps://urlcod.com/2uIcku



      -

      However, not all clone scripts are created equal. Some of them might be outdated, buggy, or insecure. That's why you need to be careful when choosing a clone script for your marketplace project. In this article, we will introduce you to Taskrabbit Clone Script Nulled 14, a premium and reliable clone script that lets you create your own Taskrabbit-like platform in minutes.

      -

      What is Taskrabbit Clone Script Nulled 14?

      -

      Taskrabbit Clone Script Nulled 14 is a fully customizable and scalable clone script that allows you to build your own online marketplace platform for local services. It is based on the Laravel framework, which ensures high performance, security, and code quality. It also supports multi-vendor functionality, which means you can allow multiple service providers to register and offer their services on your platform.

      -

      Taskrabbit Clone Script Nulled 14 comes with all the essential features that you need to run a successful marketplace platform, such as:

      -
        -
      • User-friendly interface and responsive design
      • -
      • Advanced search and filter options
      • -
      • Booking and payment system
      • -
      • Rating and review system
      • -
      • Chat and messaging system
      • -
      • Admin panel and dashboard
      • -
      • Social media integration
      • -
      • SEO optimization and analytics
      • -
      • And much more!
      • -
      -

      How to Start Your Own Marketplace with Taskrabbit Clone Script Nulled 14?

      -

      Starting your own marketplace platform with Taskrabbit Clone Script Nulled 14 is easy and fast. Here are the steps you need to follow:

      -

      -
        -
      1. Purchase Taskrabbit Clone Script Nulled 14 from Migrateshop.com[^1^], the official and trusted provider of clone scripts.
      2. -
      3. Download the script and install it on your server.
      4. -
      5. Customize the script according to your preferences and requirements.
      6. -
      7. Add your own logo, brand name, content, and images.
      8. -
      9. Promote your platform and attract service providers and customers.
      10. -
      11. Earn commissions from each transaction on your platform.
      12. -
      -

      That's it! You are now ready to launch your own online marketplace platform like Taskrabbit with Taskrabbit Clone Script Nulled 14.

      -

      Why Choose Taskrabbit Clone Script Nulled 14?

      -

      There are many reasons why you should choose Taskrabbit Clone Script Nulled 14 for your marketplace project. Here are some of them:

      -
        -
      • It is affordable and cost-effective. You don't have to spend thousands of dollars on hiring developers or buying expensive software licenses. You can get Taskrabbit Clone Script Nulled 14 for a one-time payment of $299.
      • -
      • It is easy and quick to set up. You don't need any technical skills or coding knowledge to install and customize the script. You can do it yourself or hire Migrateshop's professional installation service for a nominal fee.
      • -
      • It is flexible and adaptable. You can modify the script as per your needs and preferences. You can also add new features or integrations with third-party services using Migrateshop's customization service.
      • -
      • It is secure and reliable. The script is built on the Laravel framework, which ensures high security standards and protection from hackers. It also comes with regular updates and bug fixes from Migrateshop.
      • -
      • It is supported and maintained. Migrateshop offers 24/7 customer support and technical assistance for any issues or queries related to the script. They also provide free lifetime updates and upgrades for the script.
      • -
      -

      Conclusion

      -

      If you want to start your own online marketplace platform like Taskrabbit, you don't have to reinvent the wheel. You can use Taskrabbit Clone

      e93f5a0c3f
      -
      -
      \ No newline at end of file diff --git a/spaces/nishantup/LLMsIntro/README.md b/spaces/nishantup/LLMsIntro/README.md deleted file mode 100644 index a1b9de602a2b2852c32f294f7512a9c3e9266ff5..0000000000000000000000000000000000000000 --- a/spaces/nishantup/LLMsIntro/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: LLMsIntro -emoji: 📊 -colorFrom: gray -colorTo: purple -sdk: streamlit -sdk_version: 1.21.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/nomic-ai/nomic-ai_gpt4all_prompt_generations/index.html b/spaces/nomic-ai/nomic-ai_gpt4all_prompt_generations/index.html deleted file mode 100644 index 1310508fd4b4142b526a6af9b4caf60fba85a324..0000000000000000000000000000000000000000 --- a/spaces/nomic-ai/nomic-ai_gpt4all_prompt_generations/index.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - nomic-ai/gpt4all_prompt_generations - - - - -
      - -
      - - - \ No newline at end of file diff --git a/spaces/ntt123/vietnam-male-voice-wavegru-tts/sparse_matmul/compute/gru_gates_avx_fixed.h b/spaces/ntt123/vietnam-male-voice-wavegru-tts/sparse_matmul/compute/gru_gates_avx_fixed.h deleted file mode 100644 index cf7cf0e770d27d583dd63116c350c6dd49d8a528..0000000000000000000000000000000000000000 --- a/spaces/ntt123/vietnam-male-voice-wavegru-tts/sparse_matmul/compute/gru_gates_avx_fixed.h +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * 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. - */ - -#ifndef LYRA_CODEC_SPARSE_MATMUL_COMPUTE_GRU_GATES_AVX_FIXED_H_ -#define LYRA_CODEC_SPARSE_MATMUL_COMPUTE_GRU_GATES_AVX_FIXED_H_ - -#include -#if defined __AVX2__ -#include -#endif -#include - -#include "sparse_matmul/compute/ar_inputs.h" -#include "sparse_matmul/numerics/fast_transcendentals.h" - -namespace csrblocksparse { - -#if defined __AVX2__ - -constexpr int kAVX2SIMDWidth = 8; - -// Loads 8x fixed32 from |ptr0| and adds to |input|. -// If |kTwoInputs|, also loads from |ptr1| and adds that as well. -// Returns the 2 or 3-way sum. -template -inline __m256i LoadAndAddFixed32(const int32_t* ptr0, const int32_t* ptr1, - const __m256i& input) { - __m256i data0 = _mm256_load_si256(reinterpret_cast(ptr0)); - if (kTwoInputs) { - __m256i data1 = _mm256_load_si256(reinterpret_cast(ptr1)); - data0 = _mm256_add_epi32(data0, data1); - } - return _mm256_add_epi32(data0, input); -} - -// Loads 8x fixed32 from ptr0. -// If |kTwoInputs|, also loads from |ptr1| and adds. -// Multiplies the loaded values by the factor and adds to |input|, which also -// is converted to float. -// Returns the sum. -template -inline __m256 LoadMultiplyAddToFloat(const int32_t* ptr0, const int32_t* ptr1, - const __m256& float_factor, - const __m256& input) { - __m256i data0 = _mm256_load_si256(reinterpret_cast(ptr0)); - if (kTwoInputs) { - __m256i data1 = _mm256_load_si256(reinterpret_cast(ptr1)); - data0 = _mm256_add_epi32(data0, data1); - } - __m256 float_result = _mm256_cvtepi32_ps(data0); - float_result = _mm256_mul_ps(float_result, float_factor); - return _mm256_add_ps(float_result, input); -} - -// Loads 16x float in 2x 8x registers from |ptr0_1| and multiplies by -// |input_pairs|, likewise formatted as 8x floats, alternating between the two -// AR inputs and sums each pair of results, making 8x float results. -// If |kThreeInputs|, also loads 8x float from |ptr2| and multiplies by -// |third_input|, which must be formatted as 8x float. The second product is -// added to the previous result. -// Returns the sum added to |accumulator|. -template -inline __m256 MultiplyAddFloat(const __m256& input_pairs, - const __m256& third_input, const float* ptr0_1, - const float* ptr2, const __m256& accumulator) { - __m256 data_pair0 = _mm256_load_ps(ptr0_1); - __m256 data_pair1 = _mm256_load_ps(ptr0_1 + 8); - data_pair0 = _mm256_mul_ps(data_pair0, input_pairs); - data_pair1 = _mm256_mul_ps(data_pair1, input_pairs); - data_pair0 = _mm256_hadd_ps(data_pair0, data_pair1); - // Swap the middle 2 64 bit pairs to correct the hadd result. - data_pair0 = _mm256_permute4x64_pd((__m256d)data_pair0, 0xd8); - if (kThreeInputs) { - // Load 256 bits (8 x float) of data, then multiply-accumulate. - data_pair1 = _mm256_load_ps(ptr2); - data_pair1 = _mm256_mul_ps(data_pair1, third_input); - data_pair0 = _mm256_add_ps(data_pair0, data_pair1); - } - // Add conditioning. - return _mm256_add_ps(data_pair0, accumulator); -} - -// Processes the tanh and the final combination, returns the new GRU state. -template -inline __m256i GRUComputeState(const __m256& cell0, const __m256& cell1, - const __m256& reset0, const __m256& reset1, - const __m256& update0, const __m256& update1, - const int32_t* gate_ptr, - const int32_t* gate_other_ptr, - const void* gru_h_ptr) { - // Multiply the cell gru output and the reset. - __m256 float_gru0 = LoadMultiplyAddToFloat( - gate_ptr, gate_other_ptr, reset0, cell0); - __m256 float_gru1 = LoadMultiplyAddToFloat( - gate_ptr + kAVX2SIMDWidth, gate_other_ptr + kAVX2SIMDWidth, reset1, - cell1); - // Compute tanh on the result. - __m256 hbar0, hbar1; - float_tanh_float(float_gru0, float_gru1, - hbar0, hbar1); - // Load the 16-bit previous gru state and update. - __m256i gru = _mm256_load_si256(reinterpret_cast<__m256i const*>(gru_h_ptr)); - __m256 state_factor = - _mm256_set1_ps(1.0f / (static_cast(1 << kStateMantissaBits))); - float_gru0 = - _mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(_mm256_castsi256_si128(gru))); - float_gru1 = _mm256_cvtepi32_ps( - _mm256_cvtepi16_epi32(_mm256_extractf128_si256(gru, 1))); - float_gru0 = _mm256_mul_ps(float_gru0, state_factor); - float_gru1 = _mm256_mul_ps(float_gru1, state_factor); - float_gru0 = _mm256_sub_ps(float_gru0, hbar0); - float_gru1 = _mm256_sub_ps(float_gru1, hbar1); - float_gru0 = _mm256_mul_ps(float_gru0, update0); - float_gru1 = _mm256_mul_ps(float_gru1, update1); - state_factor = _mm256_set1_ps(static_cast(1 << kStateMantissaBits)); - float_gru0 = _mm256_add_ps(float_gru0, hbar0); - float_gru1 = _mm256_add_ps(float_gru1, hbar1); - float_gru0 = _mm256_mul_ps(float_gru0, state_factor); - float_gru1 = _mm256_mul_ps(float_gru1, state_factor); - return PackFloatsToFixed16(float_gru0, float_gru1); -} - -// According to |kInputsMode|, processes 0, 2 or 3 autoregressive inputs and -// combines with |input| and |gates*|. -// With 2 AR inputs, loads 8x pairs of float from |pair_weights| and multiplies -// by |paired_ar|, likewise formatted as 8x float, but scaled such that the -// product with pair_weights is on the same scale as |*input| and |*gates0|, -// and sums each pair result, making 8x float results. -// If 3 AR inputs, also loads 8x float from |third_weights| and multiplies by -// |third_ar|, which must be formatted as 8x scaled floats. The second product -// is added to the previous result. -// Inputs, 8x fixed32 are loaded from |input|, and added to the total. -// Finally 8x fixed32 from |gates0| (and |gates1| if |kTwoGates|) are added as -// well. -// Returns the total sum as a float, but on the scale of |*input|. -template -inline __m256 GruInput32ToFloat(const __m256& paired_ar, - const __m256& third_ar, - const float* pair_weights, - const float* third_weights, - const int32_t* gates0, const int32_t* gates1, - const int32_t* input) { - __m256i data32 = _mm256_load_si256(reinterpret_cast<__m256i const*>(input)); - data32 = LoadAndAddFixed32(gates0, gates1, data32); - __m256 float_data = _mm256_cvtepi32_ps(data32); - if (kInputsMode != ARInputsMode::k0ARInputs) { - float_data = MultiplyAddFloat( - paired_ar, third_ar, pair_weights, third_weights, float_data); - } - return float_data; -} - -// Generic GRU gates function controlled by template parameters thus: -// - |kInputBits|: the mantissa bits in |*input_ptr|, |*gru_recurrent_ptr|. -// - |kStateBits|: the mantissa_bits in |*gru_state_ptr|. -// - |kInputsMode == |k0ARInputs|: There are no autoregressive inputs so -// |ar_sample, |ar_sample1|, |ar_sample2|, |ar_01_weights|, |ar_2_weights| are -// ignored. -// - |kInputsMode| == |k2ARInputs|: |ar_sample0|, |ar_sample1| are multiplied by -// |ar_01_weights| and added to the (conditioning) input. -// - |kInputsMode| == |k3ARInputs|: |ar_sample2| is multiplied by |ar_2_weights| -// and added to the other two AR inputs (and added to the conditioning input). -// - |kReplicas| determines the number of duplicates of the output to be -// written, separated by |replica_stride|. If zero, then the number of -// replicas is variable and taken from the |replicas| argument. -// - If |kSplitGates| is true: The |*gru_recurrent_other_ptr| is secondary -// recurrent input that must be added to |*gru_recurrent_ptr|. -// - |start|, |end| are |rows| in [0, |state_size|] to be processed by this -// thread. -// -// Previous state is read from |*gru_state_ptr| and the new state is written to -// *(|gru_state_ptr| + i * |replica_stride| for i in [0, |kReplicas|]). -template -inline void GruGatesTemplate( - int start, int end, int state_size, int replicas, int replica_stride, - const int32_t* gru_recurrent_ptr, const int32_t* input_ptr, - const std::pair* ar_sample01, const float* ar_01_weights, - const float* ar_sample2, const float* ar_2_weights, - const int32_t* gru_recurrent_other_ptr, int16_t* gru_state_ptr) { - constexpr int kQRIncrement = kAVX2SIMDWidth; - // Increment all the pointers to save on pointer arithmetic in the loop. - input_ptr += start; - gru_state_ptr += start; - gru_recurrent_ptr += start; - if (kSplitGates) gru_recurrent_other_ptr += start; - __m256 ar_2_inputs, ar_3rd_input; - if (kInputsMode != ARInputsMode::k0ARInputs) { - ar_01_weights += 2 * start; - ar_2_inputs = _mm256_castsi256_ps( - _mm256_set1_epi64x(*reinterpret_cast(ar_sample01))); - if (kInputsMode == ARInputsMode::k3ARInputs) { - ar_2_weights += start; - ar_3rd_input = _mm256_set1_ps(*ar_sample2); - } else { - ar_3rd_input = {}; - } - } else { - ar_2_inputs = {}; - ar_3rd_input = {}; - } - // The transcendentals handle 2x registers of data at once, so we have to do - // everything in duplicate. - for (int i = start; i < end; i += kQRIncrement * 2) { - // Load 8 pairs of fixed16s for each of reset, update and cell. - __m256 reset0 = GruInput32ToFloat( - ar_2_inputs, ar_3rd_input, ar_01_weights, ar_2_weights, - gru_recurrent_ptr, gru_recurrent_other_ptr, input_ptr); - __m256 reset1 = GruInput32ToFloat( - ar_2_inputs, ar_3rd_input, ar_01_weights + 2 * kQRIncrement, - ar_2_weights + kQRIncrement, gru_recurrent_ptr + kAVX2SIMDWidth, - gru_recurrent_other_ptr + kAVX2SIMDWidth, input_ptr + kAVX2SIMDWidth); - float_sigmoid_float(reset0, reset1); - __m256 update0 = GruInput32ToFloat( - ar_2_inputs, ar_3rd_input, ar_01_weights + 2 * state_size, - ar_2_weights + state_size, gru_recurrent_ptr + state_size, - gru_recurrent_other_ptr + state_size, input_ptr + state_size); - __m256 update1 = GruInput32ToFloat( - ar_2_inputs, ar_3rd_input, - ar_01_weights + 2 * state_size + 2 * kQRIncrement, - ar_2_weights + state_size + kQRIncrement, - gru_recurrent_ptr + state_size + kAVX2SIMDWidth, - gru_recurrent_other_ptr + state_size + kAVX2SIMDWidth, - input_ptr + state_size + kAVX2SIMDWidth); - float_sigmoid_float(update0, update1); - __m256 cell0 = _mm256_cvtepi32_ps(_mm256_load_si256( - reinterpret_cast<__m256i const*>(input_ptr + 2 * state_size))); - __m256 cell1 = - _mm256_cvtepi32_ps(_mm256_load_si256(reinterpret_cast<__m256i const*>( - input_ptr + 2 * state_size + kAVX2SIMDWidth))); - if (kInputsMode != ARInputsMode::k0ARInputs) { - cell0 = MultiplyAddFloat( - ar_2_inputs, ar_3rd_input, ar_01_weights + 4 * state_size, - ar_2_weights + 2 * state_size, cell0); - cell1 = MultiplyAddFloat( - ar_2_inputs, ar_3rd_input, - ar_01_weights + 4 * state_size + 2 * kQRIncrement, - ar_2_weights + 2 * state_size + kQRIncrement, cell1); - } - __m256i gru_state = GRUComputeState( - cell0, cell1, reset0, reset1, update0, update1, - gru_recurrent_ptr + 2 * state_size, - gru_recurrent_other_ptr + 2 * state_size, gru_state_ptr); - if (kReplicas > 0) { - // With |kReplicas| a template parameter, the compiler will unroll the - // loop. - for (int j = 0; j < kReplicas; ++j) { - _mm256_store_si256( - reinterpret_cast<__m256i*>(gru_state_ptr + j * replica_stride), - gru_state); - } - } else { - // This loop will not unroll as replicas is variable. - for (int j = 0; j < replicas; ++j) { - _mm256_store_si256( - reinterpret_cast<__m256i*>(gru_state_ptr + j * replica_stride), - gru_state); - } - } - // Increment all the pointers. - input_ptr += 2 * kAVX2SIMDWidth; - gru_state_ptr += 2 * kAVX2SIMDWidth; - gru_recurrent_ptr += 2 * kAVX2SIMDWidth; - if (kSplitGates) gru_recurrent_other_ptr += 2 * kAVX2SIMDWidth; - if (kInputsMode != ARInputsMode::k0ARInputs) { - ar_01_weights += 4 * kQRIncrement; - if (kInputsMode == ARInputsMode::k3ARInputs) - ar_2_weights += 2 * kQRIncrement; - } - } -} - -// Dispatches calls to the GruGatesTemplate function above converting the -// replicas variable argument to a template parameter to allow the compiler to -// unroll the write loop. -// |ar_sample01| packs sample 0 and 1 into a pair because the QR weights are -// formatted with the weights interleaved for sample 0 and 1. The two samples -// represent coarse and fine for WaveRNN. -template -inline void GruGatesAVXFixed( - int start, int end, int state_size, const int32_t* gru_recurrent_ptr, - const int32_t* input_ptr, const std::pair* ar_sample01, - const float* ar_01_weights, int num_replicas, int replica_stride, - const float* ar_sample2, const float* ar_2_weights, - const int32_t* gru_recurrent_other_ptr, int16_t* gru_state_ptr) { - // Convert the number of replicas from a variable to a template parameter - // with a switch. This enables the compiler to unroll the loop for - // the write, making it faster for common numbers of threads. - switch (num_replicas) { - case 1: - GruGatesTemplate( - start, end, state_size, num_replicas, replica_stride, - gru_recurrent_ptr, input_ptr, ar_sample01, ar_01_weights, ar_sample2, - ar_2_weights, gru_recurrent_other_ptr, gru_state_ptr); - break; - case 2: - GruGatesTemplate( - start, end, state_size, num_replicas, replica_stride, - gru_recurrent_ptr, input_ptr, ar_sample01, ar_01_weights, ar_sample2, - ar_2_weights, gru_recurrent_other_ptr, gru_state_ptr); - break; - case 4: - GruGatesTemplate( - start, end, state_size, num_replicas, replica_stride, - gru_recurrent_ptr, input_ptr, ar_sample01, ar_01_weights, ar_sample2, - ar_2_weights, gru_recurrent_other_ptr, gru_state_ptr); - break; - case 6: - GruGatesTemplate( - start, end, state_size, num_replicas, replica_stride, - gru_recurrent_ptr, input_ptr, ar_sample01, ar_01_weights, ar_sample2, - ar_2_weights, gru_recurrent_other_ptr, gru_state_ptr); - break; - default: - // Zero |kReplicas| tells the function to use the |num_replicas| variable. - GruGatesTemplate( - start, end, state_size, num_replicas, replica_stride, - gru_recurrent_ptr, input_ptr, ar_sample01, ar_01_weights, ar_sample2, - ar_2_weights, gru_recurrent_other_ptr, gru_state_ptr); - } -} - -#endif // __AVX2__ - -} // namespace csrblocksparse - -#endif // LYRA_CODEC_SPARSE_MATMUL_COMPUTE_GRU_GATES_AVX_FIXED_H_ diff --git a/spaces/nus-cs5647-team-5/Mandarin_Tone_Evaluation/speech_features/__init__.py b/spaces/nus-cs5647-team-5/Mandarin_Tone_Evaluation/speech_features/__init__.py deleted file mode 100644 index e7e460085fc4bc01784e80cf9ba56c78749cf2b5..0000000000000000000000000000000000000000 --- a/spaces/nus-cs5647-team-5/Mandarin_Tone_Evaluation/speech_features/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .speech_features import * diff --git a/spaces/olivierdehaene/chat-ui-example/README.md b/spaces/olivierdehaene/chat-ui-example/README.md deleted file mode 100644 index 76541fc59707ba795019266f30ac8d7c99e20ca3..0000000000000000000000000000000000000000 --- a/spaces/olivierdehaene/chat-ui-example/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Chat UI Example -emoji: 🔥 -colorFrom: purple -colorTo: purple -sdk: docker -pinned: false -license: apache-2.0 -app_port: 3000 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/examples/community/stable_diffusion_controlnet_reference.py b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/examples/community/stable_diffusion_controlnet_reference.py deleted file mode 100644 index 0814c6b22af9969142a6b32254601be178fdb543..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/examples/community/stable_diffusion_controlnet_reference.py +++ /dev/null @@ -1,835 +0,0 @@ -# Inspired by: https://github.com/Mikubill/sd-webui-controlnet/discussions/1236 and https://github.com/Mikubill/sd-webui-controlnet/discussions/1280 -from typing import Any, Callable, Dict, List, Optional, Tuple, Union - -import numpy as np -import PIL.Image -import torch - -from diffusers import StableDiffusionControlNetPipeline -from diffusers.models import ControlNetModel -from diffusers.models.attention import BasicTransformerBlock -from diffusers.models.unet_2d_blocks import CrossAttnDownBlock2D, CrossAttnUpBlock2D, DownBlock2D, UpBlock2D -from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel -from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput -from diffusers.utils import logging -from diffusers.utils.torch_utils import is_compiled_module, randn_tensor - - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - -EXAMPLE_DOC_STRING = """ - Examples: - ```py - >>> import cv2 - >>> import torch - >>> import numpy as np - >>> from PIL import Image - >>> from diffusers import UniPCMultistepScheduler - >>> from diffusers.utils import load_image - - >>> input_image = load_image("https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png") - - >>> # get canny image - >>> image = cv2.Canny(np.array(input_image), 100, 200) - >>> image = image[:, :, None] - >>> image = np.concatenate([image, image, image], axis=2) - >>> canny_image = Image.fromarray(image) - - >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16) - >>> pipe = StableDiffusionControlNetReferencePipeline.from_pretrained( - "runwayml/stable-diffusion-v1-5", - controlnet=controlnet, - safety_checker=None, - torch_dtype=torch.float16 - ).to('cuda:0') - - >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe_controlnet.scheduler.config) - - >>> result_img = pipe(ref_image=input_image, - prompt="1girl", - image=canny_image, - num_inference_steps=20, - reference_attn=True, - reference_adain=True).images[0] - - >>> result_img.show() - ``` -""" - - -def torch_dfs(model: torch.nn.Module): - result = [model] - for child in model.children(): - result += torch_dfs(child) - return result - - -class StableDiffusionControlNetReferencePipeline(StableDiffusionControlNetPipeline): - def prepare_ref_latents(self, refimage, batch_size, dtype, device, generator, do_classifier_free_guidance): - refimage = refimage.to(device=device, dtype=dtype) - - # encode the mask image into latents space so we can concatenate it to the latents - if isinstance(generator, list): - ref_image_latents = [ - self.vae.encode(refimage[i : i + 1]).latent_dist.sample(generator=generator[i]) - for i in range(batch_size) - ] - ref_image_latents = torch.cat(ref_image_latents, dim=0) - else: - ref_image_latents = self.vae.encode(refimage).latent_dist.sample(generator=generator) - ref_image_latents = self.vae.config.scaling_factor * ref_image_latents - - # duplicate mask and ref_image_latents for each generation per prompt, using mps friendly method - if ref_image_latents.shape[0] < batch_size: - if not batch_size % ref_image_latents.shape[0] == 0: - raise ValueError( - "The passed images and the required batch size don't match. Images are supposed to be duplicated" - f" to a total batch size of {batch_size}, but {ref_image_latents.shape[0]} images were passed." - " Make sure the number of images that you pass is divisible by the total requested batch size." - ) - ref_image_latents = ref_image_latents.repeat(batch_size // ref_image_latents.shape[0], 1, 1, 1) - - ref_image_latents = torch.cat([ref_image_latents] * 2) if do_classifier_free_guidance else ref_image_latents - - # aligning device to prevent device errors when concating it with the latent model input - ref_image_latents = ref_image_latents.to(device=device, dtype=dtype) - return ref_image_latents - - @torch.no_grad() - def __call__( - self, - prompt: Union[str, List[str]] = None, - image: Union[ - torch.FloatTensor, - PIL.Image.Image, - np.ndarray, - List[torch.FloatTensor], - List[PIL.Image.Image], - List[np.ndarray], - ] = None, - ref_image: Union[torch.FloatTensor, PIL.Image.Image] = None, - height: Optional[int] = None, - width: Optional[int] = None, - num_inference_steps: int = 50, - guidance_scale: float = 7.5, - negative_prompt: Optional[Union[str, List[str]]] = None, - num_images_per_prompt: Optional[int] = 1, - eta: float = 0.0, - generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, - latents: Optional[torch.FloatTensor] = None, - prompt_embeds: Optional[torch.FloatTensor] = None, - negative_prompt_embeds: Optional[torch.FloatTensor] = None, - output_type: Optional[str] = "pil", - return_dict: bool = True, - callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, - callback_steps: int = 1, - cross_attention_kwargs: Optional[Dict[str, Any]] = None, - controlnet_conditioning_scale: Union[float, List[float]] = 1.0, - guess_mode: bool = False, - attention_auto_machine_weight: float = 1.0, - gn_auto_machine_weight: float = 1.0, - style_fidelity: float = 0.5, - reference_attn: bool = True, - reference_adain: bool = True, - ): - r""" - Function invoked when calling the pipeline for generation. - - Args: - prompt (`str` or `List[str]`, *optional*): - The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. - instead. - image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,: - `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`): - The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If - the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can - also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If - height and/or width are passed, `image` is resized according to them. If multiple ControlNets are - specified in init, images must be passed as a list such that each element of the list can be correctly - batched for input to a single controlnet. - ref_image (`torch.FloatTensor`, `PIL.Image.Image`): - The Reference Control input condition. Reference Control uses this input condition to generate guidance to Unet. If - the type is specified as `Torch.FloatTensor`, it is passed to Reference Control as is. `PIL.Image.Image` can - also be accepted as an image. - height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): - The height in pixels of the generated image. - width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): - The width in pixels of the generated image. - num_inference_steps (`int`, *optional*, defaults to 50): - The number of denoising steps. More denoising steps usually lead to a higher quality image at the - expense of slower inference. - guidance_scale (`float`, *optional*, defaults to 7.5): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - negative_prompt (`str` or `List[str]`, *optional*): - The prompt or prompts not to guide the image generation. If not defined, one has to pass - `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is - less than `1`). - num_images_per_prompt (`int`, *optional*, defaults to 1): - The number of images to generate per prompt. - eta (`float`, *optional*, defaults to 0.0): - Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to - [`schedulers.DDIMScheduler`], will be ignored for others. - generator (`torch.Generator` or `List[torch.Generator]`, *optional*): - One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) - to make generation deterministic. - latents (`torch.FloatTensor`, *optional*): - Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image - generation. Can be used to tweak the same generation with different prompts. If not provided, a latents - tensor will ge generated by sampling using the supplied random `generator`. - prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not - provided, text embeddings will be generated from `prompt` input argument. - negative_prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt - weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input - argument. - output_type (`str`, *optional*, defaults to `"pil"`): - The output format of the generate image. Choose between - [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. - return_dict (`bool`, *optional*, defaults to `True`): - Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a - plain tuple. - callback (`Callable`, *optional*): - A function that will be called every `callback_steps` steps during inference. The function will be - called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. - callback_steps (`int`, *optional*, defaults to 1): - The frequency at which the `callback` function will be called. If not specified, the callback will be - called at every step. - cross_attention_kwargs (`dict`, *optional*): - A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under - `self.processor` in - [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). - controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0): - The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added - to the residual in the original unet. If multiple ControlNets are specified in init, you can set the - corresponding scale as a list. - guess_mode (`bool`, *optional*, defaults to `False`): - In this mode, the ControlNet encoder will try best to recognize the content of the input image even if - you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended. - attention_auto_machine_weight (`float`): - Weight of using reference query for self attention's context. - If attention_auto_machine_weight=1.0, use reference query for all self attention's context. - gn_auto_machine_weight (`float`): - Weight of using reference adain. If gn_auto_machine_weight=2.0, use all reference adain plugins. - style_fidelity (`float`): - style fidelity of ref_uncond_xt. If style_fidelity=1.0, control more important, - elif style_fidelity=0.0, prompt more important, else balanced. - reference_attn (`bool`): - Whether to use reference query for self attention's context. - reference_adain (`bool`): - Whether to use reference adain. - - Examples: - - Returns: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: - [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. - When returning a tuple, the first element is a list with the generated images, and the second element is a - list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" - (nsfw) content, according to the `safety_checker`. - """ - assert reference_attn or reference_adain, "`reference_attn` or `reference_adain` must be True." - - # 1. Check inputs. Raise error if not correct - self.check_inputs( - prompt, - image, - callback_steps, - negative_prompt, - prompt_embeds, - negative_prompt_embeds, - controlnet_conditioning_scale, - ) - - # 2. Define call parameters - if prompt is not None and isinstance(prompt, str): - batch_size = 1 - elif prompt is not None and isinstance(prompt, list): - batch_size = len(prompt) - else: - batch_size = prompt_embeds.shape[0] - - device = self._execution_device - # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) - # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` - # corresponds to doing no classifier free guidance. - do_classifier_free_guidance = guidance_scale > 1.0 - - controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet - - if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float): - controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets) - - global_pool_conditions = ( - controlnet.config.global_pool_conditions - if isinstance(controlnet, ControlNetModel) - else controlnet.nets[0].config.global_pool_conditions - ) - guess_mode = guess_mode or global_pool_conditions - - # 3. Encode input prompt - text_encoder_lora_scale = ( - cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None - ) - prompt_embeds = self._encode_prompt( - prompt, - device, - num_images_per_prompt, - do_classifier_free_guidance, - negative_prompt, - prompt_embeds=prompt_embeds, - negative_prompt_embeds=negative_prompt_embeds, - lora_scale=text_encoder_lora_scale, - ) - - # 4. Prepare image - if isinstance(controlnet, ControlNetModel): - image = self.prepare_image( - image=image, - width=width, - height=height, - batch_size=batch_size * num_images_per_prompt, - num_images_per_prompt=num_images_per_prompt, - device=device, - dtype=controlnet.dtype, - do_classifier_free_guidance=do_classifier_free_guidance, - guess_mode=guess_mode, - ) - height, width = image.shape[-2:] - elif isinstance(controlnet, MultiControlNetModel): - images = [] - - for image_ in image: - image_ = self.prepare_image( - image=image_, - width=width, - height=height, - batch_size=batch_size * num_images_per_prompt, - num_images_per_prompt=num_images_per_prompt, - device=device, - dtype=controlnet.dtype, - do_classifier_free_guidance=do_classifier_free_guidance, - guess_mode=guess_mode, - ) - - images.append(image_) - - image = images - height, width = image[0].shape[-2:] - else: - assert False - - # 5. Preprocess reference image - ref_image = self.prepare_image( - image=ref_image, - width=width, - height=height, - batch_size=batch_size * num_images_per_prompt, - num_images_per_prompt=num_images_per_prompt, - device=device, - dtype=prompt_embeds.dtype, - ) - - # 6. Prepare timesteps - self.scheduler.set_timesteps(num_inference_steps, device=device) - timesteps = self.scheduler.timesteps - - # 7. Prepare latent variables - num_channels_latents = self.unet.config.in_channels - latents = self.prepare_latents( - batch_size * num_images_per_prompt, - num_channels_latents, - height, - width, - prompt_embeds.dtype, - device, - generator, - latents, - ) - - # 8. Prepare reference latent variables - ref_image_latents = self.prepare_ref_latents( - ref_image, - batch_size * num_images_per_prompt, - prompt_embeds.dtype, - device, - generator, - do_classifier_free_guidance, - ) - - # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline - extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) - - # 9. Modify self attention and group norm - MODE = "write" - uc_mask = ( - torch.Tensor([1] * batch_size * num_images_per_prompt + [0] * batch_size * num_images_per_prompt) - .type_as(ref_image_latents) - .bool() - ) - - def hacked_basic_transformer_inner_forward( - self, - hidden_states: torch.FloatTensor, - attention_mask: Optional[torch.FloatTensor] = None, - encoder_hidden_states: Optional[torch.FloatTensor] = None, - encoder_attention_mask: Optional[torch.FloatTensor] = None, - timestep: Optional[torch.LongTensor] = None, - cross_attention_kwargs: Dict[str, Any] = None, - class_labels: Optional[torch.LongTensor] = None, - ): - if self.use_ada_layer_norm: - norm_hidden_states = self.norm1(hidden_states, timestep) - elif self.use_ada_layer_norm_zero: - norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1( - hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype - ) - else: - norm_hidden_states = self.norm1(hidden_states) - - # 1. Self-Attention - cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {} - if self.only_cross_attention: - attn_output = self.attn1( - norm_hidden_states, - encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, - attention_mask=attention_mask, - **cross_attention_kwargs, - ) - else: - if MODE == "write": - self.bank.append(norm_hidden_states.detach().clone()) - attn_output = self.attn1( - norm_hidden_states, - encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, - attention_mask=attention_mask, - **cross_attention_kwargs, - ) - if MODE == "read": - if attention_auto_machine_weight > self.attn_weight: - attn_output_uc = self.attn1( - norm_hidden_states, - encoder_hidden_states=torch.cat([norm_hidden_states] + self.bank, dim=1), - # attention_mask=attention_mask, - **cross_attention_kwargs, - ) - attn_output_c = attn_output_uc.clone() - if do_classifier_free_guidance and style_fidelity > 0: - attn_output_c[uc_mask] = self.attn1( - norm_hidden_states[uc_mask], - encoder_hidden_states=norm_hidden_states[uc_mask], - **cross_attention_kwargs, - ) - attn_output = style_fidelity * attn_output_c + (1.0 - style_fidelity) * attn_output_uc - self.bank.clear() - else: - attn_output = self.attn1( - norm_hidden_states, - encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None, - attention_mask=attention_mask, - **cross_attention_kwargs, - ) - if self.use_ada_layer_norm_zero: - attn_output = gate_msa.unsqueeze(1) * attn_output - hidden_states = attn_output + hidden_states - - if self.attn2 is not None: - norm_hidden_states = ( - self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states) - ) - - # 2. Cross-Attention - attn_output = self.attn2( - norm_hidden_states, - encoder_hidden_states=encoder_hidden_states, - attention_mask=encoder_attention_mask, - **cross_attention_kwargs, - ) - hidden_states = attn_output + hidden_states - - # 3. Feed-forward - norm_hidden_states = self.norm3(hidden_states) - - if self.use_ada_layer_norm_zero: - norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] - - ff_output = self.ff(norm_hidden_states) - - if self.use_ada_layer_norm_zero: - ff_output = gate_mlp.unsqueeze(1) * ff_output - - hidden_states = ff_output + hidden_states - - return hidden_states - - def hacked_mid_forward(self, *args, **kwargs): - eps = 1e-6 - x = self.original_forward(*args, **kwargs) - if MODE == "write": - if gn_auto_machine_weight >= self.gn_weight: - var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0) - self.mean_bank.append(mean) - self.var_bank.append(var) - if MODE == "read": - if len(self.mean_bank) > 0 and len(self.var_bank) > 0: - var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0) - std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5 - mean_acc = sum(self.mean_bank) / float(len(self.mean_bank)) - var_acc = sum(self.var_bank) / float(len(self.var_bank)) - std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5 - x_uc = (((x - mean) / std) * std_acc) + mean_acc - x_c = x_uc.clone() - if do_classifier_free_guidance and style_fidelity > 0: - x_c[uc_mask] = x[uc_mask] - x = style_fidelity * x_c + (1.0 - style_fidelity) * x_uc - self.mean_bank = [] - self.var_bank = [] - return x - - def hack_CrossAttnDownBlock2D_forward( - self, - hidden_states: torch.FloatTensor, - temb: Optional[torch.FloatTensor] = None, - encoder_hidden_states: Optional[torch.FloatTensor] = None, - attention_mask: Optional[torch.FloatTensor] = None, - cross_attention_kwargs: Optional[Dict[str, Any]] = None, - encoder_attention_mask: Optional[torch.FloatTensor] = None, - ): - eps = 1e-6 - - # TODO(Patrick, William) - attention mask is not used - output_states = () - - for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)): - hidden_states = resnet(hidden_states, temb) - hidden_states = attn( - hidden_states, - encoder_hidden_states=encoder_hidden_states, - cross_attention_kwargs=cross_attention_kwargs, - attention_mask=attention_mask, - encoder_attention_mask=encoder_attention_mask, - return_dict=False, - )[0] - if MODE == "write": - if gn_auto_machine_weight >= self.gn_weight: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - self.mean_bank.append([mean]) - self.var_bank.append([var]) - if MODE == "read": - if len(self.mean_bank) > 0 and len(self.var_bank) > 0: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5 - mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i])) - var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i])) - std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5 - hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc - hidden_states_c = hidden_states_uc.clone() - if do_classifier_free_guidance and style_fidelity > 0: - hidden_states_c[uc_mask] = hidden_states[uc_mask] - hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc - - output_states = output_states + (hidden_states,) - - if MODE == "read": - self.mean_bank = [] - self.var_bank = [] - - if self.downsamplers is not None: - for downsampler in self.downsamplers: - hidden_states = downsampler(hidden_states) - - output_states = output_states + (hidden_states,) - - return hidden_states, output_states - - def hacked_DownBlock2D_forward(self, hidden_states, temb=None): - eps = 1e-6 - - output_states = () - - for i, resnet in enumerate(self.resnets): - hidden_states = resnet(hidden_states, temb) - - if MODE == "write": - if gn_auto_machine_weight >= self.gn_weight: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - self.mean_bank.append([mean]) - self.var_bank.append([var]) - if MODE == "read": - if len(self.mean_bank) > 0 and len(self.var_bank) > 0: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5 - mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i])) - var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i])) - std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5 - hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc - hidden_states_c = hidden_states_uc.clone() - if do_classifier_free_guidance and style_fidelity > 0: - hidden_states_c[uc_mask] = hidden_states[uc_mask] - hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc - - output_states = output_states + (hidden_states,) - - if MODE == "read": - self.mean_bank = [] - self.var_bank = [] - - if self.downsamplers is not None: - for downsampler in self.downsamplers: - hidden_states = downsampler(hidden_states) - - output_states = output_states + (hidden_states,) - - return hidden_states, output_states - - def hacked_CrossAttnUpBlock2D_forward( - self, - hidden_states: torch.FloatTensor, - res_hidden_states_tuple: Tuple[torch.FloatTensor, ...], - temb: Optional[torch.FloatTensor] = None, - encoder_hidden_states: Optional[torch.FloatTensor] = None, - cross_attention_kwargs: Optional[Dict[str, Any]] = None, - upsample_size: Optional[int] = None, - attention_mask: Optional[torch.FloatTensor] = None, - encoder_attention_mask: Optional[torch.FloatTensor] = None, - ): - eps = 1e-6 - # TODO(Patrick, William) - attention mask is not used - for i, (resnet, attn) in enumerate(zip(self.resnets, self.attentions)): - # pop res hidden states - res_hidden_states = res_hidden_states_tuple[-1] - res_hidden_states_tuple = res_hidden_states_tuple[:-1] - hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) - hidden_states = resnet(hidden_states, temb) - hidden_states = attn( - hidden_states, - encoder_hidden_states=encoder_hidden_states, - cross_attention_kwargs=cross_attention_kwargs, - attention_mask=attention_mask, - encoder_attention_mask=encoder_attention_mask, - return_dict=False, - )[0] - - if MODE == "write": - if gn_auto_machine_weight >= self.gn_weight: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - self.mean_bank.append([mean]) - self.var_bank.append([var]) - if MODE == "read": - if len(self.mean_bank) > 0 and len(self.var_bank) > 0: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5 - mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i])) - var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i])) - std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5 - hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc - hidden_states_c = hidden_states_uc.clone() - if do_classifier_free_guidance and style_fidelity > 0: - hidden_states_c[uc_mask] = hidden_states[uc_mask] - hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc - - if MODE == "read": - self.mean_bank = [] - self.var_bank = [] - - if self.upsamplers is not None: - for upsampler in self.upsamplers: - hidden_states = upsampler(hidden_states, upsample_size) - - return hidden_states - - def hacked_UpBlock2D_forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None): - eps = 1e-6 - for i, resnet in enumerate(self.resnets): - # pop res hidden states - res_hidden_states = res_hidden_states_tuple[-1] - res_hidden_states_tuple = res_hidden_states_tuple[:-1] - hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1) - hidden_states = resnet(hidden_states, temb) - - if MODE == "write": - if gn_auto_machine_weight >= self.gn_weight: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - self.mean_bank.append([mean]) - self.var_bank.append([var]) - if MODE == "read": - if len(self.mean_bank) > 0 and len(self.var_bank) > 0: - var, mean = torch.var_mean(hidden_states, dim=(2, 3), keepdim=True, correction=0) - std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5 - mean_acc = sum(self.mean_bank[i]) / float(len(self.mean_bank[i])) - var_acc = sum(self.var_bank[i]) / float(len(self.var_bank[i])) - std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5 - hidden_states_uc = (((hidden_states - mean) / std) * std_acc) + mean_acc - hidden_states_c = hidden_states_uc.clone() - if do_classifier_free_guidance and style_fidelity > 0: - hidden_states_c[uc_mask] = hidden_states[uc_mask] - hidden_states = style_fidelity * hidden_states_c + (1.0 - style_fidelity) * hidden_states_uc - - if MODE == "read": - self.mean_bank = [] - self.var_bank = [] - - if self.upsamplers is not None: - for upsampler in self.upsamplers: - hidden_states = upsampler(hidden_states, upsample_size) - - return hidden_states - - if reference_attn: - attn_modules = [module for module in torch_dfs(self.unet) if isinstance(module, BasicTransformerBlock)] - attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0]) - - for i, module in enumerate(attn_modules): - module._original_inner_forward = module.forward - module.forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock) - module.bank = [] - module.attn_weight = float(i) / float(len(attn_modules)) - - if reference_adain: - gn_modules = [self.unet.mid_block] - self.unet.mid_block.gn_weight = 0 - - down_blocks = self.unet.down_blocks - for w, module in enumerate(down_blocks): - module.gn_weight = 1.0 - float(w) / float(len(down_blocks)) - gn_modules.append(module) - - up_blocks = self.unet.up_blocks - for w, module in enumerate(up_blocks): - module.gn_weight = float(w) / float(len(up_blocks)) - gn_modules.append(module) - - for i, module in enumerate(gn_modules): - if getattr(module, "original_forward", None) is None: - module.original_forward = module.forward - if i == 0: - # mid_block - module.forward = hacked_mid_forward.__get__(module, torch.nn.Module) - elif isinstance(module, CrossAttnDownBlock2D): - module.forward = hack_CrossAttnDownBlock2D_forward.__get__(module, CrossAttnDownBlock2D) - elif isinstance(module, DownBlock2D): - module.forward = hacked_DownBlock2D_forward.__get__(module, DownBlock2D) - elif isinstance(module, CrossAttnUpBlock2D): - module.forward = hacked_CrossAttnUpBlock2D_forward.__get__(module, CrossAttnUpBlock2D) - elif isinstance(module, UpBlock2D): - module.forward = hacked_UpBlock2D_forward.__get__(module, UpBlock2D) - module.mean_bank = [] - module.var_bank = [] - module.gn_weight *= 2 - - # 11. Denoising loop - num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order - with self.progress_bar(total=num_inference_steps) as progress_bar: - for i, t in enumerate(timesteps): - # expand the latents if we are doing classifier free guidance - latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents - latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) - - # controlnet(s) inference - if guess_mode and do_classifier_free_guidance: - # Infer ControlNet only for the conditional batch. - control_model_input = latents - control_model_input = self.scheduler.scale_model_input(control_model_input, t) - controlnet_prompt_embeds = prompt_embeds.chunk(2)[1] - else: - control_model_input = latent_model_input - controlnet_prompt_embeds = prompt_embeds - - down_block_res_samples, mid_block_res_sample = self.controlnet( - control_model_input, - t, - encoder_hidden_states=controlnet_prompt_embeds, - controlnet_cond=image, - conditioning_scale=controlnet_conditioning_scale, - guess_mode=guess_mode, - return_dict=False, - ) - - if guess_mode and do_classifier_free_guidance: - # Infered ControlNet only for the conditional batch. - # To apply the output of ControlNet to both the unconditional and conditional batches, - # add 0 to the unconditional batch to keep it unchanged. - down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples] - mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample]) - - # ref only part - noise = randn_tensor( - ref_image_latents.shape, generator=generator, device=device, dtype=ref_image_latents.dtype - ) - ref_xt = self.scheduler.add_noise( - ref_image_latents, - noise, - t.reshape( - 1, - ), - ) - ref_xt = self.scheduler.scale_model_input(ref_xt, t) - - MODE = "write" - self.unet( - ref_xt, - t, - encoder_hidden_states=prompt_embeds, - cross_attention_kwargs=cross_attention_kwargs, - return_dict=False, - ) - - # predict the noise residual - MODE = "read" - noise_pred = self.unet( - latent_model_input, - t, - encoder_hidden_states=prompt_embeds, - cross_attention_kwargs=cross_attention_kwargs, - down_block_additional_residuals=down_block_res_samples, - mid_block_additional_residual=mid_block_res_sample, - return_dict=False, - )[0] - - # perform guidance - if do_classifier_free_guidance: - noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) - noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) - - # compute the previous noisy sample x_t -> x_t-1 - latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] - - # call the callback, if provided - if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): - progress_bar.update() - if callback is not None and i % callback_steps == 0: - callback(i, t, latents) - - # If we do sequential model offloading, let's offload unet and controlnet - # manually for max memory savings - if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: - self.unet.to("cpu") - self.controlnet.to("cpu") - torch.cuda.empty_cache() - - if not output_type == "latent": - image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] - image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) - else: - image = latents - has_nsfw_concept = None - - if has_nsfw_concept is None: - do_denormalize = [True] * image.shape[0] - else: - do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] - - image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) - - # Offload last model to CPU - if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: - self.final_offload_hook.offload() - - if not return_dict: - return (image, has_nsfw_concept) - - return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) diff --git a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py b/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py deleted file mode 100644 index 627857592abe9a913312bb4cdb6c005aedd64bf0..0000000000000000000000000000000000000000 --- a/spaces/pablodawson/ldm3d-inpainting/diffuserslocal/src/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +++ /dev/null @@ -1,344 +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 typing import Callable, List, Optional, Union - -import numpy as np -import PIL -import torch -from PIL import Image - -from ...models import UNet2DConditionModel, VQModel -from ...schedulers import DDPMScheduler -from ...utils import ( - logging, -) -from ...utils.torch_utils import randn_tensor -from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput - - -logger = logging.get_logger(__name__) # pylint: disable=invalid-name - -EXAMPLE_DOC_STRING = """ - Examples: - ```py - >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline - >>> from diffusers.utils import load_image - >>> import torch - - >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( - ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 - ... ) - >>> pipe_prior.to("cuda") - - >>> prompt = "A red cartoon frog, 4k" - >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) - - >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( - ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 - ... ) - >>> pipe.to("cuda") - - >>> init_image = load_image( - ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" - ... "/kandinsky/frog.png" - ... ) - - >>> image = pipe( - ... image=init_image, - ... image_embeds=image_emb, - ... negative_image_embeds=zero_image_emb, - ... height=768, - ... width=768, - ... num_inference_steps=100, - ... strength=0.2, - ... ).images - - >>> image[0].save("red_frog.png") - ``` -""" - - -# Copied from diffusers.pipelines.kandinsky2_2.pipeline_kandinsky2_2.downscale_height_and_width -def downscale_height_and_width(height, width, scale_factor=8): - new_height = height // scale_factor**2 - if height % scale_factor**2 != 0: - new_height += 1 - new_width = width // scale_factor**2 - if width % scale_factor**2 != 0: - new_width += 1 - return new_height * scale_factor, new_width * scale_factor - - -# Copied from diffusers.pipelines.kandinsky.pipeline_kandinsky_img2img.prepare_image -def prepare_image(pil_image, w=512, h=512): - pil_image = pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1) - arr = np.array(pil_image.convert("RGB")) - arr = arr.astype(np.float32) / 127.5 - 1 - arr = np.transpose(arr, [2, 0, 1]) - image = torch.from_numpy(arr).unsqueeze(0) - return image - - -class KandinskyV22Img2ImgPipeline(DiffusionPipeline): - """ - Pipeline for image-to-image generation using Kandinsky - - This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the - library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) - - Args: - scheduler ([`DDIMScheduler`]): - A scheduler to be used in combination with `unet` to generate image latents. - unet ([`UNet2DConditionModel`]): - Conditional U-Net architecture to denoise the image embedding. - movq ([`VQModel`]): - MoVQ Decoder to generate the image from the latents. - """ - - model_cpu_offload_seq = "unet->movq" - - def __init__( - self, - unet: UNet2DConditionModel, - scheduler: DDPMScheduler, - movq: VQModel, - ): - super().__init__() - - self.register_modules( - unet=unet, - scheduler=scheduler, - movq=movq, - ) - self.movq_scale_factor = 2 ** (len(self.movq.config.block_out_channels) - 1) - - # Copied from diffusers.pipelines.kandinsky.pipeline_kandinsky_img2img.KandinskyImg2ImgPipeline.get_timesteps - def get_timesteps(self, num_inference_steps, strength, device): - # get the original timestep using init_timestep - init_timestep = min(int(num_inference_steps * strength), num_inference_steps) - - t_start = max(num_inference_steps - init_timestep, 0) - timesteps = self.scheduler.timesteps[t_start:] - - return timesteps, num_inference_steps - t_start - - def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None): - if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)): - raise ValueError( - f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}" - ) - - image = image.to(device=device, dtype=dtype) - - batch_size = batch_size * num_images_per_prompt - - if image.shape[1] == 4: - init_latents = image - - else: - if isinstance(generator, list) and len(generator) != batch_size: - raise ValueError( - f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" - f" size of {batch_size}. Make sure the batch size matches the length of the generators." - ) - - elif isinstance(generator, list): - init_latents = [ - self.movq.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size) - ] - init_latents = torch.cat(init_latents, dim=0) - else: - init_latents = self.movq.encode(image).latent_dist.sample(generator) - - init_latents = self.movq.config.scaling_factor * init_latents - - init_latents = torch.cat([init_latents], dim=0) - - shape = init_latents.shape - noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) - - # get latents - init_latents = self.scheduler.add_noise(init_latents, noise, timestep) - - latents = init_latents - - return latents - - @torch.no_grad() - def __call__( - self, - image_embeds: Union[torch.FloatTensor, List[torch.FloatTensor]], - image: Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]], - negative_image_embeds: Union[torch.FloatTensor, List[torch.FloatTensor]], - height: int = 512, - width: int = 512, - num_inference_steps: int = 100, - guidance_scale: float = 4.0, - strength: float = 0.3, - num_images_per_prompt: int = 1, - generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, - output_type: Optional[str] = "pil", - callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, - callback_steps: int = 1, - return_dict: bool = True, - ): - """ - Function invoked when calling the pipeline for generation. - - Args: - image_embeds (`torch.FloatTensor` or `List[torch.FloatTensor]`): - The clip image embeddings for text prompt, that will be used to condition the image generation. - image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`): - `Image`, or tensor representing an image batch, that will be used as the starting point for the - process. Can also accept image latents as `image`, if passing latents directly, it will not be encoded - again. - strength (`float`, *optional*, defaults to 0.8): - Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image` - will be used as a starting point, adding more noise to it the larger the `strength`. The number of - denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will - be maximum and the denoising process will run for the full number of iterations specified in - `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. - negative_image_embeds (`torch.FloatTensor` or `List[torch.FloatTensor]`): - The clip image embeddings for negative text prompt, will be used to condition the image generation. - height (`int`, *optional*, defaults to 512): - The height in pixels of the generated image. - width (`int`, *optional*, defaults to 512): - The width in pixels of the generated image. - num_inference_steps (`int`, *optional*, defaults to 100): - The number of denoising steps. More denoising steps usually lead to a higher quality image at the - expense of slower inference. - guidance_scale (`float`, *optional*, defaults to 4.0): - Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). - `guidance_scale` is defined as `w` of equation 2. of [Imagen - Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > - 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, - usually at the expense of lower image quality. - num_images_per_prompt (`int`, *optional*, defaults to 1): - The number of images to generate per prompt. - generator (`torch.Generator` or `List[torch.Generator]`, *optional*): - One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) - to make generation deterministic. - output_type (`str`, *optional*, defaults to `"pil"`): - The output format of the generate image. Choose between: `"pil"` (`PIL.Image.Image`), `"np"` - (`np.array`) or `"pt"` (`torch.Tensor`). - callback (`Callable`, *optional*): - A function that calls every `callback_steps` steps during inference. The function is called with the - following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. - callback_steps (`int`, *optional*, defaults to 1): - The frequency at which the `callback` function is called. If not specified, the callback is called at - every step. - return_dict (`bool`, *optional*, defaults to `True`): - Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple. - - Examples: - - Returns: - [`~pipelines.ImagePipelineOutput`] or `tuple` - """ - device = self._execution_device - - do_classifier_free_guidance = guidance_scale > 1.0 - - if isinstance(image_embeds, list): - image_embeds = torch.cat(image_embeds, dim=0) - batch_size = image_embeds.shape[0] - if isinstance(negative_image_embeds, list): - negative_image_embeds = torch.cat(negative_image_embeds, dim=0) - - if do_classifier_free_guidance: - image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0) - negative_image_embeds = negative_image_embeds.repeat_interleave(num_images_per_prompt, dim=0) - - image_embeds = torch.cat([negative_image_embeds, image_embeds], dim=0).to( - dtype=self.unet.dtype, device=device - ) - - if not isinstance(image, list): - image = [image] - if not all(isinstance(i, (PIL.Image.Image, torch.Tensor)) for i in image): - raise ValueError( - f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support PIL image and pytorch tensor" - ) - - image = torch.cat([prepare_image(i, width, height) for i in image], dim=0) - image = image.to(dtype=image_embeds.dtype, device=device) - - latents = self.movq.encode(image)["latents"] - latents = latents.repeat_interleave(num_images_per_prompt, dim=0) - self.scheduler.set_timesteps(num_inference_steps, device=device) - timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device) - latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) - height, width = downscale_height_and_width(height, width, self.movq_scale_factor) - latents = self.prepare_latents( - latents, latent_timestep, batch_size, num_images_per_prompt, image_embeds.dtype, device, generator - ) - for i, t in enumerate(self.progress_bar(timesteps)): - # expand the latents if we are doing classifier free guidance - latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents - - added_cond_kwargs = {"image_embeds": image_embeds} - noise_pred = self.unet( - sample=latent_model_input, - timestep=t, - encoder_hidden_states=None, - added_cond_kwargs=added_cond_kwargs, - return_dict=False, - )[0] - - if do_classifier_free_guidance: - noise_pred, variance_pred = noise_pred.split(latents.shape[1], dim=1) - noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) - _, variance_pred_text = variance_pred.chunk(2) - noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) - noise_pred = torch.cat([noise_pred, variance_pred_text], dim=1) - - if not ( - hasattr(self.scheduler.config, "variance_type") - and self.scheduler.config.variance_type in ["learned", "learned_range"] - ): - noise_pred, _ = noise_pred.split(latents.shape[1], dim=1) - - # compute the previous noisy sample x_t -> x_t-1 - latents = self.scheduler.step( - noise_pred, - t, - latents, - generator=generator, - )[0] - - if callback is not None and i % callback_steps == 0: - callback(i, t, latents) - - # post-processing - image = self.movq.decode(latents, force_not_quantize=True)["sample"] - - # Offload all models - self.maybe_free_model_hooks() - - if output_type not in ["pt", "np", "pil"]: - raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}") - - if output_type in ["np", "pil"]: - image = image * 0.5 + 0.5 - image = image.clamp(0, 1) - image = image.cpu().permute(0, 2, 3, 1).float().numpy() - - if output_type == "pil": - image = self.numpy_to_pil(image) - - if not return_dict: - return (image,) - - return ImagePipelineOutput(images=image) diff --git a/spaces/paufeldman/vv/modelovae.py b/spaces/paufeldman/vv/modelovae.py deleted file mode 100644 index e61ae1f0269690ec9d4c7b9063dc456a1914934b..0000000000000000000000000000000000000000 --- a/spaces/paufeldman/vv/modelovae.py +++ /dev/null @@ -1,661 +0,0 @@ -import torch -from torch import nn -import torch -torch.manual_seed(125) -import random -random.seed(125) -import numpy as np -import torch_f as torch_f - -use_gpu = True -device = torch.device("cuda:0" if use_gpu and torch.cuda.is_available() else "cpu") - -def traverse(root, tree): - - if root is not None: - traverse(root.left, tree) - tree.append((root.radius, root.data)) - traverse(root.right, tree) - return tree - -def count_fn(f): - def wrapper(*args, **kwargs): - wrapper.count += 1 - return f(*args, **kwargs) - wrapper.count = 0 - return wrapper - -@count_fn -def createNode(data, radius, left = None, right = None, ): - """ - Utility function to create a node. - """ - return Node(data, radius, left, right) - -def deserialize(data): - if not data: - return - nodes = data.split(';') - def post_order(nodes): - if nodes[-1] == '#': - nodes.pop() - return None - node = nodes.pop().split('_') - data = int(node[0]) - radius = node[1] - rad = radius.split(",") - rad [0] = rad[0].replace('[','') - rad [3] = rad[3].replace(']','') - r = [] - for value in rad: - r.append(float(value)) - r = torch.tensor(r, device=device) - root = createNode(data, r) - root.right = post_order(nodes) - root.left = post_order(nodes) - - return root - return post_order(nodes) - - -def read_tree(filename, dir): - with open('./' +dir +'/' +filename, "r") as f: - byte = f.read() - return byte - -def numerarNodos(root, count): - if root is not None: - numerarNodos(root.left, count) - root.data = len(count) - count.append(1) - numerarNodos(root.right, count) - return - - -def traverseFeatures(root, features): - - if root is not None: - traverseFeatures(root.left, features) - features.append(root.radius) - traverseFeatures(root.right, features) - return features - - -def searchNode(node, key): - - if (node == None): - return False - if (node.data == key): - return node - - """ then recur on left subtree """ - res1 = searchNode(node.left, key) - # node found, no need to look further - if res1: - return res1 - - """ node is not found in left, - so recur on right subtree """ - res2 = searchNode(node.right, key) - return res2 - -def getLevelUtil(node, data, level): - if (node == None): - return 0 - - if (node.data == data): - return level - - downlevel = getLevelUtil(node.left, data, level + 1) - - if (downlevel != 0): - return downlevel - - downlevel = getLevelUtil(node.right, data, level + 1) - return downlevel - -# Returns level of given data value - - -def getLevel(node, data): - return getLevelUtil(node, data, 1) - - -def setLevel(data_loader): - for d in data_loader: - for data in d: - max_level = 0 - tree = list(data.keys())[0] - n_nodes = data[tree]#[0] - count = [] - numerarNodos(tree, count) - for x in range(0, n_nodes): - level = getLevel(tree, x) - if level > max_level: - max_level = level - if (level): - node = searchNode(tree, x) - node.level = getLevel(tree, x) - else: - print(x, "is not present in tree") - tree_level = [] - tree.getTreeLevel(tree, tree_level) - tree_level = [max_level - nodelevel for nodelevel in tree_level] - tree.setTreeLevel(tree, sum(tree_level)) - tree.setMaxLevel(tree, max_level) - -def StructureLoss(cl_p, original, mult): - - if original is None: - return - ce = nn.CrossEntropyLoss(weight = mult) - - if original.childs() == 0: - vector = [1, 0, 0] - if original.childs() == 1: - vector = [0, 1, 0] - if original.childs() == 2: - vector = [0, 0, 1] - - c = ce(cl_p, torch.tensor(vector, device=device, dtype = torch.float).reshape(1, 3)) - return c - -def numberNodes(data_loader, batch_size): - n_no = [] - qzero = 0 - qOne = 0 - qtwo = 0 - for batch in data_loader: - for treed in batch: - tree = list(treed.keys())[0] - n = treed[tree] - n_no.append(n) - li = [] - tree.traverseInorderChilds(tree, li) - zero = [a for a in li if a == 0] - one = [a for a in li if a == 1] - two = [a for a in li if a == 2] - qzero += len(zero) - qOne += len(one) - qtwo += len(two) - - qzero /= len(data_loader)*batch_size - qOne /= len(data_loader)*batch_size - qtwo /= len(data_loader)*batch_size - if round(qzero) == 0: - qzero = 1 - if round(qOne) == 0: - qOne = 1 - if round(qtwo) == 0: - qtwo = 1 - mult = torch.tensor([1/round(qzero),1/round(qOne),1/round(qtwo)], device = device) - return mult - - -class Node: - """ - Class Node - """ - def __init__(self, value, radius, left = None, right = None, level = None, treelevel = None, maxlevel = None): - self.left = left - self.data = value - self.radius = radius - self.right = right - self.children = [self.left, self.right] - self.level = level - self.treelevel = treelevel - self.maxlevel = maxlevel - - def agregarHijo(self, children): - - if self.right is None: - self.right = children - elif self.left is None: - self.left = children - - else: - raise ValueError ("solo arbol binario ") - - - def isLeaf(self): - if self.right is None and self.left is None: - return True - else: - return False - - def isTwoChild(self): - if self.right is not None and self.left is not None: - return True - else: - return False - - def isOneChild(self): - if self.isTwoChild(): - return False - elif self.isLeaf(): - return False - else: - return True - - def childs(self): - if self.isLeaf(): - return 0 - if self.isOneChild(): - return 1 - else: - return 2 - - - def traverseInorder(self, root): - """ - traverse function will print all the node in the tree. - """ - if root is not None: - self.traverseInorder(root.left) - print (root.data, root.radius) - self.traverseInorder(root.right) - - - - def traverseInorderwl(self, root): - """ - traverse function will print all the node in the tree, including node level and tree level. - """ - if root is not None: - self.traverseInorderwl(root.left) - print (root.data, root.radius, root.level, root.treelevel) - self.traverseInorderwl(root.right) - - def getTreeLevel(self, root, c): - """ - - """ - if root is not None: - self.getTreeLevel(root.left, c) - c.append(root.level) - self.getTreeLevel(root.right, c) - - def setTreeLevel(self, root, c): - """ - - """ - if root is not None: - self.setTreeLevel(root.left, c) - root.treelevel = c - self.setTreeLevel(root.right, c) - - def setMaxLevel(self, root, m): - """ - - """ - if root is not None: - self.setMaxLevel(root.left, m) - root.maxlevel = m - self.setMaxLevel(root.right, m) - - - - def traverseInorderChilds(self, root, l): - """ - - """ - if root is not None: - self.traverseInorderChilds(root.left, l) - l.append(root.childs()) - self.traverseInorderChilds(root.right, l) - return l - - - - def height(self, root): - # Check if the binary tree is empty - if root is None: - return 0 - # Recursively call height of each node - leftAns = self.height(root.left) - rightAns = self.height(root.right) - - # Return max(leftHeight, rightHeight) at each iteration - return max(leftAns, rightAns) + 1 - - # Print nodes at a current level - def printCurrentLevel(self, root, level): - if root is None: - return - if level == 1: - print(root.data, end=" ") - elif level > 1: - self.printCurrentLevel(root.left, level-1) - self.printCurrentLevel(root.right, level-1) - - def printLevelOrder(self, root): - h = self.height(root) - for i in range(1, h+1): - self.printCurrentLevel(root, i) - - - def countNodes(self, root, counter): - if root is not None: - self.countNodes(root.left, counter) - counter.append(root.data) - self.countNodes(root.right, counter) - return counter - - - def serialize(self, root): - def post_order(root): - if root: - post_order(root.left) - post_order(root.right) - ret[0] += str(root.data)+'_'+ str(root.radius) +';' - - else: - ret[0] += '#;' - - ret = [''] - post_order(root) - return ret[0][:-1] # remove last , - - def toGraph( self, graph, index, dec, flag, proc=True): - - radius = self.radius.cpu().detach().numpy() - if dec: - radius= radius[0] - - if flag == 0: - b = True - flag = 1 - else: - b = False - graph.add_nodes_from( [ (self.data, {'posicion': radius[0:3], 'radio': radius[3], 'root': b} ) ]) - - - if self.right is not None: - self.right.toGraph( graph, index + 1, dec, flag = 1)# - graph.add_edge( self.data, self.right.data ) - - if self.left is not None: - self.left.toGraph( graph, 0, dec, flag = 1)# - - graph.add_edge( self.data, self.left.data) - - else: - return - -class Sampler(nn.Module): - - def __init__(self, feature_size, hidden_size): - super(Sampler, self).__init__() - self.mlp1 = nn.Linear(feature_size, hidden_size) - self.mlp2mu = nn.Linear(hidden_size, feature_size) - self.mlp2var = nn.Linear(hidden_size, feature_size) - self.LeakyReLu = nn.LeakyReLU() - self.latent_dim = feature_size - - - def forward(self, input): - encode = self.LeakyReLu(self.mlp1(input)) - mu = self.mlp2mu(encode) - logvar = self.mlp2var(encode) - - - std = logvar.mul(0.5).exp_() # calculate the STDEV - eps = torch.Tensor(std.size()).normal_().cuda() # random normalized noise - - KLD_element = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp()) - - if self.training: - out = torch.cat([eps.mul(std).add_(mu), KLD_element], 1) - else: - out = mu - return out - -class InternalEncoder(nn.Module): - - def __init__(self, input_size: int, feature_size: int, hidden_size: int): - super(InternalEncoder, self).__init__() - - # Encoders atributos - self.attribute_lin_encoder_1 = nn.Linear(input_size,hidden_size) - self.attribute_lin_encoder_2 = nn.Linear(hidden_size,feature_size) - - # Encoders derecho e izquierdo - self.right_lin_encoder_1 = nn.Linear(feature_size,hidden_size) - self.right_lin_encoder_2 = nn.Linear(hidden_size,feature_size) - - - self.left_lin_encoder_1 = nn.Linear(feature_size,hidden_size) - self.left_lin_encoder_2 = nn.Linear(hidden_size,feature_size) - - # Encoder final - self.final_lin_encoder_1 = nn.Linear(2*feature_size, feature_size) - - # Funciones / Parametros utiles - self.LeakyReLu = nn.LeakyReLU() - self.feature_size = feature_size - - - def forward(self, input, right_input, left_input): - device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") - # Encodeo los atributos - attributes = self.attribute_lin_encoder_1(input) - attributes = self.LeakyReLu(attributes) - - attributes = self.attribute_lin_encoder_2(attributes) - attributes = self.LeakyReLu(attributes) - - - # Encodeo el derecho - if right_input is not None: - context = self.right_lin_encoder_1(right_input) - context = self.LeakyReLu(context) - context = self.right_lin_encoder_2(context) - context = self.LeakyReLu(context) - - # Encodeo el izquierdo - if left_input is not None: - left = self.left_lin_encoder_1(left_input) - #print("izquierdo", left.shape) - left = self.LeakyReLu(left) - context += self.left_lin_encoder_2(left) - context = self.LeakyReLu(context) - else: - context = torch.zeros(input.shape[0],self.feature_size, requires_grad=True, device=device) - - feature = torch.cat((attributes,context), 1) - feature = self.final_lin_encoder_1(feature) - feature = self.LeakyReLu(feature) - return feature - -class GRASSEncoder(nn.Module): - - def __init__(self, input_size: int, feature_size : int, hidden_size: int): - super(GRASSEncoder, self).__init__() - self.leaf_encoder = InternalEncoder(input_size,feature_size, hidden_size) - self.internal_encoder = InternalEncoder(input_size,feature_size, hidden_size) - self.bifurcation_encoder = InternalEncoder(input_size,feature_size, hidden_size) - self.sample_encoder = Sampler(feature_size = feature_size, hidden_size = hidden_size) - - def leafEncoder(self, node, right=None, left = None): - return self.internal_encoder(node, right, left) - def internalEncoder(self, node, right, left = None): - return self.internal_encoder(node, right, left) - def bifurcationEncoder(self, node, right, left): - return self.bifurcation_encoder(node, right, left) - def sampleEncoder(self, feature): - return self.sample_encoder(feature) - -class NodeClassifier(nn.Module): - - def __init__(self, latent_size : int, hidden_size : int): - super(NodeClassifier, self).__init__() - self.mlp1 = nn.Linear(latent_size, hidden_size) - self.mlp2 = nn.Linear(hidden_size, hidden_size) - self.mlp3 = nn.Linear(hidden_size, 3) - self.LeakyReLu = nn.LeakyReLU() - - def forward(self, input_feature): - output = self.mlp1(input_feature) - output = self.LeakyReLu(output) - output = self.mlp2(output) - output = self.LeakyReLu(output) - output = self.mlp3(output) - return output - -class SampleDecoder(nn.Module): - """ Decode a randomly sampled noise into a feature vector """ - def __init__(self, feature_size, hidden_size): - super(SampleDecoder, self).__init__() - self.mlp1 = nn.Linear(feature_size, hidden_size) - self.mlp2 = nn.Linear(hidden_size, hidden_size) - self.mlp3 = nn.Linear(hidden_size, feature_size) - #self.mlp4 = nn.Linear(hidden_size, feature_size) - #self.mlp5 = nn.Linear(feature_size, feature_size) - #self.dropout = nn.Dropout(0.1) - - self.LeakyReLu = nn.LeakyReLU() - self.tanh = nn.Tanh() - - def forward(self, input_feature): - output = self.LeakyReLu(self.mlp1(input_feature)) - #output = self.dropout (output) - output = self.tanh(self.mlp2(output)) - output = self.tanh(self.mlp3(output)) - #output = self.LeakyReLu(self.mlp4(output)) - #output = self.LeakyReLu(self.mlp5(output)) - - return output - - -class Decoder(nn.Module): - - """ Decode an input (parent) feature into a left-child and a right-child feature """ - def __init__(self, latent_size : int, hidden_size : int): - super(Decoder, self).__init__() - - self.mlp = nn.Linear(latent_size,hidden_size) - self.mlp_left = nn.Linear(hidden_size, hidden_size) - self.mlp_left2 = nn.Linear(hidden_size, latent_size) - self.mlp_right = nn.Linear(hidden_size, hidden_size) - self.mlp_right2 = nn.Linear(hidden_size, latent_size) - self.mlp2 = nn.Linear(hidden_size,latent_size) - self.mlp3 = nn.Linear(latent_size,4) - self.LeakyReLu = nn.LeakyReLU() - - def common_branch(self, parent_feature): - - vector = self.mlp(parent_feature) - vector = self.LeakyReLu(vector) - return vector - - def attr_branch(self, vector): - vector = self.mlp2(vector) - vector = self.LeakyReLu(vector) - vector = self.mlp3(vector) - vector = self.LeakyReLu(vector) - return vector - - def right_branch(self, vector): - right_feature = self.mlp_right(vector) - right_feature = self.LeakyReLu(right_feature) - right_feature = self.mlp_right2(right_feature) - right_feature = self.LeakyReLu(right_feature) - return right_feature - - def left_branch(self, vector): - left_feature = self.mlp_left(vector) - left_feature = self.LeakyReLu(left_feature) - left_feature = self.mlp_left2(left_feature) - left_feature = self.LeakyReLu(left_feature) - return left_feature - - def forward(self, parent_feature): - - vector = self.common_branch(parent_feature) - attr_vector = self.attr_branch(vector) - - return attr_vector - - def forward1(self, parent_feature): - - vector = self.common_branch(parent_feature) - attr_vector = self.attr_branch(vector) - right_vector = self.right_branch(vector) - return right_vector, attr_vector - - def forward2(self, parent_feature): - - - vector = self.common_branch(parent_feature) - attr_vector = self.attr_branch(vector) - right_vector = self.right_branch(vector) - left_vector = self.left_branch(vector) - return left_vector, right_vector, attr_vector - - -alfa = 0.3 -class GRASSDecoder(nn.Module): - def __init__(self, latent_size : int, hidden_size: int, mult: torch.Tensor): - super(GRASSDecoder, self).__init__() - self.decoder = Decoder(latent_size, hidden_size) - self.node_classifier = NodeClassifier(latent_size, hidden_size) - self.sample_decoder = SampleDecoder(feature_size = latent_size, hidden_size = hidden_size) - self.mseLoss = nn.MSELoss() # pytorch's mean squared error loss - self.ceLoss = nn.CrossEntropyLoss(weight = mult) # pytorch's cross entropy loss (NOTE: no softmax is needed before) - - - def featureDecoder(self, feature): - return self.decoder.forward(feature) - - def internalDecoder(self, feature): - return self.decoder.forward1(feature) - - def bifurcationDecoder(self, feature): - return self.decoder.forward2(feature) - - def nodeClassifier(self, feature): - return self.node_classifier(feature) - - def sampleDecoder(self, feature): - return self.sample_decoder(feature) - - def calcularLossAtributo(self, nodo, radio): - - if nodo is None: - return - else: - nodo = torch.stack(nodo) - l = [self.mseLoss(b.reshape(1,4), gt.reshape(1,4)).mul(1-alfa) for b, gt in zip(radio.reshape(-1,4), nodo.reshape(-1,4))] - return l - - - def classifyLossEstimator(self, label_vector, original): - device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") - if original is None: - return - else: - - v = [] - for o in original: - if o == 0: - vector = torch.tensor([1, 0, 0], device = device, dtype = torch.float) - if o == 1: - vector = torch.tensor([0, 1, 0], device = device, dtype = torch.float) - if o == 2: - vector = torch.tensor([0, 0, 1], device = device, dtype = torch.float) - v.append(vector) - - v = torch.stack(v) - l = [self.ceLoss(b.reshape(1,3), gt.reshape(1,3)).mul(alfa) for b, gt in zip(label_vector.reshape(-1,3), v.reshape(-1,3))] - return l - - def vectorAdder(self, v1, v2): - v = v1.add(v2) - return v - - def vectorMult(self, m, v): - z = zip(v, m) - r = [] - for c, d in z: - r.append(torch.mul(c, d)) - return r \ No newline at end of file diff --git a/spaces/paulengstler/interpretable-vertebral-fracture-diagnosis/netdissect/fullablate.py b/spaces/paulengstler/interpretable-vertebral-fracture-diagnosis/netdissect/fullablate.py deleted file mode 100644 index 4f89381c6ec3119bc4fa3d1de3a5b92c14b62cc5..0000000000000000000000000000000000000000 --- a/spaces/paulengstler/interpretable-vertebral-fracture-diagnosis/netdissect/fullablate.py +++ /dev/null @@ -1,218 +0,0 @@ -import torch, sys, os, argparse, textwrap, numbers, numpy, json, PIL -from torchvision import transforms -from torch.utils.data import TensorDataset -from netdissect import pbar -from netdissect.nethook import edit_layers -from netdissect.zdataset import standard_z_sample -from netdissect.autoeval import autoimport_eval -from netdissect.easydict import EasyDict -from netdissect.modelconfig import create_instrumented_model - -help_epilog = '''\ -Example: - -python -m netdissect.evalablate \ - --segmenter "netdissect.GanImageSegmenter(segvocab='lowres', segsizes=[160,288], segdiv='quad')" \ - --model "proggan.from_pth_file('models/lsun_models/${SCENE}_lsun.pth')" \ - --outdir dissect/dissectdir \ - --classname tree \ - --layer layer4 \ - --size 1000 - -Output layout: -dissectdir/layer5/ablation/mirror-iqr.json -{ class: "mirror", - classnum: 43, - pixel_total: 41342300, - class_pixels: 1234531, - layer: "layer5", - ranking: "mirror-iqr", - ablation_units: [341, 23, 12, 142, 83, ...] - ablation_pixels: [143242, 132344, 429931, ...] -} - -''' - -def main(): - # Training settings - def strpair(arg): - p = tuple(arg.split(':')) - if len(p) == 1: - p = p + p - return p - - parser = argparse.ArgumentParser(description='Ablation eval', - epilog=textwrap.dedent(help_epilog), - formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument('--model', type=str, default=None, - help='constructor for the model to test') - parser.add_argument('--pthfile', type=str, default=None, - help='filename of .pth file for the model') - parser.add_argument('--outdir', type=str, default='dissect', required=True, - help='directory for dissection output') - parser.add_argument('--layer', type=strpair, - help='space-separated list of layer names to edit' + - ', in the form layername[:reportedname]') - parser.add_argument('--classname', type=str, - help='class name to ablate') - parser.add_argument('--metric', type=str, default='iou', - help='ordering metric for selecting units') - parser.add_argument('--unitcount', type=int, default=30, - help='number of units to ablate') - parser.add_argument('--segmenter', type=str, - help='directory containing segmentation dataset') - parser.add_argument('--netname', type=str, default=None, - help='name for network in generated reports') - parser.add_argument('--batch_size', type=int, default=25, - help='batch size for forward pass') - parser.add_argument('--mixed_units', action='store_true', default=False, - help='true to keep alpha for non-zeroed units') - parser.add_argument('--size', type=int, default=200, - help='number of images to test') - parser.add_argument('--no-cuda', action='store_true', default=False, - help='disables CUDA usage') - parser.add_argument('--quiet', action='store_true', default=False, - help='silences console output') - if len(sys.argv) == 1: - parser.print_usage(sys.stderr) - sys.exit(1) - args = parser.parse_args() - - # Set up console output - pbar.verbose(not args.quiet) - - # Speed up pytorch - torch.backends.cudnn.benchmark = True - - # Set up CUDA - args.cuda = not args.no_cuda and torch.cuda.is_available() - if args.cuda: - torch.backends.cudnn.benchmark = True - - # Take defaults for model constructor etc from dissect.json settings. - with open(os.path.join(args.outdir, 'dissect.json')) as f: - dissection = EasyDict(json.load(f)) - if args.model is None: - args.model = dissection.settings.model - if args.pthfile is None: - args.pthfile = dissection.settings.pthfile - if args.segmenter is None: - args.segmenter = dissection.settings.segmenter - if args.layer is None: - args.layer = dissection.settings.layers[0] - args.layers = [args.layer] - - # Also load specific analysis - layername = args.layer[1] - if args.metric == 'iou': - summary = dissection - else: - with open(os.path.join(args.outdir, layername, args.metric, - args.classname, 'summary.json')) as f: - summary = EasyDict(json.load(f)) - - # Instantiate generator - model = create_instrumented_model(args, gen=True, edit=True) - if model is None: - print('No model specified') - sys.exit(1) - - # Instantiate model - device = next(model.parameters()).device - input_shape = model.input_shape - - # 4d input if convolutional, 2d input if first layer is linear. - raw_sample = standard_z_sample(args.size, input_shape[1], seed=3).view( - (args.size,) + input_shape[1:]) - dataset = TensorDataset(raw_sample) - - # Create the segmenter - segmenter = autoimport_eval(args.segmenter) - - # Now do the actual work. - labelnames, catnames = ( - segmenter.get_label_and_category_names(dataset)) - label_category = [catnames.index(c) if c in catnames else 0 - for l, c in labelnames] - labelnum_from_name = {n[0]: i for i, n in enumerate(labelnames)} - - segloader = torch.utils.data.DataLoader(dataset, - batch_size=args.batch_size, num_workers=10, - pin_memory=(device.type == 'cuda')) - - # Index the dissection layers by layer name. - - # First, collect a baseline - for l in model.ablation: - model.ablation[l] = None - - # For each sort-order, do an ablation - classname = args.classname - classnum = labelnum_from_name[classname] - - # Get iou ranking from dissect.json - iou_rankname = '%s-%s' % (classname, 'iou') - dissect_layer = {lrec.layer: lrec for lrec in dissection.layers} - iou_ranking = next(r for r in dissect_layer[layername].rankings - if r.name == iou_rankname) - - # Get trained ranking from summary.json - rankname = '%s-%s' % (classname, args.metric) - summary_layer = {lrec.layer: lrec for lrec in summary.layers} - ranking = next(r for r in summary_layer[layername].rankings - if r.name == rankname) - - # Get ordering, first by ranking, then break ties by iou. - ordering = [t[2] for t in sorted([(s1, s2, i) - for i, (s1, s2) in enumerate(zip(ranking.score, iou_ranking.score))])] - values = (-numpy.array(ranking.score))[ordering] - if not args.mixed_units: - values[...] = 1 - - ablationdir = os.path.join(args.outdir, layername, 'fullablation') - measurements = measure_full_ablation(segmenter, segloader, - model, classnum, layername, - ordering[:args.unitcount], values[:args.unitcount]) - measurements = measurements.cpu().numpy().tolist() - os.makedirs(ablationdir, exist_ok=True) - with open(os.path.join(ablationdir, '%s.json'%rankname), 'w') as f: - json.dump(dict( - classname=classname, - classnum=classnum, - baseline=measurements[0], - layer=layername, - metric=args.metric, - ablation_units=ordering, - ablation_values=values.tolist(), - ablation_effects=measurements[1:]), f) - -def measure_full_ablation(segmenter, loader, model, classnum, layer, - ordering, values): - ''' - Quick and easy counting of segmented pixels reduced by ablating units. - ''' - device = next(model.parameters()).device - feature_units = model.feature_shape[layer][1] - feature_shape = model.feature_shape[layer][2:] - repeats = len(ordering) - total_scores = torch.zeros(repeats + 1) - print(ordering) - print(values.tolist()) - with torch.no_grad(): - for l in model.ablation: - model.ablation[l] = None - for i, [ibz] in enumerate(pbar(loader)): - ibz = ibz.cuda() - for num_units in pbar(range(len(ordering) + 1)): - ablation = torch.zeros(feature_units, device=device) - ablation[ordering[:num_units]] = torch.tensor( - values[:num_units]).to(ablation.device, ablation.dtype) - model.ablation[layer] = ablation - tensor_images = model(ibz) - seg = segmenter.segment_batch(tensor_images, downsample=2) - mask = (seg == classnum).max(1)[0] - total_scores[num_units] += mask.sum().float().cpu() - return total_scores - -if __name__ == '__main__': - main() diff --git a/spaces/paulengstler/interpretable-vertebral-fracture-diagnosis/netdissect/statedict.py b/spaces/paulengstler/interpretable-vertebral-fracture-diagnosis/netdissect/statedict.py deleted file mode 100644 index 858a903b57724d9e3a17b8150beea30bdc206b97..0000000000000000000000000000000000000000 --- a/spaces/paulengstler/interpretable-vertebral-fracture-diagnosis/netdissect/statedict.py +++ /dev/null @@ -1,100 +0,0 @@ -''' -Utilities for dealing with simple state dicts as npz files instead of pth files. -''' - -import torch -from collections.abc import MutableMapping, Mapping - -def load_from_numpy_dict(model, numpy_dict, prefix='', examples=None): - ''' - Loads a model from numpy_dict using load_state_dict. - Converts numpy types to torch types using the current state_dict - of the model to determine types and devices for the tensors. - Supports loading a subdict by prepending the given prefix to all keys. - ''' - if prefix: - if not prefix.endswith('.'): - prefix = prefix + '.' - numpy_dict = PrefixSubDict(numpy_dict, prefix) - if examples is None: - exampels = model.state_dict() - torch_state_dict = TorchTypeMatchingDict(numpy_dict, examples) - model.load_state_dict(torch_state_dict) - -def save_to_numpy_dict(model, numpy_dict, prefix=''): - ''' - Saves a model by copying tensors to numpy_dict. - Converts torch types to numpy types using `t.detach().cpu().numpy()`. - Supports saving a subdict by prepending the given prefix to all keys. - ''' - if prefix: - if not prefix.endswith('.'): - prefix = prefix + '.' - for k, v in model.numpy_dict().items(): - if isinstance(v, torch.Tensor): - v = v.detach().cpu().numpy() - numpy_dict[prefix + k] = v - -class TorchTypeMatchingDict(Mapping): - ''' - Provides a view of a dict of numpy values as torch tensors, where the - types are converted to match the types and devices in the given - dict of examples. - ''' - def __init__(self, data, examples): - self.data = data - self.examples = examples - self.cached_data = {} - def __getitem__(self, key): - if key in self.cached_data: - return self.cached_data[key] - val = self.data[key] - if key not in self.examples: - return val - example = self.examples.get(key, None) - example_type = type(example) - if example is not None and type(val) != example_type: - if isinstance(example, torch.Tensor): - val = torch.from_numpy(val) - else: - val = example_type(val) - if isinstance(example, torch.Tensor): - val = val.to(dtype=example.dtype, device=example.device) - self.cached_data[key] = val - return val - def __iter__(self): - return self.data.keys() - def __len__(self): - return len(self.data) - -class PrefixSubDict(MutableMapping): - ''' - Provides a view of the subset of a dict where string keys begin with - the given prefix. The prefix is stripped from all keys of the view. - ''' - def __init__(self, data, prefix=''): - self.data = data - self.prefix = prefix - self._cached_keys = None - def __getitem__(self, key): - return self.data[self.prefix + key] - def __setitem__(self, key, value): - pkey = self.prefix + key - if self._cached_keys is not None and pkey not in self.data: - self._cached_keys = None - self.data[pkey] = value - def __delitem__(self, key): - pkey = self.prefix + key - if self._cached_keys is not None and pkey in self.data: - self._cached_keys = None - del self.data[pkey] - def __cached_keys(self): - if self._cached_keys is None: - plen = len(self.prefix) - self._cached_keys = list(k[plen:] for k in self.data - if k.startswith(self.prefix)) - return self._cached_keys - def __iter__(self): - return iter(self.__cached_keys()) - def __len__(self): - return len(self.__cached_keys()) diff --git a/spaces/pierreguillou/Inference-APP-Document-Understanding-at-linelevel-v2/README.md b/spaces/pierreguillou/Inference-APP-Document-Understanding-at-linelevel-v2/README.md deleted file mode 100644 index 30b84e8b9e4b4bbbd61ada4eb52a4961f8d97e96..0000000000000000000000000000000000000000 --- a/spaces/pierreguillou/Inference-APP-Document-Understanding-at-linelevel-v2/README.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Document Understanding Inference APP (v2 - line level - LayoutXLM base) -emoji: 🐢 -colorFrom: blue -colorTo: yellow -sdk: gradio -sdk_version: 3.18.0 -app_file: app.py -pinned: false -models: -- >- - pierreguillou/layout-xlm-base-finetuned-with-DocLayNet-base-at-linelevel-ml384 -duplicated_from: pierreguillou/Inference-APP-Document-Understanding-at-linelevel-v1 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/pierreguillou/question-answering-portuguese/app.py b/spaces/pierreguillou/question-answering-portuguese/app.py deleted file mode 100644 index 0057ecbe49c80dc29b4a6ec73f050d1027246ef1..0000000000000000000000000000000000000000 --- a/spaces/pierreguillou/question-answering-portuguese/app.py +++ /dev/null @@ -1,19 +0,0 @@ -import gradio as gr - -title = "QA App | BERT base finetuned on SQuAD 1.1 in Portuguese" -description = "Forneça seu próprio parágrafo e faça perguntas sobre o texto. Quão bem o modelo responde? (este aplicativo usa o modelo https://huggingface.co/pierreguillou/bert-base-cased-squad-v1.1-portuguese)" -article = f"" - -context = "A pandemia de COVID-19, também conhecida como pandemia de coronavírus, é uma pandemia em curso de COVID-19, uma doença respiratória aguda causada pelo coronavírus da síndrome respiratória aguda grave 2 (SARS-CoV-2). A doença foi identificada pela primeira vez em Wuhan, na província de Hubei, República Popular da China, em 1 de dezembro de 2019, mas o primeiro caso foi reportado em 31 de dezembro do mesmo ano." - -question = "Quando começou a pandemia de Covid-19 no mundo?" - -gr.Interface.load( - "huggingface/pierreguillou/bert-base-cased-squad-v1.1-portuguese", - css=".footer {display:none !important}", - inputs=[gr.inputs.Textbox(lines=7, default=context, label="Context paragraph"), gr.inputs.Textbox(lines=2, default=question, label="Question")], - outputs=[gr.outputs.Textbox(label="Answer"), gr.outputs.Textbox(label="Score")], - title=title, - description=description, - article=article, - ).launch() \ No newline at end of file diff --git a/spaces/pix2pix-zero-library/pix2pix-zero-demo/submodules/pix2pix-zero/src/utils/base_pipeline.py b/spaces/pix2pix-zero-library/pix2pix-zero-demo/submodules/pix2pix-zero/src/utils/base_pipeline.py deleted file mode 100644 index ff084fbfc70d90aa70dcbcf516d35ed2882624ec..0000000000000000000000000000000000000000 --- a/spaces/pix2pix-zero-library/pix2pix-zero-demo/submodules/pix2pix-zero/src/utils/base_pipeline.py +++ /dev/null @@ -1,322 +0,0 @@ - -import torch -import inspect -from packaging import version -from typing import Any, Callable, Dict, List, Optional, Union - -from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer -from diffusers import DiffusionPipeline -from diffusers.models import AutoencoderKL, UNet2DConditionModel -from diffusers.schedulers import KarrasDiffusionSchedulers -from diffusers.utils import deprecate, is_accelerate_available, logging, randn_tensor, replace_example_docstring -from diffusers import StableDiffusionPipeline -from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker - - - -class BasePipeline(DiffusionPipeline): - _optional_components = ["safety_checker", "feature_extractor"] - def __init__( - self, - vae: AutoencoderKL, - text_encoder: CLIPTextModel, - tokenizer: CLIPTokenizer, - unet: UNet2DConditionModel, - scheduler: KarrasDiffusionSchedulers, - safety_checker: StableDiffusionSafetyChecker, - feature_extractor: CLIPFeatureExtractor, - requires_safety_checker: bool = True, - ): - super().__init__() - - if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" - f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " - "to update the config accordingly as leaving `steps_offset` might led to incorrect results" - " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," - " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" - " file" - ) - deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["steps_offset"] = 1 - scheduler._internal_dict = FrozenDict(new_config) - - if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: - deprecation_message = ( - f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." - " `clip_sample` should be set to False in the configuration file. Please make sure to update the" - " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" - " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" - " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" - ) - deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(scheduler.config) - new_config["clip_sample"] = False - scheduler._internal_dict = FrozenDict(new_config) - - if safety_checker is None and requires_safety_checker: - logger.warning( - f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" - " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" - " results in services or applications open to the public. Both the diffusers team and Hugging Face" - " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" - " it only for use-cases that involve analyzing network behavior or auditing its results. For more" - " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." - ) - - if safety_checker is not None and feature_extractor is None: - raise ValueError( - "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" - " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." - ) - - is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( - version.parse(unet.config._diffusers_version).base_version - ) < version.parse("0.9.0.dev0") - is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 - if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: - deprecation_message = ( - "The configuration file of the unet has set the default `sample_size` to smaller than" - " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" - " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" - " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" - " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" - " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" - " in the config might lead to incorrect results in future versions. If you have downloaded this" - " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" - " the `unet/config.json` file" - ) - deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) - new_config = dict(unet.config) - new_config["sample_size"] = 64 - unet._internal_dict = FrozenDict(new_config) - - self.register_modules( - vae=vae, - text_encoder=text_encoder, - tokenizer=tokenizer, - unet=unet, - scheduler=scheduler, - safety_checker=safety_checker, - feature_extractor=feature_extractor, - ) - self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) - self.register_to_config(requires_safety_checker=requires_safety_checker) - - @property - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device - def _execution_device(self): - r""" - Returns the device on which the pipeline's models will be executed. After calling - `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module - hooks. - """ - if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"): - return self.device - for module in self.unet.modules(): - if ( - hasattr(module, "_hf_hook") - and hasattr(module._hf_hook, "execution_device") - and module._hf_hook.execution_device is not None - ): - return torch.device(module._hf_hook.execution_device) - return self.device - - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt - def _encode_prompt( - self, - prompt, - device, - num_images_per_prompt, - do_classifier_free_guidance, - negative_prompt=None, - prompt_embeds: Optional[torch.FloatTensor] = None, - negative_prompt_embeds: Optional[torch.FloatTensor] = None, - ): - r""" - Encodes the prompt into text encoder hidden states. - - Args: - prompt (`str` or `List[str]`, *optional*): - prompt to be encoded - device: (`torch.device`): - torch device - num_images_per_prompt (`int`): - number of images that should be generated per prompt - do_classifier_free_guidance (`bool`): - whether to use classifier free guidance or not - negative_ prompt (`str` or `List[str]`, *optional*): - The prompt or prompts not to guide the image generation. If not defined, one has to pass - `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead. - Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). - prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not - provided, text embeddings will be generated from `prompt` input argument. - negative_prompt_embeds (`torch.FloatTensor`, *optional*): - Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt - weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input - argument. - """ - if prompt is not None and isinstance(prompt, str): - batch_size = 1 - elif prompt is not None and isinstance(prompt, list): - batch_size = len(prompt) - else: - batch_size = prompt_embeds.shape[0] - - if prompt_embeds is None: - text_inputs = self.tokenizer( - prompt, - padding="max_length", - max_length=self.tokenizer.model_max_length, - truncation=True, - return_tensors="pt", - ) - text_input_ids = text_inputs.input_ids - untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids - - if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( - text_input_ids, untruncated_ids - ): - removed_text = self.tokenizer.batch_decode( - untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] - ) - logger.warning( - "The following part of your input was truncated because CLIP can only handle sequences up to" - f" {self.tokenizer.model_max_length} tokens: {removed_text}" - ) - - if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: - attention_mask = text_inputs.attention_mask.to(device) - else: - attention_mask = None - - prompt_embeds = self.text_encoder( - text_input_ids.to(device), - attention_mask=attention_mask, - ) - prompt_embeds = prompt_embeds[0] - - prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) - - bs_embed, seq_len, _ = prompt_embeds.shape - # duplicate text embeddings for each generation per prompt, using mps friendly method - prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) - prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) - - # get unconditional embeddings for classifier free guidance - if do_classifier_free_guidance and negative_prompt_embeds is None: - uncond_tokens: List[str] - if negative_prompt is None: - uncond_tokens = [""] * batch_size - elif type(prompt) is not type(negative_prompt): - raise TypeError( - f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" - f" {type(prompt)}." - ) - elif isinstance(negative_prompt, str): - uncond_tokens = [negative_prompt] - elif batch_size != len(negative_prompt): - raise ValueError( - f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" - f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" - " the batch size of `prompt`." - ) - else: - uncond_tokens = negative_prompt - - max_length = prompt_embeds.shape[1] - uncond_input = self.tokenizer( - uncond_tokens, - padding="max_length", - max_length=max_length, - truncation=True, - return_tensors="pt", - ) - - if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: - attention_mask = uncond_input.attention_mask.to(device) - else: - attention_mask = None - - negative_prompt_embeds = self.text_encoder( - uncond_input.input_ids.to(device), - attention_mask=attention_mask, - ) - negative_prompt_embeds = negative_prompt_embeds[0] - - if do_classifier_free_guidance: - # duplicate unconditional embeddings for each generation per prompt, using mps friendly method - seq_len = negative_prompt_embeds.shape[1] - - negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device) - - negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) - negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) - - # For classifier free guidance, we need to do two forward passes. - # Here we concatenate the unconditional and text embeddings into a single batch - # to avoid doing two forward passes - prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) - - return prompt_embeds - - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents - def decode_latents(self, latents): - latents = 1 / 0.18215 * latents - image = self.vae.decode(latents).sample - image = (image / 2 + 0.5).clamp(0, 1) - # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16 - image = image.detach().cpu().permute(0, 2, 3, 1).float().numpy() - return image - - def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None): - shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) - if isinstance(generator, list) and len(generator) != batch_size: - raise ValueError( - f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" - f" size of {batch_size}. Make sure the batch size matches the length of the generators." - ) - - if latents is None: - latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype) - else: - latents = latents.to(device) - - # scale the initial noise by the standard deviation required by the scheduler - latents = latents * self.scheduler.init_noise_sigma - return latents - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs - def prepare_extra_step_kwargs(self, generator, eta): - # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature - # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. - # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 - # and should be between [0, 1] - - accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) - extra_step_kwargs = {} - if accepts_eta: - extra_step_kwargs["eta"] = eta - - # check if the scheduler accepts generator - accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) - if accepts_generator: - extra_step_kwargs["generator"] = generator - return extra_step_kwargs - - # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker - def run_safety_checker(self, image, device, dtype): - if self.safety_checker is not None: - safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device) - image, has_nsfw_concept = self.safety_checker( - images=image, clip_input=safety_checker_input.pixel_values.to(dtype) - ) - else: - has_nsfw_concept = None - return image, has_nsfw_concept - diff --git a/spaces/pixiou/bingo/postcss.config.js b/spaces/pixiou/bingo/postcss.config.js deleted file mode 100644 index 33ad091d26d8a9dc95ebdf616e217d985ec215b8..0000000000000000000000000000000000000000 --- a/spaces/pixiou/bingo/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} diff --git a/spaces/pkiage/time_series_autocorrelation_demo/setup.py b/spaces/pkiage/time_series_autocorrelation_demo/setup.py deleted file mode 100644 index a1d285fe13965273e3abafe74ae025c770bed1ed..0000000000000000000000000000000000000000 --- a/spaces/pkiage/time_series_autocorrelation_demo/setup.py +++ /dev/null @@ -1,10 +0,0 @@ -from setuptools import find_packages, setup - -setup( - name='src', - packages=find_packages(), - version='0.1.0', - description='Tool demonstrating time series autocorrelation analysis with Python', - author='Author', - license='MIT', -) diff --git a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py b/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py deleted file mode 100644 index d2dddd6a106f021a4723c1e8f5953ccc09e55e1f..0000000000000000000000000000000000000000 --- a/spaces/pknez/face-swap-docker/mynewshinyroop/Lib/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py +++ /dev/null @@ -1,51 +0,0 @@ -import re - - -SPLIT_RE = re.compile(r'[\.\[\]]+') - - -class JsonSchemaException(ValueError): - """ - Base exception of ``fastjsonschema`` library. - """ - - -class JsonSchemaValueException(JsonSchemaException): - """ - Exception raised by validation function. Available properties: - - * ``message`` containing human-readable information what is wrong (e.g. ``data.property[index] must be smaller than or equal to 42``), - * invalid ``value`` (e.g. ``60``), - * ``name`` of a path in the data structure (e.g. ``data.property[index]``), - * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``), - * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``), - * ``rule`` which the ``value`` is breaking (e.g. ``maximum``) - * and ``rule_definition`` (e.g. ``42``). - - .. versionchanged:: 2.14.0 - Added all extra properties. - """ - - def __init__(self, message, value=None, name=None, definition=None, rule=None): - super().__init__(message) - self.message = message - self.value = value - self.name = name - self.definition = definition - self.rule = rule - - @property - def path(self): - return [item for item in SPLIT_RE.split(self.name) if item != ''] - - @property - def rule_definition(self): - if not self.rule or not self.definition: - return None - return self.definition.get(self.rule) - - -class JsonSchemaDefinitionException(JsonSchemaException): - """ - Exception raised by generator of validation function. - """ diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/unicode.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/unicode.py deleted file mode 100644 index a9ffeefac1c9e553c53bc12346e49e7ece8d364a..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/fontTools/unicode.py +++ /dev/null @@ -1,50 +0,0 @@ -def _makeunicodes(f): - lines = iter(f.readlines()) - unicodes = {} - for line in lines: - if not line: - continue - num, name = line.split(";")[:2] - if name[0] == "<": - continue # "", etc. - num = int(num, 16) - unicodes[num] = name - return unicodes - - -class _UnicodeCustom(object): - def __init__(self, f): - if isinstance(f, str): - with open(f) as fd: - codes = _makeunicodes(fd) - else: - codes = _makeunicodes(f) - self.codes = codes - - def __getitem__(self, charCode): - try: - return self.codes[charCode] - except KeyError: - return "????" - - -class _UnicodeBuiltin(object): - def __getitem__(self, charCode): - try: - # use unicodedata backport to python2, if available: - # https://github.com/mikekap/unicodedata2 - import unicodedata2 as unicodedata - except ImportError: - import unicodedata - try: - return unicodedata.name(chr(charCode)) - except ValueError: - return "????" - - -Unicode = _UnicodeBuiltin() - - -def setUnicodeData(f): - global Unicode - Unicode = _UnicodeCustom(f) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/backends/backend_wxcairo.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/backends/backend_wxcairo.py deleted file mode 100644 index c53e6af4b87390455d02fab1bd3060648cac7fe8..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/matplotlib/backends/backend_wxcairo.py +++ /dev/null @@ -1,23 +0,0 @@ -import wx.lib.wxcairo as wxcairo - -from .backend_cairo import cairo, FigureCanvasCairo -from .backend_wx import _BackendWx, _FigureCanvasWxBase -from .backend_wx import ( # noqa: F401 # pylint: disable=W0611 - NavigationToolbar2Wx as NavigationToolbar2WxCairo) - - -class FigureCanvasWxCairo(FigureCanvasCairo, _FigureCanvasWxBase): - def draw(self, drawDC=None): - size = self.figure.bbox.size.astype(int) - surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size) - self._renderer.set_context(cairo.Context(surface)) - self._renderer.dpi = self.figure.dpi - self.figure.draw(self._renderer) - self.bitmap = wxcairo.BitmapFromImageSurface(surface) - self._isDrawn = True - self.gui_repaint(drawDC=drawDC) - - -@_BackendWx.export -class _BackendWxCairo(_BackendWx): - FigureCanvas = FigureCanvasWxCairo diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/array_api/tests/test_elementwise_functions.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/array_api/tests/test_elementwise_functions.py deleted file mode 100644 index 1228d0af2e6a6a8ae504297c7562d3beb5ba9516..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/array_api/tests/test_elementwise_functions.py +++ /dev/null @@ -1,114 +0,0 @@ -from inspect import getfullargspec - -from numpy.testing import assert_raises - -from .. import asarray, _elementwise_functions -from .._elementwise_functions import bitwise_left_shift, bitwise_right_shift -from .._dtypes import ( - _dtype_categories, - _boolean_dtypes, - _floating_dtypes, - _integer_dtypes, -) - - -def nargs(func): - return len(getfullargspec(func).args) - - -def test_function_types(): - # Test that every function accepts only the required input types. We only - # test the negative cases here (error). The positive cases are tested in - # the array API test suite. - - elementwise_function_input_types = { - "abs": "numeric", - "acos": "floating-point", - "acosh": "floating-point", - "add": "numeric", - "asin": "floating-point", - "asinh": "floating-point", - "atan": "floating-point", - "atan2": "real floating-point", - "atanh": "floating-point", - "bitwise_and": "integer or boolean", - "bitwise_invert": "integer or boolean", - "bitwise_left_shift": "integer", - "bitwise_or": "integer or boolean", - "bitwise_right_shift": "integer", - "bitwise_xor": "integer or boolean", - "ceil": "real numeric", - "conj": "complex floating-point", - "cos": "floating-point", - "cosh": "floating-point", - "divide": "floating-point", - "equal": "all", - "exp": "floating-point", - "expm1": "floating-point", - "floor": "real numeric", - "floor_divide": "real numeric", - "greater": "real numeric", - "greater_equal": "real numeric", - "imag": "complex floating-point", - "isfinite": "numeric", - "isinf": "numeric", - "isnan": "numeric", - "less": "real numeric", - "less_equal": "real numeric", - "log": "floating-point", - "logaddexp": "real floating-point", - "log10": "floating-point", - "log1p": "floating-point", - "log2": "floating-point", - "logical_and": "boolean", - "logical_not": "boolean", - "logical_or": "boolean", - "logical_xor": "boolean", - "multiply": "numeric", - "negative": "numeric", - "not_equal": "all", - "positive": "numeric", - "pow": "numeric", - "real": "complex floating-point", - "remainder": "real numeric", - "round": "numeric", - "sign": "numeric", - "sin": "floating-point", - "sinh": "floating-point", - "sqrt": "floating-point", - "square": "numeric", - "subtract": "numeric", - "tan": "floating-point", - "tanh": "floating-point", - "trunc": "real numeric", - } - - def _array_vals(): - for d in _integer_dtypes: - yield asarray(1, dtype=d) - for d in _boolean_dtypes: - yield asarray(False, dtype=d) - for d in _floating_dtypes: - yield asarray(1.0, dtype=d) - - for x in _array_vals(): - for func_name, types in elementwise_function_input_types.items(): - dtypes = _dtype_categories[types] - func = getattr(_elementwise_functions, func_name) - if nargs(func) == 2: - for y in _array_vals(): - if x.dtype not in dtypes or y.dtype not in dtypes: - assert_raises(TypeError, lambda: func(x, y)) - else: - if x.dtype not in dtypes: - assert_raises(TypeError, lambda: func(x)) - - -def test_bitwise_shift_error(): - # bitwise shift functions should raise when the second argument is negative - assert_raises( - ValueError, lambda: bitwise_left_shift(asarray([1, 1]), asarray([1, -1])) - ) - assert_raises( - ValueError, lambda: bitwise_right_shift(asarray([1, 1]), asarray([1, -1])) - ) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/tests/test_scripts.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/tests/test_scripts.py deleted file mode 100644 index 892c04eef0bed4b9d92408419c547f8258a005e3..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/numpy/tests/test_scripts.py +++ /dev/null @@ -1,47 +0,0 @@ -""" Test scripts - -Test that we can run executable scripts that have been installed with numpy. -""" -import sys -import os -import pytest -from os.path import join as pathjoin, isfile, dirname -import subprocess - -import numpy as np -from numpy.testing import assert_equal, IS_WASM - -is_inplace = isfile(pathjoin(dirname(np.__file__), '..', 'setup.py')) - - -def find_f2py_commands(): - if sys.platform == 'win32': - exe_dir = dirname(sys.executable) - if exe_dir.endswith('Scripts'): # virtualenv - return [os.path.join(exe_dir, 'f2py')] - else: - return [os.path.join(exe_dir, "Scripts", 'f2py')] - else: - # Three scripts are installed in Unix-like systems: - # 'f2py', 'f2py{major}', and 'f2py{major.minor}'. For example, - # if installed with python3.9 the scripts would be named - # 'f2py', 'f2py3', and 'f2py3.9'. - version = sys.version_info - major = str(version.major) - minor = str(version.minor) - return ['f2py', 'f2py' + major, 'f2py' + major + '.' + minor] - - -@pytest.mark.skipif(is_inplace, reason="Cannot test f2py command inplace") -@pytest.mark.xfail(reason="Test is unreliable") -@pytest.mark.parametrize('f2py_cmd', find_f2py_commands()) -def test_f2py(f2py_cmd): - # test that we can run f2py script - stdout = subprocess.check_output([f2py_cmd, '-v']) - assert_equal(stdout.strip(), np.__version__.encode('ascii')) - - -@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess") -def test_pep338(): - stdout = subprocess.check_output([sys.executable, '-mnumpy.f2py', '-v']) - assert_equal(stdout.strip(), np.__version__.encode('ascii')) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/core/arrays/sparse/accessor.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/core/arrays/sparse/accessor.py deleted file mode 100644 index 6eb1387c63a0ab23d947f74bebabaf1a530ae50f..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/core/arrays/sparse/accessor.py +++ /dev/null @@ -1,414 +0,0 @@ -"""Sparse accessor""" -from __future__ import annotations - -from typing import TYPE_CHECKING - -import numpy as np - -from pandas.compat._optional import import_optional_dependency - -from pandas.core.dtypes.cast import find_common_type -from pandas.core.dtypes.dtypes import SparseDtype - -from pandas.core.accessor import ( - PandasDelegate, - delegate_names, -) -from pandas.core.arrays.sparse.array import SparseArray - -if TYPE_CHECKING: - from pandas import ( - DataFrame, - Series, - ) - - -class BaseAccessor: - _validation_msg = "Can only use the '.sparse' accessor with Sparse data." - - def __init__(self, data=None) -> None: - self._parent = data - self._validate(data) - - def _validate(self, data): - raise NotImplementedError - - -@delegate_names( - SparseArray, ["npoints", "density", "fill_value", "sp_values"], typ="property" -) -class SparseAccessor(BaseAccessor, PandasDelegate): - """ - Accessor for SparseSparse from other sparse matrix data types. - - Examples - -------- - >>> ser = pd.Series([0, 0, 2, 2, 2], dtype="Sparse[int]") - >>> ser.sparse.density - 0.6 - >>> ser.sparse.sp_values - array([2, 2, 2]) - """ - - def _validate(self, data): - if not isinstance(data.dtype, SparseDtype): - raise AttributeError(self._validation_msg) - - def _delegate_property_get(self, name: str, *args, **kwargs): - return getattr(self._parent.array, name) - - def _delegate_method(self, name: str, *args, **kwargs): - if name == "from_coo": - return self.from_coo(*args, **kwargs) - elif name == "to_coo": - return self.to_coo(*args, **kwargs) - else: - raise ValueError - - @classmethod - def from_coo(cls, A, dense_index: bool = False) -> Series: - """ - Create a Series with sparse values from a scipy.sparse.coo_matrix. - - Parameters - ---------- - A : scipy.sparse.coo_matrix - dense_index : bool, default False - If False (default), the index consists of only the - coords of the non-null entries of the original coo_matrix. - If True, the index consists of the full sorted - (row, col) coordinates of the coo_matrix. - - Returns - ------- - s : Series - A Series with sparse values. - - Examples - -------- - >>> from scipy import sparse - - >>> A = sparse.coo_matrix( - ... ([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), shape=(3, 4) - ... ) - >>> A - <3x4 sparse matrix of type '' - with 3 stored elements in COOrdinate format> - - >>> A.todense() - matrix([[0., 0., 1., 2.], - [3., 0., 0., 0.], - [0., 0., 0., 0.]]) - - >>> ss = pd.Series.sparse.from_coo(A) - >>> ss - 0 2 1.0 - 3 2.0 - 1 0 3.0 - dtype: Sparse[float64, nan] - """ - from pandas import Series - from pandas.core.arrays.sparse.scipy_sparse import coo_to_sparse_series - - result = coo_to_sparse_series(A, dense_index=dense_index) - result = Series(result.array, index=result.index, copy=False) - - return result - - def to_coo(self, row_levels=(0,), column_levels=(1,), sort_labels: bool = False): - """ - Create a scipy.sparse.coo_matrix from a Series with MultiIndex. - - Use row_levels and column_levels to determine the row and column - coordinates respectively. row_levels and column_levels are the names - (labels) or numbers of the levels. {row_levels, column_levels} must be - a partition of the MultiIndex level names (or numbers). - - Parameters - ---------- - row_levels : tuple/list - column_levels : tuple/list - sort_labels : bool, default False - Sort the row and column labels before forming the sparse matrix. - When `row_levels` and/or `column_levels` refer to a single level, - set to `True` for a faster execution. - - Returns - ------- - y : scipy.sparse.coo_matrix - rows : list (row labels) - columns : list (column labels) - - Examples - -------- - >>> s = pd.Series([3.0, np.nan, 1.0, 3.0, np.nan, np.nan]) - >>> s.index = pd.MultiIndex.from_tuples( - ... [ - ... (1, 2, "a", 0), - ... (1, 2, "a", 1), - ... (1, 1, "b", 0), - ... (1, 1, "b", 1), - ... (2, 1, "b", 0), - ... (2, 1, "b", 1) - ... ], - ... names=["A", "B", "C", "D"], - ... ) - >>> s - A B C D - 1 2 a 0 3.0 - 1 NaN - 1 b 0 1.0 - 1 3.0 - 2 1 b 0 NaN - 1 NaN - dtype: float64 - - >>> ss = s.astype("Sparse") - >>> ss - A B C D - 1 2 a 0 3.0 - 1 NaN - 1 b 0 1.0 - 1 3.0 - 2 1 b 0 NaN - 1 NaN - dtype: Sparse[float64, nan] - - >>> A, rows, columns = ss.sparse.to_coo( - ... row_levels=["A", "B"], column_levels=["C", "D"], sort_labels=True - ... ) - >>> A - <3x4 sparse matrix of type '' - with 3 stored elements in COOrdinate format> - >>> A.todense() - matrix([[0., 0., 1., 3.], - [3., 0., 0., 0.], - [0., 0., 0., 0.]]) - - >>> rows - [(1, 1), (1, 2), (2, 1)] - >>> columns - [('a', 0), ('a', 1), ('b', 0), ('b', 1)] - """ - from pandas.core.arrays.sparse.scipy_sparse import sparse_series_to_coo - - A, rows, columns = sparse_series_to_coo( - self._parent, row_levels, column_levels, sort_labels=sort_labels - ) - return A, rows, columns - - def to_dense(self) -> Series: - """ - Convert a Series from sparse values to dense. - - Returns - ------- - Series: - A Series with the same values, stored as a dense array. - - Examples - -------- - >>> series = pd.Series(pd.arrays.SparseArray([0, 1, 0])) - >>> series - 0 0 - 1 1 - 2 0 - dtype: Sparse[int64, 0] - - >>> series.sparse.to_dense() - 0 0 - 1 1 - 2 0 - dtype: int64 - """ - from pandas import Series - - return Series( - self._parent.array.to_dense(), - index=self._parent.index, - name=self._parent.name, - copy=False, - ) - - -class SparseFrameAccessor(BaseAccessor, PandasDelegate): - """ - DataFrame accessor for sparse data. - - Examples - -------- - >>> df = pd.DataFrame({"a": [1, 2, 0, 0], - ... "b": [3, 0, 0, 4]}, dtype="Sparse[int]") - >>> df.sparse.density - 0.5 - """ - - def _validate(self, data): - dtypes = data.dtypes - if not all(isinstance(t, SparseDtype) for t in dtypes): - raise AttributeError(self._validation_msg) - - @classmethod - def from_spmatrix(cls, data, index=None, columns=None) -> DataFrame: - """ - Create a new DataFrame from a scipy sparse matrix. - - Parameters - ---------- - data : scipy.sparse.spmatrix - Must be convertible to csc format. - index, columns : Index, optional - Row and column labels to use for the resulting DataFrame. - Defaults to a RangeIndex. - - Returns - ------- - DataFrame - Each column of the DataFrame is stored as a - :class:`arrays.SparseArray`. - - Examples - -------- - >>> import scipy.sparse - >>> mat = scipy.sparse.eye(3) - >>> pd.DataFrame.sparse.from_spmatrix(mat) - 0 1 2 - 0 1.0 0.0 0.0 - 1 0.0 1.0 0.0 - 2 0.0 0.0 1.0 - """ - from pandas._libs.sparse import IntIndex - - from pandas import DataFrame - - data = data.tocsc() - index, columns = cls._prep_index(data, index, columns) - n_rows, n_columns = data.shape - # We need to make sure indices are sorted, as we create - # IntIndex with no input validation (i.e. check_integrity=False ). - # Indices may already be sorted in scipy in which case this adds - # a small overhead. - data.sort_indices() - indices = data.indices - indptr = data.indptr - array_data = data.data - dtype = SparseDtype(array_data.dtype, 0) - arrays = [] - for i in range(n_columns): - sl = slice(indptr[i], indptr[i + 1]) - idx = IntIndex(n_rows, indices[sl], check_integrity=False) - arr = SparseArray._simple_new(array_data[sl], idx, dtype) - arrays.append(arr) - return DataFrame._from_arrays( - arrays, columns=columns, index=index, verify_integrity=False - ) - - def to_dense(self) -> DataFrame: - """ - Convert a DataFrame with sparse values to dense. - - Returns - ------- - DataFrame - A DataFrame with the same values stored as dense arrays. - - Examples - -------- - >>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0])}) - >>> df.sparse.to_dense() - A - 0 0 - 1 1 - 2 0 - """ - from pandas import DataFrame - - data = {k: v.array.to_dense() for k, v in self._parent.items()} - return DataFrame(data, index=self._parent.index, columns=self._parent.columns) - - def to_coo(self): - """ - Return the contents of the frame as a sparse SciPy COO matrix. - - Returns - ------- - scipy.sparse.spmatrix - If the caller is heterogeneous and contains booleans or objects, - the result will be of dtype=object. See Notes. - - Notes - ----- - The dtype will be the lowest-common-denominator type (implicit - upcasting); that is to say if the dtypes (even of numeric types) - are mixed, the one that accommodates all will be chosen. - - e.g. If the dtypes are float16 and float32, dtype will be upcast to - float32. By numpy.find_common_type convention, mixing int64 and - and uint64 will result in a float64 dtype. - - Examples - -------- - >>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0, 1])}) - >>> df.sparse.to_coo() - <4x1 sparse matrix of type '' - with 2 stored elements in COOrdinate format> - """ - import_optional_dependency("scipy") - from scipy.sparse import coo_matrix - - dtype = find_common_type(self._parent.dtypes.to_list()) - if isinstance(dtype, SparseDtype): - dtype = dtype.subtype - - cols, rows, data = [], [], [] - for col, (_, ser) in enumerate(self._parent.items()): - sp_arr = ser.array - if sp_arr.fill_value != 0: - raise ValueError("fill value must be 0 when converting to COO matrix") - - row = sp_arr.sp_index.indices - cols.append(np.repeat(col, len(row))) - rows.append(row) - data.append(sp_arr.sp_values.astype(dtype, copy=False)) - - cols = np.concatenate(cols) - rows = np.concatenate(rows) - data = np.concatenate(data) - return coo_matrix((data, (rows, cols)), shape=self._parent.shape) - - @property - def density(self) -> float: - """ - Ratio of non-sparse points to total (dense) data points. - - Examples - -------- - >>> df = pd.DataFrame({"A": pd.arrays.SparseArray([0, 1, 0, 1])}) - >>> df.sparse.density - 0.5 - """ - tmp = np.mean([column.array.density for _, column in self._parent.items()]) - return tmp - - @staticmethod - def _prep_index(data, index, columns): - from pandas.core.indexes.api import ( - default_index, - ensure_index, - ) - - N, K = data.shape - if index is None: - index = default_index(N) - else: - index = ensure_index(index) - if columns is None: - columns = default_index(K) - else: - columns = ensure_index(columns) - - if len(columns) != K: - raise ValueError(f"Column length mismatch: {len(columns)} vs. {K}") - if len(index) != N: - raise ValueError(f"Index length mismatch: {len(index)} vs. {N}") - return index, columns diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_pct_change.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_pct_change.py deleted file mode 100644 index 92b66e12d4356ca33d6351b092e3655541c9e8bb..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/frame/methods/test_pct_change.py +++ /dev/null @@ -1,180 +0,0 @@ -import numpy as np -import pytest - -from pandas import ( - DataFrame, - Series, -) -import pandas._testing as tm - - -class TestDataFramePctChange: - @pytest.mark.parametrize( - "periods, fill_method, limit, exp", - [ - (1, "ffill", None, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, 0]), - (1, "ffill", 1, [np.nan, np.nan, np.nan, 1, 1, 1.5, 0, np.nan]), - (1, "bfill", None, [np.nan, 0, 0, 1, 1, 1.5, np.nan, np.nan]), - (1, "bfill", 1, [np.nan, np.nan, 0, 1, 1, 1.5, np.nan, np.nan]), - (-1, "ffill", None, [np.nan, np.nan, -0.5, -0.5, -0.6, 0, 0, np.nan]), - (-1, "ffill", 1, [np.nan, np.nan, -0.5, -0.5, -0.6, 0, np.nan, np.nan]), - (-1, "bfill", None, [0, 0, -0.5, -0.5, -0.6, np.nan, np.nan, np.nan]), - (-1, "bfill", 1, [np.nan, 0, -0.5, -0.5, -0.6, np.nan, np.nan, np.nan]), - ], - ) - def test_pct_change_with_nas( - self, periods, fill_method, limit, exp, frame_or_series - ): - vals = [np.nan, np.nan, 1, 2, 4, 10, np.nan, np.nan] - obj = frame_or_series(vals) - - msg = ( - "The 'fill_method' keyword being not None and the 'limit' keyword in " - f"{type(obj).__name__}.pct_change are deprecated" - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - res = obj.pct_change(periods=periods, fill_method=fill_method, limit=limit) - tm.assert_equal(res, frame_or_series(exp)) - - def test_pct_change_numeric(self): - # GH#11150 - pnl = DataFrame( - [np.arange(0, 40, 10), np.arange(0, 40, 10), np.arange(0, 40, 10)] - ).astype(np.float64) - pnl.iat[1, 0] = np.nan - pnl.iat[1, 1] = np.nan - pnl.iat[2, 3] = 60 - - msg = ( - "The 'fill_method' keyword being not None and the 'limit' keyword in " - "DataFrame.pct_change are deprecated" - ) - - for axis in range(2): - expected = pnl.ffill(axis=axis) / pnl.ffill(axis=axis).shift(axis=axis) - 1 - - with tm.assert_produces_warning(FutureWarning, match=msg): - result = pnl.pct_change(axis=axis, fill_method="pad") - tm.assert_frame_equal(result, expected) - - def test_pct_change(self, datetime_frame): - msg = ( - "The 'fill_method' keyword being not None and the 'limit' keyword in " - "DataFrame.pct_change are deprecated" - ) - - rs = datetime_frame.pct_change(fill_method=None) - tm.assert_frame_equal(rs, datetime_frame / datetime_frame.shift(1) - 1) - - rs = datetime_frame.pct_change(2) - filled = datetime_frame.ffill() - tm.assert_frame_equal(rs, filled / filled.shift(2) - 1) - - with tm.assert_produces_warning(FutureWarning, match=msg): - rs = datetime_frame.pct_change(fill_method="bfill", limit=1) - filled = datetime_frame.bfill(limit=1) - tm.assert_frame_equal(rs, filled / filled.shift(1) - 1) - - rs = datetime_frame.pct_change(freq="5D") - filled = datetime_frame.ffill() - tm.assert_frame_equal( - rs, (filled / filled.shift(freq="5D") - 1).reindex_like(filled) - ) - - def test_pct_change_shift_over_nas(self): - s = Series([1.0, 1.5, np.nan, 2.5, 3.0]) - - df = DataFrame({"a": s, "b": s}) - - msg = "The default fill_method='pad' in DataFrame.pct_change is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - chg = df.pct_change() - - expected = Series([np.nan, 0.5, 0.0, 2.5 / 1.5 - 1, 0.2]) - edf = DataFrame({"a": expected, "b": expected}) - tm.assert_frame_equal(chg, edf) - - @pytest.mark.parametrize( - "freq, periods, fill_method, limit", - [ - ("5B", 5, None, None), - ("3B", 3, None, None), - ("3B", 3, "bfill", None), - ("7B", 7, "pad", 1), - ("7B", 7, "bfill", 3), - ("14B", 14, None, None), - ], - ) - def test_pct_change_periods_freq( - self, datetime_frame, freq, periods, fill_method, limit - ): - msg = ( - "The 'fill_method' keyword being not None and the 'limit' keyword in " - "DataFrame.pct_change are deprecated" - ) - - # GH#7292 - with tm.assert_produces_warning(FutureWarning, match=msg): - rs_freq = datetime_frame.pct_change( - freq=freq, fill_method=fill_method, limit=limit - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - rs_periods = datetime_frame.pct_change( - periods, fill_method=fill_method, limit=limit - ) - tm.assert_frame_equal(rs_freq, rs_periods) - - empty_ts = DataFrame(index=datetime_frame.index, columns=datetime_frame.columns) - with tm.assert_produces_warning(FutureWarning, match=msg): - rs_freq = empty_ts.pct_change( - freq=freq, fill_method=fill_method, limit=limit - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - rs_periods = empty_ts.pct_change( - periods, fill_method=fill_method, limit=limit - ) - tm.assert_frame_equal(rs_freq, rs_periods) - - -@pytest.mark.parametrize("fill_method", ["pad", "ffill", None]) -def test_pct_change_with_duplicated_indices(fill_method): - # GH30463 - data = DataFrame( - {0: [np.nan, 1, 2, 3, 9, 18], 1: [0, 1, np.nan, 3, 9, 18]}, index=["a", "b"] * 3 - ) - - warn = None if fill_method is None else FutureWarning - msg = ( - "The 'fill_method' keyword being not None and the 'limit' keyword in " - "DataFrame.pct_change are deprecated" - ) - with tm.assert_produces_warning(warn, match=msg): - result = data.pct_change(fill_method=fill_method) - - if fill_method is None: - second_column = [np.nan, np.inf, np.nan, np.nan, 2.0, 1.0] - else: - second_column = [np.nan, np.inf, 0.0, 2.0, 2.0, 1.0] - expected = DataFrame( - {0: [np.nan, np.nan, 1.0, 0.5, 2.0, 1.0], 1: second_column}, - index=["a", "b"] * 3, - ) - tm.assert_frame_equal(result, expected) - - -def test_pct_change_none_beginning_no_warning(): - # GH#54481 - df = DataFrame( - [ - [1, None], - [2, 1], - [3, 2], - [4, 3], - [5, 4], - ] - ) - result = df.pct_change() - expected = DataFrame( - {0: [np.nan, 1, 0.5, 1 / 3, 0.25], 1: [np.nan, np.nan, 1, 0.5, 1 / 3]} - ) - tm.assert_frame_equal(result, expected) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/io/parser/common/test_verbose.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/io/parser/common/test_verbose.py deleted file mode 100644 index 335065db974dc5ee06ebad9980c96408fe1d02fb..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/io/parser/common/test_verbose.py +++ /dev/null @@ -1,55 +0,0 @@ -""" -Tests that work on both the Python and C engines but do not have a -specific classification into the other test modules. -""" -from io import StringIO - -import pytest - -pytestmark = pytest.mark.usefixtures("pyarrow_skip") - - -def test_verbose_read(all_parsers, capsys): - parser = all_parsers - data = """a,b,c,d -one,1,2,3 -one,1,2,3 -,1,2,3 -one,1,2,3 -,1,2,3 -,1,2,3 -one,1,2,3 -two,1,2,3""" - - # Engines are verbose in different ways. - parser.read_csv(StringIO(data), verbose=True) - captured = capsys.readouterr() - - if parser.engine == "c": - assert "Tokenization took:" in captured.out - assert "Parser memory cleanup took:" in captured.out - else: # Python engine - assert captured.out == "Filled 3 NA values in column a\n" - - -def test_verbose_read2(all_parsers, capsys): - parser = all_parsers - data = """a,b,c,d -one,1,2,3 -two,1,2,3 -three,1,2,3 -four,1,2,3 -five,1,2,3 -,1,2,3 -seven,1,2,3 -eight,1,2,3""" - - parser.read_csv(StringIO(data), verbose=True, index_col=0) - captured = capsys.readouterr() - - # Engines are verbose in different ways. - if parser.engine == "c": - assert "Tokenization took:" in captured.out - assert "Parser memory cleanup took:" in captured.out - else: # Python engine - assert captured.out == "Filled 1 NA values in column a\n" diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/series/methods/test_interpolate.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/series/methods/test_interpolate.py deleted file mode 100644 index 549f429f09d35270654f919630210015878ab1f4..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pandas/tests/series/methods/test_interpolate.py +++ /dev/null @@ -1,868 +0,0 @@ -import numpy as np -import pytest - -import pandas.util._test_decorators as td - -import pandas as pd -from pandas import ( - Index, - MultiIndex, - Series, - date_range, - isna, -) -import pandas._testing as tm - - -@pytest.fixture( - params=[ - "linear", - "index", - "values", - "nearest", - "slinear", - "zero", - "quadratic", - "cubic", - "barycentric", - "krogh", - "polynomial", - "spline", - "piecewise_polynomial", - "from_derivatives", - "pchip", - "akima", - "cubicspline", - ] -) -def nontemporal_method(request): - """Fixture that returns an (method name, required kwargs) pair. - - This fixture does not include method 'time' as a parameterization; that - method requires a Series with a DatetimeIndex, and is generally tested - separately from these non-temporal methods. - """ - method = request.param - kwargs = {"order": 1} if method in ("spline", "polynomial") else {} - return method, kwargs - - -@pytest.fixture( - params=[ - "linear", - "slinear", - "zero", - "quadratic", - "cubic", - "barycentric", - "krogh", - "polynomial", - "spline", - "piecewise_polynomial", - "from_derivatives", - "pchip", - "akima", - "cubicspline", - ] -) -def interp_methods_ind(request): - """Fixture that returns a (method name, required kwargs) pair to - be tested for various Index types. - - This fixture does not include methods - 'time', 'index', 'nearest', - 'values' as a parameterization - """ - method = request.param - kwargs = {"order": 1} if method in ("spline", "polynomial") else {} - return method, kwargs - - -class TestSeriesInterpolateData: - @pytest.mark.xfail(reason="EA.fillna does not handle 'linear' method") - def test_interpolate_period_values(self): - orig = Series(date_range("2012-01-01", periods=5)) - ser = orig.copy() - ser[2] = pd.NaT - - # period cast - ser_per = ser.dt.to_period("D") - res_per = ser_per.interpolate() - expected_per = orig.dt.to_period("D") - tm.assert_series_equal(res_per, expected_per) - - def test_interpolate(self, datetime_series): - ts = Series(np.arange(len(datetime_series), dtype=float), datetime_series.index) - - ts_copy = ts.copy() - ts_copy[5:10] = np.nan - - linear_interp = ts_copy.interpolate(method="linear") - tm.assert_series_equal(linear_interp, ts) - - ord_ts = Series( - [d.toordinal() for d in datetime_series.index], index=datetime_series.index - ).astype(float) - - ord_ts_copy = ord_ts.copy() - ord_ts_copy[5:10] = np.nan - - time_interp = ord_ts_copy.interpolate(method="time") - tm.assert_series_equal(time_interp, ord_ts) - - def test_interpolate_time_raises_for_non_timeseries(self): - # When method='time' is used on a non-TimeSeries that contains a null - # value, a ValueError should be raised. - non_ts = Series([0, 1, 2, np.nan]) - msg = "time-weighted interpolation only works on Series.* with a DatetimeIndex" - with pytest.raises(ValueError, match=msg): - non_ts.interpolate(method="time") - - def test_interpolate_cubicspline(self): - pytest.importorskip("scipy") - ser = Series([10, 11, 12, 13]) - - expected = Series( - [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00], - index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]), - ) - # interpolate at new_index - new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype( - float - ) - result = ser.reindex(new_index).interpolate(method="cubicspline").loc[1:3] - tm.assert_series_equal(result, expected) - - def test_interpolate_pchip(self): - pytest.importorskip("scipy") - ser = Series(np.sort(np.random.default_rng(2).uniform(size=100))) - - # interpolate at new_index - new_index = ser.index.union( - Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75]) - ).astype(float) - interp_s = ser.reindex(new_index).interpolate(method="pchip") - # does not blow up, GH5977 - interp_s.loc[49:51] - - def test_interpolate_akima(self): - pytest.importorskip("scipy") - ser = Series([10, 11, 12, 13]) - - # interpolate at new_index where `der` is zero - expected = Series( - [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00], - index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]), - ) - new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype( - float - ) - interp_s = ser.reindex(new_index).interpolate(method="akima") - tm.assert_series_equal(interp_s.loc[1:3], expected) - - # interpolate at new_index where `der` is a non-zero int - expected = Series( - [11.0, 1.0, 1.0, 1.0, 12.0, 1.0, 1.0, 1.0, 13.0], - index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]), - ) - new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype( - float - ) - interp_s = ser.reindex(new_index).interpolate(method="akima", der=1) - tm.assert_series_equal(interp_s.loc[1:3], expected) - - def test_interpolate_piecewise_polynomial(self): - pytest.importorskip("scipy") - ser = Series([10, 11, 12, 13]) - - expected = Series( - [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00], - index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]), - ) - # interpolate at new_index - new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype( - float - ) - interp_s = ser.reindex(new_index).interpolate(method="piecewise_polynomial") - tm.assert_series_equal(interp_s.loc[1:3], expected) - - def test_interpolate_from_derivatives(self): - pytest.importorskip("scipy") - ser = Series([10, 11, 12, 13]) - - expected = Series( - [11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00], - index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]), - ) - # interpolate at new_index - new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype( - float - ) - interp_s = ser.reindex(new_index).interpolate(method="from_derivatives") - tm.assert_series_equal(interp_s.loc[1:3], expected) - - @pytest.mark.parametrize( - "kwargs", - [ - {}, - pytest.param( - {"method": "polynomial", "order": 1}, marks=td.skip_if_no_scipy - ), - ], - ) - def test_interpolate_corners(self, kwargs): - s = Series([np.nan, np.nan]) - tm.assert_series_equal(s.interpolate(**kwargs), s) - - s = Series([], dtype=object).interpolate() - tm.assert_series_equal(s.interpolate(**kwargs), s) - - def test_interpolate_index_values(self): - s = Series(np.nan, index=np.sort(np.random.default_rng(2).random(30))) - s.loc[::3] = np.random.default_rng(2).standard_normal(10) - - vals = s.index.values.astype(float) - - result = s.interpolate(method="index") - - expected = s.copy() - bad = isna(expected.values) - good = ~bad - expected = Series( - np.interp(vals[bad], vals[good], s.values[good]), index=s.index[bad] - ) - - tm.assert_series_equal(result[bad], expected) - - # 'values' is synonymous with 'index' for the method kwarg - other_result = s.interpolate(method="values") - - tm.assert_series_equal(other_result, result) - tm.assert_series_equal(other_result[bad], expected) - - def test_interpolate_non_ts(self): - s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - msg = ( - "time-weighted interpolation only works on Series or DataFrames " - "with a DatetimeIndex" - ) - with pytest.raises(ValueError, match=msg): - s.interpolate(method="time") - - @pytest.mark.parametrize( - "kwargs", - [ - {}, - pytest.param( - {"method": "polynomial", "order": 1}, marks=td.skip_if_no_scipy - ), - ], - ) - def test_nan_interpolate(self, kwargs): - s = Series([0, 1, np.nan, 3]) - result = s.interpolate(**kwargs) - expected = Series([0.0, 1.0, 2.0, 3.0]) - tm.assert_series_equal(result, expected) - - def test_nan_irregular_index(self): - s = Series([1, 2, np.nan, 4], index=[1, 3, 5, 9]) - result = s.interpolate() - expected = Series([1.0, 2.0, 3.0, 4.0], index=[1, 3, 5, 9]) - tm.assert_series_equal(result, expected) - - def test_nan_str_index(self): - s = Series([0, 1, 2, np.nan], index=list("abcd")) - result = s.interpolate() - expected = Series([0.0, 1.0, 2.0, 2.0], index=list("abcd")) - tm.assert_series_equal(result, expected) - - def test_interp_quad(self): - pytest.importorskip("scipy") - sq = Series([1, 4, np.nan, 16], index=[1, 2, 3, 4]) - result = sq.interpolate(method="quadratic") - expected = Series([1.0, 4.0, 9.0, 16.0], index=[1, 2, 3, 4]) - tm.assert_series_equal(result, expected) - - def test_interp_scipy_basic(self): - pytest.importorskip("scipy") - s = Series([1, 3, np.nan, 12, np.nan, 25]) - # slinear - expected = Series([1.0, 3.0, 7.5, 12.0, 18.5, 25.0]) - result = s.interpolate(method="slinear") - tm.assert_series_equal(result, expected) - - msg = "The 'downcast' keyword in Series.interpolate is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.interpolate(method="slinear", downcast="infer") - tm.assert_series_equal(result, expected) - # nearest - expected = Series([1, 3, 3, 12, 12, 25]) - result = s.interpolate(method="nearest") - tm.assert_series_equal(result, expected.astype("float")) - - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.interpolate(method="nearest", downcast="infer") - tm.assert_series_equal(result, expected) - # zero - expected = Series([1, 3, 3, 12, 12, 25]) - result = s.interpolate(method="zero") - tm.assert_series_equal(result, expected.astype("float")) - - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.interpolate(method="zero", downcast="infer") - tm.assert_series_equal(result, expected) - # quadratic - # GH #15662. - expected = Series([1, 3.0, 6.823529, 12.0, 18.058824, 25.0]) - result = s.interpolate(method="quadratic") - tm.assert_series_equal(result, expected) - - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.interpolate(method="quadratic", downcast="infer") - tm.assert_series_equal(result, expected) - # cubic - expected = Series([1.0, 3.0, 6.8, 12.0, 18.2, 25.0]) - result = s.interpolate(method="cubic") - tm.assert_series_equal(result, expected) - - def test_interp_limit(self): - s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - - expected = Series([1.0, 3.0, 5.0, 7.0, np.nan, 11.0]) - result = s.interpolate(method="linear", limit=2) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize("limit", [-1, 0]) - def test_interpolate_invalid_nonpositive_limit(self, nontemporal_method, limit): - # GH 9217: make sure limit is greater than zero. - s = Series([1, 2, np.nan, 4]) - method, kwargs = nontemporal_method - with pytest.raises(ValueError, match="Limit must be greater than 0"): - s.interpolate(limit=limit, method=method, **kwargs) - - def test_interpolate_invalid_float_limit(self, nontemporal_method): - # GH 9217: make sure limit is an integer. - s = Series([1, 2, np.nan, 4]) - method, kwargs = nontemporal_method - limit = 2.0 - with pytest.raises(ValueError, match="Limit must be an integer"): - s.interpolate(limit=limit, method=method, **kwargs) - - @pytest.mark.parametrize("invalid_method", [None, "nonexistent_method"]) - def test_interp_invalid_method(self, invalid_method): - s = Series([1, 3, np.nan, 12, np.nan, 25]) - - msg = f"method must be one of.* Got '{invalid_method}' instead" - if invalid_method is None: - msg = "'method' should be a string, not None" - with pytest.raises(ValueError, match=msg): - s.interpolate(method=invalid_method) - - # When an invalid method and invalid limit (such as -1) are - # provided, the error message reflects the invalid method. - with pytest.raises(ValueError, match=msg): - s.interpolate(method=invalid_method, limit=-1) - - def test_interp_invalid_method_and_value(self): - # GH#36624 - ser = Series([1, 3, np.nan, 12, np.nan, 25]) - - msg = "'fill_value' is not a valid keyword for Series.interpolate" - msg2 = "Series.interpolate with method=pad" - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=msg2): - ser.interpolate(fill_value=3, method="pad") - - def test_interp_limit_forward(self): - s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - - # Provide 'forward' (the default) explicitly here. - expected = Series([1.0, 3.0, 5.0, 7.0, np.nan, 11.0]) - - result = s.interpolate(method="linear", limit=2, limit_direction="forward") - tm.assert_series_equal(result, expected) - - result = s.interpolate(method="linear", limit=2, limit_direction="FORWARD") - tm.assert_series_equal(result, expected) - - def test_interp_unlimited(self): - # these test are for issue #16282 default Limit=None is unlimited - s = Series([np.nan, 1.0, 3.0, np.nan, np.nan, np.nan, 11.0, np.nan]) - expected = Series([1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 11.0]) - result = s.interpolate(method="linear", limit_direction="both") - tm.assert_series_equal(result, expected) - - expected = Series([np.nan, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, 11.0]) - result = s.interpolate(method="linear", limit_direction="forward") - tm.assert_series_equal(result, expected) - - expected = Series([1.0, 1.0, 3.0, 5.0, 7.0, 9.0, 11.0, np.nan]) - result = s.interpolate(method="linear", limit_direction="backward") - tm.assert_series_equal(result, expected) - - def test_interp_limit_bad_direction(self): - s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - - msg = ( - r"Invalid limit_direction: expecting one of \['forward', " - r"'backward', 'both'\], got 'abc'" - ) - with pytest.raises(ValueError, match=msg): - s.interpolate(method="linear", limit=2, limit_direction="abc") - - # raises an error even if no limit is specified. - with pytest.raises(ValueError, match=msg): - s.interpolate(method="linear", limit_direction="abc") - - # limit_area introduced GH #16284 - def test_interp_limit_area(self): - # These tests are for issue #9218 -- fill NaNs in both directions. - s = Series([np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan]) - - expected = Series([np.nan, np.nan, 3.0, 4.0, 5.0, 6.0, 7.0, np.nan, np.nan]) - result = s.interpolate(method="linear", limit_area="inside") - tm.assert_series_equal(result, expected) - - expected = Series( - [np.nan, np.nan, 3.0, 4.0, np.nan, np.nan, 7.0, np.nan, np.nan] - ) - result = s.interpolate(method="linear", limit_area="inside", limit=1) - tm.assert_series_equal(result, expected) - - expected = Series([np.nan, np.nan, 3.0, 4.0, np.nan, 6.0, 7.0, np.nan, np.nan]) - result = s.interpolate( - method="linear", limit_area="inside", limit_direction="both", limit=1 - ) - tm.assert_series_equal(result, expected) - - expected = Series([np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0]) - result = s.interpolate(method="linear", limit_area="outside") - tm.assert_series_equal(result, expected) - - expected = Series( - [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan] - ) - result = s.interpolate(method="linear", limit_area="outside", limit=1) - tm.assert_series_equal(result, expected) - - expected = Series([np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan]) - result = s.interpolate( - method="linear", limit_area="outside", limit_direction="both", limit=1 - ) - tm.assert_series_equal(result, expected) - - expected = Series([3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan]) - result = s.interpolate( - method="linear", limit_area="outside", limit_direction="backward" - ) - tm.assert_series_equal(result, expected) - - # raises an error even if limit type is wrong. - msg = r"Invalid limit_area: expecting one of \['inside', 'outside'\], got abc" - with pytest.raises(ValueError, match=msg): - s.interpolate(method="linear", limit_area="abc") - - @pytest.mark.parametrize( - "method, limit_direction, expected", - [ - ("pad", "backward", "forward"), - ("ffill", "backward", "forward"), - ("backfill", "forward", "backward"), - ("bfill", "forward", "backward"), - ("pad", "both", "forward"), - ("ffill", "both", "forward"), - ("backfill", "both", "backward"), - ("bfill", "both", "backward"), - ], - ) - def test_interp_limit_direction_raises(self, method, limit_direction, expected): - # https://github.com/pandas-dev/pandas/pull/34746 - s = Series([1, 2, 3]) - - msg = f"`limit_direction` must be '{expected}' for method `{method}`" - msg2 = "Series.interpolate with method=" - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=msg2): - s.interpolate(method=method, limit_direction=limit_direction) - - @pytest.mark.parametrize( - "data, expected_data, kwargs", - ( - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [np.nan, np.nan, 3.0, 3.0, 3.0, 3.0, 7.0, np.nan, np.nan], - {"method": "pad", "limit_area": "inside"}, - ), - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [np.nan, np.nan, 3.0, 3.0, np.nan, np.nan, 7.0, np.nan, np.nan], - {"method": "pad", "limit_area": "inside", "limit": 1}, - ), - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, 7.0], - {"method": "pad", "limit_area": "outside"}, - ), - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [np.nan, np.nan, 3.0, np.nan, np.nan, np.nan, 7.0, 7.0, np.nan], - {"method": "pad", "limit_area": "outside", "limit": 1}, - ), - ( - [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], - [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], - {"method": "pad", "limit_area": "outside", "limit": 1}, - ), - ( - range(5), - range(5), - {"method": "pad", "limit_area": "outside", "limit": 1}, - ), - ), - ) - def test_interp_limit_area_with_pad(self, data, expected_data, kwargs): - # GH26796 - - s = Series(data) - expected = Series(expected_data) - msg = "Series.interpolate with method=pad" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.interpolate(**kwargs) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize( - "data, expected_data, kwargs", - ( - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [np.nan, np.nan, 3.0, 7.0, 7.0, 7.0, 7.0, np.nan, np.nan], - {"method": "bfill", "limit_area": "inside"}, - ), - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [np.nan, np.nan, 3.0, np.nan, np.nan, 7.0, 7.0, np.nan, np.nan], - {"method": "bfill", "limit_area": "inside", "limit": 1}, - ), - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [3.0, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], - {"method": "bfill", "limit_area": "outside"}, - ), - ( - [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 7, np.nan, np.nan], - [np.nan, 3.0, 3.0, np.nan, np.nan, np.nan, 7.0, np.nan, np.nan], - {"method": "bfill", "limit_area": "outside", "limit": 1}, - ), - ), - ) - def test_interp_limit_area_with_backfill(self, data, expected_data, kwargs): - # GH26796 - - s = Series(data) - expected = Series(expected_data) - msg = "Series.interpolate with method=bfill" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = s.interpolate(**kwargs) - tm.assert_series_equal(result, expected) - - def test_interp_limit_direction(self): - # These tests are for issue #9218 -- fill NaNs in both directions. - s = Series([1, 3, np.nan, np.nan, np.nan, 11]) - - expected = Series([1.0, 3.0, np.nan, 7.0, 9.0, 11.0]) - result = s.interpolate(method="linear", limit=2, limit_direction="backward") - tm.assert_series_equal(result, expected) - - expected = Series([1.0, 3.0, 5.0, np.nan, 9.0, 11.0]) - result = s.interpolate(method="linear", limit=1, limit_direction="both") - tm.assert_series_equal(result, expected) - - # Check that this works on a longer series of nans. - s = Series([1, 3, np.nan, np.nan, np.nan, 7, 9, np.nan, np.nan, 12, np.nan]) - - expected = Series([1.0, 3.0, 4.0, 5.0, 6.0, 7.0, 9.0, 10.0, 11.0, 12.0, 12.0]) - result = s.interpolate(method="linear", limit=2, limit_direction="both") - tm.assert_series_equal(result, expected) - - expected = Series( - [1.0, 3.0, 4.0, np.nan, 6.0, 7.0, 9.0, 10.0, 11.0, 12.0, 12.0] - ) - result = s.interpolate(method="linear", limit=1, limit_direction="both") - tm.assert_series_equal(result, expected) - - def test_interp_limit_to_ends(self): - # These test are for issue #10420 -- flow back to beginning. - s = Series([np.nan, np.nan, 5, 7, 9, np.nan]) - - expected = Series([5.0, 5.0, 5.0, 7.0, 9.0, np.nan]) - result = s.interpolate(method="linear", limit=2, limit_direction="backward") - tm.assert_series_equal(result, expected) - - expected = Series([5.0, 5.0, 5.0, 7.0, 9.0, 9.0]) - result = s.interpolate(method="linear", limit=2, limit_direction="both") - tm.assert_series_equal(result, expected) - - def test_interp_limit_before_ends(self): - # These test are for issue #11115 -- limit ends properly. - s = Series([np.nan, np.nan, 5, 7, np.nan, np.nan]) - - expected = Series([np.nan, np.nan, 5.0, 7.0, 7.0, np.nan]) - result = s.interpolate(method="linear", limit=1, limit_direction="forward") - tm.assert_series_equal(result, expected) - - expected = Series([np.nan, 5.0, 5.0, 7.0, np.nan, np.nan]) - result = s.interpolate(method="linear", limit=1, limit_direction="backward") - tm.assert_series_equal(result, expected) - - expected = Series([np.nan, 5.0, 5.0, 7.0, 7.0, np.nan]) - result = s.interpolate(method="linear", limit=1, limit_direction="both") - tm.assert_series_equal(result, expected) - - def test_interp_all_good(self): - pytest.importorskip("scipy") - s = Series([1, 2, 3]) - result = s.interpolate(method="polynomial", order=1) - tm.assert_series_equal(result, s) - - # non-scipy - result = s.interpolate() - tm.assert_series_equal(result, s) - - @pytest.mark.parametrize( - "check_scipy", [False, pytest.param(True, marks=td.skip_if_no_scipy)] - ) - def test_interp_multiIndex(self, check_scipy): - idx = MultiIndex.from_tuples([(0, "a"), (1, "b"), (2, "c")]) - s = Series([1, 2, np.nan], index=idx) - - expected = s.copy() - expected.loc[2] = 2 - result = s.interpolate() - tm.assert_series_equal(result, expected) - - msg = "Only `method=linear` interpolation is supported on MultiIndexes" - if check_scipy: - with pytest.raises(ValueError, match=msg): - s.interpolate(method="polynomial", order=1) - - def test_interp_nonmono_raise(self): - pytest.importorskip("scipy") - s = Series([1, np.nan, 3], index=[0, 2, 1]) - msg = "krogh interpolation requires that the index be monotonic" - with pytest.raises(ValueError, match=msg): - s.interpolate(method="krogh") - - @pytest.mark.parametrize("method", ["nearest", "pad"]) - def test_interp_datetime64(self, method, tz_naive_fixture): - pytest.importorskip("scipy") - df = Series( - [1, np.nan, 3], index=date_range("1/1/2000", periods=3, tz=tz_naive_fixture) - ) - warn = None if method == "nearest" else FutureWarning - msg = "Series.interpolate with method=pad is deprecated" - with tm.assert_produces_warning(warn, match=msg): - result = df.interpolate(method=method) - if warn is not None: - # check the "use ffill instead" is equivalent - alt = df.ffill() - tm.assert_series_equal(result, alt) - - expected = Series( - [1.0, 1.0, 3.0], - index=date_range("1/1/2000", periods=3, tz=tz_naive_fixture), - ) - tm.assert_series_equal(result, expected) - - def test_interp_pad_datetime64tz_values(self): - # GH#27628 missing.interpolate_2d should handle datetimetz values - dti = date_range("2015-04-05", periods=3, tz="US/Central") - ser = Series(dti) - ser[1] = pd.NaT - - msg = "Series.interpolate with method=pad is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = ser.interpolate(method="pad") - # check the "use ffill instead" is equivalent - alt = ser.ffill() - tm.assert_series_equal(result, alt) - - expected = Series(dti) - expected[1] = expected[0] - tm.assert_series_equal(result, expected) - - def test_interp_limit_no_nans(self): - # GH 7173 - s = Series([1.0, 2.0, 3.0]) - result = s.interpolate(limit=1) - expected = s - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize("method", ["polynomial", "spline"]) - def test_no_order(self, method): - # see GH-10633, GH-24014 - pytest.importorskip("scipy") - s = Series([0, 1, np.nan, 3]) - msg = "You must specify the order of the spline or polynomial" - with pytest.raises(ValueError, match=msg): - s.interpolate(method=method) - - @pytest.mark.parametrize("order", [-1, -1.0, 0, 0.0, np.nan]) - def test_interpolate_spline_invalid_order(self, order): - pytest.importorskip("scipy") - s = Series([0, 1, np.nan, 3]) - msg = "order needs to be specified and greater than 0" - with pytest.raises(ValueError, match=msg): - s.interpolate(method="spline", order=order) - - def test_spline(self): - pytest.importorskip("scipy") - s = Series([1, 2, np.nan, 4, 5, np.nan, 7]) - result = s.interpolate(method="spline", order=1) - expected = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]) - tm.assert_series_equal(result, expected) - - def test_spline_extrapolate(self): - pytest.importorskip("scipy") - s = Series([1, 2, 3, 4, np.nan, 6, np.nan]) - result3 = s.interpolate(method="spline", order=1, ext=3) - expected3 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 6.0]) - tm.assert_series_equal(result3, expected3) - - result1 = s.interpolate(method="spline", order=1, ext=0) - expected1 = Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]) - tm.assert_series_equal(result1, expected1) - - def test_spline_smooth(self): - pytest.importorskip("scipy") - s = Series([1, 2, np.nan, 4, 5.1, np.nan, 7]) - assert ( - s.interpolate(method="spline", order=3, s=0)[5] - != s.interpolate(method="spline", order=3)[5] - ) - - def test_spline_interpolation(self): - # Explicit cast to float to avoid implicit cast when setting np.nan - pytest.importorskip("scipy") - s = Series(np.arange(10) ** 2, dtype="float") - s[np.random.default_rng(2).integers(0, 9, 3)] = np.nan - result1 = s.interpolate(method="spline", order=1) - expected1 = s.interpolate(method="spline", order=1) - tm.assert_series_equal(result1, expected1) - - def test_interp_timedelta64(self): - # GH 6424 - df = Series([1, np.nan, 3], index=pd.to_timedelta([1, 2, 3])) - result = df.interpolate(method="time") - expected = Series([1.0, 2.0, 3.0], index=pd.to_timedelta([1, 2, 3])) - tm.assert_series_equal(result, expected) - - # test for non uniform spacing - df = Series([1, np.nan, 3], index=pd.to_timedelta([1, 2, 4])) - result = df.interpolate(method="time") - expected = Series([1.0, 1.666667, 3.0], index=pd.to_timedelta([1, 2, 4])) - tm.assert_series_equal(result, expected) - - def test_series_interpolate_method_values(self): - # GH#1646 - rng = date_range("1/1/2000", "1/20/2000", freq="D") - ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng) - - ts[::2] = np.nan - - result = ts.interpolate(method="values") - exp = ts.interpolate() - tm.assert_series_equal(result, exp) - - def test_series_interpolate_intraday(self): - # #1698 - index = date_range("1/1/2012", periods=4, freq="12D") - ts = Series([0, 12, 24, 36], index) - new_index = index.append(index + pd.DateOffset(days=1)).sort_values() - - exp = ts.reindex(new_index).interpolate(method="time") - - index = date_range("1/1/2012", periods=4, freq="12H") - ts = Series([0, 12, 24, 36], index) - new_index = index.append(index + pd.DateOffset(hours=1)).sort_values() - result = ts.reindex(new_index).interpolate(method="time") - - tm.assert_numpy_array_equal(result.values, exp.values) - - @pytest.mark.parametrize( - "ind", - [ - ["a", "b", "c", "d"], - pd.period_range(start="2019-01-01", periods=4), - pd.interval_range(start=0, end=4), - ], - ) - def test_interp_non_timedelta_index(self, interp_methods_ind, ind): - # gh 21662 - df = pd.DataFrame([0, 1, np.nan, 3], index=ind) - - method, kwargs = interp_methods_ind - if method == "pchip": - pytest.importorskip("scipy") - - if method == "linear": - result = df[0].interpolate(**kwargs) - expected = Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind) - tm.assert_series_equal(result, expected) - else: - expected_error = ( - "Index column must be numeric or datetime type when " - f"using {method} method other than linear. " - "Try setting a numeric or datetime index column before " - "interpolating." - ) - with pytest.raises(ValueError, match=expected_error): - df[0].interpolate(method=method, **kwargs) - - def test_interpolate_timedelta_index(self, request, interp_methods_ind): - """ - Tests for non numerical index types - object, period, timedelta - Note that all methods except time, index, nearest and values - are tested here. - """ - # gh 21662 - pytest.importorskip("scipy") - ind = pd.timedelta_range(start=1, periods=4) - df = pd.DataFrame([0, 1, np.nan, 3], index=ind) - - method, kwargs = interp_methods_ind - - if method in {"cubic", "zero"}: - request.node.add_marker( - pytest.mark.xfail( - reason=f"{method} interpolation is not supported for TimedeltaIndex" - ) - ) - result = df[0].interpolate(method=method, **kwargs) - expected = Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize( - "ascending, expected_values", - [(True, [1, 2, 3, 9, 10]), (False, [10, 9, 3, 2, 1])], - ) - def test_interpolate_unsorted_index(self, ascending, expected_values): - # GH 21037 - ts = Series(data=[10, 9, np.nan, 2, 1], index=[10, 9, 3, 2, 1]) - result = ts.sort_index(ascending=ascending).interpolate(method="index") - expected = Series(data=expected_values, index=expected_values, dtype=float) - tm.assert_series_equal(result, expected) - - def test_interpolate_asfreq_raises(self): - ser = Series(["a", None, "b"], dtype=object) - msg2 = "Series.interpolate with object dtype" - msg = "Invalid fill method" - with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, match=msg2): - ser.interpolate(method="asfreq") - - def test_interpolate_fill_value(self): - # GH#54920 - pytest.importorskip("scipy") - ser = Series([np.nan, 0, 1, np.nan, 3, np.nan]) - result = ser.interpolate(method="nearest", fill_value=0) - expected = Series([np.nan, 0, 1, 1, 3, 0]) - tm.assert_series_equal(result, expected) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/packaging/_manylinux.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/packaging/_manylinux.py deleted file mode 100644 index 4c379aa6f69ff56c8f19612002c6e3e939ea6012..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pip/_vendor/packaging/_manylinux.py +++ /dev/null @@ -1,301 +0,0 @@ -import collections -import functools -import os -import re -import struct -import sys -import warnings -from typing import IO, Dict, Iterator, NamedTuple, Optional, Tuple - - -# Python does not provide platform information at sufficient granularity to -# identify the architecture of the running executable in some cases, so we -# determine it dynamically by reading the information from the running -# process. This only applies on Linux, which uses the ELF format. -class _ELFFileHeader: - # https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header - class _InvalidELFFileHeader(ValueError): - """ - An invalid ELF file header was found. - """ - - ELF_MAGIC_NUMBER = 0x7F454C46 - ELFCLASS32 = 1 - ELFCLASS64 = 2 - ELFDATA2LSB = 1 - ELFDATA2MSB = 2 - EM_386 = 3 - EM_S390 = 22 - EM_ARM = 40 - EM_X86_64 = 62 - EF_ARM_ABIMASK = 0xFF000000 - EF_ARM_ABI_VER5 = 0x05000000 - EF_ARM_ABI_FLOAT_HARD = 0x00000400 - - def __init__(self, file: IO[bytes]) -> None: - def unpack(fmt: str) -> int: - try: - data = file.read(struct.calcsize(fmt)) - result: Tuple[int, ...] = struct.unpack(fmt, data) - except struct.error: - raise _ELFFileHeader._InvalidELFFileHeader() - return result[0] - - self.e_ident_magic = unpack(">I") - if self.e_ident_magic != self.ELF_MAGIC_NUMBER: - raise _ELFFileHeader._InvalidELFFileHeader() - self.e_ident_class = unpack("B") - if self.e_ident_class not in {self.ELFCLASS32, self.ELFCLASS64}: - raise _ELFFileHeader._InvalidELFFileHeader() - self.e_ident_data = unpack("B") - if self.e_ident_data not in {self.ELFDATA2LSB, self.ELFDATA2MSB}: - raise _ELFFileHeader._InvalidELFFileHeader() - self.e_ident_version = unpack("B") - self.e_ident_osabi = unpack("B") - self.e_ident_abiversion = unpack("B") - self.e_ident_pad = file.read(7) - format_h = "H" - format_i = "I" - format_q = "Q" - format_p = format_i if self.e_ident_class == self.ELFCLASS32 else format_q - self.e_type = unpack(format_h) - self.e_machine = unpack(format_h) - self.e_version = unpack(format_i) - self.e_entry = unpack(format_p) - self.e_phoff = unpack(format_p) - self.e_shoff = unpack(format_p) - self.e_flags = unpack(format_i) - self.e_ehsize = unpack(format_h) - self.e_phentsize = unpack(format_h) - self.e_phnum = unpack(format_h) - self.e_shentsize = unpack(format_h) - self.e_shnum = unpack(format_h) - self.e_shstrndx = unpack(format_h) - - -def _get_elf_header() -> Optional[_ELFFileHeader]: - try: - with open(sys.executable, "rb") as f: - elf_header = _ELFFileHeader(f) - except (OSError, TypeError, _ELFFileHeader._InvalidELFFileHeader): - return None - return elf_header - - -def _is_linux_armhf() -> bool: - # hard-float ABI can be detected from the ELF header of the running - # process - # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf - elf_header = _get_elf_header() - if elf_header is None: - return False - result = elf_header.e_ident_class == elf_header.ELFCLASS32 - result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB - result &= elf_header.e_machine == elf_header.EM_ARM - result &= ( - elf_header.e_flags & elf_header.EF_ARM_ABIMASK - ) == elf_header.EF_ARM_ABI_VER5 - result &= ( - elf_header.e_flags & elf_header.EF_ARM_ABI_FLOAT_HARD - ) == elf_header.EF_ARM_ABI_FLOAT_HARD - return result - - -def _is_linux_i686() -> bool: - elf_header = _get_elf_header() - if elf_header is None: - return False - result = elf_header.e_ident_class == elf_header.ELFCLASS32 - result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB - result &= elf_header.e_machine == elf_header.EM_386 - return result - - -def _have_compatible_abi(arch: str) -> bool: - if arch == "armv7l": - return _is_linux_armhf() - if arch == "i686": - return _is_linux_i686() - return arch in {"x86_64", "aarch64", "ppc64", "ppc64le", "s390x"} - - -# If glibc ever changes its major version, we need to know what the last -# minor version was, so we can build the complete list of all versions. -# For now, guess what the highest minor version might be, assume it will -# be 50 for testing. Once this actually happens, update the dictionary -# with the actual value. -_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50) - - -class _GLibCVersion(NamedTuple): - major: int - minor: int - - -def _glibc_version_string_confstr() -> Optional[str]: - """ - Primary implementation of glibc_version_string using os.confstr. - """ - # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely - # to be broken or missing. This strategy is used in the standard library - # platform module. - # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 - try: - # os.confstr("CS_GNU_LIBC_VERSION") returns a string like "glibc 2.17". - version_string = os.confstr("CS_GNU_LIBC_VERSION") - assert version_string is not None - _, version = version_string.split() - except (AssertionError, AttributeError, OSError, ValueError): - # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... - return None - return version - - -def _glibc_version_string_ctypes() -> Optional[str]: - """ - Fallback implementation of glibc_version_string using ctypes. - """ - try: - import ctypes - except ImportError: - return None - - # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen - # manpage says, "If filename is NULL, then the returned handle is for the - # main program". This way we can let the linker do the work to figure out - # which libc our process is actually using. - # - # We must also handle the special case where the executable is not a - # dynamically linked executable. This can occur when using musl libc, - # for example. In this situation, dlopen() will error, leading to an - # OSError. Interestingly, at least in the case of musl, there is no - # errno set on the OSError. The single string argument used to construct - # OSError comes from libc itself and is therefore not portable to - # hard code here. In any case, failure to call dlopen() means we - # can proceed, so we bail on our attempt. - try: - process_namespace = ctypes.CDLL(None) - except OSError: - return None - - try: - gnu_get_libc_version = process_namespace.gnu_get_libc_version - except AttributeError: - # Symbol doesn't exist -> therefore, we are not linked to - # glibc. - return None - - # Call gnu_get_libc_version, which returns a string like "2.5" - gnu_get_libc_version.restype = ctypes.c_char_p - version_str: str = gnu_get_libc_version() - # py2 / py3 compatibility: - if not isinstance(version_str, str): - version_str = version_str.decode("ascii") - - return version_str - - -def _glibc_version_string() -> Optional[str]: - """Returns glibc version string, or None if not using glibc.""" - return _glibc_version_string_confstr() or _glibc_version_string_ctypes() - - -def _parse_glibc_version(version_str: str) -> Tuple[int, int]: - """Parse glibc version. - - We use a regexp instead of str.split because we want to discard any - random junk that might come after the minor version -- this might happen - in patched/forked versions of glibc (e.g. Linaro's version of glibc - uses version strings like "2.20-2014.11"). See gh-3588. - """ - m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) - if not m: - warnings.warn( - "Expected glibc version with 2 components major.minor," - " got: %s" % version_str, - RuntimeWarning, - ) - return -1, -1 - return int(m.group("major")), int(m.group("minor")) - - -@functools.lru_cache() -def _get_glibc_version() -> Tuple[int, int]: - version_str = _glibc_version_string() - if version_str is None: - return (-1, -1) - return _parse_glibc_version(version_str) - - -# From PEP 513, PEP 600 -def _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool: - sys_glibc = _get_glibc_version() - if sys_glibc < version: - return False - # Check for presence of _manylinux module. - try: - import _manylinux # noqa - except ImportError: - return True - if hasattr(_manylinux, "manylinux_compatible"): - result = _manylinux.manylinux_compatible(version[0], version[1], arch) - if result is not None: - return bool(result) - return True - if version == _GLibCVersion(2, 5): - if hasattr(_manylinux, "manylinux1_compatible"): - return bool(_manylinux.manylinux1_compatible) - if version == _GLibCVersion(2, 12): - if hasattr(_manylinux, "manylinux2010_compatible"): - return bool(_manylinux.manylinux2010_compatible) - if version == _GLibCVersion(2, 17): - if hasattr(_manylinux, "manylinux2014_compatible"): - return bool(_manylinux.manylinux2014_compatible) - return True - - -_LEGACY_MANYLINUX_MAP = { - # CentOS 7 w/ glibc 2.17 (PEP 599) - (2, 17): "manylinux2014", - # CentOS 6 w/ glibc 2.12 (PEP 571) - (2, 12): "manylinux2010", - # CentOS 5 w/ glibc 2.5 (PEP 513) - (2, 5): "manylinux1", -} - - -def platform_tags(linux: str, arch: str) -> Iterator[str]: - if not _have_compatible_abi(arch): - return - # Oldest glibc to be supported regardless of architecture is (2, 17). - too_old_glibc2 = _GLibCVersion(2, 16) - if arch in {"x86_64", "i686"}: - # On x86/i686 also oldest glibc to be supported is (2, 5). - too_old_glibc2 = _GLibCVersion(2, 4) - current_glibc = _GLibCVersion(*_get_glibc_version()) - glibc_max_list = [current_glibc] - # We can assume compatibility across glibc major versions. - # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 - # - # Build a list of maximum glibc versions so that we can - # output the canonical list of all glibc from current_glibc - # down to too_old_glibc2, including all intermediary versions. - for glibc_major in range(current_glibc.major - 1, 1, -1): - glibc_minor = _LAST_GLIBC_MINOR[glibc_major] - glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) - for glibc_max in glibc_max_list: - if glibc_max.major == too_old_glibc2.major: - min_minor = too_old_glibc2.minor - else: - # For other glibc major versions oldest supported is (x, 0). - min_minor = -1 - for glibc_minor in range(glibc_max.minor, min_minor, -1): - glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) - tag = "manylinux_{}_{}".format(*glibc_version) - if _is_compatible(tag, arch, glibc_version): - yield linux.replace("linux", tag) - # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. - if glibc_version in _LEGACY_MANYLINUX_MAP: - legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version] - if _is_compatible(legacy_tag, arch, glibc_version): - yield linux.replace("linux", legacy_tag) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/plugin.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/plugin.py deleted file mode 100644 index 0de47bace8f3e1444f4ffcfff5ccd458deb008b6..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pygments/plugin.py +++ /dev/null @@ -1,88 +0,0 @@ -""" - pygments.plugin - ~~~~~~~~~~~~~~~ - - Pygments plugin interface. By default, this tries to use - ``importlib.metadata``, which is in the Python standard - library since Python 3.8, or its ``importlib_metadata`` - backport for earlier versions of Python. It falls back on - ``pkg_resources`` if not found. Finally, if ``pkg_resources`` - is not found either, no plugins are loaded at all. - - lexer plugins:: - - [pygments.lexers] - yourlexer = yourmodule:YourLexer - - formatter plugins:: - - [pygments.formatters] - yourformatter = yourformatter:YourFormatter - /.ext = yourformatter:YourFormatter - - As you can see, you can define extensions for the formatter - with a leading slash. - - syntax plugins:: - - [pygments.styles] - yourstyle = yourstyle:YourStyle - - filter plugin:: - - [pygments.filter] - yourfilter = yourfilter:YourFilter - - - :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -LEXER_ENTRY_POINT = 'pygments.lexers' -FORMATTER_ENTRY_POINT = 'pygments.formatters' -STYLE_ENTRY_POINT = 'pygments.styles' -FILTER_ENTRY_POINT = 'pygments.filters' - - -def iter_entry_points(group_name): - try: - from importlib.metadata import entry_points - except ImportError: - try: - from importlib_metadata import entry_points - except ImportError: - try: - from pkg_resources import iter_entry_points - except (ImportError, OSError): - return [] - else: - return iter_entry_points(group_name) - groups = entry_points() - if hasattr(groups, 'select'): - # New interface in Python 3.10 and newer versions of the - # importlib_metadata backport. - return groups.select(group=group_name) - else: - # Older interface, deprecated in Python 3.10 and recent - # importlib_metadata, but we need it in Python 3.8 and 3.9. - return groups.get(group_name, []) - - -def find_plugin_lexers(): - for entrypoint in iter_entry_points(LEXER_ENTRY_POINT): - yield entrypoint.load() - - -def find_plugin_formatters(): - for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT): - yield entrypoint.name, entrypoint.load() - - -def find_plugin_styles(): - for entrypoint in iter_entry_points(STYLE_ENTRY_POINT): - yield entrypoint.name, entrypoint.load() - - -def find_plugin_filters(): - for entrypoint in iter_entry_points(FILTER_ENTRY_POINT): - yield entrypoint.name, entrypoint.load() diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pyparsing/helpers.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pyparsing/helpers.py deleted file mode 100644 index 018f0d6ac863f2e4a27636c721669061887ae554..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/pyparsing/helpers.py +++ /dev/null @@ -1,1100 +0,0 @@ -# helpers.py -import html.entities -import re -import sys -import typing - -from . import __diag__ -from .core import * -from .util import ( - _bslash, - _flatten, - _escape_regex_range_chars, - replaced_by_pep8, -) - - -# -# global helpers -# -def counted_array( - expr: ParserElement, - int_expr: typing.Optional[ParserElement] = None, - *, - intExpr: typing.Optional[ParserElement] = None, -) -> ParserElement: - """Helper to define a counted list of expressions. - - This helper defines a pattern of the form:: - - integer expr expr expr... - - where the leading integer tells how many expr expressions follow. - The matched tokens returns the array of expr tokens as a list - the - leading count token is suppressed. - - If ``int_expr`` is specified, it should be a pyparsing expression - that produces an integer value. - - Example:: - - counted_array(Word(alphas)).parse_string('2 ab cd ef') # -> ['ab', 'cd'] - - # in this parser, the leading integer value is given in binary, - # '10' indicating that 2 values are in the array - binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2)) - counted_array(Word(alphas), int_expr=binary_constant).parse_string('10 ab cd ef') # -> ['ab', 'cd'] - - # if other fields must be parsed after the count but before the - # list items, give the fields results names and they will - # be preserved in the returned ParseResults: - count_with_metadata = integer + Word(alphas)("type") - typed_array = counted_array(Word(alphanums), int_expr=count_with_metadata)("items") - result = typed_array.parse_string("3 bool True True False") - print(result.dump()) - - # prints - # ['True', 'True', 'False'] - # - items: ['True', 'True', 'False'] - # - type: 'bool' - """ - intExpr = intExpr or int_expr - array_expr = Forward() - - def count_field_parse_action(s, l, t): - nonlocal array_expr - n = t[0] - array_expr <<= (expr * n) if n else Empty() - # clear list contents, but keep any named results - del t[:] - - if intExpr is None: - intExpr = Word(nums).set_parse_action(lambda t: int(t[0])) - else: - intExpr = intExpr.copy() - intExpr.set_name("arrayLen") - intExpr.add_parse_action(count_field_parse_action, call_during_try=True) - return (intExpr + array_expr).set_name("(len) " + str(expr) + "...") - - -def match_previous_literal(expr: ParserElement) -> ParserElement: - """Helper to define an expression that is indirectly defined from - the tokens matched in a previous expression, that is, it looks for - a 'repeat' of a previous expression. For example:: - - first = Word(nums) - second = match_previous_literal(first) - match_expr = first + ":" + second - - will match ``"1:1"``, but not ``"1:2"``. Because this - matches a previous literal, will also match the leading - ``"1:1"`` in ``"1:10"``. If this is not desired, use - :class:`match_previous_expr`. Do *not* use with packrat parsing - enabled. - """ - rep = Forward() - - def copy_token_to_repeater(s, l, t): - if t: - if len(t) == 1: - rep << t[0] - else: - # flatten t tokens - tflat = _flatten(t.as_list()) - rep << And(Literal(tt) for tt in tflat) - else: - rep << Empty() - - expr.add_parse_action(copy_token_to_repeater, callDuringTry=True) - rep.set_name("(prev) " + str(expr)) - return rep - - -def match_previous_expr(expr: ParserElement) -> ParserElement: - """Helper to define an expression that is indirectly defined from - the tokens matched in a previous expression, that is, it looks for - a 'repeat' of a previous expression. For example:: - - first = Word(nums) - second = match_previous_expr(first) - match_expr = first + ":" + second - - will match ``"1:1"``, but not ``"1:2"``. Because this - matches by expressions, will *not* match the leading ``"1:1"`` - in ``"1:10"``; the expressions are evaluated first, and then - compared, so ``"1"`` is compared with ``"10"``. Do *not* use - with packrat parsing enabled. - """ - rep = Forward() - e2 = expr.copy() - rep <<= e2 - - def copy_token_to_repeater(s, l, t): - matchTokens = _flatten(t.as_list()) - - def must_match_these_tokens(s, l, t): - theseTokens = _flatten(t.as_list()) - if theseTokens != matchTokens: - raise ParseException( - s, l, f"Expected {matchTokens}, found{theseTokens}" - ) - - rep.set_parse_action(must_match_these_tokens, callDuringTry=True) - - expr.add_parse_action(copy_token_to_repeater, callDuringTry=True) - rep.set_name("(prev) " + str(expr)) - return rep - - -def one_of( - strs: Union[typing.Iterable[str], str], - caseless: bool = False, - use_regex: bool = True, - as_keyword: bool = False, - *, - useRegex: bool = True, - asKeyword: bool = False, -) -> ParserElement: - """Helper to quickly define a set of alternative :class:`Literal` s, - and makes sure to do longest-first testing when there is a conflict, - regardless of the input order, but returns - a :class:`MatchFirst` for best performance. - - Parameters: - - - ``strs`` - a string of space-delimited literals, or a collection of - string literals - - ``caseless`` - treat all literals as caseless - (default= ``False``) - - ``use_regex`` - as an optimization, will - generate a :class:`Regex` object; otherwise, will generate - a :class:`MatchFirst` object (if ``caseless=True`` or ``as_keyword=True``, or if - creating a :class:`Regex` raises an exception) - (default= ``True``) - - ``as_keyword`` - enforce :class:`Keyword`-style matching on the - generated expressions - (default= ``False``) - - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility, - but will be removed in a future release - - Example:: - - comp_oper = one_of("< = > <= >= !=") - var = Word(alphas) - number = Word(nums) - term = var | number - comparison_expr = term + comp_oper + term - print(comparison_expr.search_string("B = 12 AA=23 B<=AA AA>12")) - - prints:: - - [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] - """ - asKeyword = asKeyword or as_keyword - useRegex = useRegex and use_regex - - if ( - isinstance(caseless, str_type) - and __diag__.warn_on_multiple_string_args_to_oneof - ): - warnings.warn( - "More than one string argument passed to one_of, pass" - " choices as a list or space-delimited string", - stacklevel=2, - ) - - if caseless: - isequal = lambda a, b: a.upper() == b.upper() - masks = lambda a, b: b.upper().startswith(a.upper()) - parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral - else: - isequal = lambda a, b: a == b - masks = lambda a, b: b.startswith(a) - parseElementClass = Keyword if asKeyword else Literal - - symbols: List[str] = [] - if isinstance(strs, str_type): - strs = typing.cast(str, strs) - symbols = strs.split() - elif isinstance(strs, Iterable): - symbols = list(strs) - else: - raise TypeError("Invalid argument to one_of, expected string or iterable") - if not symbols: - return NoMatch() - - # reorder given symbols to take care to avoid masking longer choices with shorter ones - # (but only if the given symbols are not just single characters) - if any(len(sym) > 1 for sym in symbols): - i = 0 - while i < len(symbols) - 1: - cur = symbols[i] - for j, other in enumerate(symbols[i + 1 :]): - if isequal(other, cur): - del symbols[i + j + 1] - break - elif masks(cur, other): - del symbols[i + j + 1] - symbols.insert(i, other) - break - else: - i += 1 - - if useRegex: - re_flags: int = re.IGNORECASE if caseless else 0 - - try: - if all(len(sym) == 1 for sym in symbols): - # symbols are just single characters, create range regex pattern - patt = f"[{''.join(_escape_regex_range_chars(sym) for sym in symbols)}]" - else: - patt = "|".join(re.escape(sym) for sym in symbols) - - # wrap with \b word break markers if defining as keywords - if asKeyword: - patt = rf"\b(?:{patt})\b" - - ret = Regex(patt, flags=re_flags).set_name(" | ".join(symbols)) - - if caseless: - # add parse action to return symbols as specified, not in random - # casing as found in input string - symbol_map = {sym.lower(): sym for sym in symbols} - ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()]) - - return ret - - except re.error: - warnings.warn( - "Exception creating Regex for one_of, building MatchFirst", stacklevel=2 - ) - - # last resort, just use MatchFirst - return MatchFirst(parseElementClass(sym) for sym in symbols).set_name( - " | ".join(symbols) - ) - - -def dict_of(key: ParserElement, value: ParserElement) -> ParserElement: - """Helper to easily and clearly define a dictionary by specifying - the respective patterns for the key and value. Takes care of - defining the :class:`Dict`, :class:`ZeroOrMore`, and - :class:`Group` tokens in the proper order. The key pattern - can include delimiting markers or punctuation, as long as they are - suppressed, thereby leaving the significant key text. The value - pattern can include named results, so that the :class:`Dict` results - can include named token fields. - - Example:: - - text = "shape: SQUARE posn: upper left color: light blue texture: burlap" - attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)) - print(attr_expr[1, ...].parse_string(text).dump()) - - attr_label = label - attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join) - - # similar to Dict, but simpler call format - result = dict_of(attr_label, attr_value).parse_string(text) - print(result.dump()) - print(result['shape']) - print(result.shape) # object attribute access works too - print(result.as_dict()) - - prints:: - - [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - - color: 'light blue' - - posn: 'upper left' - - shape: 'SQUARE' - - texture: 'burlap' - SQUARE - SQUARE - {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} - """ - return Dict(OneOrMore(Group(key + value))) - - -def original_text_for( - expr: ParserElement, as_string: bool = True, *, asString: bool = True -) -> ParserElement: - """Helper to return the original, untokenized text for a given - expression. Useful to restore the parsed fields of an HTML start - tag into the raw tag text itself, or to revert separate tokens with - intervening whitespace back to the original matching input text. By - default, returns a string containing the original parsed text. - - If the optional ``as_string`` argument is passed as - ``False``, then the return value is - a :class:`ParseResults` containing any results names that - were originally matched, and a single token containing the original - matched text from the input string. So if the expression passed to - :class:`original_text_for` contains expressions with defined - results names, you must set ``as_string`` to ``False`` if you - want to preserve those results name values. - - The ``asString`` pre-PEP8 argument is retained for compatibility, - but will be removed in a future release. - - Example:: - - src = "this is test bold text normal text " - for tag in ("b", "i"): - opener, closer = make_html_tags(tag) - patt = original_text_for(opener + ... + closer) - print(patt.search_string(src)[0]) - - prints:: - - [' bold text '] - ['text'] - """ - asString = asString and as_string - - locMarker = Empty().set_parse_action(lambda s, loc, t: loc) - endlocMarker = locMarker.copy() - endlocMarker.callPreparse = False - matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end") - if asString: - extractText = lambda s, l, t: s[t._original_start : t._original_end] - else: - - def extractText(s, l, t): - t[:] = [s[t.pop("_original_start") : t.pop("_original_end")]] - - matchExpr.set_parse_action(extractText) - matchExpr.ignoreExprs = expr.ignoreExprs - matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection) - return matchExpr - - -def ungroup(expr: ParserElement) -> ParserElement: - """Helper to undo pyparsing's default grouping of And expressions, - even if all but one are non-empty. - """ - return TokenConverter(expr).add_parse_action(lambda t: t[0]) - - -def locatedExpr(expr: ParserElement) -> ParserElement: - """ - (DEPRECATED - future code should use the :class:`Located` class) - Helper to decorate a returned token with its starting and ending - locations in the input string. - - This helper adds the following results names: - - - ``locn_start`` - location where matched expression begins - - ``locn_end`` - location where matched expression ends - - ``value`` - the actual parsed results - - Be careful if the input text contains ```` characters, you - may want to call :class:`ParserElement.parse_with_tabs` - - Example:: - - wd = Word(alphas) - for match in locatedExpr(wd).search_string("ljsdf123lksdjjf123lkkjj1222"): - print(match) - - prints:: - - [[0, 'ljsdf', 5]] - [[8, 'lksdjjf', 15]] - [[18, 'lkkjj', 23]] - """ - locator = Empty().set_parse_action(lambda ss, ll, tt: ll) - return Group( - locator("locn_start") - + expr("value") - + locator.copy().leaveWhitespace()("locn_end") - ) - - -def nested_expr( - opener: Union[str, ParserElement] = "(", - closer: Union[str, ParserElement] = ")", - content: typing.Optional[ParserElement] = None, - ignore_expr: ParserElement = quoted_string(), - *, - ignoreExpr: ParserElement = quoted_string(), -) -> ParserElement: - """Helper method for defining nested lists enclosed in opening and - closing delimiters (``"("`` and ``")"`` are the default). - - Parameters: - - - ``opener`` - opening character for a nested list - (default= ``"("``); can also be a pyparsing expression - - ``closer`` - closing character for a nested list - (default= ``")"``); can also be a pyparsing expression - - ``content`` - expression for items within the nested lists - (default= ``None``) - - ``ignore_expr`` - expression for ignoring opening and closing delimiters - (default= :class:`quoted_string`) - - ``ignoreExpr`` - this pre-PEP8 argument is retained for compatibility - but will be removed in a future release - - If an expression is not provided for the content argument, the - nested expression will capture all whitespace-delimited content - between delimiters as a list of separate values. - - Use the ``ignore_expr`` argument to define expressions that may - contain opening or closing characters that should not be treated as - opening or closing characters for nesting, such as quoted_string or - a comment expression. Specify multiple expressions using an - :class:`Or` or :class:`MatchFirst`. The default is - :class:`quoted_string`, but if no expressions are to be ignored, then - pass ``None`` for this argument. - - Example:: - - data_type = one_of("void int short long char float double") - decl_data_type = Combine(data_type + Opt(Word('*'))) - ident = Word(alphas+'_', alphanums+'_') - number = pyparsing_common.number - arg = Group(decl_data_type + ident) - LPAR, RPAR = map(Suppress, "()") - - code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment)) - - c_function = (decl_data_type("type") - + ident("name") - + LPAR + Opt(DelimitedList(arg), [])("args") + RPAR - + code_body("body")) - c_function.ignore(c_style_comment) - - source_code = ''' - int is_odd(int x) { - return (x%2); - } - - int dec_to_hex(char hchar) { - if (hchar >= '0' && hchar <= '9') { - return (ord(hchar)-ord('0')); - } else { - return (10+ord(hchar)-ord('A')); - } - } - ''' - for func in c_function.search_string(source_code): - print("%(name)s (%(type)s) args: %(args)s" % func) - - - prints:: - - is_odd (int) args: [['int', 'x']] - dec_to_hex (int) args: [['char', 'hchar']] - """ - if ignoreExpr != ignore_expr: - ignoreExpr = ignore_expr if ignoreExpr == quoted_string() else ignoreExpr - if opener == closer: - raise ValueError("opening and closing strings cannot be the same") - if content is None: - if isinstance(opener, str_type) and isinstance(closer, str_type): - opener = typing.cast(str, opener) - closer = typing.cast(str, closer) - if len(opener) == 1 and len(closer) == 1: - if ignoreExpr is not None: - content = Combine( - OneOrMore( - ~ignoreExpr - + CharsNotIn( - opener + closer + ParserElement.DEFAULT_WHITE_CHARS, - exact=1, - ) - ) - ).set_parse_action(lambda t: t[0].strip()) - else: - content = empty.copy() + CharsNotIn( - opener + closer + ParserElement.DEFAULT_WHITE_CHARS - ).set_parse_action(lambda t: t[0].strip()) - else: - if ignoreExpr is not None: - content = Combine( - OneOrMore( - ~ignoreExpr - + ~Literal(opener) - + ~Literal(closer) - + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) - ) - ).set_parse_action(lambda t: t[0].strip()) - else: - content = Combine( - OneOrMore( - ~Literal(opener) - + ~Literal(closer) - + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1) - ) - ).set_parse_action(lambda t: t[0].strip()) - else: - raise ValueError( - "opening and closing arguments must be strings if no content expression is given" - ) - ret = Forward() - if ignoreExpr is not None: - ret <<= Group( - Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer) - ) - else: - ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer)) - ret.set_name("nested %s%s expression" % (opener, closer)) - return ret - - -def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")): - """Internal helper to construct opening and closing tag expressions, given a tag name""" - if isinstance(tagStr, str_type): - resname = tagStr - tagStr = Keyword(tagStr, caseless=not xml) - else: - resname = tagStr.name - - tagAttrName = Word(alphas, alphanums + "_-:") - if xml: - tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes) - openTag = ( - suppress_LT - + tagStr("tag") - + Dict(ZeroOrMore(Group(tagAttrName + Suppress("=") + tagAttrValue))) - + Opt("/", default=[False])("empty").set_parse_action( - lambda s, l, t: t[0] == "/" - ) - + suppress_GT - ) - else: - tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word( - printables, exclude_chars=">" - ) - openTag = ( - suppress_LT - + tagStr("tag") - + Dict( - ZeroOrMore( - Group( - tagAttrName.set_parse_action(lambda t: t[0].lower()) - + Opt(Suppress("=") + tagAttrValue) - ) - ) - ) - + Opt("/", default=[False])("empty").set_parse_action( - lambda s, l, t: t[0] == "/" - ) - + suppress_GT - ) - closeTag = Combine(Literal("", adjacent=False) - - openTag.set_name("<%s>" % resname) - # add start results name in parse action now that ungrouped names are not reported at two levels - openTag.add_parse_action( - lambda t: t.__setitem__( - "start" + "".join(resname.replace(":", " ").title().split()), t.copy() - ) - ) - closeTag = closeTag( - "end" + "".join(resname.replace(":", " ").title().split()) - ).set_name("" % resname) - openTag.tag = resname - closeTag.tag = resname - openTag.tag_body = SkipTo(closeTag()) - return openTag, closeTag - - -def make_html_tags( - tag_str: Union[str, ParserElement] -) -> Tuple[ParserElement, ParserElement]: - """Helper to construct opening and closing tag expressions for HTML, - given a tag name. Matches tags in either upper or lower case, - attributes with namespaces and with quoted or unquoted values. - - Example:: - - text = 'More info at the pyparsing wiki page' - # make_html_tags returns pyparsing expressions for the opening and - # closing tags as a 2-tuple - a, a_end = make_html_tags("A") - link_expr = a + SkipTo(a_end)("link_text") + a_end - - for link in link_expr.search_string(text): - # attributes in the tag (like "href" shown here) are - # also accessible as named results - print(link.link_text, '->', link.href) - - prints:: - - pyparsing -> https://github.com/pyparsing/pyparsing/wiki - """ - return _makeTags(tag_str, False) - - -def make_xml_tags( - tag_str: Union[str, ParserElement] -) -> Tuple[ParserElement, ParserElement]: - """Helper to construct opening and closing tag expressions for XML, - given a tag name. Matches tags only in the given upper/lower case. - - Example: similar to :class:`make_html_tags` - """ - return _makeTags(tag_str, True) - - -any_open_tag: ParserElement -any_close_tag: ParserElement -any_open_tag, any_close_tag = make_html_tags( - Word(alphas, alphanums + "_:").set_name("any tag") -) - -_htmlEntityMap = {k.rstrip(";"): v for k, v in html.entities.html5.items()} -common_html_entity = Regex("&(?P" + "|".join(_htmlEntityMap) + ");").set_name( - "common HTML entity" -) - - -def replace_html_entity(s, l, t): - """Helper parser action to replace common HTML entities with their special characters""" - return _htmlEntityMap.get(t.entity) - - -class OpAssoc(Enum): - """Enumeration of operator associativity - - used in constructing InfixNotationOperatorSpec for :class:`infix_notation`""" - - LEFT = 1 - RIGHT = 2 - - -InfixNotationOperatorArgType = Union[ - ParserElement, str, Tuple[Union[ParserElement, str], Union[ParserElement, str]] -] -InfixNotationOperatorSpec = Union[ - Tuple[ - InfixNotationOperatorArgType, - int, - OpAssoc, - typing.Optional[ParseAction], - ], - Tuple[ - InfixNotationOperatorArgType, - int, - OpAssoc, - ], -] - - -def infix_notation( - base_expr: ParserElement, - op_list: List[InfixNotationOperatorSpec], - lpar: Union[str, ParserElement] = Suppress("("), - rpar: Union[str, ParserElement] = Suppress(")"), -) -> ParserElement: - """Helper method for constructing grammars of expressions made up of - operators working in a precedence hierarchy. Operators may be unary - or binary, left- or right-associative. Parse actions can also be - attached to operator expressions. The generated parser will also - recognize the use of parentheses to override operator precedences - (see example below). - - Note: if you define a deep operator list, you may see performance - issues when using infix_notation. See - :class:`ParserElement.enable_packrat` for a mechanism to potentially - improve your parser performance. - - Parameters: - - - ``base_expr`` - expression representing the most basic operand to - be used in the expression - - ``op_list`` - list of tuples, one for each operator precedence level - in the expression grammar; each tuple is of the form ``(op_expr, - num_operands, right_left_assoc, (optional)parse_action)``, where: - - - ``op_expr`` is the pyparsing expression for the operator; may also - be a string, which will be converted to a Literal; if ``num_operands`` - is 3, ``op_expr`` is a tuple of two expressions, for the two - operators separating the 3 terms - - ``num_operands`` is the number of terms for this operator (must be 1, - 2, or 3) - - ``right_left_assoc`` is the indicator whether the operator is right - or left associative, using the pyparsing-defined constants - ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``. - - ``parse_action`` is the parse action to be associated with - expressions matching this operator expression (the parse action - tuple member may be omitted); if the parse action is passed - a tuple or list of functions, this is equivalent to calling - ``set_parse_action(*fn)`` - (:class:`ParserElement.set_parse_action`) - - ``lpar`` - expression for matching left-parentheses; if passed as a - str, then will be parsed as ``Suppress(lpar)``. If lpar is passed as - an expression (such as ``Literal('(')``), then it will be kept in - the parsed results, and grouped with them. (default= ``Suppress('(')``) - - ``rpar`` - expression for matching right-parentheses; if passed as a - str, then will be parsed as ``Suppress(rpar)``. If rpar is passed as - an expression (such as ``Literal(')')``), then it will be kept in - the parsed results, and grouped with them. (default= ``Suppress(')')``) - - Example:: - - # simple example of four-function arithmetic with ints and - # variable names - integer = pyparsing_common.signed_integer - varname = pyparsing_common.identifier - - arith_expr = infix_notation(integer | varname, - [ - ('-', 1, OpAssoc.RIGHT), - (one_of('* /'), 2, OpAssoc.LEFT), - (one_of('+ -'), 2, OpAssoc.LEFT), - ]) - - arith_expr.run_tests(''' - 5+3*6 - (5+3)*6 - -2--11 - ''', full_dump=False) - - prints:: - - 5+3*6 - [[5, '+', [3, '*', 6]]] - - (5+3)*6 - [[[5, '+', 3], '*', 6]] - - (5+x)*y - [[[5, '+', 'x'], '*', 'y']] - - -2--11 - [[['-', 2], '-', ['-', 11]]] - """ - - # captive version of FollowedBy that does not do parse actions or capture results names - class _FB(FollowedBy): - def parseImpl(self, instring, loc, doActions=True): - self.expr.try_parse(instring, loc) - return loc, [] - - _FB.__name__ = "FollowedBy>" - - ret = Forward() - if isinstance(lpar, str): - lpar = Suppress(lpar) - if isinstance(rpar, str): - rpar = Suppress(rpar) - - # if lpar and rpar are not suppressed, wrap in group - if not (isinstance(rpar, Suppress) and isinstance(rpar, Suppress)): - lastExpr = base_expr | Group(lpar + ret + rpar) - else: - lastExpr = base_expr | (lpar + ret + rpar) - - arity: int - rightLeftAssoc: opAssoc - pa: typing.Optional[ParseAction] - opExpr1: ParserElement - opExpr2: ParserElement - for i, operDef in enumerate(op_list): - opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4] # type: ignore[assignment] - if isinstance(opExpr, str_type): - opExpr = ParserElement._literalStringClass(opExpr) - opExpr = typing.cast(ParserElement, opExpr) - if arity == 3: - if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2: - raise ValueError( - "if numterms=3, opExpr must be a tuple or list of two expressions" - ) - opExpr1, opExpr2 = opExpr - term_name = f"{opExpr1}{opExpr2} term" - else: - term_name = f"{opExpr} term" - - if not 1 <= arity <= 3: - raise ValueError("operator must be unary (1), binary (2), or ternary (3)") - - if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT): - raise ValueError("operator must indicate right or left associativity") - - thisExpr: ParserElement = Forward().set_name(term_name) - thisExpr = typing.cast(Forward, thisExpr) - if rightLeftAssoc is OpAssoc.LEFT: - if arity == 1: - matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + opExpr[1, ...]) - elif arity == 2: - if opExpr is not None: - matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group( - lastExpr + (opExpr + lastExpr)[1, ...] - ) - else: - matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr[2, ...]) - elif arity == 3: - matchExpr = _FB( - lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr - ) + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr)) - elif rightLeftAssoc is OpAssoc.RIGHT: - if arity == 1: - # try to avoid LR with this extra test - if not isinstance(opExpr, Opt): - opExpr = Opt(opExpr) - matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr) - elif arity == 2: - if opExpr is not None: - matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group( - lastExpr + (opExpr + thisExpr)[1, ...] - ) - else: - matchExpr = _FB(lastExpr + thisExpr) + Group( - lastExpr + thisExpr[1, ...] - ) - elif arity == 3: - matchExpr = _FB( - lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr - ) + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) - if pa: - if isinstance(pa, (tuple, list)): - matchExpr.set_parse_action(*pa) - else: - matchExpr.set_parse_action(pa) - thisExpr <<= (matchExpr | lastExpr).setName(term_name) - lastExpr = thisExpr - ret <<= lastExpr - return ret - - -def indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]): - """ - (DEPRECATED - use :class:`IndentedBlock` class instead) - Helper method for defining space-delimited indentation blocks, - such as those used to define block statements in Python source code. - - Parameters: - - - ``blockStatementExpr`` - expression defining syntax of statement that - is repeated within the indented block - - ``indentStack`` - list created by caller to manage indentation stack - (multiple ``statementWithIndentedBlock`` expressions within a single - grammar should share a common ``indentStack``) - - ``indent`` - boolean indicating whether block must be indented beyond - the current level; set to ``False`` for block of left-most statements - (default= ``True``) - - A valid block must contain at least one ``blockStatement``. - - (Note that indentedBlock uses internal parse actions which make it - incompatible with packrat parsing.) - - Example:: - - data = ''' - def A(z): - A1 - B = 100 - G = A2 - A2 - A3 - B - def BB(a,b,c): - BB1 - def BBA(): - bba1 - bba2 - bba3 - C - D - def spam(x,y): - def eggs(z): - pass - ''' - - - indentStack = [1] - stmt = Forward() - - identifier = Word(alphas, alphanums) - funcDecl = ("def" + identifier + Group("(" + Opt(delimitedList(identifier)) + ")") + ":") - func_body = indentedBlock(stmt, indentStack) - funcDef = Group(funcDecl + func_body) - - rvalue = Forward() - funcCall = Group(identifier + "(" + Opt(delimitedList(rvalue)) + ")") - rvalue << (funcCall | identifier | Word(nums)) - assignment = Group(identifier + "=" + rvalue) - stmt << (funcDef | assignment | identifier) - - module_body = stmt[1, ...] - - parseTree = module_body.parseString(data) - parseTree.pprint() - - prints:: - - [['def', - 'A', - ['(', 'z', ')'], - ':', - [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], - 'B', - ['def', - 'BB', - ['(', 'a', 'b', 'c', ')'], - ':', - [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], - 'C', - 'D', - ['def', - 'spam', - ['(', 'x', 'y', ')'], - ':', - [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] - """ - backup_stacks.append(indentStack[:]) - - def reset_stack(): - indentStack[:] = backup_stacks[-1] - - def checkPeerIndent(s, l, t): - if l >= len(s): - return - curCol = col(l, s) - if curCol != indentStack[-1]: - if curCol > indentStack[-1]: - raise ParseException(s, l, "illegal nesting") - raise ParseException(s, l, "not a peer entry") - - def checkSubIndent(s, l, t): - curCol = col(l, s) - if curCol > indentStack[-1]: - indentStack.append(curCol) - else: - raise ParseException(s, l, "not a subentry") - - def checkUnindent(s, l, t): - if l >= len(s): - return - curCol = col(l, s) - if not (indentStack and curCol in indentStack): - raise ParseException(s, l, "not an unindent") - if curCol < indentStack[-1]: - indentStack.pop() - - NL = OneOrMore(LineEnd().set_whitespace_chars("\t ").suppress()) - INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name("INDENT") - PEER = Empty().set_parse_action(checkPeerIndent).set_name("") - UNDENT = Empty().set_parse_action(checkUnindent).set_name("UNINDENT") - if indent: - smExpr = Group( - Opt(NL) - + INDENT - + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) - + UNDENT - ) - else: - smExpr = Group( - Opt(NL) - + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL)) - + Opt(UNDENT) - ) - - # add a parse action to remove backup_stack from list of backups - smExpr.add_parse_action( - lambda: backup_stacks.pop(-1) and None if backup_stacks else None - ) - smExpr.set_fail_action(lambda a, b, c, d: reset_stack()) - blockStatementExpr.ignore(_bslash + LineEnd()) - return smExpr.set_name("indented block") - - -# it's easy to get these comment structures wrong - they're very common, so may as well make them available -c_style_comment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + "*/").set_name( - "C style comment" -) -"Comment of the form ``/* ... */``" - -html_comment = Regex(r"").set_name("HTML comment") -"Comment of the form ````" - -rest_of_line = Regex(r".*").leave_whitespace().set_name("rest of line") -dbl_slash_comment = Regex(r"//(?:\\\n|[^\n])*").set_name("// comment") -"Comment of the form ``// ... (to end of line)``" - -cpp_style_comment = Combine( - Regex(r"/\*(?:[^*]|\*(?!/))*") + "*/" | dbl_slash_comment -).set_name("C++ style comment") -"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`" - -java_style_comment = cpp_style_comment -"Same as :class:`cpp_style_comment`" - -python_style_comment = Regex(r"#.*").set_name("Python style comment") -"Comment of the form ``# ... (to end of line)``" - - -# build list of built-in expressions, for future reference if a global default value -# gets updated -_builtin_exprs: List[ParserElement] = [ - v for v in vars().values() if isinstance(v, ParserElement) -] - - -# compatibility function, superseded by DelimitedList class -def delimited_list( - expr: Union[str, ParserElement], - delim: Union[str, ParserElement] = ",", - combine: bool = False, - min: typing.Optional[int] = None, - max: typing.Optional[int] = None, - *, - allow_trailing_delim: bool = False, -) -> ParserElement: - """(DEPRECATED - use :class:`DelimitedList` class)""" - return DelimitedList( - expr, delim, combine, min, max, allow_trailing_delim=allow_trailing_delim - ) - - -# pre-PEP8 compatible names -# fmt: off -opAssoc = OpAssoc -anyOpenTag = any_open_tag -anyCloseTag = any_close_tag -commonHTMLEntity = common_html_entity -cStyleComment = c_style_comment -htmlComment = html_comment -restOfLine = rest_of_line -dblSlashComment = dbl_slash_comment -cppStyleComment = cpp_style_comment -javaStyleComment = java_style_comment -pythonStyleComment = python_style_comment - -@replaced_by_pep8(DelimitedList) -def delimitedList(): ... - -@replaced_by_pep8(DelimitedList) -def delimited_list(): ... - -@replaced_by_pep8(counted_array) -def countedArray(): ... - -@replaced_by_pep8(match_previous_literal) -def matchPreviousLiteral(): ... - -@replaced_by_pep8(match_previous_expr) -def matchPreviousExpr(): ... - -@replaced_by_pep8(one_of) -def oneOf(): ... - -@replaced_by_pep8(dict_of) -def dictOf(): ... - -@replaced_by_pep8(original_text_for) -def originalTextFor(): ... - -@replaced_by_pep8(nested_expr) -def nestedExpr(): ... - -@replaced_by_pep8(make_html_tags) -def makeHTMLTags(): ... - -@replaced_by_pep8(make_xml_tags) -def makeXMLTags(): ... - -@replaced_by_pep8(replace_html_entity) -def replaceHTMLEntity(): ... - -@replaced_by_pep8(infix_notation) -def infixNotation(): ... -# fmt: on diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/starlette/middleware/authentication.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/starlette/middleware/authentication.py deleted file mode 100644 index 76e4a246d2c0190627e388d43d28c5202d7c556b..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/starlette/middleware/authentication.py +++ /dev/null @@ -1,52 +0,0 @@ -import typing - -from starlette.authentication import ( - AuthCredentials, - AuthenticationBackend, - AuthenticationError, - UnauthenticatedUser, -) -from starlette.requests import HTTPConnection -from starlette.responses import PlainTextResponse, Response -from starlette.types import ASGIApp, Receive, Scope, Send - - -class AuthenticationMiddleware: - def __init__( - self, - app: ASGIApp, - backend: AuthenticationBackend, - on_error: typing.Optional[ - typing.Callable[[HTTPConnection, AuthenticationError], Response] - ] = None, - ) -> None: - self.app = app - self.backend = backend - self.on_error: typing.Callable[ - [HTTPConnection, AuthenticationError], Response - ] = (on_error if on_error is not None else self.default_on_error) - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] not in ["http", "websocket"]: - await self.app(scope, receive, send) - return - - conn = HTTPConnection(scope) - try: - auth_result = await self.backend.authenticate(conn) - except AuthenticationError as exc: - response = self.on_error(conn, exc) - if scope["type"] == "websocket": - await send({"type": "websocket.close", "code": 1000}) - else: - await response(scope, receive, send) - return - - if auth_result is None: - auth_result = AuthCredentials(), UnauthenticatedUser() - scope["auth"], scope["user"] = auth_result - await self.app(scope, receive, send) - - @staticmethod - def default_on_error(conn: HTTPConnection, exc: Exception) -> Response: - return PlainTextResponse(str(exc), status_code=400) diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/tzdata/zoneinfo/America/Argentina/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/websockets/server.py b/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/websockets/server.py deleted file mode 100644 index ecb0f74a692d76c7d225fb6f7319e23e7c6b25be..0000000000000000000000000000000000000000 --- a/spaces/profayle/TerrapinTalk/myenv/lib/python3.9/site-packages/websockets/server.py +++ /dev/null @@ -1,575 +0,0 @@ -from __future__ import annotations - -import base64 -import binascii -import email.utils -import http -import warnings -from typing import Any, Callable, Generator, List, Optional, Sequence, Tuple, cast - -from .datastructures import Headers, MultipleValuesError -from .exceptions import ( - InvalidHandshake, - InvalidHeader, - InvalidHeaderValue, - InvalidOrigin, - InvalidStatus, - InvalidUpgrade, - NegotiationError, -) -from .extensions import Extension, ServerExtensionFactory -from .headers import ( - build_extension, - parse_connection, - parse_extension, - parse_subprotocol, - parse_upgrade, -) -from .http11 import Request, Response -from .protocol import CONNECTING, OPEN, SERVER, Protocol, State -from .typing import ( - ConnectionOption, - ExtensionHeader, - LoggerLike, - Origin, - Subprotocol, - UpgradeProtocol, -) -from .utils import accept_key - - -# See #940 for why lazy_import isn't used here for backwards compatibility. -from .legacy.server import * # isort:skip # noqa: I001 - - -__all__ = ["ServerProtocol"] - - -class ServerProtocol(Protocol): - """ - Sans-I/O implementation of a WebSocket server connection. - - Args: - origins: acceptable values of the ``Origin`` header; include - :obj:`None` in the list if the lack of an origin is acceptable. - This is useful for defending against Cross-Site WebSocket - Hijacking attacks. - extensions: list of supported extensions, in order in which they - should be tried. - subprotocols: list of supported subprotocols, in order of decreasing - preference. - select_subprotocol: Callback for selecting a subprotocol among - those supported by the client and the server. It has the same - signature as the :meth:`select_subprotocol` method, including a - :class:`ServerProtocol` instance as first argument. - state: initial state of the WebSocket connection. - max_size: maximum size of incoming messages in bytes; - :obj:`None` disables the limit. - logger: logger for this connection; - defaults to ``logging.getLogger("websockets.client")``; - see the :doc:`logging guide <../../topics/logging>` for details. - - """ - - def __init__( - self, - *, - origins: Optional[Sequence[Optional[Origin]]] = None, - extensions: Optional[Sequence[ServerExtensionFactory]] = None, - subprotocols: Optional[Sequence[Subprotocol]] = None, - select_subprotocol: Optional[ - Callable[ - [ServerProtocol, Sequence[Subprotocol]], - Optional[Subprotocol], - ] - ] = None, - state: State = CONNECTING, - max_size: Optional[int] = 2**20, - logger: Optional[LoggerLike] = None, - ): - super().__init__( - side=SERVER, - state=state, - max_size=max_size, - logger=logger, - ) - self.origins = origins - self.available_extensions = extensions - self.available_subprotocols = subprotocols - if select_subprotocol is not None: - # Bind select_subprotocol then shadow self.select_subprotocol. - # Use setattr to work around https://github.com/python/mypy/issues/2427. - setattr( - self, - "select_subprotocol", - select_subprotocol.__get__(self, self.__class__), - ) - - def accept(self, request: Request) -> Response: - """ - Create a handshake response to accept the connection. - - If the connection cannot be established, the handshake response - actually rejects the handshake. - - You must send the handshake response with :meth:`send_response`. - - You may modify it before sending it, for example to add HTTP headers. - - Args: - request: WebSocket handshake request event received from the client. - - Returns: - WebSocket handshake response event to send to the client. - - """ - try: - ( - accept_header, - extensions_header, - protocol_header, - ) = self.process_request(request) - except InvalidOrigin as exc: - request._exception = exc - self.handshake_exc = exc - if self.debug: - self.logger.debug("! invalid origin", exc_info=True) - return self.reject( - http.HTTPStatus.FORBIDDEN, - f"Failed to open a WebSocket connection: {exc}.\n", - ) - except InvalidUpgrade as exc: - request._exception = exc - self.handshake_exc = exc - if self.debug: - self.logger.debug("! invalid upgrade", exc_info=True) - response = self.reject( - http.HTTPStatus.UPGRADE_REQUIRED, - ( - f"Failed to open a WebSocket connection: {exc}.\n" - f"\n" - f"You cannot access a WebSocket server directly " - f"with a browser. You need a WebSocket client.\n" - ), - ) - response.headers["Upgrade"] = "websocket" - return response - except InvalidHandshake as exc: - request._exception = exc - self.handshake_exc = exc - if self.debug: - self.logger.debug("! invalid handshake", exc_info=True) - return self.reject( - http.HTTPStatus.BAD_REQUEST, - f"Failed to open a WebSocket connection: {exc}.\n", - ) - except Exception as exc: - # Handle exceptions raised by user-provided select_subprotocol and - # unexpected errors. - request._exception = exc - self.handshake_exc = exc - self.logger.error("opening handshake failed", exc_info=True) - return self.reject( - http.HTTPStatus.INTERNAL_SERVER_ERROR, - ( - "Failed to open a WebSocket connection.\n" - "See server log for more information.\n" - ), - ) - - headers = Headers() - - headers["Date"] = email.utils.formatdate(usegmt=True) - - headers["Upgrade"] = "websocket" - headers["Connection"] = "Upgrade" - headers["Sec-WebSocket-Accept"] = accept_header - - if extensions_header is not None: - headers["Sec-WebSocket-Extensions"] = extensions_header - - if protocol_header is not None: - headers["Sec-WebSocket-Protocol"] = protocol_header - - self.logger.info("connection open") - return Response(101, "Switching Protocols", headers) - - def process_request( - self, - request: Request, - ) -> Tuple[str, Optional[str], Optional[str]]: - """ - Check a handshake request and negotiate extensions and subprotocol. - - This function doesn't verify that the request is an HTTP/1.1 or higher - GET request and doesn't check the ``Host`` header. These controls are - usually performed earlier in the HTTP request handling code. They're - the responsibility of the caller. - - Args: - request: WebSocket handshake request received from the client. - - Returns: - Tuple[str, Optional[str], Optional[str]]: - ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and - ``Sec-WebSocket-Protocol`` headers for the handshake response. - - Raises: - InvalidHandshake: if the handshake request is invalid; - then the server must return 400 Bad Request error. - - """ - headers = request.headers - - connection: List[ConnectionOption] = sum( - [parse_connection(value) for value in headers.get_all("Connection")], [] - ) - - if not any(value.lower() == "upgrade" for value in connection): - raise InvalidUpgrade( - "Connection", ", ".join(connection) if connection else None - ) - - upgrade: List[UpgradeProtocol] = sum( - [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] - ) - - # For compatibility with non-strict implementations, ignore case when - # checking the Upgrade header. The RFC always uses "websocket", except - # in section 11.2. (IANA registration) where it uses "WebSocket". - if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): - raise InvalidUpgrade("Upgrade", ", ".join(upgrade) if upgrade else None) - - try: - key = headers["Sec-WebSocket-Key"] - except KeyError as exc: - raise InvalidHeader("Sec-WebSocket-Key") from exc - except MultipleValuesError as exc: - raise InvalidHeader( - "Sec-WebSocket-Key", "more than one Sec-WebSocket-Key header found" - ) from exc - - try: - raw_key = base64.b64decode(key.encode(), validate=True) - except binascii.Error as exc: - raise InvalidHeaderValue("Sec-WebSocket-Key", key) from exc - if len(raw_key) != 16: - raise InvalidHeaderValue("Sec-WebSocket-Key", key) - - try: - version = headers["Sec-WebSocket-Version"] - except KeyError as exc: - raise InvalidHeader("Sec-WebSocket-Version") from exc - except MultipleValuesError as exc: - raise InvalidHeader( - "Sec-WebSocket-Version", - "more than one Sec-WebSocket-Version header found", - ) from exc - - if version != "13": - raise InvalidHeaderValue("Sec-WebSocket-Version", version) - - accept_header = accept_key(key) - - self.origin = self.process_origin(headers) - - extensions_header, self.extensions = self.process_extensions(headers) - - protocol_header = self.subprotocol = self.process_subprotocol(headers) - - return ( - accept_header, - extensions_header, - protocol_header, - ) - - def process_origin(self, headers: Headers) -> Optional[Origin]: - """ - Handle the Origin HTTP request header. - - Args: - headers: WebSocket handshake request headers. - - Returns: - Optional[Origin]: origin, if it is acceptable. - - Raises: - InvalidHandshake: if the Origin header is invalid. - InvalidOrigin: if the origin isn't acceptable. - - """ - # "The user agent MUST NOT include more than one Origin header field" - # per https://www.rfc-editor.org/rfc/rfc6454.html#section-7.3. - try: - origin = cast(Optional[Origin], headers.get("Origin")) - except MultipleValuesError as exc: - raise InvalidHeader("Origin", "more than one Origin header found") from exc - if self.origins is not None: - if origin not in self.origins: - raise InvalidOrigin(origin) - return origin - - def process_extensions( - self, - headers: Headers, - ) -> Tuple[Optional[str], List[Extension]]: - """ - Handle the Sec-WebSocket-Extensions HTTP request header. - - Accept or reject each extension proposed in the client request. - Negotiate parameters for accepted extensions. - - Per :rfc:`6455`, negotiation rules are defined by the specification of - each extension. - - To provide this level of flexibility, for each extension proposed by - the client, we check for a match with each extension available in the - server configuration. If no match is found, the extension is ignored. - - If several variants of the same extension are proposed by the client, - it may be accepted several times, which won't make sense in general. - Extensions must implement their own requirements. For this purpose, - the list of previously accepted extensions is provided. - - This process doesn't allow the server to reorder extensions. It can - only select a subset of the extensions proposed by the client. - - Other requirements, for example related to mandatory extensions or the - order of extensions, may be implemented by overriding this method. - - Args: - headers: WebSocket handshake request headers. - - Returns: - Tuple[Optional[str], List[Extension]]: ``Sec-WebSocket-Extensions`` - HTTP response header and list of accepted extensions. - - Raises: - InvalidHandshake: if the Sec-WebSocket-Extensions header is invalid. - - """ - response_header_value: Optional[str] = None - - extension_headers: List[ExtensionHeader] = [] - accepted_extensions: List[Extension] = [] - - header_values = headers.get_all("Sec-WebSocket-Extensions") - - if header_values and self.available_extensions: - parsed_header_values: List[ExtensionHeader] = sum( - [parse_extension(header_value) for header_value in header_values], [] - ) - - for name, request_params in parsed_header_values: - for ext_factory in self.available_extensions: - # Skip non-matching extensions based on their name. - if ext_factory.name != name: - continue - - # Skip non-matching extensions based on their params. - try: - response_params, extension = ext_factory.process_request_params( - request_params, accepted_extensions - ) - except NegotiationError: - continue - - # Add matching extension to the final list. - extension_headers.append((name, response_params)) - accepted_extensions.append(extension) - - # Break out of the loop once we have a match. - break - - # If we didn't break from the loop, no extension in our list - # matched what the client sent. The extension is declined. - - # Serialize extension header. - if extension_headers: - response_header_value = build_extension(extension_headers) - - return response_header_value, accepted_extensions - - def process_subprotocol(self, headers: Headers) -> Optional[Subprotocol]: - """ - Handle the Sec-WebSocket-Protocol HTTP request header. - - Args: - headers: WebSocket handshake request headers. - - Returns: - Optional[Subprotocol]: Subprotocol, if one was selected; this is - also the value of the ``Sec-WebSocket-Protocol`` response header. - - Raises: - InvalidHandshake: if the Sec-WebSocket-Subprotocol header is invalid. - - """ - subprotocols: Sequence[Subprotocol] = sum( - [ - parse_subprotocol(header_value) - for header_value in headers.get_all("Sec-WebSocket-Protocol") - ], - [], - ) - - return self.select_subprotocol(subprotocols) - - def select_subprotocol( - self, - subprotocols: Sequence[Subprotocol], - ) -> Optional[Subprotocol]: - """ - Pick a subprotocol among those offered by the client. - - If several subprotocols are supported by both the client and the server, - pick the first one in the list declared the server. - - If the server doesn't support any subprotocols, continue without a - subprotocol, regardless of what the client offers. - - If the server supports at least one subprotocol and the client doesn't - offer any, abort the handshake with an HTTP 400 error. - - You provide a ``select_subprotocol`` argument to :class:`ServerProtocol` - to override this logic. For example, you could accept the connection - even if client doesn't offer a subprotocol, rather than reject it. - - Here's how to negotiate the ``chat`` subprotocol if the client supports - it and continue without a subprotocol otherwise:: - - def select_subprotocol(protocol, subprotocols): - if "chat" in subprotocols: - return "chat" - - Args: - subprotocols: list of subprotocols offered by the client. - - Returns: - Optional[Subprotocol]: Selected subprotocol, if a common subprotocol - was found. - - :obj:`None` to continue without a subprotocol. - - Raises: - NegotiationError: custom implementations may raise this exception - to abort the handshake with an HTTP 400 error. - - """ - # Server doesn't offer any subprotocols. - if not self.available_subprotocols: # None or empty list - return None - - # Server offers at least one subprotocol but client doesn't offer any. - if not subprotocols: - raise NegotiationError("missing subprotocol") - - # Server and client both offer subprotocols. Look for a shared one. - proposed_subprotocols = set(subprotocols) - for subprotocol in self.available_subprotocols: - if subprotocol in proposed_subprotocols: - return subprotocol - - # No common subprotocol was found. - raise NegotiationError( - "invalid subprotocol; expected one of " - + ", ".join(self.available_subprotocols) - ) - - def reject( - self, - status: http.HTTPStatus, - text: str, - ) -> Response: - """ - Create a handshake response to reject the connection. - - A short plain text response is the best fallback when failing to - establish a WebSocket connection. - - You must send the handshake response with :meth:`send_response`. - - You can modify it before sending it, for example to alter HTTP headers. - - Args: - status: HTTP status code. - text: HTTP response body; will be encoded to UTF-8. - - Returns: - Response: WebSocket handshake response event to send to the client. - - """ - body = text.encode() - headers = Headers( - [ - ("Date", email.utils.formatdate(usegmt=True)), - ("Connection", "close"), - ("Content-Length", str(len(body))), - ("Content-Type", "text/plain; charset=utf-8"), - ] - ) - response = Response(status.value, status.phrase, headers, body) - # When reject() is called from accept(), handshake_exc is already set. - # If a user calls reject(), set handshake_exc to guarantee invariant: - # "handshake_exc is None if and only if opening handshake succeeded." - if self.handshake_exc is None: - self.handshake_exc = InvalidStatus(response) - self.logger.info("connection failed (%d %s)", status.value, status.phrase) - return response - - def send_response(self, response: Response) -> None: - """ - Send a handshake response to the client. - - Args: - response: WebSocket handshake response event to send. - - """ - if self.debug: - code, phrase = response.status_code, response.reason_phrase - self.logger.debug("> HTTP/1.1 %d %s", code, phrase) - for key, value in response.headers.raw_items(): - self.logger.debug("> %s: %s", key, value) - if response.body is not None: - self.logger.debug("> [body] (%d bytes)", len(response.body)) - - self.writes.append(response.serialize()) - - if response.status_code == 101: - assert self.state is CONNECTING - self.state = OPEN - else: - self.send_eof() - self.parser = self.discard() - next(self.parser) # start coroutine - - def parse(self) -> Generator[None, None, None]: - if self.state is CONNECTING: - try: - request = yield from Request.parse( - self.reader.read_line, - ) - except Exception as exc: - self.handshake_exc = exc - self.send_eof() - self.parser = self.discard() - next(self.parser) # start coroutine - yield - - if self.debug: - self.logger.debug("< GET %s HTTP/1.1", request.path) - for key, value in request.headers.raw_items(): - self.logger.debug("< %s: %s", key, value) - - self.events.append(request) - - yield from super().parse() - - -class ServerConnection(ServerProtocol): - def __init__(self, *args: Any, **kwargs: Any) -> None: - warnings.warn( - "ServerConnection was renamed to ServerProtocol", - DeprecationWarning, - ) - super().__init__(*args, **kwargs) diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Arcsoft Photoimpression 6.5 Gold Serial Keygen TOP.md b/spaces/quidiaMuxgu/Expedit-SAM/Arcsoft Photoimpression 6.5 Gold Serial Keygen TOP.md deleted file mode 100644 index 893fed3930131579055b0251d91975b00b65963a..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Arcsoft Photoimpression 6.5 Gold Serial Keygen TOP.md +++ /dev/null @@ -1,6 +0,0 @@ -

      arcsoft photoimpression 6.5 gold serial keygen


      DOWNLOAD --->>> https://geags.com/2uCsbG



      -
      -PhotoImpression Editor's Review Arcsoft's PhotoImpression is a ... crack or patch ArcSoft PhotoImpression 6.5 Gold serial numbers, cracks and. 1fdad05405
      -
      -
      -

      diff --git a/spaces/quidiaMuxgu/Expedit-SAM/B R Automation Studio 4 Download Crack For Idm [UPD].md b/spaces/quidiaMuxgu/Expedit-SAM/B R Automation Studio 4 Download Crack For Idm [UPD].md deleted file mode 100644 index f9698376600ea9d6de32a34ce57bd94bc0ef71ba..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/B R Automation Studio 4 Download Crack For Idm [UPD].md +++ /dev/null @@ -1,111 +0,0 @@ - -

      Corazon Salvaje English Subtitles: How to Watch and Enjoy the Classic Telenovela

      - -

      Corazon Salvaje (Wild Heart) is a Mexican telenovela that was released in 1993 and became one of the most popular and successful telenovelas of all time. It is based on the novel of the same name by Caridad Bravo Adams and tells the story of Juan del Diablo, a rebellious and passionate man who falls in love with Monica, a noble and innocent woman who is engaged to his half-brother.

      - -

      Corazon Salvaje is a masterpiece of romance, drama, adventure, and history that captivated millions of viewers around the world. It features an amazing cast of actors, such as Eduardo Palomo, Edith Gonzalez, Ana Colchero, Ariel Lopez Padilla, Enrique Lizalde, and Claudia Islas. It also has a beautiful soundtrack composed by Jorge Avendaño and performed by Mijares.

      -

      B r Automation Studio 4 Download Crack For Idm


      Download Zip >> https://geags.com/2uCqCv



      - -

      However, if you are not a native speaker of Spanish or you want to improve your Spanish skills, you may want to watch Corazon Salvaje with English subtitles. This way, you can understand every dialogue and emotion of this telenovela and enjoy it to the fullest. In this article, we will show you how to watch Corazon Salvaje with English subtitles and what are the benefits of doing so.

      - -

      How to Watch Corazon Salvaje with English Subtitles

      - -

      There are different ways to watch Corazon Salvaje with English subtitles, depending on your preferences and availability. Here are some of them:

      - -
        -
      • You can watch Corazon Salvaje with English subtitles on YouTube. There are several channels that upload the episodes of this telenovela with English subtitles, such as Corazon Salvaje Subtitled and Corazon Salvaje. You can search for them on YouTube and subscribe to them to get notified when they upload new episodes. You can also adjust the quality and speed of the videos according to your internet connection.
      • -
      • You can watch Corazon Salvaje with English subtitles on DVD. You can buy or rent the DVD box set of this telenovela from online or offline stores that sell or rent DVDs. The DVD box set contains all the episodes of this telenovela with English subtitles as an option. You can also enjoy other features such as behind-the-scenes footage, interviews, and bloopers.
      • -
      • You can watch Corazon Salvaje with English subtitles on streaming platforms. You can find this telenovela on some streaming platforms that offer Spanish-language content with English subtitles, such as Netflix or Hulu. You can sign up for these platforms and pay a monthly or yearly fee to access their content library. You can also watch this telenovela on any device that supports these platforms, such as your computer, smartphone, tablet, or smart TV.
      • -
      - -

      Benefits of Watching Corazon Salvaje with English Subtitles

      - -

      Watching Corazon Salvaje with English subtitles has many benefits that will enhance your viewing experience and enjoyment of this telenovela. Some of these benefits are:

      - -
        -
      • You can understand every dialogue and emotion of this telenovela without missing any detail or nuance. You can also learn new words and expressions in Spanish that may not have a direct translation in English.
      • -
      • You can improve your Spanish skills by listening to the original audio and reading the English subtitles at the same time. You can practice your listening comprehension, pronunciation, vocabulary, grammar, and syntax by following along with the dialogues and narrations.
      • -
      • You can appreciate the cultural and historical aspects of this telenovela more deeply by learning about the customs, traditions, values, beliefs, and events that shaped the lives and personalities of the characters.
      • -
      • You can enjoy the artistic and technical aspects of this telenovela more fully by noticing the cinematography, editing, music, costumes, makeup, and special effects that make this telenovela a visual and auditory feast.
      • -
      - -

      Conclusion

      - -

      Corazon Salvaje is a classic telenovela that deserves to be watched and enjoyed by everyone who loves romance, drama, adventure, and history. It is a captivating story that will make you laugh, cry, sigh, and dream with its unforgettable characters and scenes.

      - -

      If you want to watch Corazon Salvaje with English subtitles, you have different options to choose from depending on your preferences and availability. You can watch it on YouTube, DVD, or streaming platforms that offer Spanish-language content with English subtitles.

      -

      - -

      By watching Corazon Salvaje with English subtitles, you will not only understand every dialogue and emotion of this telenovela but also improve your Spanish skills, appreciate its cultural and historical aspects more deeply, and enjoy its artistic and technical aspects more fully.

      - -

      We hope that this article has helped you learn how to watch Corazon Salvaje with English subtitles and what are the benefits of doing so. If you have any questions or comments, please feel free to leave them below.

      -

      Reviews of Corazon Salvaje with English Subtitles

      - -

      Corazon Salvaje with English subtitles has received many positive reviews from viewers who have watched and enjoyed this telenovela. Here are some of them:

      - -
      -

      "I love Corazon Salvaje with English subtitles. It is a beautiful and captivating story that makes me feel all kinds of emotions. The actors are amazing and the music is wonderful. I recommend it to everyone who loves romance and drama."

      -- Maria, USA -
      - -
      -

      "Corazon Salvaje with English subtitles is one of the best telenovelas I have ever seen. It is a classic that never gets old. It has everything: love, hate, revenge, adventure, history, and culture. The subtitles are very clear and easy to follow. I learned a lot of Spanish by watching it."

      -- John, UK -
      - -
      -

      "Corazon Salvaje with English subtitles is a masterpiece of telenovela. It is a story that touches your heart and soul. The characters are unforgettable and the scenes are breathtaking. The subtitles are very accurate and helpful. I enjoyed every episode of it."

      -- Anna, Australia -
      - -

      Frequently Asked Questions about Corazon Salvaje with English Subtitles

      - -

      Here are some frequently asked questions and answers about Corazon Salvaje with English subtitles that may help you if you have any doubts or queries about this telenovela:

      - -
      -
      How many episodes are there in Corazon Salvaje with English subtitles?
      -
      There are 80 episodes in Corazon Salvaje with English subtitles, each lasting about 45 minutes.
      - -
      Where can I watch Corazon Salvaje with English subtitles?
      -
      You can watch Corazon Salvaje with English subtitles on YouTube, DVD, or streaming platforms that offer Spanish-language content with English subtitles, such as Netflix or Hulu.
      - -
      Is Corazon Salvaje with English subtitles suitable for children?
      -
      Corazon Salvaje with English subtitles is suitable for children above 13 years old, as it contains some scenes of violence, sexuality, and mature themes.
      - -
      Is Corazon Salvaje with English subtitles based on a true story?
      -
      Corazon Salvaje with English subtitles is not based on a true story, but it is inspired by the historical events and figures of Mexico in the late 19th century.
      - -
      Is Corazon Salvaje with English subtitles available in other languages?
      -
      Corazon Salvaje with English subtitles is available in other languages besides Spanish and English, such as French, Italian, Portuguese, German, and Arabic.
      -
      -

      History and Background of Corazon Salvaje with English Subtitles

      - -

      Corazon Salvaje with English subtitles is based on the novel of the same name by Caridad Bravo Adams, a Mexican writer who published it in 1957. The novel is set in Mexico in the late 19th century and tells the story of Juan del Diablo, a rebellious and passionate man who is the illegitimate son of a wealthy landowner and a poor peasant woman. Juan falls in love with Monica, a noble and innocent woman who is engaged to his half-brother Andres.

      - -

      The novel has been adapted into several telenovelas, movies, and radio dramas over the years. The most famous and successful adaptation is the 1993 telenovela produced by Televisa and starring Eduardo Palomo and Edith Gonzalez as Juan and Monica. The 1993 telenovela was a huge hit in Mexico and abroad, winning several awards and breaking ratings records. It was also praised for its faithful adaptation of the novel, its high production values, its historical accuracy, and its outstanding performances.

      - -

      Corazon Salvaje with English subtitles is a way to watch and enjoy the 1993 telenovela with subtitles in English for those who do not speak or understand Spanish. The subtitles are made by fans who love this telenovela and want to share it with others who may not know Spanish or want to improve their Spanish skills. The subtitles are available on various platforms such as YouTube, DVD, or streaming services.

      - -

      Characters and Cast of Corazon Salvaje with English Subtitles

      - -

      Corazon Salvaje with English subtitles has a large and talented cast of actors who bring to life the complex and fascinating characters of this telenovela. Here are some of the main characters and their actors:

      - -
        -
      • Juan del Diablo (Eduardo Palomo): He is the protagonist of this telenovela. He is a rebellious and passionate man who lives by his own rules. He is the illegitimate son of Francisco Alcazar, a wealthy landowner, and Guadalupe, a poor peasant woman. He grows up in poverty and suffers from discrimination and abuse. He becomes a smuggler and a pirate to survive and to get revenge on his father and his half-brothers. He falls in love with Monica, a noble and innocent woman who is engaged to his half-brother Andres.
      • -
      • Monica Molina (Edith Gonzalez): She is the female protagonist of this telenovela. She is a noble and innocent woman who lives in Veracruz with her father Don Noel, her sister Aimee, and her aunt Prudencia. She is engaged to Andres Alcazar, her childhood friend and cousin, but she does not love him. She meets Juan del Diablo by chance and feels an instant attraction to him. She eventually marries him and discovers his true identity.
      • -
      • Aimee Molina (Ana Colchero): She is Monica's sister and rival. She is a beautiful and ambitious woman who wants to marry Andres Alcazar for his money and status. She does not care about Monica's feelings or happiness. She schemes to separate Monica and Juan del Diablo by seducing Juan and lying to him that she is pregnant with his child.
      • -
      • Andres Alcazar (Ariel Lopez Padilla): He is Juan del Diablo's half-brother and Monica's fiance. He is a noble and honorable man who loves Monica sincerely. He does not know that Juan del Diablo is his half-brother until later in the story. He tries to protect Monica from Juan's influence and danger.
      • -
      • Francisco Alcazar (Enrique Lizalde): He is Juan del Diablo's father and Andres' father. He is a wealthy landowner who has two legitimate sons with his wife Sofia: Andres and Alberto. He also has an illegitimate son with Guadalupe: Juan del Diablo. He does not acknowledge or care for Juan until he finds out that he is his son.
      • -
      • Sofia Alcazar (Claudia Islas): She is Francisco Alcazar's wife and Andres' mother. She is a proud and elegant woman who hates Juan del Diablo for being her husband's illegitimate son. She also hates Monica for marrying Juan instead of Andres.
      • -
      -

      Conclusion

      - -

      Corazon Salvaje with English subtitles is a way to watch and enjoy the classic telenovela that tells the story of Juan del Diablo and Monica, a couple who face many obstacles and challenges to be together. It is based on the novel by Caridad Bravo Adams and adapted into a 1993 telenovela that was a huge success in Mexico and abroad.

      - -

      If you want to watch Corazon Salvaje with English subtitles, you have different options to choose from depending on your preferences and availability. You can watch it on YouTube, DVD, or streaming platforms that offer Spanish-language content with English subtitles.

      - -

      By watching Corazon Salvaje with English subtitles, you will not only understand every dialogue and emotion of this telenovela but also improve your Spanish skills, appreciate its cultural and historical aspects more deeply, and enjoy its artistic and technical aspects more fully.

      - -

      We hope that this article has helped you learn how to watch Corazon Salvaje with English subtitles and what are the benefits of doing so. If you have any questions or comments, please feel free to leave them below.

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/quidiaMuxgu/Expedit-SAM/Download Motorola Networking Interface Driver.md b/spaces/quidiaMuxgu/Expedit-SAM/Download Motorola Networking Interface Driver.md deleted file mode 100644 index 2a4f9d4fa001e42fc9239a19bc65582f5858024f..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/Download Motorola Networking Interface Driver.md +++ /dev/null @@ -1,32 +0,0 @@ -

      download motorola networking interface driver


      Download Zip ✶✶✶ https://geags.com/2uCsHB



      -
      -Wednesday, December 31, 2012 - -Over the last week or so, I’ve been working on a project where I needed to connect to a Motorola MCS-6535 switch with a Cisco C8820P switch. I ran into the same problem that I did with the Cisco 4500 series switches. The drivers did not work because the actual firmware on the switch was not from Cisco. - -Rather than go through the process of trying to get the Cisco 4500 drivers to install on the C8820P, I installed the Cisco 4500 drivers on the Motorola Network Interface, which is on the Cisco switch. - -(The Motorola drivers that I had installed on the Motorola Network Interface were causing the Cisco C8820P to go into Emergency Shutdown, which is the Cisco equivalent to the NETCONF error that I had previously been experiencing. This was an interesting twist.) - -The Cisco C8820P uses Netgear Manager for configuration. The Motorola MCS-6535 is Netgear Management capable, but only the Netgear version of the Cisco C8820P can be configured through Netgear Manager. - -The process of installation is pretty much identical on both the Cisco and Motorola switches. If you haven’t already, open the VMware Console by going to Start -> Programs -> VMware -> VMware Console. - -Once the VMware Console is open, click on “Console > Connect to the Switch” and enter the IP address of the switch that you want to connect to. - -In this case, I have a Cisco C8820P that I want to connect to a Motorola MCS-6535. You can find the IP address of the Motorola switch by going to Settings -> Network Connections and clicking on your modem/router. Look for the IP address listed in the IP Configuration tab. - -Once you have that information, click “Connect” on the VMware Console. - -Click “Save and close” when you are finished with your configuration. - -Since I’m now connected to the switch, I need to go into “Migration Setup” and select the “Setup.” - -Click “Next” to continue. - -The first screen will ask if you want to use the “System Control Utility.” Click “Yes” if you don’t know what you are doing. - -The next screen will ask if you want to use the “ 4fefd39f24
      -
      -
      -

      diff --git a/spaces/quidiaMuxgu/Expedit-SAM/FreeVimager V9.0.5 ( ) [PATCHED].md b/spaces/quidiaMuxgu/Expedit-SAM/FreeVimager V9.0.5 ( ) [PATCHED].md deleted file mode 100644 index 9675157e715ead541b87668ff9bd144b82a8c0eb..0000000000000000000000000000000000000000 --- a/spaces/quidiaMuxgu/Expedit-SAM/FreeVimager V9.0.5 ( ) [PATCHED].md +++ /dev/null @@ -1,9 +0,0 @@ -
      -

      FreeVimager's interface was quite easy to navigate and understand. The program had only one single view, leaving us to adjust the settings by tapping on the appropriate option in the left pane. As you can guess from the above, we didn't use the application's scanning functions as they weren't as useful to us as the manual scanning process.

      -

      FreeVimager v9.0.5 ( )


      Download Zip 🆓 https://geags.com/2uCqk4



      -

      The best feature of FreeVimager is that you will be able to save as many images as you want. After clicking on the Save as icon in the toolbar, you will be able to save any chosen file type as JPEG, BMP, GIF, TIFF, PCX, and EMF or select PDF. It even has a print preview as well as the ability to scan in (up to) 35 pages at one time. The only downside to this program is that some users couldn't get it to open on the Mac. Another neat thing is that it includes the ability to rotate and crop any of the chosen images with support for up to eight different monitors. With FreeVimager, you have the ability to scan in any type of files including picture, audio and video files.

      -

      One of the best features with FreeVimager is its ability to rotate and crop any of the chosen images with its multi-screen support. You also have the ability to scan in any type of files, including picture, audio and video files. With FreeVimager, you have the ability to scan in any type of files including picture, audio and video files. You can crop or print out any chosen image.

      -

      For FreeVimager to run, the programs must be installed and updated. One of the benefits of FreeVimager is that there is no need to have a desktop program for image management. And it only needs a valid internet connection and most other functions can be performed at the click of a button.

      -

      899543212b
      -
      -
      \ No newline at end of file diff --git a/spaces/r2d2/decision-triptych/README.md b/spaces/r2d2/decision-triptych/README.md deleted file mode 100644 index 875a76d2f29b15aab98ceb2e617b9ab8957581d6..0000000000000000000000000000000000000000 --- a/spaces/r2d2/decision-triptych/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Decision Tryptich -emoji: 👀 -colorFrom: indigo -colorTo: indigo -sdk: streamlit -sdk_version: 1.2.0 -app_file: app.py -pinned: false -license: cc-by-4.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference diff --git a/spaces/r3gm/RVC_HF/MDXNet.py b/spaces/r3gm/RVC_HF/MDXNet.py deleted file mode 100644 index 9b7eb43844ad0d4f9ce61287ccf9a8a4206d3853..0000000000000000000000000000000000000000 --- a/spaces/r3gm/RVC_HF/MDXNet.py +++ /dev/null @@ -1,272 +0,0 @@ -import soundfile as sf -import torch, pdb, os, warnings, librosa -import numpy as np -import onnxruntime as ort -from tqdm import tqdm -import torch - -dim_c = 4 - - -class Conv_TDF_net_trim: - def __init__( - self, device, model_name, target_name, L, dim_f, dim_t, n_fft, hop=1024 - ): - super(Conv_TDF_net_trim, self).__init__() - - self.dim_f = dim_f - self.dim_t = 2**dim_t - self.n_fft = n_fft - self.hop = hop - self.n_bins = self.n_fft // 2 + 1 - self.chunk_size = hop * (self.dim_t - 1) - self.window = torch.hann_window(window_length=self.n_fft, periodic=True).to( - device - ) - self.target_name = target_name - self.blender = "blender" in model_name - - out_c = dim_c * 4 if target_name == "*" else dim_c - self.freq_pad = torch.zeros( - [1, out_c, self.n_bins - self.dim_f, self.dim_t] - ).to(device) - - self.n = L // 2 - - def stft(self, x): - x = x.reshape([-1, self.chunk_size]) - x = torch.stft( - x, - n_fft=self.n_fft, - hop_length=self.hop, - window=self.window, - center=True, - return_complex=True, - ) - x = torch.view_as_real(x) - x = x.permute([0, 3, 1, 2]) - x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape( - [-1, dim_c, self.n_bins, self.dim_t] - ) - return x[:, :, : self.dim_f] - - def istft(self, x, freq_pad=None): - freq_pad = ( - self.freq_pad.repeat([x.shape[0], 1, 1, 1]) - if freq_pad is None - else freq_pad - ) - x = torch.cat([x, freq_pad], -2) - c = 4 * 2 if self.target_name == "*" else 2 - x = x.reshape([-1, c, 2, self.n_bins, self.dim_t]).reshape( - [-1, 2, self.n_bins, self.dim_t] - ) - x = x.permute([0, 2, 3, 1]) - x = x.contiguous() - x = torch.view_as_complex(x) - x = torch.istft( - x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True - ) - return x.reshape([-1, c, self.chunk_size]) - - -def get_models(device, dim_f, dim_t, n_fft): - return Conv_TDF_net_trim( - device=device, - model_name="Conv-TDF", - target_name="vocals", - L=11, - dim_f=dim_f, - dim_t=dim_t, - n_fft=n_fft, - ) - - -warnings.filterwarnings("ignore") -cpu = torch.device("cpu") -if torch.cuda.is_available(): - device = torch.device("cuda:0") -elif torch.backends.mps.is_available(): - device = torch.device("mps") -else: - device = torch.device("cpu") - - -class Predictor: - def __init__(self, args): - self.args = args - self.model_ = get_models( - device=cpu, dim_f=args.dim_f, dim_t=args.dim_t, n_fft=args.n_fft - ) - self.model = ort.InferenceSession( - os.path.join(args.onnx, self.model_.target_name + ".onnx"), - providers=["CUDAExecutionProvider", "CPUExecutionProvider"], - ) - print("onnx load done") - - def demix(self, mix): - samples = mix.shape[-1] - margin = self.args.margin - chunk_size = self.args.chunks * 44100 - assert not margin == 0, "margin cannot be zero!" - if margin > chunk_size: - margin = chunk_size - - segmented_mix = {} - - if self.args.chunks == 0 or samples < chunk_size: - chunk_size = samples - - counter = -1 - for skip in range(0, samples, chunk_size): - counter += 1 - - s_margin = 0 if counter == 0 else margin - end = min(skip + chunk_size + margin, samples) - - start = skip - s_margin - - segmented_mix[skip] = mix[:, start:end].copy() - if end == samples: - break - - sources = self.demix_base(segmented_mix, margin_size=margin) - """ - mix:(2,big_sample) - segmented_mix:offset->(2,small_sample) - sources:(1,2,big_sample) - """ - return sources - - def demix_base(self, mixes, margin_size): - chunked_sources = [] - progress_bar = tqdm(total=len(mixes)) - progress_bar.set_description("Processing") - for mix in mixes: - cmix = mixes[mix] - sources = [] - n_sample = cmix.shape[1] - model = self.model_ - trim = model.n_fft // 2 - gen_size = model.chunk_size - 2 * trim - pad = gen_size - n_sample % gen_size - mix_p = np.concatenate( - (np.zeros((2, trim)), cmix, np.zeros((2, pad)), np.zeros((2, trim))), 1 - ) - mix_waves = [] - i = 0 - while i < n_sample + pad: - waves = np.array(mix_p[:, i : i + model.chunk_size]) - mix_waves.append(waves) - i += gen_size - mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(cpu) - with torch.no_grad(): - _ort = self.model - spek = model.stft(mix_waves) - if self.args.denoise: - spec_pred = ( - -_ort.run(None, {"input": -spek.cpu().numpy()})[0] * 0.5 - + _ort.run(None, {"input": spek.cpu().numpy()})[0] * 0.5 - ) - tar_waves = model.istft(torch.tensor(spec_pred)) - else: - tar_waves = model.istft( - torch.tensor(_ort.run(None, {"input": spek.cpu().numpy()})[0]) - ) - tar_signal = ( - tar_waves[:, :, trim:-trim] - .transpose(0, 1) - .reshape(2, -1) - .numpy()[:, :-pad] - ) - - start = 0 if mix == 0 else margin_size - end = None if mix == list(mixes.keys())[::-1][0] else -margin_size - if margin_size == 0: - end = None - sources.append(tar_signal[:, start:end]) - - progress_bar.update(1) - - chunked_sources.append(sources) - _sources = np.concatenate(chunked_sources, axis=-1) - # del self.model - progress_bar.close() - return _sources - - def prediction(self, m, vocal_root, others_root, format): - os.makedirs(vocal_root, exist_ok=True) - os.makedirs(others_root, exist_ok=True) - basename = os.path.basename(m) - mix, rate = librosa.load(m, mono=False, sr=44100) - if mix.ndim == 1: - mix = np.asfortranarray([mix, mix]) - mix = mix.T - sources = self.demix(mix.T) - opt = sources[0].T - if format in ["wav", "flac"]: - sf.write( - "%s/%s_main_vocal.%s" % (vocal_root, basename, format), mix - opt, rate - ) - sf.write("%s/%s_others.%s" % (others_root, basename, format), opt, rate) - else: - path_vocal = "%s/%s_main_vocal.wav" % (vocal_root, basename) - path_other = "%s/%s_others.wav" % (others_root, basename) - sf.write(path_vocal, mix - opt, rate) - sf.write(path_other, opt, rate) - if os.path.exists(path_vocal): - os.system( - "ffmpeg -i %s -vn %s -q:a 2 -y" - % (path_vocal, path_vocal[:-4] + ".%s" % format) - ) - if os.path.exists(path_other): - os.system( - "ffmpeg -i %s -vn %s -q:a 2 -y" - % (path_other, path_other[:-4] + ".%s" % format) - ) - - -class MDXNetDereverb: - def __init__(self, chunks): - self.onnx = "uvr5_weights/onnx_dereverb_By_FoxJoy" - self.shifts = 10 #'Predict with randomised equivariant stabilisation' - self.mixing = "min_mag" # ['default','min_mag','max_mag'] - self.chunks = chunks - self.margin = 44100 - self.dim_t = 9 - self.dim_f = 3072 - self.n_fft = 6144 - self.denoise = True - self.pred = Predictor(self) - - def _path_audio_(self, input, vocal_root, others_root, format): - self.pred.prediction(input, vocal_root, others_root, format) - - -if __name__ == "__main__": - dereverb = MDXNetDereverb(15) - from time import time as ttime - - t0 = ttime() - dereverb._path_audio_( - "雪雪伴奏对消HP5.wav", - "vocal", - "others", - ) - t1 = ttime() - print(t1 - t0) - - -""" - -runtime\python.exe MDXNet.py - -6G: -15/9:0.8G->6.8G -14:0.8G->6.5G -25:炸 - -half15:0.7G->6.6G,22.69s -fp32-15:0.7G->6.6G,20.85s - -""" diff --git a/spaces/radames/MusicGen-Continuation/audiocraft/modules/streaming.py b/spaces/radames/MusicGen-Continuation/audiocraft/modules/streaming.py deleted file mode 100644 index fdbdf5e90fc0c6560873d66bf273460b38e5ed7e..0000000000000000000000000000000000000000 --- a/spaces/radames/MusicGen-Continuation/audiocraft/modules/streaming.py +++ /dev/null @@ -1,135 +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. - -""" -Streaming module API that should be implemented by all Streaming components, -""" - -from contextlib import contextmanager -import typing as tp -from torch import nn -import torch - - -State = tp.Dict[str, torch.Tensor] - - -class StreamingModule(nn.Module): - """Common API for streaming components. - - Each streaming component has a streaming state, which is just a dict[str, Tensor]. - By convention, the first dim of each tensor must be the batch size. - Don't use dots in the key names, as this would clash with submodules - (like in state_dict). - - If `self._is_streaming` is True, the component should use and remember - the proper state inside `self._streaming_state`. - - To set a streaming component in streaming state, use - - with module.streaming(): - ... - - This will automatically reset the streaming state when exiting the context manager. - This also automatically propagates to all streaming children module. - - Some module might also implement the `StreamingModule.flush` method, although - this one is trickier, as all parents module must be StreamingModule and implement - it as well for it to work properly. See `StreamingSequential` after. - """ - def __init__(self) -> None: - super().__init__() - self._streaming_state: State = {} - self._is_streaming = False - - def _apply_named_streaming(self, fn: tp.Any): - for name, module in self.named_modules(): - if isinstance(module, StreamingModule): - fn(name, module) - - def _set_streaming(self, streaming: bool): - def _set_streaming(name, module): - module._is_streaming = streaming - self._apply_named_streaming(_set_streaming) - - @contextmanager - def streaming(self): - """Context manager to enter streaming mode. Reset streaming state on exit. - """ - self._set_streaming(True) - try: - yield - finally: - self._set_streaming(False) - self.reset_streaming() - - def reset_streaming(self): - """Reset the streaming state. - """ - def _reset(name: str, module: StreamingModule): - module._streaming_state.clear() - - self._apply_named_streaming(_reset) - - def get_streaming_state(self) -> State: - """Return the streaming state, including that of sub-modules. - """ - state: State = {} - - def _add(name: str, module: StreamingModule): - if name: - name += "." - for key, value in module._streaming_state.items(): - state[name + key] = value - - self._apply_named_streaming(_add) - return state - - def set_streaming_state(self, state: State): - """Set the streaming state, including that of sub-modules. - """ - state = dict(state) - - def _set(name: str, module: StreamingModule): - if name: - name += "." - module._streaming_state.clear() - for key, value in list(state.items()): - # complexity is not ideal here, but probably fine. - if key.startswith(name): - local_key = key[len(name):] - if '.' not in local_key: - module._streaming_state[local_key] = value - del state[key] - - self._apply_named_streaming(_set) - assert len(state) == 0, list(state.keys()) - - def flush(self, x: tp.Optional[torch.Tensor] = None): - """Flush any remaining outputs that were waiting for completion. - Typically, for convolutions, this will add the final padding - and process the last buffer. - - This should take an optional argument `x`, which will be provided - if a module before this one in the streaming pipeline has already - spitted out a flushed out buffer. - """ - if x is None: - return None - else: - return self(x) - - -class StreamingSequential(StreamingModule, nn.Sequential): - """A streaming compatible alternative of `nn.Sequential`. - """ - def flush(self, x: tp.Optional[torch.Tensor] = None): - for module in self: - if isinstance(module, StreamingModule): - x = module.flush(x) - elif x is not None: - x = module(x) - return x diff --git a/spaces/radames/gradio-blender-bpy/README.md b/spaces/radames/gradio-blender-bpy/README.md deleted file mode 100644 index 16c7fb38f9526d1849e75f2d7539684fdb0cb3ee..0000000000000000000000000000000000000000 --- a/spaces/radames/gradio-blender-bpy/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Gradio Blender Bpy -emoji: 🚀 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.43.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/raedeXanto/academic-chatgpt-beta/Adobe XD CC 2019 Free Download 32Bit-64Bit Latest Version Best Practices and Examples.md b/spaces/raedeXanto/academic-chatgpt-beta/Adobe XD CC 2019 Free Download 32Bit-64Bit Latest Version Best Practices and Examples.md deleted file mode 100644 index 56326508cced4d67ee5c53f0ff9b7b86acb3d97e..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Adobe XD CC 2019 Free Download 32Bit-64Bit Latest Version Best Practices and Examples.md +++ /dev/null @@ -1,95 +0,0 @@ -
      -

      Adobe XD CC 2019: A Powerful Tool for UI/UX Designers

      -

      If you are a UI/UX designer, you probably know how important it is to have a reliable and versatile tool that can help you create stunning designs and prototypes for your projects. Whether you are working on a website, an app, a game, or any other digital product, you need a tool that can handle your creative vision and workflow.

      -

      One of the best tools that can meet your needs is Adobe XD CC 2019, a comprehensive solution for designing and prototyping user experiences. Adobe XD is part of the Creative Cloud suite of applications, which means you can access it with your subscription and integrate it with other Adobe products. In this article, we will show you how to download Adobe XD CC 2019 for free, how to use it for designing and prototyping, and why you should use it for your next project.

      -

      Adobe XD CC 2019 free download 32Bit-64Bit latest version


      Download File ✶✶✶ https://tinourl.com/2uL1QL



      -

      How to Download Adobe XD CC 2019 for Free

      -

      One of the great things about Adobe XD is that you can download it for free and use it without any limitations. You can create unlimited projects, share them with others, and access all the features that Adobe XD has to offer. Here are the steps on how to download and install Adobe XD CC 2019 on your Windows or Mac computer:

      -
        -
      1. Go to https://www.adobe.com/products/xd.html and click on the Download button.
      2. -
      3. If you are not signed in to your Creative Cloud account, you will be prompted to do so. If you don't have an account yet, you can create one for free.
      4. -
      5. After signing in, you will see a pop-up window that asks you to choose your operating system (Windows or Mac) and language. Click on Continue.
      6. -
      7. The download will start automatically. Once it is finished, open the file and follow the instructions on the screen to install Adobe XD on your computer.
      8. -
      9. After the installation is complete, you can launch Adobe XD from your desktop or start menu.
      10. -
      -

      How to Use Adobe XD CC 2019 for Designing and Prototyping

      -

      Now that you have downloaded and installed Adobe XD on your computer, you are ready to start designing and prototyping your user experiences. In this section, we will give you an overview of the workspace and tools that you will find in Adobe XD CC 2019.

      -

      How to Create a New Project in Adobe XD CC 2019

      -

      To create a new project in Adobe XD, you can either start from scratch or use one of the many UI kits that are available for free. A UI kit is a collection of pre-made design elements that you can use as a starting point or inspiration for your project. To create a new project:

      -

      How to get Adobe XD CC 2019 for free on Windows 10
      -Adobe XD CC 2019 full version download with crack
      -Best websites to download Adobe XD CC 2019 for free
      -Adobe XD CC 2019 offline installer 32-bit and 64-bit
      -Adobe XD CC 2019 system requirements and features
      -Adobe XD CC 2019 tutorial for beginners pdf
      -Adobe XD CC 2019 vs Sketch vs Figma comparison
      -Adobe XD CC 2019 license key generator online
      -Adobe XD CC 2019 activation code free
      -Adobe XD CC 2019 latest update download
      -Adobe XD CC 2019 review and rating
      -Adobe XD CC 2019 alternatives and competitors
      -Adobe XD CC 2019 tips and tricks for designers
      -Adobe XD CC 2019 plugins and extensions download
      -Adobe XD CC 2019 templates and UI kits free download
      -Adobe XD CC 2019 portable version download
      -Adobe XD CC 2019 trial reset tool download
      -Adobe XD CC 2019 keyboard shortcuts cheat sheet
      -Adobe XD CC 2019 bugs and issues fix
      -Adobe XD CC 2019 new features and improvements
      -How to uninstall Adobe XD CC 2019 completely
      -How to export Adobe XD CC 2019 files to HTML/CSS/JS
      -How to import Photoshop files to Adobe XD CC 2019
      -How to create animations in Adobe XD CC 2019
      -How to use voice commands in Adobe XD CC 2019
      -How to collaborate with others in Adobe XD CC 2019
      -How to use responsive resize in Adobe XD CC 2019
      -How to use auto-animate in Adobe XD CC 2019
      -How to use repeat grid in Adobe XD CC 2019
      -How to use symbols in Adobe XD CC 2019
      -How to use artboards in Adobe XD CC 2019
      -How to use layers in Adobe XD CC 2019
      -How to use masks in Adobe XD CC 2019
      -How to use gradients in Adobe XD CC 2019
      -How to use text tools in Adobe XD CC 2019
      -How to use shapes tools in Adobe XD CC 2019
      -How to use pen tool in Adobe XD CC 2019
      -How to use assets panel in Adobe XD CC 2019
      -How to use prototyping mode in Adobe XD CC 2019
      -How to use share mode in Adobe XD CC 2019
      -How to use design specs in Adobe XD CC 2019
      -How to use feedback mode in Adobe XD CC 2019
      -How to use developer mode in Adobe XD CC 2019
      -How to use presentation mode in Adobe XD CC 2019
      -How to use preview mode in Adobe XD CC 2019
      -How to use cloud documents in Adobe XD CC 2019
      -How to use coediting in Adobe XD CC 2019
      -How to use component states in Adobe XD CC 2019
      -How to use hover effects in Adobe XD CC 2019

      -
        -
      • Launch Adobe XD and click on Create new.
      • -
      • You will see a window that lets you choose the size of your artboard (the canvas where you will design your user interface). You can select from various presets (such as web, iPhone, iPad, Android, etc.) or enter custom dimensions.
      • -
      • If you want to use a UI kit, click on UI Kits at the top right corner of the window. You will see a list of UI kits that are categorized by platform (such as web, iOS, Android, etc.). Click on the one that suits your project and it will open in a new tab.
      • -
      • To start designing your user interface, drag and drop elements from the UI kit or draw your own shapes using the tools on the left side of the workspace.
      • -
      -

      How to Design a User Interface in Adobe XD CC 2019

      -

      The design process in Adobe XD is simple and intuitive. You can use various tools and features to create your user interface elements such as artboards, layers, components, assets, styles, text tools etc.

      -

      Artboards are the canvases where you design your user interface. You can create multiple artboards for different screens or states of your project. To create an artboard:

      -
        -
      • Select the Artboard tool (A) from the toolbar on the left side of the workspace.
      • -
      • Click anywhere on the canvas or drag an area to create an artboard.
      • -
      • You can resize or rename your artboard using the handles or the Property Inspector on the right side of the workspace.
      • -
      • You can also duplicate or delete an artboard by right-clicking on it or using keyboard shortcuts.
      • -
      -

      Layers are the individual elements that make up your user interface. You can organize your layers into groups or subgroups for easier management. To work with layers:

      -
        -
      • Select the Select tool (V) from the toolbar on the left side of the workspace.
      • -
      • Click on any element on your artboard to select it. You can also select multiple elements by holding Shift or dragging a marquee around them.
      • -
      • You can see all your layers in the Layers panel on the left side of the workspace. You can rename, reorder, lock, hide or group your layers using this panel.
      • -
      • You can also edit your layers using the Property Inspector on the right side of the workspace. You can change their position, size, rotation, opacity, fill, stroke, shadow, blur, etc.
      • -
      -

      Components are reusable design elements that you can create once and use across multiple artboards or projects. Components have a main instance and multiple instances that inherit their properties from the main instance. You can also override some properties of each instance such as text, image, or color. To create and use components:

      -
        -
      • Select one or more elements on your artboard that you want to make into a component.
      • -
      • Click on Create Component button in the Property Inspector or press Ctrl+K (Windows) or Command+K (Mac).
      • 0a6ba089eb
        -
        -
        \ No newline at end of file diff --git a/spaces/raedeXanto/academic-chatgpt-beta/Command And Conquer 4 Tiberian Twilight Keygen Generator 20 How to Activate Your CD Key on Steam.md b/spaces/raedeXanto/academic-chatgpt-beta/Command And Conquer 4 Tiberian Twilight Keygen Generator 20 How to Activate Your CD Key on Steam.md deleted file mode 100644 index bdee6eb4f0373ce760095116cab00155165270f9..0000000000000000000000000000000000000000 --- a/spaces/raedeXanto/academic-chatgpt-beta/Command And Conquer 4 Tiberian Twilight Keygen Generator 20 How to Activate Your CD Key on Steam.md +++ /dev/null @@ -1,113 +0,0 @@ - -

        Command And Conquer 4 Tiberian Twilight Keygen Generator 20

        -

        If you are a fan of real-time strategy games, you might have heard of Command And Conquer 4 Tiberian Twilight, the final chapter in the Tiberium saga. This game offers an exciting and immersive gameplay experience, with two playable factions, three unique classes, and a massive, mobile, all-in-one base. However, to play this game, you need a valid serial key that can activate your copy of the game. This is where Command And Conquer 4 Tiberian Twilight Keygen Generator 20 comes in handy. In this article, we will explain what this tool is, how to use it, and what benefits it can bring to you.

        -

        Introduction

        -

        What is Command And Conquer 4 Tiberian Twilight?

        -

        Command And Conquer 4 Tiberian Twilight is a real-time strategy video game, part of the Command And Conquer franchise, released on March 16, 2010. It constitutes a final chapter in the Tiberium saga. The game was originally intended to be an Asian market online-only version of Command And Conquer 3.

        -

        Command And Conquer 4 Tiberian Twilight Keygen Generator 20


        Download ····· https://tinourl.com/2uL3p6



        -

        The game is set in the year 2062, when the world is being consumed by the rampant growth of Tiberium, a mysterious alien crystalline structure that has infested Earth for decades and served as the primary reason for years of relentless conflict between the Global Defense Initiative (GDI) and the Brotherhood of Nod. The game features two playable factions: GDI and Nod, each with three upgradeable classes: offense, defense, and support. The game also introduces a new gameplay mechanic: a massive, mobile, all-in-one base called The Crawler, which allows the player to build units and structures on the move. The game has a single-player campaign that can be played solo or cooperatively with another player, as well as a multiplayer mode that supports up to 10 players in 5 vs 5 objective-based battles.

        -

        What is a keygen generator?

        -

        A keygen generator is a software tool that can generate random and unique serial keys for various software products, such as games, applications, or operating systems. A serial key is a string of alphanumeric characters that acts as a code to verify the authenticity and legitimacy of a software product. A serial key is usually required to activate or register a software product after installation.

        -

        A keygen generator can be useful for users who want to use a software product without paying for it or obtaining it legally. However, using a keygen generator can also be risky and unethical, as it can expose the user to malware infections, legal issues, or moral dilemmas.

        -

        Command And Conquer 4 Tiberian Twilight Serial Number Generator
        -How To Get Command And Conquer 4 Tiberian Twilight Activation Code
        -Command And Conquer 4 Tiberian Twilight Crack Download Free
        -Command And Conquer 4 Tiberian Twilight License Key Generator Online
        -Command And Conquer 4 Tiberian Twilight CD Key Generator No Survey
        -Command And Conquer 4 Tiberian Twilight Product Key Generator For PC
        -Command And Conquer 4 Tiberian Twilight Steam Key Generator Download
        -Command And Conquer 4 Tiberian Twilight Keygen Generator Full Version
        -Command And Conquer 4 Tiberian Twilight Registration Code Generator
        -Command And Conquer 4 Tiberian Twilight Key Generator Without Human Verification
        -Command And Conquer 4 Tiberian Twilight Activation Key Generator Free Download
        -Command And Conquer 4 Tiberian Twilight Crack + Keygen Generator Torrent
        -Command And Conquer 4 Tiberian Twilight Serial Key Generator For Windows
        -Command And Conquer 4 Tiberian Twilight Keygen Generator No Password
        -Command And Conquer 4 Tiberian Twilight License Code Generator Software
        -Command And Conquer 4 Tiberian Twilight CD Key Generator Online Free
        -Command And Conquer 4 Tiberian Twilight Product Code Generator No Download
        -Command And Conquer 4 Tiberian Twilight Steam Code Generator For Mac
        -Command And Conquer 4 Tiberian Twilight Keygen Generator Download Link
        -Command And Conquer 4 Tiberian Twilight Registration Key Generator Working
        -Command And Conquer 4 Tiberian Twilight Key Generator With Proof
        -Command And Conquer 4 Tiberian Twilight Activation Code Generator Online No Survey
        -Command And Conquer 4 Tiberian Twilight Crack + Serial Number Generator Zip
        -Command And Conquer 4 Tiberian Twilight Serial Code Generator For Android
        -Command And Conquer 4 Tiberian Twilight Keygen Generator Free No Survey
        -Command And Conquer 4 Tiberian Twilight License Key Generator Download No Password
        -Command And Conquer 4 Tiberian Twilight CD Code Generator For Linux
        -Command And Conquer 4 Tiberian Twilight Product Key Generator Online No Download
        -Command And Conquer 4 Tiberian Twilight Steam Key Generator No Human Verification
        -Command And Conquer 4 Tiberian Twilight Keygen Generator Full Crack
        -Command And Conquer 4 Tiberian Twilight Registration Code Generator No Password
        -Command And Conquer 4 Tiberian Twilight Key Generator Online Free Download
        -Command And Conquer 4 Tiberian Twilight Activation Key Generator No Download No Survey
        -Command And Conquer 4 Tiberian Twilight Crack + Product Key Generator Rar
        -Command And Conquer 4 Tiberian Twilight Serial Key Generator No Survey No Password
        -Command And Conquer 4 Tiberian Twilight Keygen Generator Online Working
        -Command And Conquer 4 Tiberian Twilight License Code Generator No Survey No Password
        -Command And Conquer 4 Tiberian Twilight CD Key Generator Download Link No Survey
        -Command And Conquer 4 Tiberian Twilight Product Code Generator Working No Survey
        -Command And Conquer 4 Tiberian Twilight Steam Code Generator No Download No Password
        -Command And Conquer 4 Tiberian Twilight Keygen Generator Free Download Link No Survey
        -Command And Conquer 4 Tiberian Twilight Registration Key Generator Online No Password
        -Command And Conquer 4 Tiberian Twilight Key Generator Without Survey Without Password
        -Command And Conquer 4 Tiberian Twilight Activation Code Generator Working Without Survey
        -Command And Conquer 4 Tiberian Twilight Crack + License Key Generator Zip File No Password
        -Command And Conquer 4 Tiberian Twilight Serial Code Generator Download Without Survey Without Password
        -Command And Conquer 4 Tiberian Twilight Keygen Generator Full Version Free Download Without Survey Without Password

        -

        Why do you need a keygen generator for Command And Conquer 4 Tiberian Twilight?

        -

        As mentioned earlier, to play Command And Conquer 4 Tiberian Twilight, you need a valid serial key that can activate your copy of the game. However, obtaining a serial key can be difficult or expensive for some users. For example, you might have lost your original serial key, or you might not be able to afford buying the game from an official source.

        -

        In such cases, you might want to use a keygen generator for Command And Conquer 4 Tiberian Twilight. This tool can help you generate a random and unique serial key that can activate your game and allow you to enjoy its full features. However, before you decide to use this tool, you should be aware of its potential drawbacks and consequences.

        -

        How to use Command And Conquer 4 Tiberian Twilight Keygen Generator 20

        -

        Download the keygen generator from a reliable source

        -

        The first step to use Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is to download it from a reliable source. You should be careful when choosing where to download this tool from, as some sources might contain viruses or malware that can harm your computer or steal your personal information.

        -

        One possible source that claims to offer this tool is https://www.keygensforgames.org/command-and-conquer-4-tiberian-twilight-key-generator/. However, we cannot guarantee that this source is safe or trustworthy. Therefore, we advise you to scan any file that you download with an antivirus program before opening it.

        -

        Run the keygen generator and select your platform

        -

        The next step is to run the keygen generator and select your platform. The tool should work for both Windows and Mac operating systems. After selecting your platform, click on "Generate" button and wait for a few seconds.

        -

        Generate a unique serial key and copy it

        -

        The tool will then generate a unique serial key for Command And Conquer 4 Tiberian Twilight and display it on the screen. You should copy this serial key and save it somewhere safe.

        -

        Activate your game with the serial key

        -

        The final step is to activate your game with the serial key that you generated. To do this, you need to install Command And Conquer 4 Tiberian Twilight on your computer if you haven't already done so. Then, launch the game and enter the serial key when prompted. If everything goes well, your game should be activated and ready to play.

        -

        Benefits of using Command And Conquer 4 Tiberian Twilight Keygen Generator 20

        -

        Save money and time

        -

        One of the main benefits of using Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is that it can save you money and time. By using this tool, you don't have to pay for buying the game from an official source or spend hours searching for a valid serial key online.

        -

        Enjoy the full features of the game

        -

        Another benefit of using Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is that it can allow you to enjoy the full features of the game without any limitations or restrictions. You can play both single-player and multiplayer modes, choose from different factions and classes, customize your units and structures, and experience an epic story with live-action cinematics.

        -

        Play online with other players

        -

        A third benefit of using Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is that it can enable you to play online with other players who have activated their games with valid serial keys. You can join online matches with up to 10 players in 5 vs 5 objective-based battles, cooperate with your teammates using support powers and abilities,

        -and compete for ranking points and rewards.

        Support the developers of the game

        -

        A fourth benefit of using Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is that it can help you support the developers of the game by increasing their popularity and revenue. By playing their game online with other players who have bought their game legally,

        -you can show them your appreciation for their hard work and creativity.

        Conclusion

        -

        In conclusion,

        -Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is a software tool that can generate random and unique serial keys for Command And Conquer 4 Tiberian Twilight a real-time strategy video game released on March 16 2010 as part of the Command And Conquer franchise and the final chapter in the Tiberium saga This tool can help you activate your copy of the game and enjoy its full features without paying for it or obtaining it legally However using this tool can also be risky and unethical as it can expose you to malware infections legal issues

        FAQs

        -

        Here are some frequently asked questions about Command And Conquer 4 Tiberian Twilight Keygen Generator 20.

        - - - - - - - - - - - - - - - - - - - - - - - - - -
        QuestionAnswer
        Is Command And Conquer 4 Tiberian Twilight Keygen Generator 20 safe to use?Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is not a safe tool to use, as it can contain viruses or malware that can harm your computer or steal your personal information. You should always scan any file that you download with an antivirus program before opening it.
        Is Command And Conquer 4 Tiberian Twilight Keygen Generator 20 legal to use?Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is not a legal tool to use, as it violates the copyright and license agreement of the game. You should always buy the game from an official source or obtain it legally.
        Is Command And Conquer 4 Tiberian Twilight Keygen Generator 20 ethical to use?Command And Conquer 4 Tiberian Twilight Keygen Generator 20 is not an ethical tool to use, as it deprives the developers of the game of their deserved income and recognition. You should always support the developers of the game by paying for their product or showing them your appreciation.
        Does Command And Conquer 4 Tiberian Twilight Keygen Generator 20 work for all platforms?Command And Conquer 4 Tiberian Twilight Keygen Generator 20 should work for both Windows and Mac operating systems. However, we cannot guarantee that it will work for every platform or version of the game.
        Does Command And Conquer 4 Tiberian Twilight Keygen Generator 20 guarantee a valid serial key?Command And Conquer 4 Tiberian Twilight Keygen Generator 20 can generate a random and unique serial key for Command And Conquer 4 Tiberian Twilight. However, we cannot guarantee that every serial key that it generates will be valid or accepted by the game.
        -

        0a6ba089eb
        -
        -
        \ No newline at end of file diff --git a/spaces/rafayqayyum/IdentifyDogBreed/README.md b/spaces/rafayqayyum/IdentifyDogBreed/README.md deleted file mode 100644 index b72bf7166514e6cea79e42af5b080a059a7b5591..0000000000000000000000000000000000000000 --- a/spaces/rafayqayyum/IdentifyDogBreed/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: IdentifyDogBreed -emoji: 🌍 -colorFrom: green -colorTo: pink -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/rajistics/cars/README.md b/spaces/rajistics/cars/README.md deleted file mode 100644 index 636153810b843bb25978fd3d407121b71f700844..0000000000000000000000000000000000000000 --- a/spaces/rajistics/cars/README.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: Cars -emoji: 📚 -colorFrom: red -colorTo: blue -sdk: static -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/randstad/Skills_Education_Gaps_Finder/README.md b/spaces/randstad/Skills_Education_Gaps_Finder/README.md deleted file mode 100644 index 8f5c3b12f4b06a9d07df5db1b58493ea07c30ffd..0000000000000000000000000000000000000000 --- a/spaces/randstad/Skills_Education_Gaps_Finder/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Skills Education Gaps Finder -emoji: 💻 -colorFrom: yellow -colorTo: red -sdk: gradio -sdk_version: 3.35.2 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/realfill-library/RealFill-Training-UI/README.md b/spaces/realfill-library/RealFill-Training-UI/README.md deleted file mode 100644 index 188a13f593f0c74ead09daa8ba9729322db993fb..0000000000000000000000000000000000000000 --- a/spaces/realfill-library/RealFill-Training-UI/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: RealFill Training UI -emoji: ⚡ -colorFrom: red -colorTo: purple -sdk: gradio -sdk_version: 3.16.2 -python_version: 3.10.9 -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/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Breaking Bad S05E16 Felina 1080p WEB DL DD5 1 H 264 BS [PublicHD].md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Breaking Bad S05E16 Felina 1080p WEB DL DD5 1 H 264 BS [PublicHD].md deleted file mode 100644 index b7215e27308173eca417658f135165a32664c1b5..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Breaking Bad S05E16 Felina 1080p WEB DL DD5 1 H 264 BS [PublicHD].md +++ /dev/null @@ -1,10 +0,0 @@ - -

        there may be no ending, but there is also no rest for a man who has worked so hard for so long to make his life better. the night before the milestone moment, walter sits at the kitchen table in his lab, pondering his future. he thinks back on how far he's come.

        -

        Breaking Bad S05E16 Felina 1080p WEB DL DD5 1 H 264 BS [PublicHD]


        DOWNLOADhttps://urlgoal.com/2uCJCT



        -

        the results are spectacular. i take that back. it is better than spectacular. even if it take a miracle to get there, to finish strong in my eyes. to end the show on a emotional high and an epic score, it is spectacular like a bunch of fireworks exploding at the end of a rainforest in the night. f**ck yeah!

        -

        it is dead and it has been a long time coming. with its finale, breaking bad is back at the top of its game. the series finale is also a breath of fresh air for the series, resurrecting everything that made it great. and it doesn't seem to have skipped a beat. this is a tight, moody and hugely satisfying series finale that will surely satisfy all avid viewers and anybody wanting to check the series out.

        -

        i just never watched the series before even up to episode 8. my friends told me that it is a great series, but all it takes is time and we just have to put in the time. i agree. it's one of the best series i watched up till then. it kept you stuck in suspense all along. from the series start, the drama is a great piece of work. the best part is that it creates a good contrast of the characters you are watching. you will never get bored of watching these wonderful performances.

        -

        i tried to watch the series starting with the first episode of season 1. it is a good series but i just can't watch it now. even though i only watched the last few episodes, it doesn't change the fact that this series is not for everyone. it is a fast and unpredictable show. it can make you sit up all night and watch all through the night. you will love or hate the characters but you can't deny the talent of its writer and cast. there is a lot of character's heartwarming, touching, funny, tragic, and pain. the story is truly shocking and unbelievable.

        -

        899543212b
        -
        -
        \ No newline at end of file diff --git a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Cars Education Workbook V3 Answers53.md b/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Cars Education Workbook V3 Answers53.md deleted file mode 100644 index 9a330f78af248acfe5eb2f24ca9d3c8ba7821c5f..0000000000000000000000000000000000000000 --- a/spaces/recenWmenso/ChatGPT-with-Voice-Cloning-for-All/datasets/Cars Education Workbook V3 Answers53.md +++ /dev/null @@ -1,6 +0,0 @@ -

        Cars Education Workbook V3 Answers53


        Download File 🆓 https://urlgoal.com/2uCLFz



        -
        -December 3, 2018 Tutorial v3 Answers53 raipalmo cars education. Student Workbook Answers - Ontario Driving School, Brampton. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. Answers and explanations. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. Answers and explanations. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. Answers and explanations. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. Answers and explanations. 1. 2. 3. 4. 8a78ff9644
        -
        -
        -

        diff --git a/spaces/reha/Stick_Tech/inference/__init__.py b/spaces/reha/Stick_Tech/inference/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/apis/train.py b/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/apis/train.py deleted file mode 100644 index f51f862a053e95079c1c0978c17dbdeb9f8eeea4..0000000000000000000000000000000000000000 --- a/spaces/rockeycoss/Prompt-Segment-Anything-Demo/mmdet/apis/train.py +++ /dev/null @@ -1,246 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import os -import random - -import numpy as np -import torch -import torch.distributed as dist -from mmcv.runner import (DistSamplerSeedHook, EpochBasedRunner, - Fp16OptimizerHook, OptimizerHook, build_runner, - get_dist_info) - -from mmdet.core import DistEvalHook, EvalHook, build_optimizer -from mmdet.datasets import (build_dataloader, build_dataset, - replace_ImageToTensor) -from mmdet.utils import (build_ddp, build_dp, compat_cfg, - find_latest_checkpoint, get_root_logger) - - -def init_random_seed(seed=None, device='cuda'): - """Initialize random seed. - - If the seed is not set, the seed will be automatically randomized, - and then broadcast to all processes to prevent some potential bugs. - - Args: - seed (int, Optional): The seed. Default to None. - device (str): The device where the seed will be put on. - Default to 'cuda'. - - Returns: - int: Seed to be used. - """ - if seed is not None: - return seed - - # Make sure all ranks share the same random seed to prevent - # some potential bugs. Please refer to - # https://github.com/open-mmlab/mmdetection/issues/6339 - rank, world_size = get_dist_info() - seed = np.random.randint(2**31) - if world_size == 1: - return seed - - if rank == 0: - random_num = torch.tensor(seed, dtype=torch.int32, device=device) - else: - random_num = torch.tensor(0, dtype=torch.int32, device=device) - dist.broadcast(random_num, src=0) - return random_num.item() - - -def set_random_seed(seed, deterministic=False): - """Set random seed. - - Args: - seed (int): Seed to be used. - deterministic (bool): Whether to set the deterministic option for - CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` - to True and `torch.backends.cudnn.benchmark` to False. - Default: False. - """ - random.seed(seed) - np.random.seed(seed) - torch.manual_seed(seed) - torch.cuda.manual_seed_all(seed) - if deterministic: - torch.backends.cudnn.deterministic = True - torch.backends.cudnn.benchmark = False - - -def auto_scale_lr(cfg, distributed, logger): - """Automatically scaling LR according to GPU number and sample per GPU. - - Args: - cfg (config): Training config. - distributed (bool): Using distributed or not. - logger (logging.Logger): Logger. - """ - # Get flag from config - if ('auto_scale_lr' not in cfg) or \ - (not cfg.auto_scale_lr.get('enable', False)): - logger.info('Automatic scaling of learning rate (LR)' - ' has been disabled.') - return - - # Get base batch size from config - base_batch_size = cfg.auto_scale_lr.get('base_batch_size', None) - if base_batch_size is None: - return - - # Get gpu number - if distributed: - _, world_size = get_dist_info() - num_gpus = len(range(world_size)) - else: - num_gpus = len(cfg.gpu_ids) - - # calculate the batch size - samples_per_gpu = cfg.data.train_dataloader.samples_per_gpu - batch_size = num_gpus * samples_per_gpu - logger.info(f'Training with {num_gpus} GPU(s) with {samples_per_gpu} ' - f'samples per GPU. The total batch size is {batch_size}.') - - if batch_size != base_batch_size: - # scale LR with - # [linear scaling rule](https://arxiv.org/abs/1706.02677) - scaled_lr = (batch_size / base_batch_size) * cfg.optimizer.lr - logger.info('LR has been automatically scaled ' - f'from {cfg.optimizer.lr} to {scaled_lr}') - cfg.optimizer.lr = scaled_lr - else: - logger.info('The batch size match the ' - f'base batch size: {base_batch_size}, ' - f'will not scaling the LR ({cfg.optimizer.lr}).') - - -def train_detector(model, - dataset, - cfg, - distributed=False, - validate=False, - timestamp=None, - meta=None): - - cfg = compat_cfg(cfg) - logger = get_root_logger(log_level=cfg.log_level) - - # prepare data loaders - dataset = dataset if isinstance(dataset, (list, tuple)) else [dataset] - - runner_type = 'EpochBasedRunner' if 'runner' not in cfg else cfg.runner[ - 'type'] - - train_dataloader_default_args = dict( - samples_per_gpu=2, - workers_per_gpu=2, - # `num_gpus` will be ignored if distributed - num_gpus=len(cfg.gpu_ids), - dist=distributed, - seed=cfg.seed, - runner_type=runner_type, - persistent_workers=False) - - train_loader_cfg = { - **train_dataloader_default_args, - **cfg.data.get('train_dataloader', {}) - } - - data_loaders = [build_dataloader(ds, **train_loader_cfg) for ds in dataset] - - # put model on gpus - if distributed: - find_unused_parameters = cfg.get('find_unused_parameters', False) - # Sets the `find_unused_parameters` parameter in - # torch.nn.parallel.DistributedDataParallel - model = build_ddp( - model, - cfg.device, - device_ids=[int(os.environ['LOCAL_RANK'])], - broadcast_buffers=False, - find_unused_parameters=find_unused_parameters) - else: - model = build_dp(model, cfg.device, device_ids=cfg.gpu_ids) - - # build optimizer - auto_scale_lr(cfg, distributed, logger) - optimizer = build_optimizer(model, cfg.optimizer) - - runner = build_runner( - cfg.runner, - default_args=dict( - model=model, - optimizer=optimizer, - work_dir=cfg.work_dir, - logger=logger, - meta=meta)) - - # an ugly workaround to make .log and .log.json filenames the same - runner.timestamp = timestamp - - # fp16 setting - fp16_cfg = cfg.get('fp16', None) - if fp16_cfg is None and cfg.get('device', None) == 'npu': - fp16_cfg = dict(loss_scale='dynamic') - if fp16_cfg is not None: - optimizer_config = Fp16OptimizerHook( - **cfg.optimizer_config, **fp16_cfg, distributed=distributed) - elif distributed and 'type' not in cfg.optimizer_config: - optimizer_config = OptimizerHook(**cfg.optimizer_config) - else: - optimizer_config = cfg.optimizer_config - - # register hooks - runner.register_training_hooks( - cfg.lr_config, - optimizer_config, - cfg.checkpoint_config, - cfg.log_config, - cfg.get('momentum_config', None), - custom_hooks_config=cfg.get('custom_hooks', None)) - - if distributed: - if isinstance(runner, EpochBasedRunner): - runner.register_hook(DistSamplerSeedHook()) - - # register eval hooks - if validate: - val_dataloader_default_args = dict( - samples_per_gpu=1, - workers_per_gpu=2, - dist=distributed, - shuffle=False, - persistent_workers=False) - - val_dataloader_args = { - **val_dataloader_default_args, - **cfg.data.get('val_dataloader', {}) - } - # Support batch_size > 1 in validation - - if val_dataloader_args['samples_per_gpu'] > 1: - # Replace 'ImageToTensor' to 'DefaultFormatBundle' - cfg.data.val.pipeline = replace_ImageToTensor( - cfg.data.val.pipeline) - val_dataset = build_dataset(cfg.data.val, dict(test_mode=True)) - - val_dataloader = build_dataloader(val_dataset, **val_dataloader_args) - eval_cfg = cfg.get('evaluation', {}) - eval_cfg['by_epoch'] = cfg.runner['type'] != 'IterBasedRunner' - eval_hook = DistEvalHook if distributed else EvalHook - # In this PR (https://github.com/open-mmlab/mmcv/pull/1193), the - # priority of IterTimerHook has been modified from 'NORMAL' to 'LOW'. - runner.register_hook( - eval_hook(val_dataloader, **eval_cfg), priority='LOW') - - resume_from = None - if cfg.resume_from is None and cfg.get('auto_resume'): - resume_from = find_latest_checkpoint(cfg.work_dir) - if resume_from is not None: - cfg.resume_from = resume_from - - if cfg.resume_from: - runner.resume(cfg.resume_from) - elif cfg.load_from: - runner.load_checkpoint(cfg.load_from) - runner.run(data_loaders, cfg.workflow) diff --git a/spaces/ronvolutional/iframe-test/modules/dataset.py b/spaces/ronvolutional/iframe-test/modules/dataset.py deleted file mode 100644 index 26d9108c537d6fbb2b054e23bc169e1c4fd2aa07..0000000000000000000000000000000000000000 --- a/spaces/ronvolutional/iframe-test/modules/dataset.py +++ /dev/null @@ -1,19 +0,0 @@ -from datasets import load_dataset - -dataset = load_dataset("emotion", split="train") - -emotions = dataset.info.features["label"].names - -def query_emotion(start, end): - rows = dataset[start:end] - texts, labels = [rows[k] for k in rows.keys()] - - observations = [] - - for i, text in enumerate(texts): - observations.append({ - "text": text, - "emotion": emotions[labels[i]], - }) - - return observations diff --git a/spaces/rorallitri/biomedical-language-models/logs/GTR Evolution V1 2 0 1 Crack The Ultimate Solution for Securom Protection Issues.md b/spaces/rorallitri/biomedical-language-models/logs/GTR Evolution V1 2 0 1 Crack The Ultimate Solution for Securom Protection Issues.md deleted file mode 100644 index 7041aa813000a2e9a96706310ec78f62d55f6c20..0000000000000000000000000000000000000000 --- a/spaces/rorallitri/biomedical-language-models/logs/GTR Evolution V1 2 0 1 Crack The Ultimate Solution for Securom Protection Issues.md +++ /dev/null @@ -1,18 +0,0 @@ -
        -

        People love free steam games, no doubt. But what many people hate is downloading so many parts and trying to install them on their own. This is why we are the only site that pre-installs every game for you. We have many categories like shooters, action, racing, simulators and even VR games! We strive to satisfy our users and ask for nothing in return. We revolutionized the downloading scene and will continue being your #1 site for free games.

        -

        The TH-U Premium license includes the SuperCabinet, the revolutionary IR processor, based on Overloud's Fluid Convolution Technology, which allows to create cabinet tones in a way that has never been possible before.

        -

        GTR Evolution V1 2 0 1 Crack


        Download ->>> https://tinurll.com/2uzol0



        -

        Gravitational lensing has developed into a tool of observational astronomy. It is used to detect the presence and distribution of dark matter, provide a "natural telescope" for observing distant galaxies, and to obtain an independent estimate of the Hubble constant. Statistical evaluations of lensing data provide valuable insight into the structural evolution of galaxies.[115]

        -

        Whenever the ratio of an object's mass to its radius becomes sufficiently large, general relativity predicts the formation of a black hole, a region of space from which nothing, not even light, can escape. In the currently accepted models of stellar evolution, neutron stars of around 1.4 solar masses, and stellar black holes with a few to a few dozen solar masses, are thought to be the final state for the evolution of massive stars.[123] Usually a galaxy has one supermassive black hole with a few million to a few billion solar masses in its center,[124] and its presence is thought to have played an important role in the formation of the galaxy and larger cosmic structures.[125]

        -

        Astronomical observations of the cosmological expansion rate allow the total amount of matter in the universe to be estimated, although the nature of that matter remains mysterious in part. About 90% of all matter appears to be dark matter, which has mass (or, equivalently, gravitational influence), but does not interact electromagnetically and, hence, cannot be observed directly.[141] There is no generally accepted description of this new kind of matter, within the framework of known particle physics[142] or otherwise.[143] Observational evidence from redshift surveys of distant supernovae and measurements of the cosmic background radiation also show that the evolution of our universe is significantly influenced by a cosmological constant resulting in an acceleration of cosmic expansion or, equivalently, by a form of energy with an unusual equation of state, known as dark energy, the nature of which remains unclear.[144]

        -

        To understand Einstein's equations as partial differential equations, it is helpful to formulate them in a way that describes the evolution of the universe over time. This is done in "3+1" formulations, where spacetime is split into three space dimensions and one time dimension. The best-known example is the ADM formalism.[175] These decompositions show that the spacetime evolution equations of general relativity are well-behaved: solutions always exist, and are uniquely defined, once suitable initial conditions have been specified.[176] Such formulations of Einstein's field equations are the basis of numerical relativity.[177]

        -

        One attempt to overcome these limitations is string theory, a quantum theory not of point particles, but of minute one-dimensional extended objects.[197] The theory promises to be a unified description of all particles and interactions, including gravity;[198] the price to pay is unusual features such as six extra dimensions of space in addition to the usual three.[199] In what is called the second superstring revolution, it was conjectured that both string theory and a unification of general relativity and supersymmetry known as supergravity[200] form part of a hypothesized eleven-dimensional model known as M-theory, which would constitute a uniquely defined and consistent theory of quantum gravity.[201]

        -

        In general, poor thermal stability and cycle performance of nickel-rich layered oxide mainly stem from chemical reactions between delithiated cathodes and nonaqueous electrolytes at elevated temperature, which cause decomposition of cathode material and oxidation of electrolytes. The overdelithiated cathode would release oxygen from its lattice due to its high oxidability. Further, the electrolyte could react with oxygen to generate heat. If the heat generation and accumulation are more than its dissipation, a catastrophic failure of the cell will happen [81]. For the sake of designing safe cathode materials with high capacity, mechanisms of structure evolution, thermal stability and oxygen release in cathode materials during cycling should be thoroughly demonstrated. For example, some researchers investigated the structure evolution mechanism of NCM111 during cycling by in situ high-resolution synchrotron radiation diffraction and neutron powder diffraction. As shown in Fig. 3a and b, when the charge voltage is below 4.2 V, NCM111 maintains layered hexagonal phase H1 structure with slightly increased c and decreased a lattice parameters. When the voltage region is from 4.2 to 4.4 V, a new hexagonal phase H2 is detected and gradually intensified. When it is charged to a high voltage above 4.6 V, irreversible structure change appears from the original layered structure phase to a layered hexagonal phase H3 and a cubic spinel phase. After full lithiation, lattice parameters do not go back to its original ones, indicative of an irreversible structure evolution after charging to high voltage [82].

        -

        In the microlevel, Ni-rich cathode materials consist of some secondary micrometer particles, which is aggregated by primary micrometer particles. The microstructural evolution of the single Li(Ni0.8Co0.15Al0.05)O2 particle during electrochemical cycling was further demonstrated by using in situ electron microscopy (Fig. 3f, g). Compared with the as-prepared particles, the particles after three cycles showed obvious cracks, which allow penetration of electrolytes between primary particles. The above result suggests that loss of grain-to-grain connectivity between particles would result in capacity fading and performance degradation [84]. Furthermore, more exposed cathode surface during cycling will intensify reactions between cathodes and electrolytes, which would aggravate capacity fade.

        -

        Above all, with the aid of advanced characterization techniques, the reasons, for structure evolution as well as side reaction between the electrolytes and the primary particles of cathode materials, have been deeply understood in the microlevel, which would guide us to design safe cathodes.

        -

        -

        Design better particles The layered oxide materials are commonly prepared by the co-precipitation method with round-shape primary particles randomly aggregating into large secondary particles. Anisotropic lattice volume expansion or contraction between the primary particles during cycling will result in microcracks, and electrolytes will penetrate into microcracks, causing severe side reaction.

        -

        Another way to eliminate cracks in the secondary particles is directly using single-crystal cathodes. Dahn et al. compared single-crystal and polycrystalline NCM523-positive electrode materials for high-voltage LIBs. The results show that single-crystal materials yield to longer lifetime for LIBs at both 40 and 55 °C when tested at an upper cutoff potential of 4.4 V. The reasons for superior performance of the single-crystal-based cells were explored by using thermogravimetric analysis/mass spectrometry experiments on the charged electrode materials, showing that single-crystal materials are extremely resistant to oxygen loss below 100 °C compared with the polycrystalline materials [108].

        -

        A sequence of four optical micrographs showing the time evolution of color in the electrode: a-I the fresh electrode, a-II charge for 6 h, a-III charge for 9 h and a-IV charge for 13 h. Reproduced with permission from Ref. [226]. Copyright 2010, Elsevier. SEM images of the bulk LiCoO2 electrode synthesis by magnetic templating b the top view and c the side view. Reproduced with permission from Ref. [227]. Copyright 2016, Nature Publishing Group. d Schematic diagram of the working mechanism of the carbon framework-based LFP Li-ion battery. SEM images of the carbon framework-based LFP electrode: e the top view, f the side view and g the enlarged view of the side of the electrode.

        aaccfb2cb3
        -
        -
        \ No newline at end of file diff --git a/spaces/runa91/bite_gradio/src/test_time_optimization/bite_inference_model_for_ttopt.py b/spaces/runa91/bite_gradio/src/test_time_optimization/bite_inference_model_for_ttopt.py deleted file mode 100644 index 28aeb8a531e34506644fd80e2bfe030eb7f7ae96..0000000000000000000000000000000000000000 --- a/spaces/runa91/bite_gradio/src/test_time_optimization/bite_inference_model_for_ttopt.py +++ /dev/null @@ -1,158 +0,0 @@ - -import torch - -import os -import sys -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'src')) - - -from combined_model.model_shape_v7_withref_withgraphcnn import ModelImageTo3d_withshape_withproj - - -soft_max = torch.nn.Softmax(dim=1) - - -def get_summarized_bite_result(output, output_unnorm, output_reproj, output_ref_unnorm, output_orig_ref_comparison, output_ref_unnorm_new=None, output_orig_ref_comparison_new=None, result_networks=['ref']): - all_sum_res = {} - for result_network in result_networks: - assert result_network in ['normal', 'ref', 'multref'] - # variabled that are not refined - res = {} - res['hg_keyp_scores'] = output['keypoints_scores'] - res['hg_keyp_norm'] = output['keypoints_norm'] - res['hg_keyp_256'] = (output['keypoints_norm']+1)/2*(256-1) - res['hg_silh_prep'] = soft_max(output['seg_hg'])[:, 1, :, :] # (bs, 256, 256) - res['betas'] = output_reproj['betas'] - res['betas_limbs'] = output_reproj['betas_limbs'] - res['z'] = output_reproj['z'] - if result_network == 'normal': - # STEP 1: normal network - res['vertices_smal'] = output_reproj['vertices_smal'] - res['flength'] = output_unnorm['flength'] - res['pose_rotmat'] = output_unnorm['pose_rotmat'] - res['trans'] = output_unnorm['trans'] - res['pred_keyp'] = output_reproj['keyp_2d'] - res['pred_silh'] = output_reproj['silh'] - res['prefix'] = 'normal_' - elif result_network == 'ref': - # STEP 1: refinement network - res['vertices_smal'] = output_ref_unnorm['vertices_smal'] - res['flength'] = output_ref_unnorm['flength'] - res['pose_rotmat'] = output_ref_unnorm['pose_rotmat'] - res['trans'] = output_ref_unnorm['trans'] - res['pred_keyp'] = output_ref_unnorm['keyp_2d'] - res['pred_silh'] = output_ref_unnorm['silh'] - res['prefix'] = 'ref_' - if 'vertexwise_ground_contact' in output_ref_unnorm.keys(): - res['vertexwise_ground_contact'] = output_ref_unnorm['vertexwise_ground_contact'] - '''' - if return_mesh_with_gt_groundplane and 'gc' in target_dict.keys(): - bs = vertices_smal.shape[0] - target_gc_class = target_dict['gc'][:, :, 0] - sel_verts = torch.index_select(output_ref_unnorm['vertices_smal'], dim=1, index=remeshing_relevant_faces.reshape((-1))).reshape((bs, remeshing_relevant_faces.shape[0], 3, 3)) - verts_remeshed = torch.einsum('ij,aijk->aik', remeshing_relevant_barys, sel_verts) - target_gc_class_remeshed = torch.einsum('ij,aij->ai', remeshing_relevant_barys, target_gc_class[:, remeshing_relevant_faces].to(device=device, dtype=torch.float32)) - target_gc_class_remeshed_prep = torch.round(target_gc_class_remeshed).to(torch.long) - ''' - res['isflat_prep'] = soft_max(output_ref_unnorm['isflat'])[:, 1] - - - else: - # STEP 1: next loop in refinemnet network - assert (output_ref_unnorm_new is not None) - res['vertices_smal'] = output_ref_unnorm_new['vertices_smal'] - res['flength'] = output_ref_unnorm_new['flength'] - res['pose_rotmat'] = output_ref_unnorm_new['pose_rotmat'] - res['trans'] = output_ref_unnorm_new['trans'] - res['pred_keyp'] = output_ref_unnorm_new['keyp_2d'] - res['pred_silh'] = output_ref_unnorm_new['silh'] - res['prefix'] = 'multref_' - if 'vertexwise_ground_contact' in output_ref_unnorm_new.keys(): - res['vertexwise_ground_contact'] = output_ref_unnorm_new['vertexwise_ground_contact'] - all_sum_res[result_network] = res - return all_sum_res - - -class BITEInferenceModel(): #(nn.Module): - def __init__(self, cfg, path_model_file_complete, norm_dict, device='cuda'): - # def __init__(self, bp, model_weight_path=None, model_weight_stackedhg_path=None, device='cuda'): - # self.bp = bp - self.cfg = cfg - self.device = device - self.norm_dict = norm_dict - - # prepare complete model - self.complete_model = ModelImageTo3d_withshape_withproj( - smal_model_type=cfg.smal.SMAL_MODEL_TYPE, smal_keyp_conf=cfg.smal.SMAL_KEYP_CONF, \ - num_stage_comb=cfg.params.NUM_STAGE_COMB, num_stage_heads=cfg.params.NUM_STAGE_HEADS, \ - num_stage_heads_pose=cfg.params.NUM_STAGE_HEADS_POSE, trans_sep=cfg.params.TRANS_SEP, \ - arch=cfg.params.ARCH, n_joints=cfg.params.N_JOINTS, n_classes=cfg.params.N_CLASSES, \ - n_keyp=cfg.params.N_KEYP, n_bones=cfg.params.N_BONES, n_betas=cfg.params.N_BETAS, n_betas_limbs=cfg.params.N_BETAS_LIMBS, \ - n_breeds=cfg.params.N_BREEDS, n_z=cfg.params.N_Z, image_size=cfg.params.IMG_SIZE, \ - silh_no_tail=cfg.params.SILH_NO_TAIL, thr_keyp_sc=cfg.params.KP_THRESHOLD, add_z_to_3d_input=cfg.params.ADD_Z_TO_3D_INPUT, - n_segbps=cfg.params.N_SEGBPS, add_segbps_to_3d_input=cfg.params.ADD_SEGBPS_TO_3D_INPUT, add_partseg=cfg.params.ADD_PARTSEG, n_partseg=cfg.params.N_PARTSEG, \ - fix_flength=cfg.params.FIX_FLENGTH, structure_z_to_betas=cfg.params.STRUCTURE_Z_TO_B, structure_pose_net=cfg.params.STRUCTURE_POSE_NET, - nf_version=cfg.params.NF_VERSION, ref_net_type=cfg.params.REF_NET_TYPE, graphcnn_type=cfg.params.GRAPHCNN_TYPE, isflat_type=cfg.params.ISFLAT_TYPE, shaperef_type=cfg.params.SHAPEREF_TYPE) - - # load trained model - print(path_model_file_complete) - assert os.path.isfile(path_model_file_complete) - print('Loading model weights from file: {}'.format(path_model_file_complete)) - checkpoint_complete = torch.load(path_model_file_complete) - state_dict_complete = checkpoint_complete['state_dict'] - self.complete_model.load_state_dict(state_dict_complete) # , strict=False) - self.complete_model = self.complete_model.to(self.device) - self.complete_model.eval() - - self.smal_model_type = self.complete_model.smal.smal_model_type - - def get_selected_results(self, preds_dict=None, input_img_prep=None, result_networks=['ref']): - assert ((preds_dict is not None) or (input_img_prep is not None)) - if preds_dict is None: - preds_dict = self.get_all_results(input_img_prep) - all_sum_res = get_summarized_bite_result(preds_dict['output'], preds_dict['output_unnorm'], preds_dict['output_reproj'], preds_dict['output_ref_unnorm'], preds_dict['output_orig_ref_comparison'], result_networks=result_networks) - return all_sum_res - - def get_selected_results_multiple_refinements(self, preds_dict=None, input_img_prep=None, result_networks=['multref']): - assert ((preds_dict is not None) or (input_img_prep is not None)) - if preds_dict is None: - preds_dict = self.get_all_results_multiple_refinements(input_img_prep) - all_sum_res = get_summarized_bite_result(preds_dict['output'], preds_dict['output_unnorm'], preds_dict['output_reproj'], preds_dict['output_ref_unnorm'], preds_dict['output_orig_ref_comparison'], preds_dict['output_ref_unnorm_new'], preds_dict['output_orig_ref_comparison_new'], result_networks=result_networks) - return all_sum_res - - - def get_all_results(self, input_img_prep): - output, output_unnorm, output_reproj, output_ref, output_ref_comp = self.complete_model(input_img_prep, norm_dict=self.norm_dict) - preds_dict = {'output': output, - 'output_unnorm': output_unnorm, - 'output_reproj': output_reproj, - 'output_ref_unnorm': output_ref, - 'output_orig_ref_comparison': output_ref_comp - } - return preds_dict - - - def get_all_results_multiple_refinements(self, input_img_prep): - preds_dict = self.complete_model.forward_with_multiple_refinements(input_img_prep, norm_dict=self.norm_dict) - # output, output_unnorm, output_reproj, output_ref, output_ref_comp, output_ref_unnorm_new, output_orig_ref_comparison_new - return preds_dict - - - - - - - - - - - - - - - - - - - - diff --git a/spaces/sadjava/emotion-classification/README.md b/spaces/sadjava/emotion-classification/README.md deleted file mode 100644 index 35cc8e0a8e945ea4f92236b47e56cbd946d9d446..0000000000000000000000000000000000000000 --- a/spaces/sadjava/emotion-classification/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Emotion Classification -emoji: 👦 -colorFrom: red -colorTo: yellow -sdk: gradio -sdk_version: 3.33.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/sai22/vits-models/transforms.py b/spaces/sai22/vits-models/transforms.py deleted file mode 100644 index 4793d67ca5a5630e0ffe0f9fb29445c949e64dae..0000000000000000000000000000000000000000 --- a/spaces/sai22/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/sam-hq-team/sam-hq/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.py b/spaces/sam-hq-team/sam-hq/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.py deleted file mode 100644 index 10c0920c1a217af5bb3e1b13077568035ab3b7b5..0000000000000000000000000000000000000000 --- a/spaces/sam-hq-team/sam-hq/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.py +++ /dev/null @@ -1,123 +0,0 @@ -# ------------------------------------------------------------------------ -# Grounding DINO -# url: https://github.com/IDEA-Research/GroundingDINO -# Copyright (c) 2023 IDEA. All Rights Reserved. -# Licensed under the Apache License, Version 2.0 [see LICENSE for details] -# ------------------------------------------------------------------------ -# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -""" -DETR Transformer class. - -Copy-paste from torch.nn.Transformer with modifications: - * positional encodings are passed in MHattention - * extra LN at the end of encoder is removed - * decoder returns a stack of activations from all decoding layers -""" -from typing import Optional - -import torch -import torch.nn.functional as F -from torch import Tensor, nn - -from .utils import ( - MLP, - _get_activation_fn, - _get_clones, - gen_encoder_output_proposals, - gen_sineembed_for_position, - sigmoid_focal_loss, -) - - -class TextTransformer(nn.Module): - def __init__(self, num_layers, d_model=256, nheads=8, dim_feedforward=2048, dropout=0.1): - super().__init__() - self.num_layers = num_layers - self.d_model = d_model - self.nheads = nheads - self.dim_feedforward = dim_feedforward - self.norm = None - - single_encoder_layer = TransformerEncoderLayer( - d_model=d_model, nhead=nheads, dim_feedforward=dim_feedforward, dropout=dropout - ) - self.layers = _get_clones(single_encoder_layer, num_layers) - - def forward(self, memory_text: torch.Tensor, text_attention_mask: torch.Tensor): - """ - - Args: - text_attention_mask: bs, num_token - memory_text: bs, num_token, d_model - - Raises: - RuntimeError: _description_ - - Returns: - output: bs, num_token, d_model - """ - - output = memory_text.transpose(0, 1) - - for layer in self.layers: - output = layer(output, src_key_padding_mask=text_attention_mask) - - if self.norm is not None: - output = self.norm(output) - - return output.transpose(0, 1) - - -class TransformerEncoderLayer(nn.Module): - def __init__( - self, - d_model, - nhead, - dim_feedforward=2048, - dropout=0.1, - activation="relu", - normalize_before=False, - ): - super().__init__() - self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) - # Implementation of Feedforward model - self.linear1 = nn.Linear(d_model, dim_feedforward) - self.dropout = nn.Dropout(dropout) - self.linear2 = nn.Linear(dim_feedforward, d_model) - - self.norm1 = nn.LayerNorm(d_model) - self.norm2 = nn.LayerNorm(d_model) - self.dropout1 = nn.Dropout(dropout) - self.dropout2 = nn.Dropout(dropout) - - self.activation = _get_activation_fn(activation) - self.normalize_before = normalize_before - self.nhead = nhead - - def with_pos_embed(self, tensor, pos: Optional[Tensor]): - return tensor if pos is None else tensor + pos - - def forward( - self, - src, - src_mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - ): - # repeat attn mask - if src_mask.dim() == 3 and src_mask.shape[0] == src.shape[1]: - # bs, num_q, num_k - src_mask = src_mask.repeat(self.nhead, 1, 1) - - q = k = self.with_pos_embed(src, pos) - - src2 = self.self_attn(q, k, value=src, attn_mask=src_mask)[0] - - # src2 = self.self_attn(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] - src = src + self.dropout1(src2) - src = self.norm1(src) - src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) - src = src + self.dropout2(src2) - src = self.norm2(src) - return src diff --git a/spaces/samt/soteria-ml/README.md b/spaces/samt/soteria-ml/README.md deleted file mode 100644 index 683464e0b3669a6dfa24f4a6cd147d9cde1c39e2..0000000000000000000000000000000000000000 --- a/spaces/samt/soteria-ml/README.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Soteria -emoji: 🌍 -colorFrom: green -colorTo: gray -sdk: gradio -app_file: app.py -pinned: false -license: mit ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio`, `streamlit`, or `static` - -`sdk_version` : _string_ -Only applicable for `streamlit` SDK. -See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions. - -`app_file`: _string_ -Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code). -Path is relative to the root of the repository. - -`models`: _List[string]_ -HF model IDs (like "gpt2" or "deepset/roberta-base-squad2") used in the Space. -Will be parsed automatically from your code if not specified here. - -`datasets`: _List[string]_ -HF dataset IDs (like "common_voice" or "oscar-corpus/OSCAR-2109") used in the Space. -Will be parsed automatically from your code if not specified here. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/sarulab-speech/UTMOS-demo/app.py b/spaces/sarulab-speech/UTMOS-demo/app.py deleted file mode 100644 index 8ff018231aa3797b88d24240b269eab8ef62effc..0000000000000000000000000000000000000000 --- a/spaces/sarulab-speech/UTMOS-demo/app.py +++ /dev/null @@ -1,57 +0,0 @@ - -from random import sample -import gradio as gr -import torchaudio -import torch -import torch.nn as nn -import lightning_module - -class ChangeSampleRate(nn.Module): - def __init__(self, input_rate: int, output_rate: int): - super().__init__() - self.output_rate = output_rate - self.input_rate = input_rate - - def forward(self, wav: torch.tensor) -> torch.tensor: - # Only accepts 1-channel waveform input - wav = wav.view(wav.size(0), -1) - new_length = wav.size(-1) * self.output_rate // self.input_rate - indices = (torch.arange(new_length) * (self.input_rate / self.output_rate)) - round_down = wav[:, indices.long()] - round_up = wav[:, (indices.long() + 1).clamp(max=wav.size(-1) - 1)] - output = round_down * (1. - indices.fmod(1.)).unsqueeze(0) + round_up * indices.fmod(1.).unsqueeze(0) - return output - -model = lightning_module.BaselineLightningModule.load_from_checkpoint("epoch=3-step=7459.ckpt").eval() -def calc_mos(audio_path): - wav, sr = torchaudio.load(audio_path) - osr = 16_000 - batch = wav.unsqueeze(0).repeat(10, 1, 1) - csr = ChangeSampleRate(sr, osr) - out_wavs = csr(wav) - batch = { - 'wav': out_wavs, - 'domains': torch.tensor([0]), - 'judge_id': torch.tensor([288]) - } - with torch.no_grad(): - output = model(batch) - return output.mean(dim=1).squeeze().detach().numpy()*2 + 3 - - -description =""" -MOS prediction demo using UTMOS-strong w/o phoneme encoder model, which is trained on the main track dataset. -This demo only accepts .wav format. Best at 16 kHz sampling rate. - -Paper is available [here](https://arxiv.org/abs/2204.02152) -""" - -iface = gr.Interface( - fn=calc_mos, - inputs=gr.inputs.Audio(type='filepath'), - outputs="text", - title="UTMOS Demo", - description=description, - allow_flagging=False, - -).launch() \ No newline at end of file diff --git a/spaces/scedlatioru/img-to-music/example/Need For Speed Most Wanted English Without Human Verification.md b/spaces/scedlatioru/img-to-music/example/Need For Speed Most Wanted English Without Human Verification.md deleted file mode 100644 index 432df4bf61628f9361e16537f3e77c0d8adf8784..0000000000000000000000000000000000000000 --- a/spaces/scedlatioru/img-to-music/example/Need For Speed Most Wanted English Without Human Verification.md +++ /dev/null @@ -1,6 +0,0 @@ -

        Need For Speed Most Wanted English without human verification


        Download ✵✵✵ https://gohhs.com/2uEyKa



        -
        -Verify Note: Once you've passed the human verification, the $50 Eshop Code ... Need help in finding free Xbox gift card generator without survey or human ... the unlimited number of followers to your account at a blazing speed for free of cost. ... i don't wanna robux generator email robux generator english robux generator ... 1fdad05405
        -
        -
        -

        diff --git a/spaces/sczhou/ProPainter/model/vgg_arch.py b/spaces/sczhou/ProPainter/model/vgg_arch.py deleted file mode 100644 index 43fc2ff8bc1c73313d632c6ab326372d389a4772..0000000000000000000000000000000000000000 --- a/spaces/sczhou/ProPainter/model/vgg_arch.py +++ /dev/null @@ -1,157 +0,0 @@ -import os -import torch -from collections import OrderedDict -from torch import nn as nn -from torchvision.models import vgg as vgg - -VGG_PRETRAIN_PATH = 'experiments/pretrained_models/vgg19-dcbb9e9d.pth' -NAMES = { - 'vgg11': [ - 'conv1_1', 'relu1_1', 'pool1', 'conv2_1', 'relu2_1', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', - 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', - 'pool5' - ], - 'vgg13': [ - 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', - 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'pool4', - 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'pool5' - ], - 'vgg16': [ - 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', - 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', - 'relu4_2', 'conv4_3', 'relu4_3', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', - 'pool5' - ], - 'vgg19': [ - 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', - 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', - 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', - 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4', 'pool5' - ] -} - - -def insert_bn(names): - """Insert bn layer after each conv. - - Args: - names (list): The list of layer names. - - Returns: - list: The list of layer names with bn layers. - """ - names_bn = [] - for name in names: - names_bn.append(name) - if 'conv' in name: - position = name.replace('conv', '') - names_bn.append('bn' + position) - return names_bn - -class VGGFeatureExtractor(nn.Module): - """VGG network for feature extraction. - - In this implementation, we allow users to choose whether use normalization - in the input feature and the type of vgg network. Note that the pretrained - path must fit the vgg type. - - Args: - layer_name_list (list[str]): Forward function returns the corresponding - features according to the layer_name_list. - Example: {'relu1_1', 'relu2_1', 'relu3_1'}. - vgg_type (str): Set the type of vgg network. Default: 'vgg19'. - use_input_norm (bool): If True, normalize the input image. Importantly, - the input feature must in the range [0, 1]. Default: True. - range_norm (bool): If True, norm images with range [-1, 1] to [0, 1]. - Default: False. - requires_grad (bool): If true, the parameters of VGG network will be - optimized. Default: False. - remove_pooling (bool): If true, the max pooling operations in VGG net - will be removed. Default: False. - pooling_stride (int): The stride of max pooling operation. Default: 2. - """ - - def __init__(self, - layer_name_list, - vgg_type='vgg19', - use_input_norm=True, - range_norm=False, - requires_grad=False, - remove_pooling=False, - pooling_stride=2): - super(VGGFeatureExtractor, self).__init__() - - self.layer_name_list = layer_name_list - self.use_input_norm = use_input_norm - self.range_norm = range_norm - - self.names = NAMES[vgg_type.replace('_bn', '')] - if 'bn' in vgg_type: - self.names = insert_bn(self.names) - - # only borrow layers that will be used to avoid unused params - max_idx = 0 - for v in layer_name_list: - idx = self.names.index(v) - if idx > max_idx: - max_idx = idx - - if os.path.exists(VGG_PRETRAIN_PATH): - vgg_net = getattr(vgg, vgg_type)(pretrained=False) - state_dict = torch.load(VGG_PRETRAIN_PATH, map_location=lambda storage, loc: storage) - vgg_net.load_state_dict(state_dict) - else: - vgg_net = getattr(vgg, vgg_type)(pretrained=True) - - features = vgg_net.features[:max_idx + 1] - - modified_net = OrderedDict() - for k, v in zip(self.names, features): - if 'pool' in k: - # if remove_pooling is true, pooling operation will be removed - if remove_pooling: - continue - else: - # in some cases, we may want to change the default stride - modified_net[k] = nn.MaxPool2d(kernel_size=2, stride=pooling_stride) - else: - modified_net[k] = v - - self.vgg_net = nn.Sequential(modified_net) - - if not requires_grad: - self.vgg_net.eval() - for param in self.parameters(): - param.requires_grad = False - else: - self.vgg_net.train() - for param in self.parameters(): - param.requires_grad = True - - if self.use_input_norm: - # the mean is for image with range [0, 1] - self.register_buffer('mean', torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)) - # the std is for image with range [0, 1] - self.register_buffer('std', torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)) - - def forward(self, x): - """Forward function. - - Args: - x (Tensor): Input tensor with shape (n, c, h, w). - - Returns: - Tensor: Forward results. - """ - if self.range_norm: - x = (x + 1) / 2 - if self.use_input_norm: - x = (x - self.mean) / self.std - output = {} - - for key, layer in self.vgg_net._modules.items(): - x = layer(x) - if key in self.layer_name_list: - output[key] = x.clone() - - return output diff --git a/spaces/sebastianM/CarDetectionAndModernity/app.py b/spaces/sebastianM/CarDetectionAndModernity/app.py deleted file mode 100644 index 5a96bd426afde1c22cb58031c1343569ed4b4166..0000000000000000000000000000000000000000 --- a/spaces/sebastianM/CarDetectionAndModernity/app.py +++ /dev/null @@ -1,205 +0,0 @@ -import torch -import os - -### Installations ### -##################### - -os.system('pip install git+https://github.com/facebookresearch/detectron2.git') - -### Import Libraries ### -######################### - -# general -import gradio as gr -import numpy as np -import cv2 -from PIL import Image - -# Setup detectron2 logger -import detectron2 -from detectron2.utils.logger import setup_logger -setup_logger() - -# import some common detectron2 utilities -from detectron2 import model_zoo -from detectron2.engine import DefaultPredictor -from detectron2.config import get_cfg -from detectron2.data import MetadataCatalog, DatasetCatalog - -# import torchvision utilities -import torchvision.models as models -import torchvision.transforms as transforms -import torch.nn.functional as F - - -### Detectron Model ### -####################### - -# Initialize and set to cpu -cfg = get_cfg() -cfg.MODEL.DEVICE='cpu' - -# Load Model -cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")) -cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model - -# Load pretrained weights -cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml") -predictor = DefaultPredictor(cfg) - - -# get labels -metadata = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]) -class_catalog = metadata.thing_classes - - -### ResNet18 Model ### -###################### - -pretrained_model = models.resnet18(pretrained=True) - -IN_FEATURES = pretrained_model.fc.in_features -OUTPUT_DIM = 5 - -final_fc = torch.nn.Linear(IN_FEATURES, OUTPUT_DIM) - -pretrained_model.fc = final_fc - -# Load fine tuned weights -pretrained_model.load_state_dict(torch.load('model_modernity_advanced.pt', map_location = 'cpu')) -pretrained_model.eval() - -### Test Transforms ### -####################### - -pretrained_size = 224 -pretrained_means = [0.485, 0.456, 0.406] -pretrained_stds = [0.229, 0.224, 0.225] - -test_transforms = transforms.Compose([ - transforms.Resize(pretrained_size), - transforms.ToTensor(), - transforms.Normalize(mean = pretrained_means, - std = pretrained_stds) - ]) - - -### Car Modernity Function ### -############################## - -def modernity_pred(logits): - p = F.softmax(logits, dim = 1) - groups = torch.tensor([[0,1,2,3,4]]) - score = (p * groups).sum(axis = 1) - return score - - -### Image Classification function ### -##################################### - -def image_classifier(inp): - - ### Detect in full image ### - ############################ - - # detectron prediction - output = predictor(inp) - instances = output['instances'] - - # assign class names - classes = [] - for i in instances.pred_classes.detach().cpu(): - classes.append(class_catalog[i]) - - # select cars and pick largest according to pixel count of pred_mask - is_car = np.array(classes) == 'car' - - # statement to check if car was detected in the image and proceed accordingly - if is_car.any() == True: - - # select cars and pick largest according to pixel count of pred_mask - pred_masks = instances.pred_masks[is_car].detach().cpu() - idx_largest_car = pred_masks.reshape(pred_masks.shape[0], -1).sum(axis= 1).argmax() - - - ### crop image by according region of interest - ############################################## - - # extract region of interest - pred_boxes = instances.pred_boxes[is_car][int(idx_largest_car)] - box = list(pred_boxes)[0].detach().cpu().numpy() - - x_min = int(box[0]) - y_min = int(box[1]) - x_max = int(box[2]) - y_max = int(box[3]) - - - # crop image respectively - crop_img = inp[y_min:y_max, x_min:x_max, :] - - - ### Change Background to White ### - ################################## - - # convert to PIL fromat - cropped = Image.fromarray(crop_img.astype('uint8'), 'RGB') - - # select respective mask from model output - pred_mask_crop = pred_masks[idx_largest_car].numpy() - - # convert to PIL format - pred_mask_crop = Image.fromarray((pred_mask_crop * 255).astype('uint8')) - - #crop the pred_mask from model output - pred_mask_crop = pred_mask_crop.crop((x_min, y_min, x_max, y_max)) - - # create white background - s = np.array(pred_mask_crop).shape - background = Image.fromarray(np.ones(shape = (s[0], s[1], 3), dtype = np.uint8) * 255, mode = 'RGB') - - # create alpha mask - new_alpha_mask = Image.new('L', background.size, color = 0) - new_alpha_mask.paste(pred_mask_crop) - - # bring both together - composite = Image.composite(cropped, background, new_alpha_mask) - - - ### Predict modernity - - img_trans = test_transforms(composite).unsqueeze(0) - - with torch.no_grad(): - out = pretrained_model(img_trans) - - mod_score = modernity_pred(out) - - return composite, f'Modernity score: {round(float(mod_score), 5)}' - - - else: - message = 'no car was detected in image' - - # White image as place holder - placeholder = Image.fromarray(np.ones(shape = (100, 150, 3), dtype = np.uint8) * 255, mode = 'RGB') - - return placeholder, message - - -### Gradio App ### -################## - -title = "Prediction of Car Modernity Score" -description = "Upload image of car to get prediction of the modernity score. If image includes multiple cars, car with largest pixel count is extracted" -examples = [['test_img_1.jpg'], ['test_img_2.jpg'], ['test_img_3.jpg'], ['test_img_4.jpg'], ['test_img_5.jpg'], ['test_img_6.jpeg'], ['test_img_7.jpeg']] - -classif_app = gr.Interface(fn=image_classifier, - inputs="image", - outputs=["image", "label"], - title = title, - description = description, - examples = examples) - -classif_app.launch() - diff --git a/spaces/segments-tobias/conex/espnet/nets/pytorch_backend/transducer/custom_decoder.py b/spaces/segments-tobias/conex/espnet/nets/pytorch_backend/transducer/custom_decoder.py deleted file mode 100644 index ca37fe645ff71635f3ce78d6d3929cb005f58b37..0000000000000000000000000000000000000000 --- a/spaces/segments-tobias/conex/espnet/nets/pytorch_backend/transducer/custom_decoder.py +++ /dev/null @@ -1,277 +0,0 @@ -"""Custom decoder definition for transducer models.""" - -import torch - -from espnet.nets.pytorch_backend.transducer.blocks import build_blocks -from espnet.nets.pytorch_backend.transducer.utils import check_batch_state -from espnet.nets.pytorch_backend.transducer.utils import check_state -from espnet.nets.pytorch_backend.transducer.utils import pad_sequence -from espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm -from espnet.nets.pytorch_backend.transformer.mask import subsequent_mask -from espnet.nets.transducer_decoder_interface import TransducerDecoderInterface - - -class CustomDecoder(TransducerDecoderInterface, torch.nn.Module): - """Custom decoder module for transducer models. - - Args: - odim (int): dimension of outputs - dec_arch (list): list of layer definitions - input_layer (str): input layer type - repeat_block (int): repeat provided blocks N times if N > 1 - positional_encoding_type (str): positional encoding type - positionwise_layer_type (str): linear - positionwise_activation_type (str): positionwise activation type - dropout_rate_embed (float): dropout rate for embedding layer (if specified) - blank (int): blank symbol ID - - """ - - def __init__( - self, - odim, - dec_arch, - input_layer="embed", - repeat_block=0, - joint_activation_type="tanh", - positional_encoding_type="abs_pos", - positionwise_layer_type="linear", - positionwise_activation_type="relu", - dropout_rate_embed=0.0, - blank=0, - ): - """Construct a CustomDecoder object.""" - torch.nn.Module.__init__(self) - - self.embed, self.decoders, ddim, _ = build_blocks( - "decoder", - odim, - input_layer, - dec_arch, - repeat_block=repeat_block, - positional_encoding_type=positional_encoding_type, - positionwise_layer_type=positionwise_layer_type, - positionwise_activation_type=positionwise_activation_type, - dropout_rate_embed=dropout_rate_embed, - padding_idx=blank, - ) - - self.after_norm = LayerNorm(ddim) - - self.dlayers = len(self.decoders) - self.dunits = ddim - self.odim = odim - - self.blank = blank - - def set_device(self, device): - """Set GPU device to use. - - Args: - device (torch.device): device id - - """ - self.device = device - - def init_state(self, batch_size=None, device=None, dtype=None): - """Initialize decoder states. - - Args: - None - - Returns: - state (list): batch of decoder decoder states [L x None] - - """ - state = [None] * self.dlayers - - return state - - def forward(self, tgt, tgt_mask, memory): - """Forward custom decoder. - - Args: - tgt (torch.Tensor): input token ids, int64 (batch, maxlen_out) - if input_layer == "embed" - input tensor - (batch, maxlen_out, #mels) in the other cases - tgt_mask (torch.Tensor): input token mask, (batch, maxlen_out) - dtype=torch.uint8 in PyTorch 1.2- - dtype=torch.bool in PyTorch 1.2+ (include 1.2) - memory (torch.Tensor): encoded memory, float32 (batch, maxlen_in, feat) - - Return: - tgt (torch.Tensor): decoder output (batch, maxlen_out, dim_dec) - tgt_mask (torch.Tensor): score mask before softmax (batch, maxlen_out) - - """ - tgt = self.embed(tgt) - - tgt, tgt_mask = self.decoders(tgt, tgt_mask) - tgt = self.after_norm(tgt) - - return tgt, tgt_mask - - def score(self, hyp, cache): - """Forward one step. - - Args: - hyp (dataclass): hypothesis - cache (dict): states cache - - Returns: - y (torch.Tensor): decoder outputs (1, dec_dim) - (list): decoder states - [L x (1, max_len, dec_dim)] - lm_tokens (torch.Tensor): token id for LM (1) - - """ - tgt = torch.tensor([hyp.yseq], device=self.device) - lm_tokens = tgt[:, -1] - - str_yseq = "".join(list(map(str, hyp.yseq))) - - if str_yseq in cache: - y, new_state = cache[str_yseq] - else: - tgt_mask = subsequent_mask(len(hyp.yseq)).unsqueeze_(0) - - state = check_state(hyp.dec_state, (tgt.size(1) - 1), self.blank) - - tgt = self.embed(tgt) - - new_state = [] - for s, decoder in zip(state, self.decoders): - tgt, tgt_mask = decoder(tgt, tgt_mask, cache=s) - new_state.append(tgt) - - y = self.after_norm(tgt[:, -1]) - - cache[str_yseq] = (y, new_state) - - return y[0], new_state, lm_tokens - - def batch_score(self, hyps, batch_states, cache, use_lm): - """Forward batch one step. - - Args: - hyps (list): batch of hypotheses - batch_states (list): decoder states - [L x (B, max_len, dec_dim)] - cache (dict): states cache - - Returns: - batch_y (torch.Tensor): decoder output (B, dec_dim) - batch_states (list): decoder states - [L x (B, max_len, dec_dim)] - lm_tokens (torch.Tensor): batch of token ids for LM (B) - - """ - final_batch = len(hyps) - - process = [] - done = [None for _ in range(final_batch)] - - for i, hyp in enumerate(hyps): - str_yseq = "".join(list(map(str, hyp.yseq))) - - if str_yseq in cache: - done[i] = cache[str_yseq] - else: - process.append((str_yseq, hyp.yseq, hyp.dec_state)) - - if process: - _tokens = pad_sequence([p[1] for p in process], self.blank) - batch_tokens = torch.LongTensor(_tokens, device=self.device) - - tgt_mask = ( - subsequent_mask(batch_tokens.size(-1)) - .unsqueeze_(0) - .expand(len(process), -1, -1) - ) - - dec_state = self.create_batch_states( - self.init_state(), - [p[2] for p in process], - _tokens, - ) - - tgt = self.embed(batch_tokens) - - next_state = [] - for s, decoder in zip(dec_state, self.decoders): - tgt, tgt_mask = decoder(tgt, tgt_mask, cache=s) - next_state.append(tgt) - - tgt = self.after_norm(tgt[:, -1]) - - j = 0 - for i in range(final_batch): - if done[i] is None: - new_state = self.select_state(next_state, j) - - done[i] = (tgt[j], new_state) - cache[process[j][0]] = (tgt[j], new_state) - - j += 1 - - self.create_batch_states( - batch_states, [d[1] for d in done], [[0] + h.yseq for h in hyps] - ) - batch_y = torch.stack([d[0] for d in done]) - - if use_lm: - lm_tokens = torch.LongTensor( - [hyp.yseq[-1] for hyp in hyps], device=self.device - ) - - return batch_y, batch_states, lm_tokens - - return batch_y, batch_states, None - - def select_state(self, batch_states, idx): - """Get decoder state from batch of states, for given id. - - Args: - batch_states (list): batch of decoder states - [L x (B, max_len, dec_dim)] - idx (int): index to extract state from batch of states - - Returns: - state_idx (list): decoder states for given id - [L x (1, max_len, dec_dim)] - - """ - if batch_states[0] is None: - return batch_states - - state_idx = [batch_states[layer][idx] for layer in range(self.dlayers)] - - return state_idx - - def create_batch_states(self, batch_states, l_states, check_list): - """Create batch of decoder states. - - Args: - batch_states (list): batch of decoder states - [L x (B, max_len, dec_dim)] - l_states (list): list of decoder states - [B x [L x (1, max_len, dec_dim)]] - check_list (list): list of sequences for max_len - - Returns: - batch_states (list): batch of decoder states - [L x (B, max_len, dec_dim)] - - """ - if l_states[0][0] is None: - return batch_states - - max_len = max(len(elem) for elem in check_list) - 1 - - for layer in range(self.dlayers): - batch_states[layer] = check_batch_state( - [s[layer] for s in l_states], max_len, self.blank - ) - - return batch_states diff --git a/spaces/segments-tobias/conex/espnet/st/pytorch_backend/st.py b/spaces/segments-tobias/conex/espnet/st/pytorch_backend/st.py deleted file mode 100644 index d6824280c3998d59f522713df845732228f3bedd..0000000000000000000000000000000000000000 --- a/spaces/segments-tobias/conex/espnet/st/pytorch_backend/st.py +++ /dev/null @@ -1,687 +0,0 @@ -# Copyright 2019 Kyoto University (Hirofumi Inaguma) -# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) - -"""Training/decoding definition for the speech translation task.""" - -import json -import logging -import os -import sys - -from chainer import training -from chainer.training import extensions -import numpy as np -from tensorboardX import SummaryWriter -import torch - -from espnet.asr.asr_utils import adadelta_eps_decay -from espnet.asr.asr_utils import adam_lr_decay -from espnet.asr.asr_utils import add_results_to_json -from espnet.asr.asr_utils import CompareValueTrigger -from espnet.asr.asr_utils import restore_snapshot -from espnet.asr.asr_utils import snapshot_object -from espnet.asr.asr_utils import torch_load -from espnet.asr.asr_utils import torch_resume -from espnet.asr.asr_utils import torch_snapshot -from espnet.asr.pytorch_backend.asr_init import load_trained_model -from espnet.asr.pytorch_backend.asr_init import load_trained_modules - -from espnet.nets.pytorch_backend.e2e_asr import pad_list -from espnet.nets.st_interface import STInterface -from espnet.utils.dataset import ChainerDataLoader -from espnet.utils.dataset import TransformDataset -from espnet.utils.deterministic_utils import set_deterministic_pytorch -from espnet.utils.dynamic_import import dynamic_import -from espnet.utils.io_utils import LoadInputsAndTargets -from espnet.utils.training.batchfy import make_batchset -from espnet.utils.training.iterators import ShufflingEnabler -from espnet.utils.training.tensorboard_logger import TensorboardLogger -from espnet.utils.training.train_utils import check_early_stop -from espnet.utils.training.train_utils import set_early_stop - -from espnet.asr.pytorch_backend.asr import CustomConverter as ASRCustomConverter -from espnet.asr.pytorch_backend.asr import CustomEvaluator -from espnet.asr.pytorch_backend.asr import CustomUpdater - -import matplotlib - -matplotlib.use("Agg") - -if sys.version_info[0] == 2: - from itertools import izip_longest as zip_longest -else: - from itertools import zip_longest as zip_longest - - -class CustomConverter(ASRCustomConverter): - """Custom batch converter for Pytorch. - - Args: - subsampling_factor (int): The subsampling factor. - dtype (torch.dtype): Data type to convert. - use_source_text (bool): use source transcription. - - """ - - def __init__( - self, subsampling_factor=1, dtype=torch.float32, use_source_text=False - ): - """Construct a CustomConverter object.""" - super().__init__(subsampling_factor=subsampling_factor, dtype=dtype) - self.use_source_text = use_source_text - - def __call__(self, batch, device=torch.device("cpu")): - """Transform a batch and send it to a device. - - Args: - batch (list): The batch to transform. - device (torch.device): The device to send to. - - Returns: - tuple(torch.Tensor, torch.Tensor, torch.Tensor) - - """ - # batch should be located in list - assert len(batch) == 1 - xs, ys, ys_src = batch[0] - - # get batch of lengths of input sequences - ilens = np.array([x.shape[0] for x in xs]) - ilens = torch.from_numpy(ilens).to(device) - - xs_pad = pad_list([torch.from_numpy(x).float() for x in xs], 0).to( - device, dtype=self.dtype - ) - - ys_pad = pad_list( - [torch.from_numpy(np.array(y, dtype=np.int64)) for y in ys], - self.ignore_id, - ).to(device) - - if self.use_source_text: - ys_pad_src = pad_list( - [torch.from_numpy(np.array(y, dtype=np.int64)) for y in ys_src], - self.ignore_id, - ).to(device) - else: - ys_pad_src = None - - return xs_pad, ilens, ys_pad, ys_pad_src - - -def train(args): - """Train with the given args. - - Args: - args (namespace): The program arguments. - - """ - set_deterministic_pytorch(args) - - # check cuda availability - if not torch.cuda.is_available(): - logging.warning("cuda is not available") - - # get input and output dimension info - with open(args.valid_json, "rb") as f: - valid_json = json.load(f)["utts"] - utts = list(valid_json.keys()) - idim = int(valid_json[utts[0]]["input"][0]["shape"][-1]) - odim = int(valid_json[utts[0]]["output"][0]["shape"][-1]) - logging.info("#input dims : " + str(idim)) - logging.info("#output dims: " + str(odim)) - - # Initialize with pre-trained ASR encoder and MT decoder - if args.enc_init is not None or args.dec_init is not None: - model = load_trained_modules(idim, odim, args, interface=STInterface) - else: - model_class = dynamic_import(args.model_module) - model = model_class(idim, odim, args) - assert isinstance(model, STInterface) - total_subsampling_factor = model.get_total_subsampling_factor() - - # write model config - if not os.path.exists(args.outdir): - os.makedirs(args.outdir) - model_conf = args.outdir + "/model.json" - with open(model_conf, "wb") as f: - logging.info("writing a model config file to " + model_conf) - f.write( - json.dumps( - (idim, odim, vars(args)), indent=4, ensure_ascii=False, sort_keys=True - ).encode("utf_8") - ) - for key in sorted(vars(args).keys()): - logging.info("ARGS: " + key + ": " + str(vars(args)[key])) - - reporter = model.reporter - - # check the use of multi-gpu - if args.ngpu > 1: - if args.batch_size != 0: - logging.warning( - "batch size is automatically increased (%d -> %d)" - % (args.batch_size, args.batch_size * args.ngpu) - ) - args.batch_size *= args.ngpu - - # set torch device - device = torch.device("cuda" if args.ngpu > 0 else "cpu") - if args.train_dtype in ("float16", "float32", "float64"): - dtype = getattr(torch, args.train_dtype) - else: - dtype = torch.float32 - model = model.to(device=device, dtype=dtype) - - logging.warning( - "num. model params: {:,} (num. trained: {:,} ({:.1f}%))".format( - sum(p.numel() for p in model.parameters()), - sum(p.numel() for p in model.parameters() if p.requires_grad), - sum(p.numel() for p in model.parameters() if p.requires_grad) - * 100.0 - / sum(p.numel() for p in model.parameters()), - ) - ) - - # Setup an optimizer - if args.opt == "adadelta": - optimizer = torch.optim.Adadelta( - model.parameters(), rho=0.95, eps=args.eps, weight_decay=args.weight_decay - ) - elif args.opt == "adam": - optimizer = torch.optim.Adam( - model.parameters(), lr=args.lr, weight_decay=args.weight_decay - ) - elif args.opt == "noam": - from espnet.nets.pytorch_backend.transformer.optimizer import get_std_opt - - optimizer = get_std_opt( - model.parameters(), - args.adim, - args.transformer_warmup_steps, - args.transformer_lr, - ) - else: - raise NotImplementedError("unknown optimizer: " + args.opt) - - # setup apex.amp - if args.train_dtype in ("O0", "O1", "O2", "O3"): - try: - from apex import amp - except ImportError as e: - logging.error( - f"You need to install apex for --train-dtype {args.train_dtype}. " - "See https://github.com/NVIDIA/apex#linux" - ) - raise e - if args.opt == "noam": - model, optimizer.optimizer = amp.initialize( - model, optimizer.optimizer, opt_level=args.train_dtype - ) - else: - model, optimizer = amp.initialize( - model, optimizer, opt_level=args.train_dtype - ) - use_apex = True - else: - use_apex = False - - # FIXME: TOO DIRTY HACK - setattr(optimizer, "target", reporter) - setattr(optimizer, "serialize", lambda s: reporter.serialize(s)) - - # Setup a converter - converter = CustomConverter( - subsampling_factor=model.subsample[0], - dtype=dtype, - use_source_text=args.asr_weight > 0 or args.mt_weight > 0, - ) - - # read json data - with open(args.train_json, "rb") as f: - train_json = json.load(f)["utts"] - with open(args.valid_json, "rb") as f: - valid_json = json.load(f)["utts"] - - use_sortagrad = args.sortagrad == -1 or args.sortagrad > 0 - # make minibatch list (variable length) - train = make_batchset( - train_json, - args.batch_size, - args.maxlen_in, - args.maxlen_out, - args.minibatches, - min_batch_size=args.ngpu if args.ngpu > 1 else 1, - shortest_first=use_sortagrad, - count=args.batch_count, - batch_bins=args.batch_bins, - batch_frames_in=args.batch_frames_in, - batch_frames_out=args.batch_frames_out, - batch_frames_inout=args.batch_frames_inout, - iaxis=0, - oaxis=0, - ) - valid = make_batchset( - valid_json, - args.batch_size, - args.maxlen_in, - args.maxlen_out, - args.minibatches, - min_batch_size=args.ngpu if args.ngpu > 1 else 1, - count=args.batch_count, - batch_bins=args.batch_bins, - batch_frames_in=args.batch_frames_in, - batch_frames_out=args.batch_frames_out, - batch_frames_inout=args.batch_frames_inout, - iaxis=0, - oaxis=0, - ) - - load_tr = LoadInputsAndTargets( - mode="asr", - load_output=True, - preprocess_conf=args.preprocess_conf, - preprocess_args={"train": True}, # Switch the mode of preprocessing - ) - load_cv = LoadInputsAndTargets( - mode="asr", - load_output=True, - preprocess_conf=args.preprocess_conf, - preprocess_args={"train": False}, # Switch the mode of preprocessing - ) - # hack to make batchsize argument as 1 - # actual bathsize is included in a list - # default collate function converts numpy array to pytorch tensor - # we used an empty collate function instead which returns list - train_iter = ChainerDataLoader( - dataset=TransformDataset(train, lambda data: converter([load_tr(data)])), - batch_size=1, - num_workers=args.n_iter_processes, - shuffle=not use_sortagrad, - collate_fn=lambda x: x[0], - ) - valid_iter = ChainerDataLoader( - dataset=TransformDataset(valid, lambda data: converter([load_cv(data)])), - batch_size=1, - shuffle=False, - collate_fn=lambda x: x[0], - num_workers=args.n_iter_processes, - ) - - # Set up a trainer - updater = CustomUpdater( - model, - args.grad_clip, - {"main": train_iter}, - optimizer, - device, - args.ngpu, - args.grad_noise, - args.accum_grad, - use_apex=use_apex, - ) - trainer = training.Trainer(updater, (args.epochs, "epoch"), out=args.outdir) - - if use_sortagrad: - trainer.extend( - ShufflingEnabler([train_iter]), - trigger=(args.sortagrad if args.sortagrad != -1 else args.epochs, "epoch"), - ) - - # Resume from a snapshot - if args.resume: - logging.info("resumed from %s" % args.resume) - torch_resume(args.resume, trainer) - - # Evaluate the model with the test dataset for each epoch - if args.save_interval_iters > 0: - trainer.extend( - CustomEvaluator(model, {"main": valid_iter}, reporter, device, args.ngpu), - trigger=(args.save_interval_iters, "iteration"), - ) - else: - trainer.extend( - CustomEvaluator(model, {"main": valid_iter}, reporter, device, args.ngpu) - ) - - # Save attention weight at each epoch - if args.num_save_attention > 0: - data = sorted( - list(valid_json.items())[: args.num_save_attention], - key=lambda x: int(x[1]["input"][0]["shape"][1]), - reverse=True, - ) - if hasattr(model, "module"): - att_vis_fn = model.module.calculate_all_attentions - plot_class = model.module.attention_plot_class - else: - att_vis_fn = model.calculate_all_attentions - plot_class = model.attention_plot_class - att_reporter = plot_class( - att_vis_fn, - data, - args.outdir + "/att_ws", - converter=converter, - transform=load_cv, - device=device, - subsampling_factor=total_subsampling_factor, - ) - trainer.extend(att_reporter, trigger=(1, "epoch")) - else: - att_reporter = None - - # Save CTC prob at each epoch - if (args.asr_weight > 0 and args.mtlalpha > 0) and args.num_save_ctc > 0: - # NOTE: sort it by output lengths - data = sorted( - list(valid_json.items())[: args.num_save_ctc], - key=lambda x: int(x[1]["output"][0]["shape"][0]), - reverse=True, - ) - if hasattr(model, "module"): - ctc_vis_fn = model.module.calculate_all_ctc_probs - plot_class = model.module.ctc_plot_class - else: - ctc_vis_fn = model.calculate_all_ctc_probs - plot_class = model.ctc_plot_class - ctc_reporter = plot_class( - ctc_vis_fn, - data, - args.outdir + "/ctc_prob", - converter=converter, - transform=load_cv, - device=device, - subsampling_factor=total_subsampling_factor, - ) - trainer.extend(ctc_reporter, trigger=(1, "epoch")) - else: - ctc_reporter = None - - # Make a plot for training and validation values - trainer.extend( - extensions.PlotReport( - [ - "main/loss", - "validation/main/loss", - "main/loss_asr", - "validation/main/loss_asr", - "main/loss_mt", - "validation/main/loss_mt", - "main/loss_st", - "validation/main/loss_st", - ], - "epoch", - file_name="loss.png", - ) - ) - trainer.extend( - extensions.PlotReport( - [ - "main/acc", - "validation/main/acc", - "main/acc_asr", - "validation/main/acc_asr", - "main/acc_mt", - "validation/main/acc_mt", - ], - "epoch", - file_name="acc.png", - ) - ) - trainer.extend( - extensions.PlotReport( - ["main/bleu", "validation/main/bleu"], "epoch", file_name="bleu.png" - ) - ) - - # Save best models - trainer.extend( - snapshot_object(model, "model.loss.best"), - trigger=training.triggers.MinValueTrigger("validation/main/loss"), - ) - trainer.extend( - snapshot_object(model, "model.acc.best"), - trigger=training.triggers.MaxValueTrigger("validation/main/acc"), - ) - - # save snapshot which contains model and optimizer states - if args.save_interval_iters > 0: - trainer.extend( - torch_snapshot(filename="snapshot.iter.{.updater.iteration}"), - trigger=(args.save_interval_iters, "iteration"), - ) - else: - trainer.extend(torch_snapshot(), trigger=(1, "epoch")) - - # epsilon decay in the optimizer - if args.opt == "adadelta": - if args.criterion == "acc": - trainer.extend( - restore_snapshot( - model, args.outdir + "/model.acc.best", load_fn=torch_load - ), - trigger=CompareValueTrigger( - "validation/main/acc", - lambda best_value, current_value: best_value > current_value, - ), - ) - trainer.extend( - adadelta_eps_decay(args.eps_decay), - trigger=CompareValueTrigger( - "validation/main/acc", - lambda best_value, current_value: best_value > current_value, - ), - ) - elif args.criterion == "loss": - trainer.extend( - restore_snapshot( - model, args.outdir + "/model.loss.best", load_fn=torch_load - ), - trigger=CompareValueTrigger( - "validation/main/loss", - lambda best_value, current_value: best_value < current_value, - ), - ) - trainer.extend( - adadelta_eps_decay(args.eps_decay), - trigger=CompareValueTrigger( - "validation/main/loss", - lambda best_value, current_value: best_value < current_value, - ), - ) - elif args.opt == "adam": - if args.criterion == "acc": - trainer.extend( - restore_snapshot( - model, args.outdir + "/model.acc.best", load_fn=torch_load - ), - trigger=CompareValueTrigger( - "validation/main/acc", - lambda best_value, current_value: best_value > current_value, - ), - ) - trainer.extend( - adam_lr_decay(args.lr_decay), - trigger=CompareValueTrigger( - "validation/main/acc", - lambda best_value, current_value: best_value > current_value, - ), - ) - elif args.criterion == "loss": - trainer.extend( - restore_snapshot( - model, args.outdir + "/model.loss.best", load_fn=torch_load - ), - trigger=CompareValueTrigger( - "validation/main/loss", - lambda best_value, current_value: best_value < current_value, - ), - ) - trainer.extend( - adam_lr_decay(args.lr_decay), - trigger=CompareValueTrigger( - "validation/main/loss", - lambda best_value, current_value: best_value < current_value, - ), - ) - - # Write a log of evaluation statistics for each epoch - trainer.extend( - extensions.LogReport(trigger=(args.report_interval_iters, "iteration")) - ) - report_keys = [ - "epoch", - "iteration", - "main/loss", - "main/loss_st", - "main/loss_asr", - "validation/main/loss", - "validation/main/loss_st", - "validation/main/loss_asr", - "main/acc", - "validation/main/acc", - ] - if args.asr_weight > 0: - report_keys.append("main/acc_asr") - report_keys.append("validation/main/acc_asr") - report_keys += ["elapsed_time"] - if args.opt == "adadelta": - trainer.extend( - extensions.observe_value( - "eps", - lambda trainer: trainer.updater.get_optimizer("main").param_groups[0][ - "eps" - ], - ), - trigger=(args.report_interval_iters, "iteration"), - ) - report_keys.append("eps") - elif args.opt in ["adam", "noam"]: - trainer.extend( - extensions.observe_value( - "lr", - lambda trainer: trainer.updater.get_optimizer("main").param_groups[0][ - "lr" - ], - ), - trigger=(args.report_interval_iters, "iteration"), - ) - report_keys.append("lr") - if args.asr_weight > 0: - if args.mtlalpha > 0: - report_keys.append("main/cer_ctc") - report_keys.append("validation/main/cer_ctc") - if args.mtlalpha < 1: - if args.report_cer: - report_keys.append("validation/main/cer") - if args.report_wer: - report_keys.append("validation/main/wer") - if args.report_bleu: - report_keys.append("main/bleu") - report_keys.append("validation/main/bleu") - trainer.extend( - extensions.PrintReport(report_keys), - trigger=(args.report_interval_iters, "iteration"), - ) - - trainer.extend(extensions.ProgressBar(update_interval=args.report_interval_iters)) - set_early_stop(trainer, args) - - if args.tensorboard_dir is not None and args.tensorboard_dir != "": - trainer.extend( - TensorboardLogger( - SummaryWriter(args.tensorboard_dir), - att_reporter=att_reporter, - ctc_reporter=ctc_reporter, - ), - trigger=(args.report_interval_iters, "iteration"), - ) - # Run the training - trainer.run() - check_early_stop(trainer, args.epochs) - - -def trans(args): - """Decode with the given args. - - Args: - args (namespace): The program arguments. - - """ - set_deterministic_pytorch(args) - model, train_args = load_trained_model(args.model) - assert isinstance(model, STInterface) - model.trans_args = args - - # gpu - if args.ngpu == 1: - gpu_id = list(range(args.ngpu)) - logging.info("gpu id: " + str(gpu_id)) - model.cuda() - - # read json data - with open(args.trans_json, "rb") as f: - js = json.load(f)["utts"] - new_js = {} - - load_inputs_and_targets = LoadInputsAndTargets( - mode="asr", - load_output=False, - sort_in_input_length=False, - preprocess_conf=train_args.preprocess_conf - if args.preprocess_conf is None - else args.preprocess_conf, - preprocess_args={"train": False}, - ) - - if args.batchsize == 0: - with torch.no_grad(): - for idx, name in enumerate(js.keys(), 1): - logging.info("(%d/%d) decoding " + name, idx, len(js.keys())) - batch = [(name, js[name])] - feat = load_inputs_and_targets(batch)[0][0] - nbest_hyps = model.translate( - feat, - args, - train_args.char_list, - ) - new_js[name] = add_results_to_json( - js[name], nbest_hyps, train_args.char_list - ) - - else: - - def grouper(n, iterable, fillvalue=None): - kargs = [iter(iterable)] * n - return zip_longest(*kargs, fillvalue=fillvalue) - - # sort data if batchsize > 1 - keys = list(js.keys()) - if args.batchsize > 1: - feat_lens = [js[key]["input"][0]["shape"][0] for key in keys] - sorted_index = sorted(range(len(feat_lens)), key=lambda i: -feat_lens[i]) - keys = [keys[i] for i in sorted_index] - - with torch.no_grad(): - for names in grouper(args.batchsize, keys, None): - names = [name for name in names if name] - batch = [(name, js[name]) for name in names] - feats = load_inputs_and_targets(batch)[0] - nbest_hyps = model.translate_batch( - feats, - args, - train_args.char_list, - ) - - for i, nbest_hyp in enumerate(nbest_hyps): - name = names[i] - new_js[name] = add_results_to_json( - js[name], nbest_hyp, train_args.char_list - ) - - with open(args.result_label, "wb") as f: - f.write( - json.dumps( - {"utts": new_js}, indent=4, ensure_ascii=False, sort_keys=True - ).encode("utf_8") - ) diff --git a/spaces/segments/panoptic-segment-anything-api/GroundingDINO/groundingdino/util/box_ops.py b/spaces/segments/panoptic-segment-anything-api/GroundingDINO/groundingdino/util/box_ops.py deleted file mode 100644 index 781068d294e576954edb4bd07b6e0f30e4e1bcd9..0000000000000000000000000000000000000000 --- a/spaces/segments/panoptic-segment-anything-api/GroundingDINO/groundingdino/util/box_ops.py +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -""" -Utilities for bounding box manipulation and GIoU. -""" -import torch -from torchvision.ops.boxes import box_area - - -def box_cxcywh_to_xyxy(x): - x_c, y_c, w, h = x.unbind(-1) - b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] - return torch.stack(b, dim=-1) - - -def box_xyxy_to_cxcywh(x): - x0, y0, x1, y1 = x.unbind(-1) - b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)] - return torch.stack(b, dim=-1) - - -# modified from torchvision to also return the union -def box_iou(boxes1, boxes2): - area1 = box_area(boxes1) - area2 = box_area(boxes2) - - # import ipdb; ipdb.set_trace() - lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] - rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] - - wh = (rb - lt).clamp(min=0) # [N,M,2] - inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] - - union = area1[:, None] + area2 - inter - - iou = inter / (union + 1e-6) - return iou, union - - -def generalized_box_iou(boxes1, boxes2): - """ - Generalized IoU from https://giou.stanford.edu/ - - The boxes should be in [x0, y0, x1, y1] format - - Returns a [N, M] pairwise matrix, where N = len(boxes1) - and M = len(boxes2) - """ - # degenerate boxes gives inf / nan results - # so do an early check - assert (boxes1[:, 2:] >= boxes1[:, :2]).all() - assert (boxes2[:, 2:] >= boxes2[:, :2]).all() - # except: - # import ipdb; ipdb.set_trace() - iou, union = box_iou(boxes1, boxes2) - - lt = torch.min(boxes1[:, None, :2], boxes2[:, :2]) - rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:]) - - wh = (rb - lt).clamp(min=0) # [N,M,2] - area = wh[:, :, 0] * wh[:, :, 1] - - return iou - (area - union) / (area + 1e-6) - - -# modified from torchvision to also return the union -def box_iou_pairwise(boxes1, boxes2): - area1 = box_area(boxes1) - area2 = box_area(boxes2) - - lt = torch.max(boxes1[:, :2], boxes2[:, :2]) # [N,2] - rb = torch.min(boxes1[:, 2:], boxes2[:, 2:]) # [N,2] - - wh = (rb - lt).clamp(min=0) # [N,2] - inter = wh[:, 0] * wh[:, 1] # [N] - - union = area1 + area2 - inter - - iou = inter / union - return iou, union - - -def generalized_box_iou_pairwise(boxes1, boxes2): - """ - Generalized IoU from https://giou.stanford.edu/ - - Input: - - boxes1, boxes2: N,4 - Output: - - giou: N, 4 - """ - # degenerate boxes gives inf / nan results - # so do an early check - assert (boxes1[:, 2:] >= boxes1[:, :2]).all() - assert (boxes2[:, 2:] >= boxes2[:, :2]).all() - assert boxes1.shape == boxes2.shape - iou, union = box_iou_pairwise(boxes1, boxes2) # N, 4 - - lt = torch.min(boxes1[:, :2], boxes2[:, :2]) - rb = torch.max(boxes1[:, 2:], boxes2[:, 2:]) - - wh = (rb - lt).clamp(min=0) # [N,2] - area = wh[:, 0] * wh[:, 1] - - return iou - (area - union) / area - - -def masks_to_boxes(masks): - """Compute the bounding boxes around the provided masks - - The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions. - - Returns a [N, 4] tensors, with the boxes in xyxy format - """ - if masks.numel() == 0: - return torch.zeros((0, 4), device=masks.device) - - h, w = masks.shape[-2:] - - y = torch.arange(0, h, dtype=torch.float) - x = torch.arange(0, w, dtype=torch.float) - y, x = torch.meshgrid(y, x) - - x_mask = masks * x.unsqueeze(0) - x_max = x_mask.flatten(1).max(-1)[0] - x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] - - y_mask = masks * y.unsqueeze(0) - y_max = y_mask.flatten(1).max(-1)[0] - y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0] - - return torch.stack([x_min, y_min, x_max, y_max], 1) - - -if __name__ == "__main__": - x = torch.rand(5, 4) - y = torch.rand(3, 4) - iou, union = box_iou(x, y) - import ipdb - - ipdb.set_trace() diff --git a/spaces/segments/panoptic-segment-anything/segment_anything/linter.sh b/spaces/segments/panoptic-segment-anything/segment_anything/linter.sh deleted file mode 100644 index df2e17436d30e89ff1728109301599f425f1ad6b..0000000000000000000000000000000000000000 --- a/spaces/segments/panoptic-segment-anything/segment_anything/linter.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash -e -# Copyright (c) Facebook, Inc. and its affiliates. - -{ - black --version | grep -E "23\." > /dev/null -} || { - echo "Linter requires 'black==23.*' !" - exit 1 -} - -ISORT_VERSION=$(isort --version-number) -if [[ "$ISORT_VERSION" != 5.12* ]]; then - echo "Linter requires isort==5.12.0 !" - exit 1 -fi - -echo "Running isort ..." -isort . --atomic - -echo "Running black ..." -black -l 100 . - -echo "Running flake8 ..." -if [ -x "$(command -v flake8)" ]; then - flake8 . -else - python3 -m flake8 . -fi - -echo "Running mypy..." - -mypy --exclude 'setup.py|notebooks' . diff --git a/spaces/shabnam91/Sanskrit-TTS/misc.py b/spaces/shabnam91/Sanskrit-TTS/misc.py deleted file mode 100644 index 10f6062960f59cadf361f05649be72091cfddb11..0000000000000000000000000000000000000000 --- a/spaces/shabnam91/Sanskrit-TTS/misc.py +++ /dev/null @@ -1,176 +0,0 @@ -import re -from cleaner_utils import * -from datetime_cleaner import * - -# Define dictionaries for date normalization, fractions, ratios, stop words, etc. -date_dict = { - "01": "०१", "02": "०२", "03": "०३", "04": "०४", "05": "०५", "06": "०६", - "07": "०७", "08": "०८", "09": "०९", "10": "१०", "11": "११", "12": "१२", -} - -sanskrit_percentages = { - 0: "शून्य प्रतिशत", - 10: "दश प्रतिशत", - 20: "विंशतिः प्रतिशत", - 30: "त्रिंशत् प्रतिशत", - 40: "चत्वारिंशत् प्रतिशत", - 50: "पञ्चाशत् प्रतिशत", - 60: "षट्शत् प्रतिशत", - 70: "सप्तति प्रतिशत", - 80: "अशीतिम् प्रतिशत", - 90: "नवति प्रतिशत", - 100: "सत्प्रतिशत्", - # Add more percentages as needed - } - -fraction_dict = { - "1/2": "१/२", "1/3": "१/३", "1/4": "१/४", "1/5": "१/५", "1/6": "१/६", - (1, 2): "अर्ध", - (1, 3): "तृतीय", - (1, 4): "चतुर्थ", - (1, 5): "पञ्चम", - (1, 6): "षष्ठ", - (1, 7): "सप्तम", - (1, 8): "अष्टम", - (1, 9): "नवम", - (1, 10): "दशम", - (1, 11): "एकादश", - (1, 12): "द्वादश", - (1, 13): "त्रयोदश", - (1, 14): "चतुर्दश", - (1, 15): "पञ्चदश", - (1, 16): "षोडश", - (1, 17): "सप्तदश", - (1, 18): "अष्टादश", - (1, 19): "एकोनविंशति", - (1, 20): "विंशतिः", - (1, 21): "एकविंशतिः", - # Add more fractions as needed -} - -ratio_dict = { - "6:8": "६:८", "3:4": "३:४", "2:5": "२:५", "5:8": "५:८", - '0': 'शून्य', '1': 'एक', '2': 'द्वे', '3': 'त्रीणि', '4': 'चत्वारि', '5': 'पञ्च', '6': 'षट्', '7': 'सप्त', '8': 'अष्ट', '9': 'नव', - # Add more ratios as needed -} - -# ... (previous code) - -# Define stop words in Sanskrit -stop_words = { - "पूर्णविराम", "उद्घोषः", "अल्पविरामः", "प्रश्नचिह्न", "वर्गकोष्ठकाः", - "द्विगुण", "ऊर्ध्वाधर", "शलाका", "ऊर्ध्वाधर", "बार", "हाइफन्", "अर्धविराम", "बृहदान्त्रम्", "ताराचिह्नम्" -} - - -def remove_stop_words(text): - for stop_word in stop_words: - text = text.replace(stop_word, "") - return text - -# ... (previous code) - - -def handle_fractions(text): - for fraction, normalized_fraction in fraction_dict.items(): - text = text.replace(fraction, normalized_fraction) - return text - -def handle_ratios(text): - for ratio, normalized_ratio in ratio_dict.items(): - text = text.replace(ratio, normalized_ratio) - return text - -# def remove_stop_words(text): -# for stop_word in stop_words: -# text = text.replace(stop_word, "") -# return text - -def handle_number_ranges(text): - # Define regex pattern to identify number ranges like "6-8" - number_range_pattern = r"\d+-\d+" - number_ranges_found = re.findall(number_range_pattern, text) - - for number_range in number_ranges_found: - range_start, range_end = number_range.split("-") - normalized_range = f"{range_start}-{range_end}" - text = text.replace(number_range, normalized_range) - - return text - -def text_processing(text): - tokenized_sentence = tokenize_sentence(text) - segmented_sentence_list = segment_sentence(tokenized_sentence) - formatted_datetime_list = list(map(handle_time, segmented_sentence_list)) - preprocessed_text, dates = normalize_date(formatted_datetime_list) # Obtain normalized dates - formatted_datetime = ''.join(formatted_datetime_list) - parsed_datetime_sentence = parse_datetime(formatted_datetime) - print(f"Parsed datetime: {parsed_datetime_sentence}") - formatted_abbreviations = handle_abbreviations(parsed_datetime_sentence) - print(f"formatted abbrev: {formatted_abbreviations}") - - # nsw_cleaned = remove_nsw(formatted_abbreviations) - normalized_text = normalize_text(formatted_abbreviations) - syllabified_text = syllabify_text(normalized_text) - cleaned_text = clean_text(syllabified_text) - # preprocessed_text, dates = normalize_date(cleaned_text) # Obtain normalized dates - preprocessed_text = handle_fractions(preprocessed_text) - preprocessed_text = handle_ratios(preprocessed_text) - preprocessed_text = remove_stop_words(preprocessed_text) - preprocessed_text = handle_number_ranges(preprocessed_text) - return preprocessed_text, dates - -# ... (same as before) - def synthesize_text_to_speech(text, is_processed=False): - if is_processed: - def add_prosodic_markers(text): - prosodic_text = ' स̄ + ं̆ + क̆ + ॄ̄ + त̄ + म + ्̆' - vowels = set('अ आ इ ई उ ऊ ऋ ॠ ऌ ॡ ए ऐ ओ औ') - - for char in text: - if char in vowels: - # Add diacritic for short vowels, and overline for long vowels - if char in 'इउऋऌ': - prosodic_text += char + '̆' # Short vowel diacritic - elif char in 'आईऊ': - prosodic_text += char + '̄' # Long vowel overline - else: - prosodic_text += char - else: - prosodic_text += char - - return prosodic_text - -# Example usage: -processed_text = 'स + ं + क + ृ + त + म + ्' -prosodic_processed_text = add_prosodic_markers(processed_text) -print(prosodic_processed_text) - - prosodic_text = add_prosodic_markers(text) - # Synthesize the processed text with prosodic markers - text_to_speech.synthesize(prosodic_text) - else: - # Synthesize the simple text without prosodic markers - text_to_speech.synthesize(text) - -# Example usage -input_text = "संस्कृतम् जगतः एकतमा अतिप्राचीना समृद्धा शास्त्रीया च भाषासु वर्तते" -processed_text = "स + ं + स + ् + क + ृ + त + म + ् + ज + ग + त + ः + ए + क + त + म + ा + अ + त + ि + प + ् + र + ा + च + ी + न + ा + स + म + ृ + द + ् + ध + ा + श + ा + स + ् + त + ् + र + ी + य + ा + च + भ + ा + ष + ा + स + ु + व + र + ् + त + त + े" - -# Determine whether the input text is processed or simple -if "#PROCESSED#" in input_text: - synthesize_text_to_speech(input_text.replace("#PROCESSED#", ""), is_processed=True) -elif "#SIMPLE#" in input_text: - synthesize_text_to_speech(input_text.replace("#SIMPLE#", ""), is_processed=False) -else: - # Handle the case where the input text format is not recognized - print("Input text format not recognized") - - -# Example usage -sample_text = "पूर्ण विराम 27.03.2007 27-03-2007 1/2 6:8" -preprocessed_text, dates = text_processing(sample_text) -print("Preprocessed Text:", preprocessed_text) - -g2p_text = grapheme_to_phoneme(preprocessed_text) -print("G2P Text:", g2p_text) diff --git a/spaces/shikunl/prismer/prismer/experts/segmentation/mask2former/modeling/pixel_decoder/ops/functions/__init__.py b/spaces/shikunl/prismer/prismer/experts/segmentation/mask2former/modeling/pixel_decoder/ops/functions/__init__.py deleted file mode 100644 index 2b06b5ac538b63bdb9a6c82e4635b95bb5491d5b..0000000000000000000000000000000000000000 --- a/spaces/shikunl/prismer/prismer/experts/segmentation/mask2former/modeling/pixel_decoder/ops/functions/__init__.py +++ /dev/null @@ -1,13 +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 -# ------------------------------------------------------------------------------------------------ - -# Copyright (c) Facebook, Inc. and its affiliates. -# Modified by Bowen Cheng from https://github.com/fundamentalvision/Deformable-DETR - -from .ms_deform_attn_func import MSDeformAttnFunction - diff --git a/spaces/shiwan10000/CodeFormer/CodeFormer/facelib/detection/yolov5face/models/common.py b/spaces/shiwan10000/CodeFormer/CodeFormer/facelib/detection/yolov5face/models/common.py deleted file mode 100644 index 497a00444c4c59725001993a63fe4617e9d323c8..0000000000000000000000000000000000000000 --- a/spaces/shiwan10000/CodeFormer/CodeFormer/facelib/detection/yolov5face/models/common.py +++ /dev/null @@ -1,299 +0,0 @@ -# This file contains modules common to various models - -import math - -import numpy as np -import torch -from torch import nn - -from facelib.detection.yolov5face.utils.datasets import letterbox -from facelib.detection.yolov5face.utils.general import ( - make_divisible, - non_max_suppression, - scale_coords, - xyxy2xywh, -) - - -def autopad(k, p=None): # kernel, padding - # Pad to 'same' - if p is None: - p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad - return p - - -def channel_shuffle(x, groups): - batchsize, num_channels, height, width = x.data.size() - channels_per_group = torch.div(num_channels, groups, rounding_mode="trunc") - - # reshape - x = x.view(batchsize, groups, channels_per_group, height, width) - x = torch.transpose(x, 1, 2).contiguous() - - # flatten - return x.view(batchsize, -1, height, width) - - -def DWConv(c1, c2, k=1, s=1, act=True): - # Depthwise convolution - return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act) - - -class Conv(nn.Module): - # Standard convolution - def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups - super().__init__() - self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) - self.bn = nn.BatchNorm2d(c2) - self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) - - def forward(self, x): - return self.act(self.bn(self.conv(x))) - - def fuseforward(self, x): - return self.act(self.conv(x)) - - -class StemBlock(nn.Module): - def __init__(self, c1, c2, k=3, s=2, p=None, g=1, act=True): - super().__init__() - self.stem_1 = Conv(c1, c2, k, s, p, g, act) - self.stem_2a = Conv(c2, c2 // 2, 1, 1, 0) - self.stem_2b = Conv(c2 // 2, c2, 3, 2, 1) - self.stem_2p = nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True) - self.stem_3 = Conv(c2 * 2, c2, 1, 1, 0) - - def forward(self, x): - stem_1_out = self.stem_1(x) - stem_2a_out = self.stem_2a(stem_1_out) - stem_2b_out = self.stem_2b(stem_2a_out) - stem_2p_out = self.stem_2p(stem_1_out) - return self.stem_3(torch.cat((stem_2b_out, stem_2p_out), 1)) - - -class Bottleneck(nn.Module): - # Standard bottleneck - def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion - super().__init__() - c_ = int(c2 * e) # hidden channels - self.cv1 = Conv(c1, c_, 1, 1) - self.cv2 = Conv(c_, c2, 3, 1, g=g) - self.add = shortcut and c1 == c2 - - def forward(self, x): - return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) - - -class BottleneckCSP(nn.Module): - # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks - def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion - super().__init__() - c_ = int(c2 * e) # hidden channels - self.cv1 = Conv(c1, c_, 1, 1) - self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) - self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) - self.cv4 = Conv(2 * c_, c2, 1, 1) - self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) - self.act = nn.LeakyReLU(0.1, inplace=True) - self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) - - def forward(self, x): - y1 = self.cv3(self.m(self.cv1(x))) - y2 = self.cv2(x) - return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1)))) - - -class C3(nn.Module): - # CSP Bottleneck with 3 convolutions - def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion - super().__init__() - c_ = int(c2 * e) # hidden channels - self.cv1 = Conv(c1, c_, 1, 1) - self.cv2 = Conv(c1, c_, 1, 1) - self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2) - self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n))) - - def forward(self, x): - return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1)) - - -class ShuffleV2Block(nn.Module): - def __init__(self, inp, oup, stride): - super().__init__() - - if not 1 <= stride <= 3: - raise ValueError("illegal stride value") - self.stride = stride - - branch_features = oup // 2 - - if self.stride > 1: - self.branch1 = nn.Sequential( - self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1), - nn.BatchNorm2d(inp), - nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False), - nn.BatchNorm2d(branch_features), - nn.SiLU(), - ) - else: - self.branch1 = nn.Sequential() - - self.branch2 = nn.Sequential( - nn.Conv2d( - inp if (self.stride > 1) else branch_features, - branch_features, - kernel_size=1, - stride=1, - padding=0, - bias=False, - ), - nn.BatchNorm2d(branch_features), - nn.SiLU(), - self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1), - nn.BatchNorm2d(branch_features), - nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False), - nn.BatchNorm2d(branch_features), - nn.SiLU(), - ) - - @staticmethod - def depthwise_conv(i, o, kernel_size, stride=1, padding=0, bias=False): - return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i) - - def forward(self, x): - if self.stride == 1: - x1, x2 = x.chunk(2, dim=1) - out = torch.cat((x1, self.branch2(x2)), dim=1) - else: - out = torch.cat((self.branch1(x), self.branch2(x)), dim=1) - out = channel_shuffle(out, 2) - return out - - -class SPP(nn.Module): - # Spatial pyramid pooling layer used in YOLOv3-SPP - def __init__(self, c1, c2, k=(5, 9, 13)): - super().__init__() - c_ = c1 // 2 # hidden channels - self.cv1 = Conv(c1, c_, 1, 1) - self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) - self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) - - def forward(self, x): - x = self.cv1(x) - return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) - - -class Focus(nn.Module): - # Focus wh information into c-space - def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups - super().__init__() - self.conv = Conv(c1 * 4, c2, k, s, p, g, act) - - def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) - return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) - - -class Concat(nn.Module): - # Concatenate a list of tensors along dimension - def __init__(self, dimension=1): - super().__init__() - self.d = dimension - - def forward(self, x): - return torch.cat(x, self.d) - - -class NMS(nn.Module): - # Non-Maximum Suppression (NMS) module - conf = 0.25 # confidence threshold - iou = 0.45 # IoU threshold - classes = None # (optional list) filter by class - - def forward(self, x): - return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) - - -class AutoShape(nn.Module): - # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS - img_size = 640 # inference size (pixels) - conf = 0.25 # NMS confidence threshold - iou = 0.45 # NMS IoU threshold - classes = None # (optional list) filter by class - - def __init__(self, model): - super().__init__() - self.model = model.eval() - - def autoshape(self): - print("autoShape already enabled, skipping... ") # model already converted to model.autoshape() - return self - - def forward(self, imgs, size=640, augment=False, profile=False): - # Inference from various sources. For height=720, width=1280, RGB images example inputs are: - # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(720,1280,3) - # PIL: = Image.open('image.jpg') # HWC x(720,1280,3) - # numpy: = np.zeros((720,1280,3)) # HWC - # torch: = torch.zeros(16,3,720,1280) # BCHW - # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images - - p = next(self.model.parameters()) # for device and type - if isinstance(imgs, torch.Tensor): # torch - return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference - - # Pre-process - n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images - shape0, shape1 = [], [] # image and inference shapes - for i, im in enumerate(imgs): - im = np.array(im) # to numpy - if im.shape[0] < 5: # image in CHW - im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) - im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input - s = im.shape[:2] # HWC - shape0.append(s) # image shape - g = size / max(s) # gain - shape1.append([y * g for y in s]) - imgs[i] = im # update - shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape - x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad - x = np.stack(x, 0) if n > 1 else x[0][None] # stack - x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW - x = torch.from_numpy(x).to(p.device).type_as(p) / 255.0 # uint8 to fp16/32 - - # Inference - with torch.no_grad(): - y = self.model(x, augment, profile)[0] # forward - y = non_max_suppression(y, conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) # NMS - - # Post-process - for i in range(n): - scale_coords(shape1, y[i][:, :4], shape0[i]) - - return Detections(imgs, y, self.names) - - -class Detections: - # detections class for YOLOv5 inference results - def __init__(self, imgs, pred, names=None): - super().__init__() - d = pred[0].device # device - gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1.0, 1.0], device=d) for im in imgs] # normalizations - self.imgs = imgs # list of images as numpy arrays - self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) - self.names = names # class names - self.xyxy = pred # xyxy pixels - self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels - self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized - self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized - self.n = len(self.pred) - - def __len__(self): - return self.n - - def tolist(self): - # return a list of Detections objects, i.e. 'for result in results.tolist():' - x = [Detections([self.imgs[i]], [self.pred[i]], self.names) for i in range(self.n)] - for d in x: - for k in ["imgs", "pred", "xyxy", "xyxyn", "xywh", "xywhn"]: - setattr(d, k, getattr(d, k)[0]) # pop out of list - return x diff --git a/spaces/silencewing/server/youyou/.history/math_20230613231948.html b/spaces/silencewing/server/youyou/.history/math_20230613231948.html deleted file mode 100644 index 78edc05dd4c48fbf90783e97953b459a05becfbd..0000000000000000000000000000000000000000 --- a/spaces/silencewing/server/youyou/.history/math_20230613231948.html +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - - - - Document - - - - -
        - - - - - - - - - - - - - - - - - - - - - - - - -
        题目
        答案
        正误
        得分
        -
        - - - - diff --git a/spaces/simonraj/ELOralCoachTestFeedback/README.md b/spaces/simonraj/ELOralCoachTestFeedback/README.md deleted file mode 100644 index 81b1dd2f206fefefbfe2cc9b943dad20dd444547..0000000000000000000000000000000000000000 --- a/spaces/simonraj/ELOralCoachTestFeedback/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: OralCoachStreamingEL -emoji: 📉 -colorFrom: yellow -colorTo: gray -sdk: gradio -sdk_version: 3.42.0 -app_file: app.py -pinned: false -duplicated_from: simonraj/ELOralCoachv1 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Buff Game for Mac and Level Up Everywhere.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Buff Game for Mac and Level Up Everywhere.md deleted file mode 100644 index ccd2a206c55a32585e9d8362fc40b41ba5ac3bd4..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download Buff Game for Mac and Level Up Everywhere.md +++ /dev/null @@ -1,93 +0,0 @@ -
        -

        How to Download Buff Game on Mac and Earn Rewards for Playing Games

        -

        If you are a gamer who loves playing games on your Mac, you might be interested in a new app that can make your gaming experience even more rewarding. It's called Buff Game, and it's a gamer's reward program that lets you earn items in real life for playing games. Sounds too good to be true, right? Well, it's not. In this article, we will show you how to download Buff Game on Mac and how to use it to level up everywhere.

        -

        What is Buff Game and Why You Should Try It

        -

        Buff Game is an app that runs in the background while you play your favorite games. It tracks your gameplay, performance, and achievements, and rewards you with buffs, which are points that you can redeem for real-life items at the marketplace. You can choose from a variety of items, such as gift cards, gaming gear, Steam keys, and many more. The better you play, the more buffs you earn.

        -

        buff game mac download


        Download ⚙⚙⚙ https://ssurll.com/2uNW11



        -

        But that's not all. Buff Game also has some other cool features that make it a must-have app for gamers. Here are some of them:

        -

        Buff Game supports over 1500 games and has a user-friendly interface

        -

        Whether you are into Valorant, LOL, Fortnite, Apex Legends, COD, PUBG, Rocket League, or any other popular game, chances are that Buff Game supports it. You can check out the full list of supported games on their website. And don't worry about compatibility issues. Buff Game works seamlessly with any game launcher or platform, such as Steam, Epic Games, Origin, etc.

        -

        Moreover, Buff Game has a simple and intuitive interface that lets you access all its features easily. You can see your buffs balance, challenges, highlights, marketplace, settings, and more from the main dashboard. You can also customize your profile, preferences, notifications, and more from the settings menu.

        -

        Buff Game is safe, secure, and compliant with game publishers' terms

        -

        You might be wondering if using Buff Game will get you banned from your games or compromise your security. The answer is no. Buff Game is an authorized app by Overwolf, which is the world's best in-game creation platform. It has passed rigorous tests of security and authenticity by Overwolf and game publishers. It does not interfere with your gameplay or affect your performance in any way.

        -

        Furthermore, Buff Game does not collect any personal or sensitive data from you or your device. It only tracks your gameplay data anonymously and uses see the price of the item in buffs, the availability of the item in stock, and the description of the item. If you have enough buffs to redeem the item, you will see a button that says "Redeem". Click on it and you will be taken to the next step.

        -

        Confirm your order and enter your shipping details

        -

        After clicking on "Redeem", you will see a confirmation screen that shows you the details of your order, such as the item name, price, quantity, and total. You will also see a form that asks you to enter your shipping details, such as your name, address, phone number, and email. Fill in the required fields and click on "Confirm Order". You will then see a message that says "Your order has been placed successfully".

        -

        Wait for your item to arrive and enjoy it

        -

        The last step is to wait for your item to arrive and enjoy it. Depending on the item and your location, it may take a few days or weeks for your item to be shipped and delivered. You can track your order status from the "Orders" tab on the main dashboard of Buff Game. You will also receive an email confirmation and a tracking number for your order. Once you receive your item, you can use it, share it, or review it on Buff Game.

        -

        buff game mac download free
        -buff game mac download overwolf
        -buff game mac download link
        -buff game mac download app
        -buff game mac download apk
        -buff game mac download full version
        -buff game mac download cracked
        -buff game mac download offline
        -buff game mac download installer
        -buff game mac download setup
        -buff game mac download rewards
        -buff game mac download review
        -buff game mac download guide
        -buff game mac download tutorial
        -buff game mac download support
        -buff game mac download problems
        -buff game mac download issues
        -buff game mac download error
        -buff game mac download update
        -buff game mac download patch
        -buff game mac download latest version
        -buff game mac download beta
        -buff game mac download release date
        -buff game mac download system requirements
        -buff game mac download features
        -buff game mac download gameplay
        -buff game mac download trailer
        -buff game mac download tips
        -buff game mac download tricks
        -buff game mac download hacks
        -buff game mac download cheats
        -buff game mac download codes
        -buff game mac download coupons
        -buff game mac download deals
        -buff game mac download discounts
        -buff game mac download offers
        -buff game mac download promotions
        -buff game mac download testimonials
        -buff game mac download ratings
        -buff game mac download feedbacks
        -buff game mac download opinions
        -buff game mac download questions
        -buff game mac download answers
        -buff game mac download faqs
        -buff game mac download forums
        -buff game mac download blogs
        -buff game mac download videos
        -buff game mac download images
        -buff game mac download screenshots

        -

        How to Capture and Share Your Gaming Highlights with Buff TV

        -

        Another cool feature of Buff Game is that you can capture and share your gaming highlights with Buff TV. Buff TV is a feature that automatically records your best moments in your games and lets you edit and share them with your friends or on social media platforms. Here is how to use it:

        -

        Enable the highlight capture feature in the settings of Buff Game

        -

        To use Buff TV, you need to enable the highlight capture feature in the settings of Buff Game. To do so, click on the "Settings" tab on the main dashboard of Buff Game. Then, click on the "Highlights" tab and toggle the switch that says "Enable highlight capture". You can also customize your highlight settings, such as the quality, duration, hotkey, storage location, etc.

        -

        Play your games as usual and let Buff Game record your best moments

        -

        Once you have enabled the highlight capture feature, you can play your games as usual and let Buff Game record your best moments. Buff Game will automatically detect when you perform well in your games, such as when you get a kill, a win, an achievement, etc., and record a short clip of that moment. You can also manually trigger a highlight capture by pressing the hotkey that you have set in the settings.

        -

        Review your highlights and edit them if you want

        -

        After playing your games, you can review your highlights and edit them if you want. To do so, click on the "Highlights" tab on the main dashboard of Buff Game. You will then see a list of all your highlights sorted by date and game. You can click on any highlight to watch it or edit it. You can also delete any highlight that you don't like.

        -

        Share your highlights with your friends or on social media platforms

        -

        The final step is to share your highlights with your friends or on social media platforms. To do so, click on the "Share" button next to any highlight that you want to share. You will then see a pop-up window that lets you choose where you want to share it. You can share it on Buff TV, which is a platform where you can watch other gamers' highlights and interact with them. You can also share it on Facebook, Twitter, YouTube, Twitch, Discord, or any other platform that you prefer.

        -

        Conclusion

        -

        In conclusion, Buff Game is an amazing app that lets you earn rewards for playing games on your Mac. It supports over 1500 games and has a user-friendly interface. It is safe, secure, and compliant with game publishers' terms. It also has some other cool features, such as Buff TV, which lets you capture and share your gaming highlights.

        -

        If you want to download Buff Game on Mac and start earning buffs for playing games, all you need to do is to follow the steps that we have explained in this article. It's very easy and fast. You will be amazed by how much fun and rewarding gaming can be with Buff Game.

        -

        FAQs

        -

        Here are some frequently asked questions about Buff Game and their answers:

        -

        Q: How many buffs can I earn per game?

        -

        A: The number of buffs that you can earn per game depends on various factors, such as the game, the mode, the difficulty, the duration, the performance, the achievements, etc. There is no fixed rate or limit for earning buffs. The more you play and the better you play, the more buffs you earn.

        -

        Q: How can I check my buffs balance and history?

        -

        A: You can check your buffs balance and history from the main dashboard of Buff Game. You will see your current buffs balance on the top right corner of the screen. You will also see a graph that shows your buffs earnings over time. You can click on the graph to see more details, such as the date, time, game, and amount of buffs earned.

        -

        Q: What kind of items can I redeem with my buffs?

        -

        A: You can redeem your buffs for a variety of items at the marketplace. You can choose from different categories, such as gaming, lifestyle, entertainment, etc. Some examples of items that you can redeem are gift cards, gaming gear, Steam keys, and many more. You can browse through the available items and see their prices and availability on the marketplace.

        -

        Q: How long does it take for my item to be shipped and delivered?

        -

        A: The shipping and delivery time of your item depends on the item and your location. It may take a few days or weeks for your item to be shipped and delivered. You can track your order status from the "Orders" tab on the main dashboard of Buff Game. You will also receive an email confirmation and a tracking number for your order.

        -

        Q: How can I contact Buff Game if I have any questions or issues?

        -

        A: If you have any questions or issues regarding Buff Game, you can contact them through their website or their social media channels. You can also check out their FAQ section or their blog for more information and tips. They have a friendly and helpful customer support team that will assist you with any queries or problems.

        197e85843d
        -
        -
        \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download GTA Romania 5 and Explore the Stunning City of Bucharest.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download GTA Romania 5 and Explore the Stunning City of Bucharest.md deleted file mode 100644 index 6e7fe7b6d01cc62549eea9bc325e44f899619cd7..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Download GTA Romania 5 and Explore the Stunning City of Bucharest.md +++ /dev/null @@ -1,110 +0,0 @@ -
        -

        Download GTA Romania 5: How to Play the Latest Version of the Popular Game

        -

        If you are a fan of the Grand Theft Auto series, you might be interested in downloading GTA Romania 5, the latest mod that transforms the original game into a Romanian-themed adventure. In this article, we will show you how to download and play GTA Romania 5, as well as some of the features and benefits of this mod.

        -

        Introduction

        -

        What is GTA Romania 5?

        -

        GTA Romania 5 is a mod for Grand Theft Auto V, the fifth installment of the popular action-adventure game developed by Rockstar Games. A mod is a modification that changes some aspects of the original game, such as graphics, gameplay, characters, vehicles, or locations. GTA Romania 5 is a mod that replaces the fictional city of Los Santos with a realistic representation of Romania, a country in Eastern Europe. The mod also adds new elements that reflect the Romanian culture, such as music, language, landmarks, clothing, and more.

        -

        download gta romania 5


        Download Filehttps://ssurll.com/2uNUCB



        -

        Why should you download GTA Romania 5?

        -

        There are many reasons why you should download GTA Romania 5 if you are looking for a new and exciting gaming experience. Here are some of them:

        -
          -
        • You can explore a different and diverse environment that offers many opportunities for fun and adventure.
        • -
        • You can enjoy a rich and immersive story that follows the lives of three protagonists who have different backgrounds and motivations.
        • -
        • You can experience a realistic and dynamic gameplay that adapts to your choices and actions.
        • -
        • You can access a variety of content and features that enhance your gaming experience, such as new weapons, vehicles, missions, activities, and more.
        • -
        • You can play with other players online and join a vibrant and active community of GTA fans.
        • -
        -

        How to download GTA Romania 5

        -

        Step 1: Check the system requirements

        -

        Before you download GTA Romania 5, you need to make sure that your computer meets the minimum system requirements for running the game. These are:

        - - - - - - - -
        Operating SystemWindows 10 (64-bit)
        ProcessorIntel Core i5-4460 or AMD FX-8350
        Memory8 GB RAM
        GraphicsNVIDIA GeForce GTX 660 or AMD Radeon HD 7870
        Storage100 GB available space
        Internet ConnectionBroadband (for online mode)
        -

        If your computer meets these requirements, you can proceed to the next step. If not, you might need to upgrade your hardware or lower your graphics settings.

        -

        Step 2: Choose a reliable source

        -

        The next step is to choose a reliable source from where you can download GTA Romania 5. There are many websites that offer this mod, but not all of them are safe and trustworthy. Some of them might contain viruses, malware, or other harmful software that can damage your computer or compromise your personal information. To avoid these risks, you should only download GTA Romania 5 from reputable sources that have positive reviews and ratings from other users. One of these sources is [GTA ROMANIA](^1^), which is the official website of the mod developers. Here you can find the latest version of the mod, as well as updates, news, support, and more.Step 3: Follow the installation instructions -

        The final step is to follow the installation instructions that are provided by the source that you chose. These instructions might vary depending on the source, but they usually involve the following steps:

        -
          -
        1. Download the GTA Romania 5 mod file from the source. The file size is about 10 GB, so it might take some time depending on your internet speed.
        2. -
        3. Extract the GTA Romania 5 mod file using a program like WinRAR or 7-Zip. You will get a folder named GTA Romania 5.
        4. -
        5. Copy the GTA Romania 5 folder and paste it into the Grand Theft Auto V folder on your computer. This is usually located in C:\Program Files\Rockstar Games\Grand Theft Auto V.
        6. -
        7. Run the GTA Romania 5 Launcher.exe file from the GTA Romania 5 folder. This will launch the game with the mod applied.
        8. -
        -

        Congratulations! You have successfully downloaded and installed GTA Romania 5. You can now enjoy playing the game with the Romanian theme and features.

        -

        How to play GTA Romania 5

        -

        Explore the open world of Romania

        -

        One of the main attractions of GTA Romania 5 is the open world of Romania that you can explore freely. The mod recreates the country with stunning details and accuracy, using real-life maps, satellite images, and street views. You can visit famous landmarks such as the Palace of Parliament, the Bran Castle, or the Transfagarasan Highway. You can also discover hidden gems and secrets that are scattered around the map. The mod also adds new weather effects, wildlife, vegetation, and ambient sounds that make the world more alive and realistic.

        -

        Complete missions and challenges

        -

        Another aspect of GTA Romania 5 is the missions and challenges that you can complete to advance the story and earn rewards. The mod follows the same storyline as GTA V, but with some changes and additions that reflect the Romanian context. You can play as one of the three protagonists: Michael, a retired bank robber who lives a luxurious life in Bucharest; Franklin, a young street hustler who works for a Romanian crime boss; or Trevor, a psychopathic drug dealer who operates in a rural area near Moldova. Each character has their own personality, skills, and goals, and you can switch between them at any time. The mod also adds new side missions and activities that are related to the Romanian culture, such as smuggling cigarettes, racing on dirt roads, or playing manele music.

        Customize your character and vehicles

        -

        GTA Romania 5 also allows you to customize your character and vehicles to suit your preferences and style. You can change your character's appearance, clothing, accessories, tattoos, and more. You can also modify your vehicles with different parts, colors, decals, and more. The mod adds new items and options that are inspired by the Romanian culture, such as traditional costumes, flags, or stickers. You can also buy and sell properties, weapons, and other items in the game.

        -

        download gta romania 5 for pc
        -download gta romania 5 for ps4
        -download gta romania 5 for ps5
        -download gta romania 5 for steam
        -download gta romania 5 mod
        -download gta romania 5 online
        -download gta romania 5 free
        -download gta romania 5 full version
        -download gta romania 5 apk
        -download gta romania 5 android
        -download gta romania 5 ios
        -download gta romania 5 torrent
        -download gta romania 5 crack
        -download gta romania 5 update
        -download gta romania 5 gameplay
        -download gta romania 5 walkthrough
        -download gta romania 5 cheats
        -download gta romania 5 trainer
        -download gta romania 5 patch
        -download gta romania 5 mods pack
        -download gta romania 5 youtube
        -download gta romania 5 video
        -download gta romania 5 review
        -download gta romania 5 tips
        -download gta romania 5 guide
        -download gta romania 5 system requirements
        -download gta romania 5 graphics settings
        -download gta romania 5 best cars
        -download gta romania 5 missions
        -download gta romania 5 characters
        -download gta romania 5 map
        -download gta romania 5 locations
        -download gta romania 5 weapons
        -download gta romania 5 outfits
        -download gta romania 5 skins
        -download gta romania 5 radio stations
        -download gta romania 5 soundtrack
        -download gta romania 5 codes
        -download gta romania 5 secrets
        -download gta romania 5 easter eggs
        -download gta romania 5 glitches
        -download gta romania 5 bugs
        -download gta romania 5 fixes
        -download gta romania 5 multiplayer
        -download gta romania 5 co-op mode
        -download gta romania 5 heists mode

        -

        Interact with other players online

        -

        If you want to play with other players online, you can join the GTA Online mode, which is also compatible with GTA Romania 5. GTA Online is a multiplayer mode that lets you create your own character and join a shared world with up to 30 other players. You can cooperate or compete with other players in various missions, races, deathmatches, heists, and more. You can also join or create crews, which are groups of players that share a common interest or goal. GTA Online also has its own economy, ranking system, and events that add more fun and challenge to the game.

        -

        Conclusion

        -

        Summary of the main points

        -

        In conclusion, GTA Romania 5 is a mod that transforms GTA V into a Romanian-themed game that offers a new and exciting gaming experience. You can download GTA Romania 5 from a reliable source and follow the installation instructions to play the game. You can explore the open world of Romania, complete missions and challenges, customize your character and vehicles, and interact with other players online. GTA Romania 5 is a mod that you should try if you are looking for a different and diverse environment that offers many opportunities for fun and adventure.

        -

        Call to action

        -

        If you are interested in downloading GTA Romania 5, you can visit the official website of the mod developers at [GTA ROMANIA] and follow the steps that we have explained in this article. You can also find more information, updates, news, support, and feedback from the mod developers and the community on the website. Don't miss this chance to play GTA Romania 5 and enjoy the Romanian culture and features in the game.

        -

        FAQs

        -

        What is GTA Romania 5?

        -

        GTA Romania 5 is a mod for GTA V that replaces the fictional city of Los Santos with a realistic representation of Romania.

        -

        How do I download GTA Romania 5?

        -

        You need to choose a reliable source from where you can download GTA Romania 5, such as the official website of the mod developers. Then you need to follow the installation instructions that are provided by the source.

        -

        How do I play GTA Romania 5?

        -

        You can play GTA Romania 5 by launching the game with the mod applied. You can explore the open world of Romania, complete missions and challenges, customize your character and vehicles, and interact with other players online.

        -

        Is GTA Romania 5 safe to download?

        -

        GTA Romania 5 is safe to download if you choose a reputable source that has positive reviews and ratings from other users. You should also scan the mod file with an antivirus program before installing it.

        -

        Is GTA Romania 5 free to download?

        -

        GTA Romania 5 is free to download from the official website of the mod developers. However, you need to have a copy of GTA V on your computer to play the mod.

        197e85843d
        -
        -
        \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Dragons Rise of Berk - The Ultimate Viking and Dragon Adventure for iOS Devices.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Dragons Rise of Berk - The Ultimate Viking and Dragon Adventure for iOS Devices.md deleted file mode 100644 index 7107673aea672d64e622ecacb9b9ede97d9b3f40..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Dragons Rise of Berk - The Ultimate Viking and Dragon Adventure for iOS Devices.md +++ /dev/null @@ -1,135 +0,0 @@ - -

        How to Download and Play Dragons: Rise of Berk on Mac

        -

        Do you love dragons? Do you want to build your own Viking village and train your favorite DreamWorks dragons? If you answered yes, then you should try Dragons: Rise of Berk, a simulation game based on the popular How to Train Your Dragon franchise. In this game, you can join Hiccup, Toothless and other characters from the movies and TV shows as you rescue, hatch and train over 600 different dragon species. You can also explore uncharted lands, discover new islands, complete missions, protect your village and fight against enemies with your dragons' powers and abilities. Sounds exciting, right?

        -

        But what if you don't have an Android or iOS device to play the game? Don't worry, you can still enjoy Dragons: Rise of Berk on your Mac computer. In this article, we will show you how to download and play Dragons: Rise of Berk on Mac using two different methods. We will also give you some tips and tricks on how to play the game better and have more fun. Let's get started!

        -

        dragons rise of berk download mac


        DOWNLOADhttps://ssurll.com/2uNYO5



        -

        How to Download Dragons: Rise of Berk on Mac

        -

        There are two ways to download and play Dragons: Rise of Berk on Mac: using the Mac App Store or using an Android emulator. Here are the steps for each option:

        -

        Option 1: Use the Mac App Store

        -

        The Mac App Store is the official app store for macOS devices. It allows you to download and install apps and games that are compatible with your Mac. Here's how to use it to download Dragons: Rise of Berk on Mac:

        -
          -
        1. Open the Mac App Store and search for Dragons: Rise of Berk in the search bar.
        2. -
        3. Click on the Get button and enter your Apple ID and password if prompted.
        4. -
        5. Wait for the download to finish and launch the game from the Launchpad.
        6. -
        -

        Congratulations, you have successfully downloaded and installed Dragons: Rise of Berk on Mac using the Mac App Store. You can now enjoy the game on your Mac.

        -

        Option 2: Use an Android emulator

        -

        An Android emulator is a software that allows you to run Android apps and games on your Mac. It creates a virtual Android environment on your Mac, where you can access the Google Play Store and other Android features. There are many Android emulators available for Mac, such as BlueStacks, NoxPlayer, MEmu, etc. Here's how to use one of them to download Dragons: Rise of Berk on Mac:

        -
          -
        1. Download and install an Android emulator of your choice from its official website.
        2. -
        3. Open the emulator and sign in with your Google account.
        4. -
        5. Go to the Google Play Store and search for Dragons: Rise of Berk.
        6. -
        7. Click on the Install button and wait for the game to download.
        8. -
        9. Launch the game from the emulator's home screen.
        10. -
        -

        Congratulations, you have successfully downloaded and installed Dragons: Rise of Berk on Mac using an Android emulator. You can now enjoy the game on your Mac.

        -

        How to play dragons rise of berk on mac
        -Dragons rise of berk mac emulator
        -Dragons rise of berk app store mac
        -Dragons rise of berk game for mac
        -Dragons rise of berk free download mac
        -Dragons rise of berk bluestacks mac
        -Dragons rise of berk pc download mac
        -Dragons rise of berk online game mac
        -Dragons rise of berk cheats and hacks mac
        -Dragons rise of berk mod apk mac
        -Dragons rise of berk latest version mac
        -Dragons rise of berk tips and tricks mac
        -Dragons rise of berk best dragons mac
        -Dragons rise of berk review mac
        -Dragons rise of berk gameplay mac
        -Dragons rise of berk walkthrough mac
        -Dragons rise of berk guide mac
        -Dragons rise of berk wiki mac
        -Dragons rise of berk forum mac
        -Dragons rise of berk support mac
        -Dragons rise of berk update mac
        -Dragons rise of berk patch notes mac
        -Dragons rise of berk events mac
        -Dragons rise of berk codes mac
        -Dragons rise of berk redeem code mac
        -Dragons rise of berk legendary dragons mac
        -Dragons rise of berk toothless mac
        -Dragons rise of berk stormfly mac
        -Dragons rise of berk hookfang mac
        -Dragons rise of berk skullcrusher mac
        -Dragons rise of berk deadly nadder mac
        -Dragons rise of berk monstrous nightmare mac
        -Dragons rise of berk typhoomerang mac
        -Dragons rise of berk hiccup and astrid mac
        -Dragons rise of berk how to train your dragon mac
        -Dragons rise of berk dreamworks animation mac
        -Dragons rise of berk jam city inc. mac
        -Dragons rise of berk simulation game mac
        -Dragons rise of berk viking world mac
        -Dragons rise of berk island building game mac
        -Dragons rise of berk dragon collection game mac
        -Dragons rise of berk dragon training game mac
        -Dragons rise of berk dragon breeding game mac
        -Dragons rise of berk dragon battle game mac
        -Dragons rise of berk brawl mode mac
        -Dragons rise of berk gauntlet mode mac
        -Dragons rise of berk champions mode mac
        -Dragons rise of berk membership benefits mac
        -Dragons rise of berk in-app purchases mac

        -

        How to Play Dragons: Rise of Berk on Mac

        -

        Now that you have downloaded and installed Dragons: Rise of Berk on Mac, you might be wondering how to play it. Don't worry, we have got you covered. Here are some basic gameplay features and tips that will help you get started:

        -

        Build your own Berk and train your dragons

        -

        The main goal of Dragons: Rise of Berk is to build your own Viking village and train your dragons. You can rescue, hatch and train over 600 different dragon species, each with their own unique abilities and personalities. You can also explore uncharted lands and discover new islands with your dragons. Here are some tips on how to do that:

        -
          -
        • To rescue a dragon, you need to send Toothless or another dragon on a search mission. You can choose from different locations, such as forests, mountains, caves, etc. Each location has a different chance of finding a dragon egg or a collection item.
        • -
        • To hatch a dragon egg, you need to place it in a hatchery. You can have up to four hatcheries in your village, each with a different capacity and speed. You can also upgrade your hatcheries to increase their efficiency.
        • -
        • To train a dragon, you need to feed it fish or wood. Feeding a dragon increases its level, which unlocks new abilities and stats. You can also upgrade your dragons by spending runes, which are the premium currency of the game.
        • -
        • To explore new lands, you need to send Valka or another dragon on an exploration mission. You can choose from different regions, such as Mystery, Glacier, Wildwood, etc. Each region has a different number of islands to discover and unlock.
        • -
        • To unlock new islands, you need to meet certain requirements, such as having a specific number of dragons or buildings in your village. Unlocking new islands gives you more space to expand your village and access new resources.
        • -
        -

        Protect your village and fight against enemies

        -

        Besides building your village and training your dragons, you also need to protect your village and fight against enemies. You can use your dragons' powers and abilities in battles, such as fireballs, ice blasts, lightning strikes, etc. You can also go head to head with rival riders in Brawl or Gauntlet modes, where you can test your skills and strategy. Here are some tips on how to do that:

        -
          -
        • To protect your village, you need to build and upgrade defensive structures, such as catapults, ballistas, towers, etc. These structures will help you fend off attacks from wild dragons or other enemies.
        • -
        • To fight against enemies, you need to select a team of dragons and tap on the enemy icon. You can choose from different types of enemies, such as outcasts, hunters, trappers, etc. Each enemy has a different difficulty level and reward.
        • -
        • To use your dragons' powers and abilities in battles, you need to fill up their energy bars by tapping on them. Each dragon has a different energy bar and power. You can also switch between your dragons during the battle by swiping left or right.
        • -
        • To go head to head with rival riders in Brawl or Gauntlet modes, you need to select a team of dragons and tap on the mode icon. You can choose from different leagues and tiers, each with a different entry fee and reward. You can also view your rank and stats in the leaderboard.
        • -
        • To participate in Berkian Feasts or help around the village for rewards, you need to tap on the event icon or the villager icon. You can choose from different tasks and challenges, such as collecting resources, training dragons, winning battles, etc. Each task and challenge has a different duration and reward.
        • -
        -

        Conclusion

        -

        Dragons: Rise of Berk is a fun and exciting game that lets you experience the world of How to Train Your Dragon on your Mac. You can build your own Berk and train your dragons, protect your village and fight against enemies, and explore new lands and discover new islands. You can also enjoy stunning visual and audio effects with 3D animations on a larger screen, use your keyboard and mouse for better control and accuracy, and save your progress across different devices with iCloud or Google Play Games.

        -

        If you are a fan of dragons and How to Train Your Dragon, you should definitely download and play Dragons: Rise of Berk on Mac. It is free to play but offers some game items for purchase with real money. You can download it from the Mac App Store or use an Android emulator to run it on your Mac. Either way, you will have a blast with this game.

        -

        So what are you waiting for? Download Dragons: Rise of Berk on Mac today and join the adventure!

        -

        FAQs

        -

        Here are some frequently asked questions about Dragons: Rise of Berk on Mac:

        -
          -
        1. Is Dragons: Rise of Berk free to play?
        2. -

          Yes, Dragons: Rise of Berk is free to play but offers some game items for purchase with real money.

          -
        3. Is Dragons: Rise of Berk compatible with macOS?
        4. -

          Yes, Dragons: Rise of Berk is compatible with macOS version 10.6.6 or later.

          -
        5. What are the benefits of playing Dragons: Rise of Berk on Mac?
        6. -

          Some of the benefits of playing Dragons: Rise of Berk on Mac are:

          -
            -
          • You can enjoy stunning visual and audio effects with 3D animations on a larger screen.
          • -
          • You can use your keyboard and mouse for better control and accuracy.
          • -
          • You can save your progress across different devices with iCloud or Google Play Games.
          • -
          -
        7. What are some tips and tricks for playing Dragons: Rise of Berk on Mac?
        8. -

          Some tips and tricks for playing Dragons: Rise of Berk on Mac are:

          -
            -
          • Collect fish and wood regularly to feed your dragons and upgrade your buildings.
          • -
          • Hatch eggs in batches to save time and resources.
          • -
          • Join a clan or create your own to chat with other players and exchange gifts.
          • -
          • Check the daily quests, achievements and collections for extra rewards.
          • -
          • Follow the official Facebook page for news, updates and events.
          • -
          -
        9. Where can I find more information about Dragons: Rise of Berk on Mac?
        10. -

          You can find more information about Dragons: Rise of Berk on Mac on the following websites:

          -
            -
          • The official website of Jam City, the developer of the game. [text]
          • -
          • The official wiki of Dragons, where you can find more information about Dragons: Rise of Berk on Mac on the following websites:

            -
              -
            • The official website of Jam City, the developer of the game. [Jam City](^1^)
            • -
            • The official wiki of Dragons, where you can find guides, tips, trivia and more. [Dragons Wiki](^5^)
            • -
            • The official subreddit of Dragons, where you can join discussions, share screenshots, videos and fan art. [Dragons Subreddit](^8^)
            • -
            -

            I hope you enjoyed this article and learned something new about Dragons: Rise of Berk on Mac. If you have any questions or feedback, please leave a comment below. I would love to hear from you.

            -

            Thank you for reading and happy gaming!

            401be4b1e0
            -
            -
            \ No newline at end of file diff --git a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Enjoy Hours of Fun with Dominoes Free - The Tile Game that Never Gets Old.md b/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Enjoy Hours of Fun with Dominoes Free - The Tile Game that Never Gets Old.md deleted file mode 100644 index 85ff0f6a2851e592c4cd92c304e393c9bcaae0ce..0000000000000000000000000000000000000000 --- a/spaces/simple0urra/skops-model-card-creator-2a23515a-d54e-4804-b365-27ed6e938735/example/Enjoy Hours of Fun with Dominoes Free - The Tile Game that Never Gets Old.md +++ /dev/null @@ -1,172 +0,0 @@ - -

            Dominoes: A Classic Tile Game for Everyone

            -

            Dominoes is one of the most popular and widely played board games in the world. It is a simple, yet challenging game that can be enjoyed by people of all ages and skill levels. But did you know that playing dominoes can also have numerous benefits for your brain and health? And did you know that you can download a free dominoes game on your mobile device and play it anytime, anywhere? In this article, we will tell you everything you need to know about dominoes, including how to play it, how to download it, and how to have fun with it!

            -

            What is Dominoes and Why is it Popular?

            -

            Dominoes is a game played with rectangular tiles, also called pieces, bones, or cards. Each tile has two squares on its face, each marked with a number of dots or pips, or blank. The tiles are usually made of wood, plastic, or metal, and come in different sizes and colors.

            -

            download dominoes free


            Download Zip ✫✫✫ https://ssurll.com/2uNZTI



            -

            The most common type of domino set is the double-six set, which has 28 tiles, featuring all combinations of numbers from zero to six. Larger sets, such as double-nine or double-twelve, have more tiles and allow for more players and more complex games.

            -

            The objective of most domino games is to place tiles on the table in a line or a pattern, matching the numbers on adjacent sides. The first player to use up all their tiles wins the game. Some games also involve scoring points based on the values of the tiles or the shape of the layout.

            -

            Dominoes is popular because it is easy to learn, yet offers a lot of variety and challenge. There are dozens of different types of domino games, each with its own rules and strategies. Some games are simple and relaxing, while others are fast-paced and competitive. Some games are based on luck, while others require skill and logic. Some games are played individually, while others are played in teams or partnerships.

            -

            Dominoes is also popular because it is a social game that can bring people together. It can be played by anyone, regardless of age, gender, or background. It can be played at home, at school, at work, or at parties. It can be played casually or seriously, for fun or for money. It can be played with friends or family, or with strangers online.

            -

            What are the Benefits of Playing Dominoes?

            -

            Playing dominoes can have many benefits for your brain and health. Here are some of them:

            -
              -
            • Improves cognitive function: Playing dominoes can help improve your memory, concentration, problem-solving skills, logic, arithmetic, spatial awareness, and creativity. It can also help prevent cognitive decline and dementia by keeping your brain active and stimulated.
            • -
            • Increases social interaction: Playing dominoes can help you make new friends or strengthen existing relationships.

              How to Play Dominoes

              -

              Dominoes is a game that can be played in many different ways, depending on the type of domino set, the number of players, and the rules of the game. However, there are some basic rules and equipment that are common to most domino games. Here is how to play dominoes:

              -

              download dominoes free app
              -download dominoes free game for pc
              -download dominoes free online
              -download dominoes free offline
              -download dominoes free apk
              -download dominoes free for android
              -download dominoes free for windows 10
              -download dominoes free for iphone
              -download dominoes free classic tile game
              -download dominoes free by loop games
              -download dominoes free by mobilityware
              -download dominoes free microsoft store
              -download dominoes free google play
              -download dominoes free no ads
              -download dominoes free with friends
              -download dominoes free multiplayer
              -download dominoes free mod apk
              -download dominoes free latest version
              -download dominoes free board game
              -download dominoes free casual game
              -download dominoes free draw mode
              -download dominoes free all fives mode
              -download dominoes free for mac
              -download dominoes free for laptop
              -download dominoes free for chromebook
              -download dominoes free for tablet
              -download dominoes free for tv
              -download dominoes free for hololens
              -download dominoes free for kindle fire
              -download dominoes free for ios
              -download dominoes free 3d graphics
              -download dominoes free realistic physics
              -download dominoes free easy to play
              -download dominoes free fun and relaxing
              -download dominoes free with leaderboards
              -download dominoes free with achievements
              -download dominoes free with statistics
              -download dominoes free with hints
              -download dominoes free with sound effects
              -download dominoes free with music
              -download dominoes free with different themes
              -download dominoes free with custom rules
              -download dominoes free with different levels of difficulty
              -download dominoes free with smart AI opponents
              -download dominoes free with tutorial
              -download dominos pizza app for android

              -

              What are the Basic Rules and Equipment of Dominoes?

              -

              The basic equipment of dominoes is a set of rectangular tiles, each with two squares marked with a number of dots or blank. The most common set is the double-six set, which has 28 tiles, featuring all combinations of numbers from zero to six. Larger sets, such as double-nine or double-twelve, have more tiles and allow for more players and more complex games.

              -

              The basic rules of dominoes are as follows:

              -
                -
              • The tiles are shuffled and each player draws a certain number of tiles, depending on the type of game. The remaining tiles are left face down on the table, forming the boneyard.
              • -
              • The first player places a tile on the table, starting the line of play. The line of play is the chain of tiles that are placed on the table during the game.
              • -
              • The next player and all subsequent players must place a tile that matches one of the open ends of the line of play. A tile matches an end if it has the same number of dots as that end. For example, a 3-4 tile can match an end with 3 or 4 dots.
              • -
              • If a player cannot place a tile, they must draw from the boneyard until they can place a tile or until the boneyard is empty. If the boneyard is empty and the player still cannot place a tile, they must pass their turn.
              • -
              • The game ends when one player plays all their tiles or when no one can play a tile. The player who plays all their tiles wins the game. If no one can play a tile, the game is blocked and the player with the lowest sum of dots on their tiles wins the game.
              • -
              • Some games also involve scoring points based on the values of the tiles or the shape of the line of play. The scoring rules vary depending on the type of game.
              • -
              -

              How to Play Draw, Block, and All Fives Dominoes Games?

              -

              Draw, block, and all fives are three of the most popular types of domino games. They have similar rules but differ in some aspects. Here is how to play each of them:

              -

              Draw Dominoes

              -

              Draw dominoes is a simple and relaxing game that can be played by two to four players using a double-six set. The rules are as follows:

              -
                -
              • Each player draws seven tiles at the start of the game. The first player places any tile on the table, starting the line of play.
              • -
              • The next player and all subsequent players must place a matching tile at one of the open ends of the line of play. If they cannot place a tile, they must draw from the boneyard until they can place a tile or until the boneyard is empty.
              • -
              • The game ends when one player plays all their tiles or when no one can play a tile. The player who plays all their tiles wins the game and scores the sum of dots on their opponents' tiles. If no one can play a tile, the game is blocked and the player with the lowest sum of dots on their tiles wins the game and scores the sum of dots on their opponents' tiles minus their own sum.
              • -
              -

              Block Dominoes

              -

              Block dominoes is a similar game to draw dominoes but more challenging and competitive. It can be played by two to four players using a double-six set. The rules are as follows:

              -
                -
              • Each player draws seven tiles at the start of the game. The first player places any tile on the table, starting the line of play.
              • -
              • The next player and all subsequent players must place a matching tile at one of the open ends of the line of play. If they cannot place a tile, they must pass their turn. They cannot draw from the boneyard.
              • -
              • The game ends when one player plays all their tiles or when no one can play a tile. The player who plays all their tiles wins the game and scores the sum of dots on their opponents' tiles. If no one can play a tile, the game is blocked and the player with the lowest sum of dots on their tiles wins the game and scores the sum of dots on their opponents' tiles minus their own sum.
              • -
              -

              All Fives Dominoes

              -

              All fives dominoes is a more complex and strategic game that can be played by two to four players using a double-six set. The rules are as follows:

              -
                -
              • Each player draws five tiles at the start of the game. The first player places any tile on the table, starting the line of play.
              • -
              • The next player and all subsequent players must place a matching tile at one of the open ends of the line of play. If they cannot place a tile, they must draw from the boneyard until they can place a tile or until the boneyard is empty.
              • -
              • After each tile is placed, the player scores points if the sum of dots on both open ends of the line of play is a multiple of five. For example, if the open ends are 2-3 and 4-1, the sum is 10 and the player scores 10 points. The player also scores points if they play a double tile at one of the open ends and the sum of dots on both sides of that end is a multiple of five. For example, if the open end is 2-3 and the player plays a 5-5 tile, the sum is 15 and the player scores 15 points.
              • -
              • The game ends when one player plays all their tiles or when no one can play a tile. The player who plays all their tiles wins the game and scores an additional 5 points for each tile left in their opponents' hands. If no one can play a tile, the game is blocked and the player with the lowest sum of dots on their tiles wins the game and scores an additional 5 points for each tile left in their opponents' hands minus their own sum.
              • -
              -

              How to Play Other Variations of Dominoes Games?

              -

              There are many other variations of dominoes games that have different rules, objectives, and scoring methods. Some examples are:

              -
                -
              • Bergen: A game played with a double-six set by two to four players. The objective is to score points by placing tiles that match in number or suit (the side with more dots) with any tile on the table. The first player to reach 61 points wins.
              • -
              • Mexican Train: A game played with a double-nine or larger set by two to eight players. The objective is to play all your tiles on your own train (a line of tiles starting from a central hub) or on other players' trains when they are marked as open. The player with the lowest sum of dots on their tiles at the end wins.
              • -
              • Chicken Foot: A game played with a double-nine or larger set by two to eight players. The objective is to play all your tiles on a chicken foot (a layout that has three tiles branching out from a double tile) or on other chicken feet on the table. The player with the lowest sum of dots on their tiles at the end wins.
              • -
              -

              How to Download Dominoes Free

              -

              If you want to play dominoes on your mobile device, you can download a free dominoes app from your app store. There are many dominoes apps available for Android and iOS devices, each with its own features and options. Here are some of the best dominoes apps for you to try:

              -

              What are Some of the Best Dominoes Apps for Android and iOS Devices?

              -

              Here are some of the best dominoes apps for Android and iOS devices, based on user ratings, reviews, and downloads:

              - - - - - - - -
              NameDescriptionDownload Link
              Dominoes OnlineA popular app that lets you play dominoes online with other players from around the world. You can choose from different types of domino games, such as draw, block, all fives, and more. You can also chat with other players, customize your avatar, and earn coins and rewards.Download for Android or Download for iOS
              Dominoes - Classic Domino Tile Based GameA classic app that lets you play dominoes offline with the computer or online with other players. You can choose from three difficulty levels and four game modes: draw, block, muggins, and Bergen. You can also track your statistics, achievements, and leaderboards.Download for Android or Download for iOS
              Dominoes Gold - Win Real MoneyA fun app that lets you play dominoes for real money. You can compete with other players in cash tournaments and win prizes. You can also play for free and practice your skills. You can choose from different types of domino games, such as draw, block, all fives, and more.Download for Android or Download for iOS
              Dominoes Jogatina: Classic Board GameA colorful app that lets you play dominoes offline with the computer or online with your friends or other players. You can choose from four game modes: draw, block, all fives, and turbo. You can also customize your tiles, table, and background.Download for Android or Download for iOS
              Dominoes Pro | Play Offline or Online With FriendsA professional app that lets you play dominoes offline with the computer or online with your friends or other players. You can choose from three game modes: draw, block, and points. You can also adjust the game speed, sound effects, and rules.Download for Android or Download for iOS
              -

              How to Download and Install Dominoes Apps on Your Device?

              -

              Downloading and installing dominoes apps on your device is easy and fast. Here are the steps to follow:

              -
                -
              1. Go to your app store (Google Play Store for Android devices or App Store for iOS devices) and search for the dominoes app you want to download.
              2. -
              3. Select the app from the list of results and tap on the install button.
              4. -
              5. Wait for the app to download and install on your device.
              6. -
              7. Open the app and follow the instructions to create an account, sign in, or play as a guest.
              8. -
              9. Enjoy playing dominoes on your device!
              10. -
              -

              How to Play Online or Offline Dominoes Games with Your Friends or Other Players?

              -

              Playing online or offline dominoes games with your friends or other players is fun and easy. Here are some tips to follow:

              -
                -
              • To play online dominoes games with your friends or other players, you need to have an internet connection and a dominoes app that supports online multiplayer mode. You can either join an existing game room or create your own game room and invite your friends or other players to join. You can also chat with other players, send emojis, and share your scores.
              • -
              • To play offline dominoes games with your friends or other players, you need to have a dominoes app that supports offline multiplayer mode. You can either play on the same device by passing it around or play on different devices by connecting them via Bluetooth or Wi-Fi. You can also adjust the game settings, such as the number of players, the type of game, and the difficulty level.
              • -
              • To play dominoes games with the computer, you need to have a dominoes app that supports offline single-player mode. You can choose from different difficulty levels and game modes. You can also track your progress, statistics, and achievements.
              • -
              -

              Conclusion

              -

              Dominoes is a classic tile game that can be played in many different ways and has many benefits for your brain and health. It is easy to learn, yet offers a lot of variety and challenge. It is also a social game that can bring people together.

              -

              In this article, we have shown you how to play dominoes, how to download a free dominoes game on your mobile device, and how to have fun with it. We hope you have learned something new and useful from this article and that you will give dominoes a try. Dominoes is a game that can provide you with hours of entertainment and enjoyment, as well as improve your cognitive function and social interaction.

              -

              Here are some tips and resources for playing dominoes:

              -
                -
              • Practice makes perfect: The more you play dominoes, the more you will improve your skills and strategies. You can practice by playing against the computer or online with other players of different skill levels.
              • -
              • Learn from the experts: You can learn a lot from watching and studying how the experts play dominoes. You can watch videos, read articles, or join forums and communities of dominoes enthusiasts.
              • -
              • Have fun and be respectful: Dominoes is a game that can be enjoyed by anyone, regardless of age, gender, or background. It is also a game that can foster friendship and camaraderie. Therefore, always have fun and be respectful when playing dominoes with others. Follow the rules, be fair, be polite, and be gracious.
              • -
              -

              FAQs

              -

              Here are some frequently asked questions about dominoes:

              -

              What is the Origin and History of Dominoes?

              -

              The origin and history of dominoes is not clear, but it is believed that dominoes originated in China around the 12th century. The earliest known domino tiles were made of ivory or bone and had markings representing the 21 results of throwing two six-sided dice. The Chinese domino tiles also had symbols for military ranks, civil officials, and celestial bodies.

              -

              The game of dominoes spread to Europe in the 18th century, probably through Italian missionaries or merchants who visited China. The European domino tiles were made of wood or stone and had markings representing the numbers from zero to six. The European domino tiles also had different colors and shapes for different suits.

              -

              The game of dominoes evolved over time and became popular in different countries and regions, such as France, Italy, Spain, Germany, England, Mexico, Cuba, Brazil, and the Caribbean. Each country and region developed its own variations and rules of domino games.

              -

              How Many Tiles are in a Standard Domino Set?

              -

              The most common type of domino set is the double-six set, which has 28 tiles, featuring all combinations of numbers from zero to six. Larger sets, such as double-nine (55 tiles), double-twelve (91 tiles), double-fifteen (136 tiles), or double-eighteen (190 tiles), have more tiles and allow for more players and more complex games.

              -

              How do You Score Points in Domino Games?

              -

              The scoring method in domino games depends on the type of game. Some games do not involve scoring points at all, but only winning or losing based on who plays all their tiles first or who has the lowest sum of dots on their tiles at the end. Some games involve scoring points based on the values of the tiles played or left in the players' hands. Some games involve scoring points based on the sum of dots on both open ends of the line of play being a multiple of five or three. Some games involve scoring points based on the shape or pattern of the line of play.

              -

              What are Some Strategies and Tips for Winning Domino Games?

              -

              The strategies and tips for winning domino games vary depending on the type of game, but some general ones are:

              -
                -
              • Know your tiles: Keep track of the tiles you have in your hand and the tiles that have been played on the table. This will help you plan your moves and anticipate your opponents' moves.
              • -
              • Know your opponents: Observe your opponents' behavior and style of play. This will help you guess what tiles they have in their hand and what moves they are likely to make.
              • -
              • Know your options: Always consider all your possible moves before making one. This will help you choose the best move that will give you an advantage or prevent your opponents from gaining an advantage.
              • -
              • Know when to play or pass: Sometimes it is better to play a tile than to pass your turn, even if you do not have a matching tile. This will help you get rid of your tiles faster or score points. Sometimes it is better to pass your turn than to play a tile, even if you have a matching tile. This will help you save your tiles for later or avoid giving points to your opponents.
              • Know when to bluff or trap: Sometimes it is better to play a tile that does not match your strategy or that gives your opponents a false impression of your hand. This will help you bluff or trap your opponents into making a mistake or giving you an opportunity.
              • -
              -

              What are Some Fun and Creative Ways to Use Dominoes Besides Playing Games?

              -

              Dominoes are not only for playing games, but also for having fun and being creative. Here are some fun and creative ways to use dominoes besides playing games:

              -
                -
              • Make domino art: You can use domino tiles to create various shapes, patterns, designs, or images on a flat surface. You can use different colors, sizes, and orientations of the tiles to make your domino art more interesting and attractive.
              • -
              • Make domino chains: You can use domino tiles to create long chains of tiles that stand on their edges and fall over when pushed. You can make simple or complex domino chains by arranging the tiles in different ways and adding curves, turns, gaps, bridges, stairs, or other elements.
              • -
              • Make domino puzzles: You can use domino tiles to create puzzles that challenge your logic, arithmetic, or spatial skills. You can make simple or difficult domino puzzles by setting up the tiles in different configurations and asking questions or giving clues about them.
              • -
              • Make domino crafts: You can use domino tiles to create various crafts, such as jewelry, magnets, coasters, keychains, ornaments, or decorations. You can decorate the tiles with paint, stickers, glitter, beads, or other materials.
              • -
              • Make domino experiments: You can use domino tiles to conduct various experiments that demonstrate scientific principles, such as gravity, momentum, energy, friction, or sound. You can observe how the tiles behave when they are placed in different situations or conditions.
              • -
              -

              -

              This is the end of the article. I hope you have enjoyed reading it and learning about dominoes. Dominoes is a classic tile game that can be played in many different ways and has many benefits for your brain and health. It is also a social game that can bring people together. If you want to play dominoes on your mobile device, you can download a free dominoes app from your app store and play it anytime, anywhere. Have fun and be creative with dominoes!

              197e85843d
              -
              -
              \ No newline at end of file diff --git a/spaces/siya02/Konakni-TTS/ttsv/src/glow_tts/modules.py b/spaces/siya02/Konakni-TTS/ttsv/src/glow_tts/modules.py deleted file mode 100644 index a192251aaccb036780d77d6c8b538b652a5e24e2..0000000000000000000000000000000000000000 --- a/spaces/siya02/Konakni-TTS/ttsv/src/glow_tts/modules.py +++ /dev/null @@ -1,276 +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 - -import commons - - -class LayerNorm(nn.Module): - def __init__(self, channels, eps=1e-4): - 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): - n_dims = len(x.shape) - mean = torch.mean(x, 1, keepdim=True) - variance = torch.mean((x - mean) ** 2, 1, keepdim=True) - - x = (x - mean) * torch.rsqrt(variance + self.eps) - - shape = [1, -1] + [1] * (n_dims - 2) - x = x * self.gamma.view(*shape) + self.beta.view(*shape) - return x - - -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 WN(torch.nn.Module): - def __init__( - self, - in_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - p_dropout=0, - ): - super(WN, self).__init__() - assert kernel_size % 2 == 1 - assert hidden_channels % 2 == 0 - self.in_channels = in_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.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=None, 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) - x_in = self.drop(x_in) - 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) - - res_skip_acts = self.res_skip_layers[i](acts) - if i < self.n_layers - 1: - x = (x + res_skip_acts[:, : self.hidden_channels, :]) * 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 ActNorm(nn.Module): - def __init__(self, channels, ddi=False, **kwargs): - super().__init__() - self.channels = channels - self.initialized = not ddi - - self.logs = nn.Parameter(torch.zeros(1, channels, 1)) - self.bias = nn.Parameter(torch.zeros(1, channels, 1)) - - def forward(self, x, x_mask=None, reverse=False, **kwargs): - if x_mask is None: - x_mask = torch.ones(x.size(0), 1, x.size(2)).to( - device=x.device, dtype=x.dtype - ) - x_len = torch.sum(x_mask, [1, 2]) - if not self.initialized: - self.initialize(x, x_mask) - self.initialized = True - - if reverse: - z = (x - self.bias) * torch.exp(-self.logs) * x_mask - logdet = None - else: - z = (self.bias + torch.exp(self.logs) * x) * x_mask - logdet = torch.sum(self.logs) * x_len # [b] - - return z, logdet - - def store_inverse(self): - pass - - def set_ddi(self, ddi): - self.initialized = not ddi - - def initialize(self, x, x_mask): - with torch.no_grad(): - denom = torch.sum(x_mask, [0, 2]) - m = torch.sum(x * x_mask, [0, 2]) / denom - m_sq = torch.sum(x * x * x_mask, [0, 2]) / denom - v = m_sq - (m ** 2) - logs = 0.5 * torch.log(torch.clamp_min(v, 1e-6)) - - bias_init = ( - (-m * torch.exp(-logs)).view(*self.bias.shape).to(dtype=self.bias.dtype) - ) - logs_init = (-logs).view(*self.logs.shape).to(dtype=self.logs.dtype) - - self.bias.data.copy_(bias_init) - self.logs.data.copy_(logs_init) - - -class InvConvNear(nn.Module): - def __init__(self, channels, n_split=4, no_jacobian=False, **kwargs): - super().__init__() - assert n_split % 2 == 0 - self.channels = channels - self.n_split = n_split - self.no_jacobian = no_jacobian - - w_init = torch.qr(torch.FloatTensor(self.n_split, self.n_split).normal_())[0] - if torch.det(w_init) < 0: - w_init[:, 0] = -1 * w_init[:, 0] - self.weight = nn.Parameter(w_init) - - def forward(self, x, x_mask=None, reverse=False, **kwargs): - b, c, t = x.size() - assert c % self.n_split == 0 - if x_mask is None: - x_mask = 1 - x_len = torch.ones((b,), dtype=x.dtype, device=x.device) * t - else: - x_len = torch.sum(x_mask, [1, 2]) - - x = x.view(b, 2, c // self.n_split, self.n_split // 2, t) - x = ( - x.permute(0, 1, 3, 2, 4) - .contiguous() - .view(b, self.n_split, c // self.n_split, t) - ) - - if reverse: - if hasattr(self, "weight_inv"): - weight = self.weight_inv - else: - weight = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype) - logdet = None - else: - weight = self.weight - if self.no_jacobian: - logdet = 0 - else: - logdet = torch.logdet(self.weight) * (c / self.n_split) * x_len # [b] - - weight = weight.view(self.n_split, self.n_split, 1, 1) - z = F.conv2d(x, weight) - - z = z.view(b, 2, self.n_split // 2, c // self.n_split, t) - z = z.permute(0, 1, 3, 2, 4).contiguous().view(b, c, t) * x_mask - return z, logdet - - def store_inverse(self): - self.weight_inv = torch.inverse(self.weight.float()).to(dtype=self.weight.dtype) diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py b/spaces/sriramelango/Social_Classification_Public/fairseq/examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py deleted file mode 100644 index 0e7fbba888c1ddd118da8238d644b4ab571177ff..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py +++ /dev/null @@ -1,475 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from dataclasses import dataclass, field - -import itertools -import logging -import os - -import numpy as np -import torch - -from fairseq import metrics -from fairseq.data import ( - ConcatDataset, - ConcatSentencesDataset, - data_utils, - Dictionary, - IdDataset, - indexed_dataset, - NestedDictionaryDataset, - NumSamplesDataset, - NumelDataset, - PrependTokenDataset, - RawLabelDataset, - RightPadDataset, - SortDataset, - TruncateDataset, - TokenBlockDataset, -) -from fairseq.dataclass import ChoiceEnum, FairseqDataclass -from fairseq.tasks import FairseqTask, register_task -from omegaconf import II, MISSING - - -EVAL_BLEU_ORDER = 4 -TARGET_METRIC_CHOICES = ChoiceEnum(["bleu", "ter"]) - -logger = logging.getLogger(__name__) - - -@dataclass -class DiscriminativeRerankingNMTConfig(FairseqDataclass): - data: str = field(default=MISSING, metadata={"help": "path to data directory"}) - num_data_splits: int = field( - default=1, metadata={"help": "total number of data splits"} - ) - no_shuffle: bool = field( - default=False, metadata={"help": "do not shuffle training data"} - ) - max_positions: int = field( - default=512, metadata={"help": "number of positional embeddings to learn"} - ) - include_src: bool = field( - default=False, metadata={"help": "include source sentence"} - ) - mt_beam: int = field(default=50, metadata={"help": "beam size of input hypotheses"}) - eval_target_metric: bool = field( - default=False, - metadata={"help": "evaluation with the target metric during validation"}, - ) - target_metric: TARGET_METRIC_CHOICES = field( - default="bleu", metadata={"help": "name of the target metric to optimize for"} - ) - train_subset: str = field( - default=II("dataset.train_subset"), - metadata={"help": "data subset to use for training (e.g. train, valid, test)"}, - ) - seed: int = field( - default=II("common.seed"), - metadata={"help": "pseudo random number generator seed"}, - ) - - -class RerankerScorer(object): - """Scores the target for a given (source (optional), target) input.""" - - def __init__(self, args, mt_beam): - self.mt_beam = mt_beam - - @torch.no_grad() - def generate(self, models, sample, **kwargs): - """Score a batch of translations.""" - net_input = sample["net_input"] - - assert len(models) == 1, "does not support model ensemble" - model = models[0] - - bs = net_input["src_tokens"].shape[0] - assert ( - model.joint_classification == "none" or bs % self.mt_beam == 0 - ), f"invalid batch size ({bs}) for joint classification with beam size ({self.mt_beam})" - - model.eval() - logits = model(**net_input) - - batch_out = model.sentence_forward(logits, net_input["src_tokens"]) - if model.joint_classification == "sent": - batch_out = model.joint_forward( - batch_out.view(self.mt_beam, bs // self.mt_beam, -1) - ) - scores = model.classification_forward( - batch_out.view(bs, 1, -1) - ) # input: B x T x C - - return scores - - -@register_task( - "discriminative_reranking_nmt", dataclass=DiscriminativeRerankingNMTConfig -) -class DiscriminativeRerankingNMTTask(FairseqTask): - """ - Translation rerank task. - The input can be either (src, tgt) sentence pairs or tgt sentence only. - """ - - cfg: DiscriminativeRerankingNMTConfig - - def __init__(self, cfg: DiscriminativeRerankingNMTConfig, data_dictionary=None): - super().__init__(cfg) - self.dictionary = data_dictionary - self._max_positions = cfg.max_positions - # args.tokens_per_sample = self._max_positions - # self.num_classes = 1 # for model - - @classmethod - def load_dictionary(cls, cfg, filename): - """Load the dictionary from the filename""" - dictionary = Dictionary.load(filename) - dictionary.add_symbol("") # for loading pretrained XLMR model - - return dictionary - - @classmethod - def setup_task(cls, cfg: DiscriminativeRerankingNMTConfig, **kwargs): - # load data dictionary (assume joint dictionary) - data_path = cfg.data - data_dict = cls.load_dictionary( - cfg, os.path.join(data_path, "input_src/dict.txt") - ) - - logger.info("[input] src dictionary: {} types".format(len(data_dict))) - - return DiscriminativeRerankingNMTTask(cfg, data_dict) - - def load_dataset(self, split, epoch=0, combine=False, **kwargs): - """Load a given dataset split (e.g., train, valid, test).""" - if self.cfg.data.endswith("1"): - data_shard = (epoch - 1) % self.cfg.num_data_splits + 1 - data_path = self.cfg.data[:-1] + str(data_shard) - else: - data_path = self.cfg.data - - def get_path(type, data_split): - return os.path.join(data_path, str(type), data_split) - - def make_dataset(type, dictionary, data_split, combine): - split_path = get_path(type, data_split) - - dataset = data_utils.load_indexed_dataset( - split_path, dictionary, combine=combine, - ) - return dataset - - def load_split(data_split, metric): - input_src = None - if self.cfg.include_src: - input_src = make_dataset( - "input_src", self.dictionary, data_split, combine=False - ) - assert input_src is not None, "could not find dataset: {}".format( - get_path("input_src", data_split) - ) - - input_tgt = make_dataset( - "input_tgt", self.dictionary, data_split, combine=False - ) - assert input_tgt is not None, "could not find dataset: {}".format( - get_path("input_tgt", data_split) - ) - - label_path = f"{get_path(metric, data_split)}.{metric}" - assert os.path.exists(label_path), f"could not find dataset: {label_path}" - - np_labels = np.loadtxt(label_path) - if self.cfg.target_metric == "ter": - np_labels = -np_labels - label = RawLabelDataset(np_labels) - - return input_src, input_tgt, label - - src_datasets = [] - tgt_datasets = [] - label_datasets = [] - - if split == self.cfg.train_subset: - for k in itertools.count(): - split_k = "train" + (str(k) if k > 0 else "") - prefix = os.path.join(data_path, "input_tgt", split_k) - if not indexed_dataset.dataset_exists(prefix, impl=None): - if k > 0: - break - else: - raise FileNotFoundError(f"Dataset not found: {prefix}") - input_src, input_tgt, label = load_split( - split_k, self.cfg.target_metric - ) - src_datasets.append(input_src) - tgt_datasets.append(input_tgt) - label_datasets.append(label) - else: - input_src, input_tgt, label = load_split(split, self.cfg.target_metric) - src_datasets.append(input_src) - tgt_datasets.append(input_tgt) - label_datasets.append(label) - - if len(tgt_datasets) == 1: - input_tgt, label = tgt_datasets[0], label_datasets[0] - if self.cfg.include_src: - input_src = src_datasets[0] - else: - input_tgt = ConcatDataset(tgt_datasets) - label = ConcatDataset(label_datasets) - if self.cfg.include_src: - input_src = ConcatDataset(src_datasets) - - input_tgt = TruncateDataset(input_tgt, self.cfg.max_positions) - if self.cfg.include_src: - input_src = PrependTokenDataset(input_src, self.dictionary.bos()) - input_src = TruncateDataset(input_src, self.cfg.max_positions) - src_lengths = NumelDataset(input_src, reduce=False) - src_tokens = ConcatSentencesDataset(input_src, input_tgt) - else: - src_tokens = PrependTokenDataset(input_tgt, self.dictionary.bos()) - src_lengths = NumelDataset(src_tokens, reduce=False) - - dataset = { - "id": IdDataset(), - "net_input": { - "src_tokens": RightPadDataset( - src_tokens, pad_idx=self.source_dictionary.pad(), - ), - "src_lengths": src_lengths, - }, - "nsentences": NumSamplesDataset(), - "ntokens": NumelDataset(src_tokens, reduce=True), - "target": label, - } - - dataset = NestedDictionaryDataset(dataset, sizes=[src_tokens.sizes],) - - assert len(dataset) % self.cfg.mt_beam == 0, ( - "dataset size (%d) is not a multiple of beam size (%d)" - % (len(dataset), self.cfg.mt_beam) - ) - - # no need to shuffle valid/test sets - if not self.cfg.no_shuffle and split == self.cfg.train_subset: - - # need to keep all hypothese together - start_idx = np.arange(0, len(dataset), self.cfg.mt_beam) - with data_utils.numpy_seed(self.cfg.seed + epoch): - np.random.shuffle(start_idx) - - idx = np.arange(0, self.cfg.mt_beam) - shuffle = np.tile(idx, (len(start_idx), 1)).reshape(-1) + np.tile( - start_idx, (self.cfg.mt_beam, 1) - ).transpose().reshape(-1) - - dataset = SortDataset(dataset, sort_order=[shuffle],) - - logger.info(f"Loaded {split} with #samples: {len(dataset)}") - - self.datasets[split] = dataset - return self.datasets[split] - - def build_dataset_for_inference(self, src_tokens, src_lengths, **kwargs): - assert not self.cfg.include_src or len(src_tokens[0]) == 2 - input_src = None - if self.cfg.include_src: - input_src = TokenBlockDataset( - [t[0] for t in src_tokens], - [l[0] for l in src_lengths], - block_size=None, # ignored for "eos" break mode - pad=self.source_dictionary.pad(), - eos=self.source_dictionary.eos(), - break_mode="eos", - ) - input_src = PrependTokenDataset(input_src, self.dictionary.bos()) - input_src = TruncateDataset(input_src, self.cfg.max_positions) - - input_tgt = TokenBlockDataset( - [t[-1] for t in src_tokens], - [l[-1] for l in src_lengths], - block_size=None, # ignored for "eos" break mode - pad=self.source_dictionary.pad(), - eos=self.source_dictionary.eos(), - break_mode="eos", - ) - input_tgt = TruncateDataset(input_tgt, self.cfg.max_positions) - if self.cfg.include_src: - src_tokens = ConcatSentencesDataset(input_src, input_tgt) - src_lengths = NumelDataset(input_src, reduce=False) - else: - input_tgt = PrependTokenDataset(input_tgt, self.dictionary.bos()) - src_tokens = input_tgt - src_lengths = NumelDataset(src_tokens, reduce=False) - - dataset = { - "id": IdDataset(), - "net_input": { - "src_tokens": RightPadDataset( - src_tokens, pad_idx=self.source_dictionary.pad(), - ), - "src_lengths": src_lengths, - }, - "nsentences": NumSamplesDataset(), - "ntokens": NumelDataset(src_tokens, reduce=True), - } - - return NestedDictionaryDataset(dataset, sizes=[src_tokens.sizes],) - - def build_model(self, cfg: FairseqDataclass): - return super().build_model(cfg) - - def build_generator(self, args): - return RerankerScorer(args, mt_beam=self.cfg.mt_beam) - - def max_positions(self): - return self._max_positions - - @property - def source_dictionary(self): - return self.dictionary - - @property - def target_dictionary(self): - return self.dictionary - - def create_dummy_batch(self, device): - dummy_target = ( - torch.zeros(self.cfg.mt_beam, EVAL_BLEU_ORDER * 2 + 3).long().to(device) - if not self.cfg.eval_ter - else torch.zeros(self.cfg.mt_beam, 3).long().to(device) - ) - - return { - "id": torch.zeros(self.cfg.mt_beam, 1).long().to(device), - "net_input": { - "src_tokens": torch.zeros(self.cfg.mt_beam, 4).long().to(device), - "src_lengths": torch.ones(self.cfg.mt_beam, 1).long().to(device), - }, - "nsentences": 0, - "ntokens": 0, - "target": dummy_target, - } - - def train_step( - self, sample, model, criterion, optimizer, update_num, ignore_grad=False - ): - if ignore_grad and sample is None: - sample = self.create_dummy_batch(model.device) - - return super().train_step( - sample, model, criterion, optimizer, update_num, ignore_grad - ) - - def valid_step(self, sample, model, criterion): - if sample is None: - sample = self.create_dummy_batch(model.device) - - loss, sample_size, logging_output = super().valid_step(sample, model, criterion) - - if not self.cfg.eval_target_metric: - return loss, sample_size, logging_output - - scores = logging_output["scores"] - - if self.cfg.target_metric == "bleu": - assert sample["target"].shape[1] == EVAL_BLEU_ORDER * 2 + 3, ( - "target does not contain enough information (" - + str(sample["target"].shape[1]) - + "for evaluating BLEU" - ) - - max_id = torch.argmax(scores, dim=1) - select_id = max_id + torch.arange( - 0, sample_size * self.cfg.mt_beam, self.cfg.mt_beam - ).to(max_id.device) - bleu_data = sample["target"][select_id, 1:].sum(0).data - - logging_output["_bleu_sys_len"] = bleu_data[0] - logging_output["_bleu_ref_len"] = bleu_data[1] - - for i in range(EVAL_BLEU_ORDER): - logging_output["_bleu_counts_" + str(i)] = bleu_data[2 + i] - logging_output["_bleu_totals_" + str(i)] = bleu_data[ - 2 + EVAL_BLEU_ORDER + i - ] - - elif self.cfg.target_metric == "ter": - assert sample["target"].shape[1] == 3, ( - "target does not contain enough information (" - + str(sample["target"].shape[1]) - + "for evaluating TER" - ) - - max_id = torch.argmax(scores, dim=1) - select_id = max_id + torch.arange( - 0, sample_size * self.cfg.mt_beam, self.cfg.mt_beam - ).to(max_id.device) - ter_data = sample["target"][select_id, 1:].sum(0).data - - logging_output["_ter_num_edits"] = -ter_data[0] - logging_output["_ter_ref_len"] = -ter_data[1] - - return loss, sample_size, logging_output - - def reduce_metrics(self, logging_outputs, criterion): - super().reduce_metrics(logging_outputs, criterion) - - if not self.cfg.eval_target_metric: - return - - def sum_logs(key): - return sum(log.get(key, 0) for log in logging_outputs) - - if self.cfg.target_metric == "bleu": - counts, totals = [], [] - for i in range(EVAL_BLEU_ORDER): - counts.append(sum_logs("_bleu_counts_" + str(i))) - totals.append(sum_logs("_bleu_totals_" + str(i))) - - if max(totals) > 0: - # log counts as numpy arrays -- log_scalar will sum them correctly - metrics.log_scalar("_bleu_counts", np.array(counts)) - metrics.log_scalar("_bleu_totals", np.array(totals)) - metrics.log_scalar("_bleu_sys_len", sum_logs("_bleu_sys_len")) - metrics.log_scalar("_bleu_ref_len", sum_logs("_bleu_ref_len")) - - def compute_bleu(meters): - import inspect - import sacrebleu - - fn_sig = inspect.getfullargspec(sacrebleu.compute_bleu)[0] - if "smooth_method" in fn_sig: - smooth = {"smooth_method": "exp"} - else: - smooth = {"smooth": "exp"} - bleu = sacrebleu.compute_bleu( - correct=meters["_bleu_counts"].sum, - total=meters["_bleu_totals"].sum, - sys_len=meters["_bleu_sys_len"].sum, - ref_len=meters["_bleu_ref_len"].sum, - **smooth, - ) - return round(bleu.score, 2) - - metrics.log_derived("bleu", compute_bleu) - elif self.cfg.target_metric == "ter": - num_edits = sum_logs("_ter_num_edits") - ref_len = sum_logs("_ter_ref_len") - - if ref_len > 0: - metrics.log_scalar("_ter_num_edits", num_edits) - metrics.log_scalar("_ter_ref_len", ref_len) - - def compute_ter(meters): - score = meters["_ter_num_edits"].sum / meters["_ter_ref_len"].sum - return round(score.item(), 2) - - metrics.log_derived("ter", compute_ter) diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/models/roberta/model_xlmr.py b/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/models/roberta/model_xlmr.py deleted file mode 100644 index cf6e354d53b918dd4c7c78bfcd38ac0d63cab3bd..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/models/roberta/model_xlmr.py +++ /dev/null @@ -1,46 +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. -""" -Unsupervised Cross-lingual Representation Learning at Scale -""" - -from fairseq.models import register_model - -from .hub_interface import RobertaHubInterface -from .model import RobertaModel - - -@register_model("xlmr") -class XLMRModel(RobertaModel): - @classmethod - def hub_models(cls): - return { - "xlmr.base": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr.base.tar.gz", - "xlmr.large": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr.large.tar.gz", - "xlmr.xl": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr/xlmr.xl.tar.gz", - "xlmr.xxl": "http://dl.fbaipublicfiles.com/fairseq/models/xlmr/xlmr.xxl.tar.gz", - } - - @classmethod - def from_pretrained( - cls, - model_name_or_path, - checkpoint_file="model.pt", - data_name_or_path=".", - bpe="sentencepiece", - **kwargs - ): - from fairseq import hub_utils - - x = hub_utils.from_pretrained( - model_name_or_path, - checkpoint_file, - data_name_or_path, - archive_map=cls.hub_models(), - bpe=bpe, - load_checkpoint_heads=True, - **kwargs, - ) - return RobertaHubInterface(x["args"], x["task"], x["models"][0]) diff --git a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/models/transformer/transformer_decoder.py b/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/models/transformer/transformer_decoder.py deleted file mode 100644 index 49e37917ccca2e847917ad25ed15cc6df716ccd8..0000000000000000000000000000000000000000 --- a/spaces/sriramelango/Social_Classification_Public/fairseq/fairseq/models/transformer/transformer_decoder.py +++ /dev/null @@ -1,482 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import math -from typing import Any, Dict, List, Optional - -import torch -import torch.nn as nn -from fairseq import utils -from fairseq.distributed import fsdp_wrap -from fairseq.models import FairseqIncrementalDecoder -from fairseq.models.transformer import TransformerConfig -from fairseq.modules import ( - AdaptiveSoftmax, - BaseLayer, - FairseqDropout, - LayerDropModuleList, - LayerNorm, - PositionalEmbedding, - SinusoidalPositionalEmbedding, -) -from fairseq.modules import transformer_layer -from fairseq.modules.checkpoint_activations import checkpoint_wrapper -from fairseq.modules.quant_noise import quant_noise as apply_quant_noise_ -from torch import Tensor - - -# rewrite name for backward compatibility in `make_generation_fast_` -def module_name_fordropout(module_name: str) -> str: - if module_name == 'TransformerDecoderBase': - return 'TransformerDecoder' - else: - return module_name - - -class TransformerDecoderBase(FairseqIncrementalDecoder): - """ - Transformer decoder consisting of *cfg.decoder.layers* layers. Each layer - is a :class:`TransformerDecoderLayer`. - - Args: - args (argparse.Namespace): parsed command-line arguments - dictionary (~fairseq.data.Dictionary): decoding dictionary - embed_tokens (torch.nn.Embedding): output embedding - no_encoder_attn (bool, optional): whether to attend to encoder outputs - (default: False). - """ - - def __init__( - self, - cfg, - dictionary, - embed_tokens, - no_encoder_attn=False, - output_projection=None, - ): - self.cfg = cfg - super().__init__(dictionary) - self.register_buffer("version", torch.Tensor([3])) - self._future_mask = torch.empty(0) - - self.dropout_module = FairseqDropout( - cfg.dropout, module_name=module_name_fordropout(self.__class__.__name__) - ) - self.decoder_layerdrop = cfg.decoder.layerdrop - self.share_input_output_embed = cfg.share_decoder_input_output_embed - - input_embed_dim = embed_tokens.embedding_dim - embed_dim = cfg.decoder.embed_dim - self.embed_dim = embed_dim - self.output_embed_dim = cfg.decoder.output_dim - - self.padding_idx = embed_tokens.padding_idx - self.max_target_positions = cfg.max_target_positions - - self.embed_tokens = embed_tokens - - self.embed_scale = 1.0 if cfg.no_scale_embedding else math.sqrt(embed_dim) - - if not cfg.adaptive_input and cfg.quant_noise.pq > 0: - self.quant_noise = apply_quant_noise_( - nn.Linear(embed_dim, embed_dim, bias=False), - cfg.quant_noise.pq, - cfg.quant_noise.pq_block_size, - ) - else: - self.quant_noise = None - - self.project_in_dim = ( - Linear(input_embed_dim, embed_dim, bias=False) - if embed_dim != input_embed_dim - else None - ) - self.embed_positions = ( - PositionalEmbedding( - self.max_target_positions, - embed_dim, - self.padding_idx, - learned=cfg.decoder.learned_pos, - ) - if not cfg.no_token_positional_embeddings - else None - ) - if cfg.layernorm_embedding: - self.layernorm_embedding = LayerNorm(embed_dim, export=cfg.export) - else: - self.layernorm_embedding = None - - self.cross_self_attention = cfg.cross_self_attention - - if self.decoder_layerdrop > 0.0: - self.layers = LayerDropModuleList(p=self.decoder_layerdrop) - else: - self.layers = nn.ModuleList([]) - self.layers.extend( - [ - self.build_decoder_layer(cfg, no_encoder_attn) - for _ in range(cfg.decoder.layers) - ] - ) - self.num_layers = len(self.layers) - - if cfg.decoder.normalize_before and not cfg.no_decoder_final_norm: - self.layer_norm = LayerNorm(embed_dim, export=cfg.export) - else: - self.layer_norm = None - - self.project_out_dim = ( - Linear(embed_dim, self.output_embed_dim, bias=False) - if embed_dim != self.output_embed_dim and not cfg.tie_adaptive_weights - else None - ) - - self.adaptive_softmax = None - self.output_projection = output_projection - if self.output_projection is None: - self.build_output_projection(cfg, dictionary, embed_tokens) - - def build_output_projection(self, cfg, dictionary, embed_tokens): - if cfg.adaptive_softmax_cutoff is not None: - self.adaptive_softmax = AdaptiveSoftmax( - len(dictionary), - self.output_embed_dim, - utils.eval_str_list(cfg.adaptive_softmax_cutoff, type=int), - dropout=cfg.adaptive_softmax_dropout, - adaptive_inputs=embed_tokens if cfg.tie_adaptive_weights else None, - factor=cfg.adaptive_softmax_factor, - tie_proj=cfg.tie_adaptive_proj, - ) - elif self.share_input_output_embed: - self.output_projection = nn.Linear( - self.embed_tokens.weight.shape[1], - self.embed_tokens.weight.shape[0], - bias=False, - ) - self.output_projection.weight = self.embed_tokens.weight - else: - self.output_projection = nn.Linear( - self.output_embed_dim, len(dictionary), bias=False - ) - nn.init.normal_( - self.output_projection.weight, mean=0, std=self.output_embed_dim ** -0.5 - ) - num_base_layers = cfg.base_layers - for i in range(num_base_layers): - self.layers.insert( - ((i + 1) * cfg.decoder.layers) // (num_base_layers + 1), - BaseLayer(cfg), - ) - - def build_decoder_layer(self, cfg, no_encoder_attn=False): - layer = transformer_layer.TransformerDecoderLayerBase(cfg, no_encoder_attn) - checkpoint = cfg.checkpoint_activations - if checkpoint: - offload_to_cpu = cfg.offload_activations - layer = checkpoint_wrapper(layer, offload_to_cpu=offload_to_cpu) - # if we are checkpointing, enforce that FSDP always wraps the - # checkpointed layer, regardless of layer size - min_params_to_wrap = cfg.min_params_to_wrap if not checkpoint else 0 - layer = fsdp_wrap(layer, min_num_params=min_params_to_wrap) - return layer - - def forward( - self, - prev_output_tokens, - encoder_out: Optional[Dict[str, List[Tensor]]] = None, - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - features_only: bool = False, - full_context_alignment: bool = False, - alignment_layer: Optional[int] = None, - alignment_heads: Optional[int] = None, - src_lengths: Optional[Any] = None, - return_all_hiddens: bool = False, - ): - """ - Args: - prev_output_tokens (LongTensor): previous decoder outputs of shape - `(batch, tgt_len)`, for teacher forcing - encoder_out (optional): output from the encoder, used for - encoder-side attention, should be of size T x B x C - incremental_state (dict): dictionary used for storing state during - :ref:`Incremental decoding` - features_only (bool, optional): only return features without - applying output layer (default: False). - full_context_alignment (bool, optional): don't apply - auto-regressive mask to self-attention (default: False). - - Returns: - tuple: - - the decoder's output of shape `(batch, tgt_len, vocab)` - - a dictionary with any model-specific outputs - """ - - x, extra = self.extract_features( - prev_output_tokens, - encoder_out=encoder_out, - incremental_state=incremental_state, - full_context_alignment=full_context_alignment, - alignment_layer=alignment_layer, - alignment_heads=alignment_heads, - ) - - if not features_only: - x = self.output_layer(x) - return x, extra - - def extract_features( - self, - prev_output_tokens, - encoder_out: Optional[Dict[str, List[Tensor]]], - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - full_context_alignment: bool = False, - alignment_layer: Optional[int] = None, - alignment_heads: Optional[int] = None, - ): - return self.extract_features_scriptable( - prev_output_tokens, - encoder_out, - incremental_state, - full_context_alignment, - alignment_layer, - alignment_heads, - ) - - """ - A scriptable subclass of this class has an extract_features method and calls - super().extract_features, but super() is not supported in torchscript. A copy of - this function is made to be used in the subclass instead. - """ - - def extract_features_scriptable( - self, - prev_output_tokens, - encoder_out: Optional[Dict[str, List[Tensor]]], - incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, - full_context_alignment: bool = False, - alignment_layer: Optional[int] = None, - alignment_heads: Optional[int] = None, - ): - """ - Similar to *forward* but only return features. - - Includes several features from "Jointly Learning to Align and - Translate with Transformer Models" (Garg et al., EMNLP 2019). - - Args: - full_context_alignment (bool, optional): don't apply - auto-regressive mask to self-attention (default: False). - alignment_layer (int, optional): return mean alignment over - heads at this layer (default: last layer). - alignment_heads (int, optional): only average alignment over - this many heads (default: all heads). - - Returns: - tuple: - - the decoder's features of shape `(batch, tgt_len, embed_dim)` - - a dictionary with any model-specific outputs - """ - bs, slen = prev_output_tokens.size() - if alignment_layer is None: - alignment_layer = self.num_layers - 1 - - enc: Optional[Tensor] = None - padding_mask: Optional[Tensor] = None - if encoder_out is not None and len(encoder_out["encoder_out"]) > 0: - enc = encoder_out["encoder_out"][0] - assert ( - enc.size()[1] == bs - ), f"Expected enc.shape == (t, {bs}, c) got {enc.shape}" - if encoder_out is not None and len(encoder_out["encoder_padding_mask"]) > 0: - padding_mask = encoder_out["encoder_padding_mask"][0] - - # embed positions - positions = None - if self.embed_positions is not None: - positions = self.embed_positions( - prev_output_tokens, incremental_state=incremental_state - ) - - if incremental_state is not None: - prev_output_tokens = prev_output_tokens[:, -1:] - if positions is not None: - positions = positions[:, -1:] - - # embed tokens and positions - x = self.embed_scale * self.embed_tokens(prev_output_tokens) - - if self.quant_noise is not None: - x = self.quant_noise(x) - - if self.project_in_dim is not None: - x = self.project_in_dim(x) - - if positions is not None: - x += positions - - if self.layernorm_embedding is not None: - x = self.layernorm_embedding(x) - - x = self.dropout_module(x) - - # B x T x C -> T x B x C - x = x.transpose(0, 1) - - self_attn_padding_mask: Optional[Tensor] = None - if self.cross_self_attention or prev_output_tokens.eq(self.padding_idx).any(): - self_attn_padding_mask = prev_output_tokens.eq(self.padding_idx) - - # decoder layers - attn: Optional[Tensor] = None - inner_states: List[Optional[Tensor]] = [x] - for idx, layer in enumerate(self.layers): - if incremental_state is None and not full_context_alignment: - self_attn_mask = self.buffered_future_mask(x) - else: - self_attn_mask = None - - x, layer_attn, _ = layer( - x, - enc, - padding_mask, - incremental_state, - self_attn_mask=self_attn_mask, - self_attn_padding_mask=self_attn_padding_mask, - need_attn=bool((idx == alignment_layer)), - need_head_weights=bool((idx == alignment_layer)), - ) - inner_states.append(x) - if layer_attn is not None and idx == alignment_layer: - attn = layer_attn.float().to(x) - - if attn is not None: - if alignment_heads is not None: - attn = attn[:alignment_heads] - - # average probabilities over heads - attn = attn.mean(dim=0) - - if self.layer_norm is not None: - x = self.layer_norm(x) - - # T x B x C -> B x T x C - x = x.transpose(0, 1) - - if self.project_out_dim is not None: - x = self.project_out_dim(x) - - return x, {"attn": [attn], "inner_states": inner_states} - - def output_layer(self, features): - """Project features to the vocabulary size.""" - if self.adaptive_softmax is None: - # project back to size of vocabulary - return self.output_projection(features) - else: - return features - - def max_positions(self): - """Maximum output length supported by the decoder.""" - if self.embed_positions is None: - return self.max_target_positions - return min(self.max_target_positions, self.embed_positions.max_positions) - - def buffered_future_mask(self, tensor): - dim = tensor.size(0) - # self._future_mask.device != tensor.device is not working in TorchScript. This is a workaround. - if ( - self._future_mask.size(0) == 0 - or (not self._future_mask.device == tensor.device) - or self._future_mask.size(0) < dim - ): - self._future_mask = torch.triu( - utils.fill_with_neg_inf(torch.zeros([dim, dim])), 1 - ) - self._future_mask = self._future_mask.to(tensor) - return self._future_mask[:dim, :dim] - - def upgrade_state_dict_named(self, state_dict, name): - """Upgrade a (possibly old) state dict for new versions of fairseq.""" - if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): - weights_key = "{}.embed_positions.weights".format(name) - if weights_key in state_dict: - del state_dict[weights_key] - state_dict[ - "{}.embed_positions._float_tensor".format(name) - ] = torch.FloatTensor(1) - - if f"{name}.output_projection.weight" not in state_dict: - if self.share_input_output_embed: - embed_out_key = f"{name}.embed_tokens.weight" - else: - embed_out_key = f"{name}.embed_out" - if embed_out_key in state_dict: - state_dict[f"{name}.output_projection.weight"] = state_dict[ - embed_out_key - ] - if not self.share_input_output_embed: - del state_dict[embed_out_key] - - for i in range(self.num_layers): - # update layer norms - layer_norm_map = { - "0": "self_attn_layer_norm", - "1": "encoder_attn_layer_norm", - "2": "final_layer_norm", - } - for old, new in layer_norm_map.items(): - for m in ("weight", "bias"): - k = "{}.layers.{}.layer_norms.{}.{}".format(name, i, old, m) - if k in state_dict: - state_dict[ - "{}.layers.{}.{}.{}".format(name, i, new, m) - ] = state_dict[k] - del state_dict[k] - - version_key = "{}.version".format(name) - if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2: - # earlier checkpoints did not normalize after the stack of layers - self.layer_norm = None - self.normalize = False - state_dict[version_key] = torch.Tensor([1]) - - return state_dict - - -def Linear(in_features, out_features, bias=True): - m = nn.Linear(in_features, out_features, bias) - nn.init.xavier_uniform_(m.weight) - if bias: - nn.init.constant_(m.bias, 0.0) - return m - - -class TransformerDecoder(TransformerDecoderBase): - def __init__( - self, - args, - dictionary, - embed_tokens, - no_encoder_attn=False, - output_projection=None, - ): - self.args = args - super().__init__( - TransformerConfig.from_namespace(args), - dictionary, - embed_tokens, - no_encoder_attn=no_encoder_attn, - output_projection=output_projection, - ) - - def build_output_projection(self, args, dictionary, embed_tokens): - super().build_output_projection( - TransformerConfig.from_namespace(args), dictionary, embed_tokens - ) - - def build_decoder_layer(self, args, no_encoder_attn=False): - return super().build_decoder_layer( - TransformerConfig.from_namespace(args), no_encoder_attn=no_encoder_attn - ) diff --git a/spaces/stomexserde/gpt4-ui/Examples/Ad 2000 Merkblatt S1 Pdf Download !!TOP!!.md b/spaces/stomexserde/gpt4-ui/Examples/Ad 2000 Merkblatt S1 Pdf Download !!TOP!!.md deleted file mode 100644 index a3939dd2f40182380e3d47e30c08c9af75476570..0000000000000000000000000000000000000000 --- a/spaces/stomexserde/gpt4-ui/Examples/Ad 2000 Merkblatt S1 Pdf Download !!TOP!!.md +++ /dev/null @@ -1,33 +0,0 @@ -
              -

              How to Download AD 2000-Merkblatt S 1 PDF for Free

              - -

              If you are looking for a free PDF download of AD 2000-Merkblatt S 1, you have come to the right place. In this article, we will explain what AD 2000-Merkblatt S 1 is, why it is important, and how you can get it for free.

              - -

              What is AD 2000-Merkblatt S 1?

              - -

              AD 2000-Merkblatt S 1 is a German technical rule that provides a simplified analysis method for cyclic loading of pressure vessels and other pressure equipment. It was published by the German Pressure Vessel Association, which includes a large number of German associations and institutions specialized in boilers and pressure vessels[^3^].

              -

              Ad 2000 Merkblatt S1 Pdf Download


              Download ····· https://urlgoal.com/2uI6CS



              - -

              AD 2000-Merkblatt S 1 is based on the European standard EN 13445-3:2014, which covers the design of unfired pressure vessels. It applies to pressure vessels with a maximum allowable pressure of more than 0.5 bar and a volume of more than 2 liters. It covers both metallic and non-metallic materials, as well as welded and non-welded joints.

              - -

              Why is AD 2000-Merkblatt S 1 important?

              - -

              AD 2000-Merkblatt S 1 is important because it provides a simplified and conservative method for calculating the fatigue life of pressure vessels and other pressure equipment under cyclic loading. Cyclic loading refers to the repeated application of stress or strain on a material, which can cause damage or failure over time.

              - -

              Cyclic loading can occur due to various factors, such as temperature changes, pressure fluctuations, vibration, or dynamic loading. It can affect the structural integrity and safety of pressure vessels and other pressure equipment, especially if they are exposed to high or low temperatures, corrosive environments, or complex loading patterns.

              - -

              By using AD 2000-Merkblatt S 1, you can ensure that your pressure vessels and other pressure equipment are designed and manufactured according to the state-of-the-art technology and comply with the relevant regulations and standards. You can also avoid overdesigning or underdesigning your pressure equipment, which can result in unnecessary costs or risks.

              - -

              How to download AD 2000-Merkblatt S 1 PDF for free?

              - -

              If you want to download AD 2000-Merkblatt S 1 PDF for free, you have two options:

              - -
                -
              • You can visit the official website of the German Pressure Vessel Association at https://www.ad-2000.de/en/home.html and purchase the PDF version of AD 2000-Merkblatt S 1 for €68.00 (including VAT). You will receive an email with a link to download the PDF file after completing the payment.
              • -
              • You can use a free online PDF downloader tool that can help you download any PDF file from any website. For example, you can use https://smallpdf.com/pdf-downloader, which is a simple and reliable tool that can download any PDF file in seconds. All you need to do is enter the URL of the PDF file you want to download (in this case, https://www.beuth.de/en/technical-rule/ad-2000-merkblatt-s-1/149679990) and click on the "Download" button. You will then be able to save the PDF file on your device or cloud storage.
              • -
              - -

              We hope this article has helped you understand what AD 2000-Merkblatt S 1 is and how you can download it for free. If you have any questions or feedback, please feel free to leave a comment below.

              -

              7b8c122e87
              -
              -
              \ No newline at end of file diff --git a/spaces/sub314xxl/MetaGPT/metagpt/tools/metagpt_text_to_image.py b/spaces/sub314xxl/MetaGPT/metagpt/tools/metagpt_text_to_image.py deleted file mode 100644 index c5a0b872ff3e42036c8b240270cda75252ce2cf4..0000000000000000000000000000000000000000 --- a/spaces/sub314xxl/MetaGPT/metagpt/tools/metagpt_text_to_image.py +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -@Time : 2023/8/18 -@Author : mashenquan -@File : metagpt_text_to_image.py -@Desc : MetaGPT Text-to-Image OAS3 api, which provides text-to-image functionality. -""" -import asyncio -import base64 -import os -import sys -from pathlib import Path -from typing import List, Dict - -import aiohttp -import requests -from pydantic import BaseModel - -from metagpt.config import CONFIG, Config - -sys.path.append(str(Path(__file__).resolve().parent.parent.parent)) # fix-bug: No module named 'metagpt' -from metagpt.logs import logger - - -class MetaGPTText2Image: - def __init__(self, model_url): - """ - :param model_url: Model reset api url - """ - self.model_url = model_url if model_url else CONFIG.METAGPT_TEXT_TO_IMAGE_MODEL - - async def text_2_image(self, text, size_type="512x512"): - """Text to image - - :param text: The text used for image conversion. - :param size_type: One of ['512x512', '512x768'] - :return: The image data is returned in Base64 encoding. - """ - - headers = { - "Content-Type": "application/json" - } - dims = size_type.split("x") - data = { - "prompt": text, - "negative_prompt": "(easynegative:0.8),black, dark,Low resolution", - "override_settings": {"sd_model_checkpoint": "galaxytimemachinesGTM_photoV20"}, - "seed": -1, - "batch_size": 1, - "n_iter": 1, - "steps": 20, - "cfg_scale": 11, - "width": int(dims[0]), - "height": int(dims[1]), # 768, - "restore_faces": False, - "tiling": False, - "do_not_save_samples": False, - "do_not_save_grid": False, - "enable_hr": False, - "hr_scale": 2, - "hr_upscaler": "Latent", - "hr_second_pass_steps": 0, - "hr_resize_x": 0, - "hr_resize_y": 0, - "hr_upscale_to_x": 0, - "hr_upscale_to_y": 0, - "truncate_x": 0, - "truncate_y": 0, - "applied_old_hires_behavior_to": None, - "eta": None, - "sampler_index": "DPM++ SDE Karras", - "alwayson_scripts": {}, - } - - class ImageResult(BaseModel): - images: List - parameters: Dict - - try: - async with aiohttp.ClientSession() as session: - async with session.post(self.model_url, headers=headers, json=data) as response: - result = ImageResult(**await response.json()) - if len(result.images) == 0: - return "" - return result.images[0] - except requests.exceptions.RequestException as e: - logger.error(f"An error occurred:{e}") - return "" - - -# Export -async def oas3_metagpt_text_to_image(text, size_type: str = "512x512", model_url=""): - """Text to image - - :param text: The text used for image conversion. - :param model_url: Model reset api - :param size_type: One of ['512x512', '512x768'] - :return: The image data is returned in Base64 encoding. - """ - if not text: - return "" - if not model_url: - model_url = CONFIG.METAGPT_TEXT_TO_IMAGE_MODEL_URL - return await MetaGPTText2Image(model_url).text_2_image(text, size_type=size_type) - - -if __name__ == "__main__": - Config() - loop = asyncio.new_event_loop() - task = loop.create_task(oas3_metagpt_text_to_image("Panda emoji")) - v = loop.run_until_complete(task) - print(v) - data = base64.b64decode(v) - with open("tmp.png", mode="wb") as writer: - writer.write(data) - print(v) diff --git a/spaces/supertori/files/stable-diffusion-webui/.github/pull_request_template.md b/spaces/supertori/files/stable-diffusion-webui/.github/pull_request_template.md deleted file mode 100644 index 69056331b8f56cb7a0f8bcff3010eb2a67c141c7..0000000000000000000000000000000000000000 --- a/spaces/supertori/files/stable-diffusion-webui/.github/pull_request_template.md +++ /dev/null @@ -1,28 +0,0 @@ -# Please read the [contributing wiki page](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Contributing) before submitting a pull request! - -If you have a large change, pay special attention to this paragraph: - -> Before making changes, if you think that your feature will result in more than 100 lines changing, find me and talk to me about the feature you are proposing. It pains me to reject the hard work someone else did, but I won't add everything to the repo, and it's better if the rejection happens before you have to waste time working on the feature. - -Otherwise, after making sure you're following the rules described in wiki page, remove this section and continue on. - -**Describe what this pull request is trying to achieve.** - -A clear and concise description of what you're trying to accomplish with this, so your intent doesn't have to be extracted from your code. - -**Additional notes and description of your changes** - -More technical discussion about your changes go here, plus anything that a maintainer might have to specifically take a look at, or be wary of. - -**Environment this was tested in** - -List the environment you have developed / tested this on. As per the contributing page, changes should be able to work on Windows out of the box. - - OS: [e.g. Windows, Linux] - - Browser: [e.g. chrome, safari] - - Graphics card: [e.g. NVIDIA RTX 2080 8GB, AMD RX 6600 8GB] - -**Screenshots or videos of your changes** - -If applicable, screenshots or a video showing off your changes. If it edits an existing UI, it should ideally contain a comparison of what used to be there, before your changes were made. - -This is **required** for anything that touches the user interface. \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/The-Hunter-Em-Hack.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/The-Hunter-Em-Hack.md deleted file mode 100644 index 451b1f5c4a991d2d64ffa295cef945d7e1727015..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/The-Hunter-Em-Hack.md +++ /dev/null @@ -1,74 +0,0 @@ -## the hunter em hack - - - - - - ![The Hunter Em Hack](https://i.imgur.com/kfc1YRV.png) - - - - - -**Click Here ---> [https://urlca.com/2tyrrp](https://urlca.com/2tyrrp)** - - - - - - - - - - - - - -# How to Hack The Hunter Game with ESP and Wallhack - - - -The Hunter is a popular hunting simulation game that lets you explore vast open worlds and hunt different animals. However, some players may find it hard to track down their prey or avoid dangerous predators. That's why some players use hacks to gain an advantage in the game. - - - -One of the most common hacks for The Hunter is the ESP (Extra Sensory Perception) hack, which allows you to see the location, name, health, and distance of any animal or player on the map. This way, you can easily find your target or avoid unwanted encounters. Another hack is the wallhack, which lets you see through walls and other obstacles. This can help you spot animals hiding behind trees or rocks, or ambush other players from behind cover. - - - -There are different ways to get these hacks for The Hunter game. Some websites offer free or paid downloads of hack tools that you can inject into the game using an auto-injector. However, these tools may be detected by the game's anti-cheat system or contain viruses or malware. Therefore, you should always be careful when downloading anything from unknown sources. - - - -Another way to hack The Hunter game is to use a cheat engine, which is a software that allows you to modify the game's memory and values. You can use cheat engine to change your ems (the game's currency), your inventory, your skills, and more. However, cheat engine requires some technical knowledge and may not work with every version of the game. Also, using cheat engine may ruin the fun and challenge of the game for yourself and others. - - - -The best way to enjoy The Hunter game is to play it fair and square, without using any hacks or cheats. The game offers a realistic and immersive hunting experience that can be rewarding and satisfying on its own. You can also join a community of hunters and share your tips, stories, and screenshots with them. The Hunter game is more fun when you play it as it was meant to be played. - - - -## How to Improve Your Hunting Skills in The Hunter Game - - - -The Hunter game is not just about shooting animals. It also requires patience, stealth, strategy, and knowledge of the wildlife and the environment. If you want to become a better hunter, you need to practice and learn some tips and tricks that can help you in your hunts. - - - -One of the most important skills in The Hunter game is tracking. Tracking allows you to follow the tracks, droppings, calls, and blood trails of animals. You can use your binoculars or your hunter mate device to scan the tracks and identify the animal, its gender, its weight, and its direction. You can also use your map to see the approximate location of animals in your vicinity. Tracking can help you find your target or discover new species. - - - -Another skill that you need to master in The Hunter game is stealth. Stealth means moving quietly and staying out of sight of animals. You can use the wind direction indicator on your hunter mate device to see which way the wind is blowing. You should always try to stay downwind of animals, as they can smell you if you are upwind. You should also avoid making noise by walking slowly, crouching, or proneing. You can use the noise indicator on your hunter mate device to see how much noise you are making. You should also avoid wearing bright colors or moving in open areas. - - - -A third skill that you need to improve in The Hunter game is strategy. Strategy means choosing the right weapon, ammo, scope, and shot placement for each animal and situation. You can use the codex on your hunter mate device to see the recommended weapons and ammo for each animal class. You should also use the appropriate scope for the distance and visibility of your target. You should aim for vital organs such as the heart, lungs, liver, or spine for a quick and ethical kill. You can use the penetration indicator on your scope to see how deep your bullet will go through the animal's body. - - dfd1c89656 - - - - - diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/116 Clique 13 Letters Full Album Zip.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/116 Clique 13 Letters Full Album Zip.md deleted file mode 100644 index 92a34b87493699bda0adb62cf64c2d3f54ba770b..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/116 Clique 13 Letters Full Album Zip.md +++ /dev/null @@ -1,6 +0,0 @@ -

              116 Clique, 13 Letters full album zip


              DOWNLOADhttps://cinurl.com/2uEXyX



              - -Hip Hop/Rap Purchase here: http://itunes.apple.com/us/album/man-up/id465216090 Tracklist: 1. Man Up Anthem feat. Lecrae, KB, Trip Lee, Tedashii, Sho Baraka, ... 4d29de3e1b
              -
              -
              -

              diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/63 Nayanmargal Story In Tamil Pdf 248 WORK.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/63 Nayanmargal Story In Tamil Pdf 248 WORK.md deleted file mode 100644 index 3883ae4abb235320b802ae4832d2b80cc471749e..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/63 Nayanmargal Story In Tamil Pdf 248 WORK.md +++ /dev/null @@ -1,111 +0,0 @@ - -

              63 Nayanmargal Story In Tamil Pdf 248: A Guide to the Devotees of Shiva

              - -

              If you are interested in learning about the 63 Nayanmargal, the saint poets who were devoted to Lord Shiva in Tamil Nadu, then you might want to download the PDF file that contains their stories. This PDF file is 248 pages long and it is based on the Periya Puranam, the 12th-century Tamil epic that narrates the lives and deeds of these saints.

              - -

              In this article, we will give you a brief overview of who the 63 Nayanmargal were, why they are important in Tamil culture and religion, and how you can access their stories in Tamil PDF format.

              -

              63 Nayanmargal Story In Tamil Pdf 248


              Download Zip ››› https://cinurl.com/2uEY4z



              - -

              Who were the 63 Nayanmargal?

              - -

              The 63 Nayanmargal were a group of devotees who lived between the 6th and 8th centuries CE in various parts of Tamil Nadu. They belonged to different castes, professions, and backgrounds, but they all shared a common love and devotion for Lord Shiva, the supreme deity of Shaivism. They expressed their bhakti (devotion) through various forms of worship, such as singing hymns, composing poems, building temples, performing miracles, serving the poor and needy, and even sacrificing their lives for Shiva.

              - -

              The word Nayanmar means "leader" or "guide" in Tamil, and it is a title of honor given to these saints by their followers. The word Nayanar is also used to refer to any Shaiva devotee in general. The number 63 is considered sacred in Shaivism, as it represents the 63 manifestations of Shiva. The list of the 63 Nayanmargal was compiled by Sekkizhar, a 12th-century poet and minister who wrote the Periya Puranam as an addition to the Tirumurai, the canonical collection of Shaiva scriptures.

              - -

              Why are the 63 Nayanmargal important?

              - -

              The 63 Nayanmargal are important for several reasons. First, they represent the diversity and inclusiveness of Shaivism, as they came from different social groups and regions. They also show that anyone can attain salvation by worshipping Shiva with sincere devotion and faith. Second, they contributed to the development and enrichment of Tamil literature and culture, as they composed many beautiful poems and songs in praise of Shiva and his various forms. These poems are known as Tevarams or Tirumurais, and they are still sung and recited by Shaivas today. Third, they inspired many generations of Shaiva devotees to follow their example and dedicate their lives to Shiva. They are revered as role models and guides by millions of Shaivas across the world.

              - -

              How can you access the 63 Nayanmargal stories in Tamil PDF format?

              - -

              If you want to read the stories of the 63 Nayanmargal in Tamil PDF format, you can download the file from this link: https://ta.wikipedia.org/wiki/%E0%AE%A8%E0%AE%BE%E0%AE%AF%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AE%BE%E0%AE%B0%E0%AF %8D_%E0 % AE % AA % E0 % AE % 9F % E0 % AF % 8D % E0 % AE % 9F % E0 % AE % BF % E0 % AE % AF % E0 % AE % B2 % E0 % AF % 8D. This file contains the stories of each Nayanmar as narrated by Sekkizhar in his Periya Puranam. You will also find information about their names, castes, regions, festivals, and temples associated with them.

              - -

              The stories of the 63 Nayanmargal are full of devotion, miracles, grace, and wisdom. They will inspire you to deepen your love for Shiva and his creation. We hope that you enjoy reading them and learning from them.

              -

              What are the benefits of reading the 63 Nayanmargal stories in Tamil PDF format?

              - -

              Reading the 63 Nayanmargal stories in Tamil PDF format has many benefits for the readers. Some of them are:

              -

              - -
                -
              • It enhances the knowledge and appreciation of the rich and diverse Tamil culture and heritage, especially the Shaiva tradition.
              • -
              • It inspires the readers to cultivate devotion, faith, humility, service, and compassion in their lives, following the footsteps of the Nayanmargal.
              • -
              • It provides spiritual guidance and solace to the readers who are facing difficulties or challenges in their lives.
              • -
              • It improves the language and literary skills of the readers, as they can enjoy the beauty and eloquence of the Tamil poems and prose.
              • -
              • It offers a convenient and accessible way of reading the stories anytime and anywhere, using a digital device.
              • -
              - -

              How to download the 63 Nayanmargal stories in Tamil PDF format?

              - -

              If you want to download the 63 Nayanmargal stories in Tamil PDF format, you can follow these simple steps:

              - -
                -
              1. Click on this link: https://ta.wikipedia.org/wiki/%E0 % AE % A8 % E0 % AE % BE % E0 % AE % AF % E0 % AE % A9 % E0 % AF % 8D % E0 % AE % AE % E0 % AE % BE % E0 % AE % B0 % E0 % AF % 8D _ % E0 % AE % AA % E0 % AE % 9F % E0 % AF % 8D % E0 % AE % 9F % E0 % AE % BF % E0 % AE % AF % E0 % AE % B2 . This is a Wikipedia page that contains the list of the 63 Nayanmargal with their names, castes, regions, festivals, and temples.
              2. -
              3. Scroll down to the bottom of the page and click on "பதிவிறக்கம் செய்ய" (Download). This will open a new page with different options for downloading.
              4. -
              5. Select "PDF வடிவம்" (PDF format) and click on "பதிவிறக்கம் செய்ய" (Download) again. This will start downloading the PDF file to your device.
              6. -
              7. Open the PDF file and enjoy reading the stories of the 63 Nayanmargal in Tamil.
              8. -
              - -

              We hope that this article has given you some useful information about the 63 Nayanmargal story in Tamil PDF 248. If you have any questions or feedback, please feel free to contact us. Thank you for reading!

              -

              Who are the 63 Nayanmargal and why are they important?

              - -

              The 63 Nayanmargal are the saint-poets who composed devotional hymns in praise of Lord Shiva in Tamil language. They lived between the 6th and 9th centuries CE and belonged to various castes, regions, and occupations. They are also known as Nayanars or Nayanmars. They are revered as the foremost devotees of Shiva and exemplified the path of bhakti (love) and sharanagati (surrender) to him.

              - -

              The 63 Nayanmargal are important for several reasons. Some of them are:

              - -
                -
              • They enriched the Tamil literature and culture with their sublime and soul-stirring poems, which are collectively known as Tirumurai. The Tirumurai consists of 12 volumes, out of which the first seven volumes contain the works of the 63 Nayanmargal.
              • -
              • They revived and reformed the Shaiva tradition in Tamil Nadu, which was facing challenges from other religions and sects. They propagated the doctrine of Shaiva Siddhanta, which is based on the Vedas, Agamas, and Tirumurai.
              • -
              • They established and renovated many Shiva temples across Tamil Nadu and beyond. They also initiated and participated in various temple rituals and festivals, such as Kumbhabhishekam, Thiruvilakku Pooja, Thiruvembavai, Thiruppalliyezhuchi, etc.
              • -
              • They demonstrated the unity and harmony among the devotees of Shiva, irrespective of their caste, creed, gender, or status. They also showed respect and reverence to other religious traditions, such as Vaishnavism, Buddhism, Jainism, etc.
              • -
              • They inspired many generations of devotees to follow their footsteps and dedicate their lives to Shiva. Some of their prominent disciples and successors include Sekkizhar, Manikkavasagar, Sundarar, etc.
              • -
              - -

              Where can I find more information about the 63 Nayanmargal stories in Tamil PDF 248?

              - -

              If you want to find more information about the 63 Nayanmargal stories in Tamil PDF 248, you can visit the following websites:

              - - - -

              We hope that this article has given you some useful information about the 63 Nayanmargal story in Tamil PDF 248. If you have any questions or feedback, please feel free to contact us. Thank you for reading!

              - - ---> ServiceClient failure for DeepLeo[/ERROR] -

              How can I read the Tirumurai and Periya Puranam of the 63 Nayanmargal?

              - -

              The Tirumurai and Periya Puranam are the sacred scriptures of the Shaiva Siddhanta tradition, which contain the hymns and stories of the 63 Nayanmargal. They are considered as the Tamil Veda and are revered by millions of devotees across the world.

              - -

              If you want to read the Tirumurai and Periya Puranam of the 63 Nayanmargal, you can follow these steps:

              - -
                -
              1. First, you need to have a basic understanding of the Tamil language and script, as these texts are written in classical Tamil. You can learn Tamil online or from a teacher or a book.
              2. -
              3. Second, you need to have a copy of the Tirumurai and Periya Puranam in Tamil PDF 248 format. You can download them from various websites or buy them from online or offline stores.
              4. -
              5. Third, you need to have a commentary or a translation of these texts in your preferred language, such as English, Hindi, Telugu, etc. You can find them online or in print.
              6. -
              7. Fourth, you need to have a devotion and a curiosity to learn from these texts. You can read them daily or weekly or whenever you feel like it. You can also listen to them as audio or watch them as video.
              8. -
              9. Fifth, you need to have a guru or a guide who can help you understand the deeper meanings and messages of these texts. You can find them online or offline or within yourself.
              10. -
              - -

              By reading the Tirumurai and Periya Puranam of the 63 Nayanmargal, you will gain immense spiritual benefits and blessings from Lord Shiva and his devotees.

              - -

              What are some of the famous stories of the 63 Nayanmargal?

              - -

              The 63 Nayanmargal have many amazing and inspiring stories that showcase their love, devotion, sacrifice, and service to Lord Shiva. Some of them are:

              - -
                -
              • The story of Kannappa Nayanar, who plucked out his eyes to offer to Shiva's bleeding idol.
              • -
              • The story of Karaikkal Ammaiyar, who renounced her beauty and family to become a ghostly devotee of Shiva.
              • -
              • The story of Sundarar, who was Shiva's friend and received his grace in various forms.
              • -
              • The story of Manikkavasagar, who composed the Thiruvasagam and Thirukkovaiyar with divine inspiration.
              • -
              • The story of Nandanar, who was a low-caste devotee who faced discrimination but attained Shiva's abode.
              • -
              • The story of Thirugnana Sambandar, who was a child prodigy who sang many hymns and performed many miracles.
              • -
              • The story of Thirunavukkarasar, who was a Jain convert who returned to Shaivism after Shiva's intervention.
              • -
              • The story of Sivakami Andar, who was a woman devotee who disguised herself as a man to serve Shiva.
              • -
              • The story of Pusalar Nayanar, who built a temple for Shiva in his heart.
              • -
              • The story of Muruganar, who was a hunter devotee who offered his own flesh to Shiva's hungry devotees.
              • -
              - -

              These are just some of the examples of the stories of the 63 Nayanmargal. There are many more stories that you can read in the Periya Puranam or listen to from various sources.

              3cee63e6c2
              -
              -
              \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Analizador Quantico Bioelectrico Software 24 ((TOP)).md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Analizador Quantico Bioelectrico Software 24 ((TOP)).md deleted file mode 100644 index 4ed83b007a50387ee67e62601468c02f23f5be3b..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Analizador Quantico Bioelectrico Software 24 ((TOP)).md +++ /dev/null @@ -1,6 +0,0 @@ -

              Analizador Quantico Bioelectrico Software 24


              Download Zip 🗸 https://cinurl.com/2uEZeb



              - -Quantico Bioelectric Analyser Software 24 Download: ( Quantico Bioelectric Software Download -- f5574a87f2 QUANTICO BIO-ELECTRIC QUANTUM SYSTEM Analyser .... The starting point for ... http://www.youtube.com/watchv=0X9F9cBcq2Y 8a78ff9644
              -
              -
              -

              diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Diary Of A Wimpy Kid Old School Pdf Full Download VERIFIED.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Diary Of A Wimpy Kid Old School Pdf Full Download VERIFIED.md deleted file mode 100644 index 33dad4c2ada0f2ddf3a535c0ebec43b32bbab93b..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Diary Of A Wimpy Kid Old School Pdf Full Download VERIFIED.md +++ /dev/null @@ -1,47 +0,0 @@ - -

              Diary of a Wimpy Kid: Old School - How to Download and Read the Funny Book by Jeff Kinney

              - -

              Do you love reading funny books? Do you want to know what happens when Greg Heffley goes back to the old school? If you answered yes, then you should read Diary of a Wimpy Kid: Old School, the tenth book in the bestselling series by Jeff Kinney. In this book, you will follow Greg as he faces the challenges of living without modern technology, going on a camping trip, and dealing with his family and friends.

              - -

              But how can you read Diary of a Wimpy Kid: Old School if you don't have a copy of the book? Don't worry, we have a solution for you. You can download the PDF version of the book for free from various websites that offer free ebooks. In this article, we will show you how to download and read Diary of a Wimpy Kid: Old School PDF for free, and what you need to know before reading it.

              -

              diary of a wimpy kid old school pdf full download


              Download Filehttps://cinurl.com/2uEXyT



              - -

              How to Download Diary of a Wimpy Kid: Old School PDF for Free

              - -

              There are many websites that offer Diary of a Wimpy Kid: Old School PDF for free download, but not all of them are safe or reliable. Some of them might contain viruses, malware, or unwanted software that can harm your computer or compromise your privacy. Therefore, you should always be careful when downloading any file from the internet, and use a trusted antivirus program to scan it before opening it.

              - -

              One of the websites that we recommend for downloading Diary of a Wimpy Kid: Old School PDF for free is Internet Archive. This website has a large collection of free ebooks that you can download or read online, without any registration or subscription. All the ebooks are tested and verified to work on various devices and platforms.

              - -

              To download Diary of a Wimpy Kid: Old School PDF from Internet Archive, follow these steps:

              - -
                -
              1. Go to https://archive.org/details/OldSchool_201801 and click on the "PDF" button under "Download Options".
              2. -
              3. You will be redirected to a page where you can choose between different formats and sizes of the PDF file. We recommend choosing the "PDF with text" option, which is a file of 9.5 MB.
              4. -
              5. Click on the "Download" button and wait for the file to be downloaded to your computer.
              6. -
              7. Once the download is complete, locate the file "OldSchool_201801.pdf" on your computer and open it with your preferred PDF reader.
              8. -
              9. Enjoy reading Diary of a Wimpy Kid: Old School!
              10. -
              - -

              What You Need to Know Before Reading Diary of a Wimpy Kid: Old School

              - -

              Diary of a Wimpy Kid: Old School is an entertaining and hilarious book that will make you laugh out loud. It is written in the form of a diary, with illustrations and comics that add to the humor and charm of the story. It is suitable for readers of all ages, especially children and teens who can relate to Greg's struggles and adventures.

              - -

              However, before you start reading Diary of a Wimpy Kid: Old School, you should also be aware that it is not an official product of Jeff Kinney or his publishers anymore, and it is not supported or endorsed by them in any way. Therefore, you should download and read it at your own risk and discretion. We do not encourage or condone any illegal activity or piracy related to this book. If you like Diary of a Wimpy Kid: Old School and want to support its author, you should buy it from a legitimate source or platform.

              - -

              Conclusion

              - -

              Diary of a Wimpy Kid: Old School is a funny and relatable book that you can download and read for free on your device. It is one of the best books in the Diary of a Wimpy Kid series, and it has many fans around the world. It tells the story of Greg Heffley as he tries to survive in an old-fashioned world without modern technology.

              - -

              If you love reading funny books, you should definitely download Diary of a Wimpy Kid: Old School PDF for free today and enjoy reading it. You will not regret it. It is a book that will keep you entertained for hours, whether you read it alone or with your friends. It is a book that will make you feel like you are part of Greg's diary.

              -

              - -

              So what are you waiting for? Download Diary of a Wimpy Kid: Old School PDF for free today and enjoy reading the funny book by Jeff Kinney!

              -

              Conclusion

              - -

              Diary of a Wimpy Kid: Old School is a funny and relatable book that you can download and read for free on your device. It is one of the best books in the Diary of a Wimpy Kid series, and it has many fans around the world. It tells the story of Greg Heffley as he tries to survive in an old-fashioned world without modern technology.

              - -

              If you love reading funny books, you should definitely download Diary of a Wimpy Kid: Old School PDF for free today and enjoy reading it. You will not regret it. It is a book that will keep you entertained for hours, whether you read it alone or with your friends. It is a book that will make you feel like you are part of Greg's diary.

              - -

              So what are you waiting for? Download Diary of a Wimpy Kid: Old School PDF for free today and enjoy reading the funny book by Jeff Kinney!

              3cee63e6c2
              -
              -
              \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Download Ben10 Theme Song In Hindi.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Download Ben10 Theme Song In Hindi.md deleted file mode 100644 index c96bd5bbf169c491fdee934f1a452dac963eea97..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Download Ben10 Theme Song In Hindi.md +++ /dev/null @@ -1,6 +0,0 @@ -

              download ben10 theme song in hindi


              DOWNLOADhttps://cinurl.com/2uEYN0



              - -Ben 10! Check out the best online for Ben 10 show fans! Play free games, watch videos, answer quizzes, get free downloads and more. 1fdad05405
              -
              -
              -

              diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/EaseUS MobiMover Free 4.8 Pre Cracked With Product Key 2019.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/EaseUS MobiMover Free 4.8 Pre Cracked With Product Key 2019.md deleted file mode 100644 index c439a214b0ec45370682bbbcc2fbc97eea8db598..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/EaseUS MobiMover Free 4.8 Pre Cracked With Product Key 2019.md +++ /dev/null @@ -1,33 +0,0 @@ -
              -

              EaseUS MobiMover Free 4.8 Pre Cracked with Product Key 2019: A Review

              -

              If you are looking for a free and easy way to transfer and manage files between your iOS devices and your computer, you might want to check out EaseUS MobiMover Free 4.8. This software is a powerful and versatile iPhone manager and data transfer tool that can help you with various tasks, such as backing up your iPhone, restoring from backup, transferring data between devices, downloading videos and audios, and more.

              -

              EaseUS MobiMover Free 4.8 Pre Cracked with Product Key 2019


              Downloadhttps://cinurl.com/2uEXPI



              -

              In this article, we will review the features and benefits of EaseUS MobiMover Free 4.8, as well as show you how to get it pre cracked with a product key for free.

              -

              Features and Benefits of EaseUS MobiMover Free 4.8

              -

              EaseUS MobiMover Free 4.8 has many features and benefits that make it a great choice for iOS users who want to manage their data easily and efficiently. Here are some of them:

              -
                -
              • It supports transferring data between computer and iPhone/iPad, such as photos, videos, music, contacts, messages, notes, calendars, bookmarks, etc.
              • -
              • It allows you to manage your iPhone/iPad files easily, such as deleting, editing, adding, or exporting files.
              • -
              • It enables you to download videos and audios from over 1000 websites, such as YouTube, Vimeo, Dailymotion, Facebook, Instagram, etc.
              • -
              • It helps you back up your iPhone/iPad data to your computer or external hard drive with one click.
              • -
              • It lets you restore your iPhone/iPad from backup without erasing any existing data.
              • -
              • It supports transferring and backing up WhatsApp chat history from your iPhone/iPad to your computer.
              • -
              • It offers 24/7 technical support and free lifetime updates.
              • -
              • It works with all iOS devices running iOS 8 or later, including iPhone 12/11/XS/XR/X/8/7/6s/6/5s/5c/5/4s/4, iPad Pro/Air/mini/4/3/2/1, iPod touch 6/5/4.
              • -
              -

              How to Get EaseUS MobiMover Free 4.8 Pre Cracked with Product Key 2019

              -

              If you want to enjoy all the features and benefits of EaseUS MobiMover Free 4.8 without any limitations or costs, you can get it pre cracked with a product key for free. Here are the steps to follow:

              -
                -
              1. Download the setup file of EaseUS MobiMover Free 4.8 from the official website or a trusted source.
              2. -
              3. Install the software on your computer by following the instructions on the screen.
              4. -
              5. Download the crack file of EaseUS MobiMover Free 4.8 from a reliable source or use the link below.
              6. -
              7. Extract the crack file and copy the product key from it.
              8. -
              9. Launch the software and enter the product key when prompted.
              10. -
              11. Enjoy using EaseUS MobiMover Free 4.8 with full features and no restrictions.
              12. -
              -

              Note: The crack file and product key are only for educational purposes. We do not encourage or support any illegal activities. Please use the software at your own risk and responsibility.

              -

              -

              Conclusion

              -

              EaseUS MobiMover Free 4.8 is a useful and user-friendly software that can help you transfer and manage your iOS data with ease. It has many features and benefits that make it stand out from other similar tools. If you want to get it pre cracked with a product key for free, you can follow the steps above. However, we recommend that you purchase the software from the official website if you find it helpful and want to support the developers.

              d5da3c52bf
              -
              -
              \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Eze Bootable Usb Windows 7 Free Download !!HOT!!.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Eze Bootable Usb Windows 7 Free Download !!HOT!!.md deleted file mode 100644 index fec9033e44db5f253a13eada526a2a23e0ca4eed..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Eze Bootable Usb Windows 7 Free Download !!HOT!!.md +++ /dev/null @@ -1,6 +0,0 @@ -

              Eze Bootable Usb Windows 7 Free Download


              Download 🔗 https://cinurl.com/2uEXvL



              -
              -Installing Wine on Mac; How to Create macOS Sierra Bootable USB Installer on ... per la gestione delle finestre in Windows 7, 8 e versioni successive e Mac OS X ... View the latest source code changes Download the VirtualBox OSE about logo ... Free Flyer Software - Easy to Create Flyers, Brochures, Leaflets, Certificate in ... 1fdad05405
              -
              -
              -

              diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/The Man Who Knew Infinity (English) Telugu Dubbed Free Download In Torrent.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/The Man Who Knew Infinity (English) Telugu Dubbed Free Download In Torrent.md deleted file mode 100644 index 5fe81cefa05e4deb341e285aa8a2605a9acc6388..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/The Man Who Knew Infinity (English) Telugu Dubbed Free Download In Torrent.md +++ /dev/null @@ -1,11 +0,0 @@ - -

              -the-man-who-knew-infinity-english-dual-audio-hindi-dubbed-movie-2021 free download strucad v16 crack strucad v16 full version with crack free. the man who knew infinity (english) telugu dubbed free download in torrent.

              -

              the man who knew infinity (english) 720p free download. the man who knew infinity movie download in hd.. captain america: civil war (2016) 720p telugu dubbed movie free download links. submit wallpaper hd. ant-man (english) movies dubbed in telugu free download in hd 720p. you can download torrent the man who knew infinity (english) 720p download movies.

              -

              The Man Who Knew Infinity (English) telugu dubbed free download in torrent


              Download Zip ->->->-> https://cinurl.com/2uEXvI



              -

              the man who knew infinity movie download in hd.. captain america: civil war (2016) 720p telugu dubbed movie free download links. submit wallpaper hd. ant-man (english) movies dubbed in telugu free download in hd 720p. you can download torrent the man who knew infinity (english) 720p download movies.

              -

              info: the man who knew infinity [english], hindi dubbed, tamil, telugu, kannada, malayalam, marathi, bhojpuri, awadhi, gujarati, assamese, oriya. hindi dubbed full movie free download, the man who knew infinity. watch the man who knew infinity [english] movie online free.

              -

              the man who knew infinity movie free download in hd.. captain america: civil war (2016) 720p telugu dubbed movie free download links. submit wallpaper hd. the man who knew infinity (english) telugu dubbed free download in torrent. watch the man who knew infinity (english) online free.

              -

              the man who knew infinity (english) telugu dubbed free download in torrent. trailer. the man who knew infinity (english) telugu dubbed free download in torrent 2018 download. the man who knew infinity (english) telugu dubbed free download in torrent new photos. the man who knew infinity (english) telugu dubbed free download in torrent. the man who knew infinity (english) telugu dubbed free download in torrent director-kumar-jaya. the man who knew infinity (english) telugu dubbed free download in torrent tv-serials-new-tv-series-dubbed. the man who knew infinity (english) telugu dubbed free download in torrent, downloader, web, screen. the man who knew infinity (english) telugu dubbed free download in torrent movie, watch online. the man who knew infinity (english) telugu dubbed free download in torrent, download, download torrent. the man who knew infinity (english) telugu dubbed free download in torrent, download the man who knew infinity (english) telugu dubbed free download in torrent 2018, download. the man who knew infinity (english) telugu dubbed free download in torrent 2018.

              -

              899543212b
              -
              -
              \ No newline at end of file diff --git a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Wartune Private Server !NEW!.md b/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Wartune Private Server !NEW!.md deleted file mode 100644 index 4c5c2ce3b52df343fb0cc4887de33f8f949929ad..0000000000000000000000000000000000000000 --- a/spaces/suppsumstagza/text-to-image-stable-diffusion-v1-5/scripts/Wartune Private Server !NEW!.md +++ /dev/null @@ -1,11 +0,0 @@ -
              -

              fully working vindictus emulated private server, high rates and mid rates, exp 25x,. server download wartune private server pvp wartune private server automation tool for wartune, legend online, divosaga lineage 2 private servers top 100 welcome. wartune vindictus private server high low rates servers.

              -

              wartune private server


              Download Zip > https://cinurl.com/2uEY6m



              -

              *how to get the activation code: 1. follow our facebook fanpage. 2. tag a friend of yours in the comment section. 3. we will send the code through private. before requesting this, please read these rules..

              -

              as long as the server can be self hosted or run by third parties, that would be a plus, but the main goal is to try the. they are working on a public p.i.t.a server in the future, though. from 2:30pm to 4:30pm edt, everyone's game state will be archived and people can download it up to a certain limit.

              -

              a client and server have been made with the purpose of upping the game by our playtesters. save from february 25th, 2018, wartune server games will be archived. > from february 25th, 2018 at 11:55 am. here are some ways to join: - join an official server > how to join an official server.

              -

              *how to get the activation code: 1. follow our facebook fanpage. 2. tag a friend of yours in the comment section. 3. we will send the code through private. july 8th, 2018, 07:00 am edt, a new east coast server [s944] maczal (.

              -

              -

              after this patch, everyone who is currently on the p.i.t.a server will be moved to the regular servers for gameplay. wartune server team env1. a client and server have been made with the purpose of upping the game by our playtesters.

              899543212b
              -
              -
              \ No newline at end of file diff --git a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmseg/models/utils/self_attention_block.py b/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmseg/models/utils/self_attention_block.py deleted file mode 100644 index 440c7b73ee4706fde555595926d63a18d7574acc..0000000000000000000000000000000000000000 --- a/spaces/svjack/ControlNet-Pose-Chinese/annotator/uniformer/mmseg/models/utils/self_attention_block.py +++ /dev/null @@ -1,159 +0,0 @@ -import torch -from annotator.uniformer.mmcv.cnn import ConvModule, constant_init -from torch import nn as nn -from torch.nn import functional as F - - -class SelfAttentionBlock(nn.Module): - """General self-attention block/non-local block. - - Please refer to https://arxiv.org/abs/1706.03762 for details about key, - query and value. - - Args: - key_in_channels (int): Input channels of key feature. - query_in_channels (int): Input channels of query feature. - channels (int): Output channels of key/query transform. - out_channels (int): Output channels. - share_key_query (bool): Whether share projection weight between key - and query projection. - query_downsample (nn.Module): Query downsample module. - key_downsample (nn.Module): Key downsample module. - key_query_num_convs (int): Number of convs for key/query projection. - value_num_convs (int): Number of convs for value projection. - matmul_norm (bool): Whether normalize attention map with sqrt of - channels - with_out (bool): Whether use out projection. - conv_cfg (dict|None): Config of conv layers. - norm_cfg (dict|None): Config of norm layers. - act_cfg (dict|None): Config of activation layers. - """ - - def __init__(self, key_in_channels, query_in_channels, channels, - out_channels, share_key_query, query_downsample, - key_downsample, key_query_num_convs, value_out_num_convs, - key_query_norm, value_out_norm, matmul_norm, with_out, - conv_cfg, norm_cfg, act_cfg): - super(SelfAttentionBlock, self).__init__() - if share_key_query: - assert key_in_channels == query_in_channels - self.key_in_channels = key_in_channels - self.query_in_channels = query_in_channels - self.out_channels = out_channels - self.channels = channels - self.share_key_query = share_key_query - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.act_cfg = act_cfg - self.key_project = self.build_project( - key_in_channels, - channels, - num_convs=key_query_num_convs, - use_conv_module=key_query_norm, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - if share_key_query: - self.query_project = self.key_project - else: - self.query_project = self.build_project( - query_in_channels, - channels, - num_convs=key_query_num_convs, - use_conv_module=key_query_norm, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - self.value_project = self.build_project( - key_in_channels, - channels if with_out else out_channels, - num_convs=value_out_num_convs, - use_conv_module=value_out_norm, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - if with_out: - self.out_project = self.build_project( - channels, - out_channels, - num_convs=value_out_num_convs, - use_conv_module=value_out_norm, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - else: - self.out_project = None - - self.query_downsample = query_downsample - self.key_downsample = key_downsample - self.matmul_norm = matmul_norm - - self.init_weights() - - def init_weights(self): - """Initialize weight of later layer.""" - if self.out_project is not None: - if not isinstance(self.out_project, ConvModule): - constant_init(self.out_project, 0) - - def build_project(self, in_channels, channels, num_convs, use_conv_module, - conv_cfg, norm_cfg, act_cfg): - """Build projection layer for key/query/value/out.""" - if use_conv_module: - convs = [ - ConvModule( - in_channels, - channels, - 1, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg) - ] - for _ in range(num_convs - 1): - convs.append( - ConvModule( - channels, - channels, - 1, - conv_cfg=conv_cfg, - norm_cfg=norm_cfg, - act_cfg=act_cfg)) - else: - convs = [nn.Conv2d(in_channels, channels, 1)] - for _ in range(num_convs - 1): - convs.append(nn.Conv2d(channels, channels, 1)) - if len(convs) > 1: - convs = nn.Sequential(*convs) - else: - convs = convs[0] - return convs - - def forward(self, query_feats, key_feats): - """Forward function.""" - batch_size = query_feats.size(0) - query = self.query_project(query_feats) - if self.query_downsample is not None: - query = self.query_downsample(query) - query = query.reshape(*query.shape[:2], -1) - query = query.permute(0, 2, 1).contiguous() - - key = self.key_project(key_feats) - value = self.value_project(key_feats) - if self.key_downsample is not None: - key = self.key_downsample(key) - value = self.key_downsample(value) - key = key.reshape(*key.shape[:2], -1) - value = value.reshape(*value.shape[:2], -1) - value = value.permute(0, 2, 1).contiguous() - - sim_map = torch.matmul(query, key) - if self.matmul_norm: - sim_map = (self.channels**-.5) * sim_map - sim_map = F.softmax(sim_map, dim=-1) - - context = torch.matmul(sim_map, value) - context = context.permute(0, 2, 1).contiguous() - context = context.reshape(batch_size, -1, *query_feats.shape[2:]) - if self.out_project is not None: - context = self.out_project(context) - return context diff --git a/spaces/t110-ai-admin/InspectLens/video_llama/models/blip2_outputs.py b/spaces/t110-ai-admin/InspectLens/video_llama/models/blip2_outputs.py deleted file mode 100644 index 92d83a0556e6c5c3c0a603279f318605ae25d6d5..0000000000000000000000000000000000000000 --- a/spaces/t110-ai-admin/InspectLens/video_llama/models/blip2_outputs.py +++ /dev/null @@ -1,111 +0,0 @@ -""" -Adapted from salesforce@LAVIS. Below is the original copyright: - Copyright (c) 2022, salesforce.com, inc. - All rights reserved. - SPDX-License-Identifier: BSD-3-Clause - For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause -""" - -from dataclasses import dataclass -from typing import Optional - -import torch -from transformers.modeling_outputs import ( - ModelOutput, - BaseModelOutputWithPoolingAndCrossAttentions, - CausalLMOutputWithCrossAttentions, -) - - -@dataclass -class BlipSimilarity(ModelOutput): - sim_i2t: torch.FloatTensor = None - sim_t2i: torch.FloatTensor = None - - sim_i2t_m: Optional[torch.FloatTensor] = None - sim_t2i_m: Optional[torch.FloatTensor] = None - - sim_i2t_targets: Optional[torch.FloatTensor] = None - sim_t2i_targets: Optional[torch.FloatTensor] = None - - -@dataclass -class BlipIntermediateOutput(ModelOutput): - """ - Data class for intermediate outputs of BLIP models. - - image_embeds (torch.FloatTensor): Image embeddings, shape (batch_size, num_patches, embed_dim). - text_embeds (torch.FloatTensor): Text embeddings, shape (batch_size, seq_len, embed_dim). - - image_embeds_m (torch.FloatTensor): Image embeddings from momentum visual encoder, shape (batch_size, num_patches, embed_dim). - text_embeds_m (torch.FloatTensor): Text embeddings from momentum text encoder, shape (batch_size, seq_len, embed_dim). - - encoder_output (BaseModelOutputWithPoolingAndCrossAttentions): output from the image-grounded text encoder. - encoder_output_neg (BaseModelOutputWithPoolingAndCrossAttentions): output from the image-grounded text encoder for negative pairs. - - decoder_output (CausalLMOutputWithCrossAttentions): output from the image-grounded text decoder. - decoder_labels (torch.LongTensor): labels for the captioning loss. - - itm_logits (torch.FloatTensor): logits for the image-text matching loss, shape (batch_size * 3, 2). - itm_labels (torch.LongTensor): labels for the image-text matching loss, shape (batch_size * 3,) - - """ - - # uni-modal features - image_embeds: torch.FloatTensor = None - text_embeds: Optional[torch.FloatTensor] = None - - image_embeds_m: Optional[torch.FloatTensor] = None - text_embeds_m: Optional[torch.FloatTensor] = None - - # intermediate outputs of multimodal encoder - encoder_output: Optional[BaseModelOutputWithPoolingAndCrossAttentions] = None - encoder_output_neg: Optional[BaseModelOutputWithPoolingAndCrossAttentions] = None - - itm_logits: Optional[torch.FloatTensor] = None - itm_labels: Optional[torch.LongTensor] = None - - # intermediate outputs of multimodal decoder - decoder_output: Optional[CausalLMOutputWithCrossAttentions] = None - decoder_labels: Optional[torch.LongTensor] = None - - -@dataclass -class BlipOutput(ModelOutput): - # some finetuned models (e.g. BlipVQA) do not compute similarity, thus optional. - sims: Optional[BlipSimilarity] = None - - intermediate_output: BlipIntermediateOutput = None - - loss: Optional[torch.FloatTensor] = None - - loss_itc: Optional[torch.FloatTensor] = None - - loss_itm: Optional[torch.FloatTensor] = None - - loss_lm: Optional[torch.FloatTensor] = None - - -@dataclass -class BlipOutputFeatures(ModelOutput): - """ - Data class of features from BlipFeatureExtractor. - - Args: - image_embeds: (torch.FloatTensor) of shape (batch_size, num_patches+1, embed_dim), optional - image_features: (torch.FloatTensor) of shape (batch_size, num_patches+1, feature_dim), optional - text_embeds: (torch.FloatTensor) of shape (batch_size, sequence_length+1, embed_dim), optional - text_features: (torch.FloatTensor) of shape (batch_size, sequence_length+1, feature_dim), optional - - The first embedding or feature is for the [CLS] token. - - Features are obtained by projecting the corresponding embedding into a normalized low-dimensional space. - """ - - image_embeds: Optional[torch.FloatTensor] = None - image_embeds_proj: Optional[torch.FloatTensor] = None - - text_embeds: Optional[torch.FloatTensor] = None - text_embeds_proj: Optional[torch.FloatTensor] = None - - multimodal_embeds: Optional[torch.FloatTensor] = None diff --git a/spaces/taesiri/Docx2Latex-Farsi/README.md b/spaces/taesiri/Docx2Latex-Farsi/README.md deleted file mode 100644 index 3740f9f00e4a32129688d54fa8642a4ce3051989..0000000000000000000000000000000000000000 --- a/spaces/taesiri/Docx2Latex-Farsi/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Docx2Latex Farsi -emoji: 📊 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.39.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/terfces0erbo/CollegeProjectV2/Advanced SystemCare Pro 12.4.0.351 Serial Key !!BETTER!!.md b/spaces/terfces0erbo/CollegeProjectV2/Advanced SystemCare Pro 12.4.0.351 Serial Key !!BETTER!!.md deleted file mode 100644 index e43513241a79d26cb39b857701ffb3461da26458..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Advanced SystemCare Pro 12.4.0.351 Serial Key !!BETTER!!.md +++ /dev/null @@ -1,9 +0,0 @@ - -

              You can find various information regarding the serial key of Advanced SystemCare Professional 14. Here, we have given you the updated serial key of Advanced SystemCare Professional 14. There are many ways to activate the serial key of Advanced SystemCare Professional 14.

              -

              Two ways to activate the serial key of Advanced SystemCare Professional 14. Here, we have given you the updated serial key of Advanced SystemCare Professional 14. There are many ways to activate the serial key of Advanced SystemCare Professional 14. Once you have downloaded Advanced SystemCare Professional 14, you can follow the instructions below:

              -

              Advanced SystemCare Pro 12.4.0.351 Serial Key


              Download Ziphttps://bytlly.com/2uGlRV



              -

              Finally, the latest serial key of Advanced SystemCare Professional 14. Follow the instruction below to activate the serial key of Advanced SystemCare Professional 14. There are many ways to activate the serial key of Advanced SystemCare Professional 14. Once you have downloaded Advanced SystemCare Professional 14, you can follow the instructions below:

              -

              I need to know which button, how to start Advanced Systemcare Service. I think in my computer in start-up manager it is enter Advanced Systemcare Control Panel. It says the service has been started. I press ok but its a green arrow. In Advanced Systemcare control panel its open a red arrow says 'Not Started' I pressed ok It says the service is started... Anyone know how to stop it?

              -

              How do I install and un-install Programs in Windows XP or vista I have this program and I can't figure out how to use it. I can only use it by pressing Install/Uninstall from the start menu. I don't think it supports an uninstall. Can someone please explain to me how to uninstall or install programs using the Advanced SystemCare Control Panel?

              899543212b
              -
              -
              \ No newline at end of file diff --git a/spaces/terfces0erbo/CollegeProjectV2/Barb Wire 1996 1080p Unrated Version Torrent.md b/spaces/terfces0erbo/CollegeProjectV2/Barb Wire 1996 1080p Unrated Version Torrent.md deleted file mode 100644 index 4e7c55c06e560c6b6d6d321efeaa1dd2ae4415fd..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Barb Wire 1996 1080p Unrated Version Torrent.md +++ /dev/null @@ -1,6 +0,0 @@ -

              Barb Wire 1996 1080p Unrated Version Torrent


              Download File ►►► https://bytlly.com/2uGjXJ



              - -Barb Wire 1996 Unrated Bluray 1080p Dts Dxvalonewolf ... Barb Wire 1996 BluRay 1080p DTS dxva-LoNeWolf. posted by bobnjeff in Movies - Sci-fi. ... Barb Wire 1996 BluRay 1080p DTS dxva-LoNeWolf - Torrent Kitty - Free ... 4d29de3e1b
              -
              -
              -

              diff --git a/spaces/terfces0erbo/CollegeProjectV2/Geogrotesque Font Family Rar.md b/spaces/terfces0erbo/CollegeProjectV2/Geogrotesque Font Family Rar.md deleted file mode 100644 index fd0b9d554fb0ad732b32eddbb2ff3900e090e1d7..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Geogrotesque Font Family Rar.md +++ /dev/null @@ -1,24 +0,0 @@ -
              -

              How to Download and Install Geogrotesque Font Family Rar

              -

              Geogrotesque is a popular sans serif font family that offers a sleek and modern look for your designs. It comes in 14 styles, ranging from thin to ultra, and supports multiple languages and glyphs. Geogrotesque is a premium font that you can purchase from various online platforms, such as MyFonts, Fontspring, or Creative Market. However, if you want to try it out for free, you can download the Geogrotesque font family rar file from the link below.

              -

              A rar file is a compressed archive that contains multiple files in one. To extract the fonts from the rar file, you will need a software that can open and unzip rar files, such as WinRAR, 7-Zip, or PeaZip. Once you have downloaded and installed one of these software on your computer, follow these steps to install the Geogrotesque font family:

              -

              Geogrotesque Font Family Rar


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



              -
                -
              1. Right-click on the Geogrotesque font family rar file and select "Extract Here" or "Extract to Geogrotesque/".
              2. -
              3. A folder named Geogrotesque will appear in the same location as the rar file. Open the folder and you will see 14 files with the extension .otf. These are the font files for each style of Geogrotesque.
              4. -
              5. Select all the font files and right-click on them. Choose "Install" from the menu. This will install the fonts on your computer and make them available for use in any software that supports OpenType fonts.
              6. -
              7. If you want to uninstall the fonts later, you can go to Control Panel > Fonts and delete the Geogrotesque fonts from there.
              8. -
              -

              Congratulations! You have successfully downloaded and installed the Geogrotesque font family rar file on your computer. You can now enjoy using this elegant and versatile font for your projects. Whether you need it for logos, headlines, posters, or web design, Geogrotesque will give your work a professional and stylish touch.

              - -

              How to Use Geogrotesque Font Family in Your Designs

              -

              Now that you have installed the Geogrotesque font family on your computer, you might be wondering how to use it in your designs. Geogrotesque is a versatile font that can suit various purposes and styles. Here are some tips and examples on how to use Geogrotesque effectively:

              -
                -
              • Geogrotesque is a geometric sans serif font, which means it has simple and clean shapes that create a minimalist and elegant look. You can use Geogrotesque for modern and minimalist designs, such as logos, web design, or branding.
              • -
              • Geogrotesque has 14 styles, from thin to ultra, that offer different weights and contrasts. You can use these styles to create hierarchy and emphasis in your text. For example, you can use a thin style for subtitles or captions, and a bold or ultra style for headlines or titles.
              • -
              • Geogrotesque supports multiple languages and glyphs, which makes it suitable for international and multilingual projects. You can use Geogrotesque for websites, magazines, books, or flyers that need to communicate with a global audience.
              • -
              • Geogrotesque has a friendly and approachable feel, which makes it ideal for casual and informal designs. You can use Geogrotesque for social media posts, invitations, cards, or stickers that need to convey a fun and playful tone.
              • -
              -

              As you can see, Geogrotesque is a font family that can adapt to different needs and contexts. You can experiment with different styles, colors, and combinations to create unique and stunning designs with Geogrotesque. If you need some inspiration, you can check out some examples of Geogrotesque in action on Behance or Dribbble.

              d5da3c52bf
              -
              -
              \ No newline at end of file diff --git a/spaces/terfces0erbo/CollegeProjectV2/Huawei-Y301-Unlock-Nck-Dongle-Cracked.md b/spaces/terfces0erbo/CollegeProjectV2/Huawei-Y301-Unlock-Nck-Dongle-Cracked.md deleted file mode 100644 index 6b395b1f3828fa5e9ef2a2b1d5bd9958495f1d71..0000000000000000000000000000000000000000 --- a/spaces/terfces0erbo/CollegeProjectV2/Huawei-Y301-Unlock-Nck-Dongle-Cracked.md +++ /dev/null @@ -1,98 +0,0 @@ -## Huawei Y301 Unlock Nck Dongle Cracked - - - - - - - - - -**Download ––– [https://bruteartapend.blogspot.com/?download=2txyzW](https://bruteartapend.blogspot.com/?download=2txyzW)** - - - - - - - - - - - - ```html - -# How to Unlock Huawei Y301 with NCK Dongle Android MTK Crack - - - -If you have a Huawei Y301 smartphone that is locked to a specific network or carrier, you might want to unlock it and use it with any SIM card of your choice. Unlocking your phone can give you more freedom and flexibility to choose the best plan and service provider for your needs. In this article, we will show you how to unlock Huawei Y301 with NCK Dongle Android MTK Crack, a free and easy tool that can bypass the network lock on your device. - - - -## What is NCK Dongle Android MTK Crack? - - - -NCK Dongle Android MTK Crack is a software program that can flash, repair and unlock many Android devices that use MediaTek (MTK) chipset. It is a cracked version of the original NCK Dongle Android MTK tool, which requires a dongle device to run. With the crack, you can use the tool without a dongle and perform various operations on your phone, such as: - - - -- Direct unlock - -- Read code - -- Unlock code calculation by IMEI - -- Flash/backup - -- IMEI repair - -- Repair security area - -- FRP reset - -- Factory reset - - - -NCK Dongle Android MTK Crack supports many models of Huawei, including Huawei Y301. You can download the latest version of the crack from [this link\[^1^\]](https://www.gsmware.com/2021/04/nck-dongle-android-mtk-crack.html). - - - -## How to Unlock Huawei Y301 with NCK Dongle Android MTK Crack? - - - -To unlock Huawei Y301 with NCK Dongle Android MTK Crack, you need to follow these steps: - - - -1. Download and extract the NCK Dongle Android MTK Crack files on your computer. You will need to disable your antivirus and other virus protection programs before extracting the files, as they may delete the loader file that is needed to run the tool. - -2. Copy the loader file "Loader XTM NCK Dongle V2.5.6.2.exe" and paste it into the NCK Dongle Android MTK portable setup folder. - -3. Run the loader file "Loader XTM NCK Dongle V2.5.6.2.exe" as administrator. The tool will launch without asking for a dongle. - -4. Select your phone model from the drop-down menu on the top left corner of the tool. In this case, choose Huawei Y301. - -5. Connect your phone to your computer via USB cable in fastboot mode. To enter fastboot mode, power off your phone and then press and hold Volume Down + Power buttons until you see a fastboot screen. - -6. Click on "Unlock" tab on the tool and then click on "Direct Unlock" button. The tool will start unlocking your phone and display a message when it is done. - -7. Disconnect your phone from your computer and reboot it. Your phone should be unlocked and ready to use with any SIM card. - - - -## Conclusion - - - -In this article, we have shown you how to unlock Huawei Y301 with NCK Dongle Android MTK Crack, a free and easy tool that can bypass the network lock on your device. You can download the latest version of the crack from [this link\[^1^\]](https://www.gsmware.com/2021/04/nck-dongle-android-mtk-crack.html). If you have any questions or problems, feel free to leave a comment below or contact us for more help. - - ``` 1b8d091108 - - - - - diff --git a/spaces/thejagstudio/picxai/static/demo.html b/spaces/thejagstudio/picxai/static/demo.html deleted file mode 100644 index 589741272738e3c68d4a1802d51c932350e59ea2..0000000000000000000000000000000000000000 --- a/spaces/thejagstudio/picxai/static/demo.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - Document - - -
              - -
              - - - \ No newline at end of file diff --git a/spaces/thomasjeon/runwayml-stable-diffusion-v1-5/README.md b/spaces/thomasjeon/runwayml-stable-diffusion-v1-5/README.md deleted file mode 100644 index f4d3c0800af892ace0ca11ddc56a79170796d5e1..0000000000000000000000000000000000000000 --- a/spaces/thomasjeon/runwayml-stable-diffusion-v1-5/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Runwayml Stable Diffusion V1 5 -emoji: ⚡ -colorFrom: pink -colorTo: purple -sdk: gradio -sdk_version: 3.19.1 -app_file: app.py -pinned: false -license: openrail ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/Grand Theft Auto Vice City Ultimate Vice City mod 2.0 free - Enjoy the new cars weapons and missions in this GTA mod.md b/spaces/tialenAdioni/chat-gpt-api/logs/Grand Theft Auto Vice City Ultimate Vice City mod 2.0 free - Enjoy the new cars weapons and missions in this GTA mod.md deleted file mode 100644 index b557e3a596bd4560bbb86cf5a054791427b28853..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/Grand Theft Auto Vice City Ultimate Vice City mod 2.0 free - Enjoy the new cars weapons and missions in this GTA mod.md +++ /dev/null @@ -1,140 +0,0 @@ - -

              Grand Theft Auto: Vice City Ultimate Vice City mod 2.0 free

              -

              If you are a fan of Grand Theft Auto: Vice City, you might want to try out the Ultimate Vice City mod 2.0, which is a free mod that adds 40 new cars, the two towers of World Trade Center, a new bridge, new billboards and more to the game. This mod will transform your GTA: Vice City into a more realistic and modern city, with vehicles from famous brands like BMW, Ferrari, Lamborghini, Porsche and more.

              -

              Grand Theft Auto: Vice City Ultimate Vice City mod 2.0 free


              Download Zip > https://urlcod.com/2uKaAE



              -

              In this article, we will show you how to download and install the Ultimate Vice City mod 2.0 for free, and what features you can expect from this amazing mod.

              -

              How to download and install the Ultimate Vice City mod 2.0 for free

              -

              The Ultimate Vice City mod 2.0 is a very easy and automatic mod to install. You just need to have Grand Theft Auto: Vice City installed on your PC, and then follow these steps:

              -
                -
              1. Download the Ultimate Vice City mod 2.0 from this link.
              2. -
              3. Extract the zip file to a folder of your choice.
              4. -
              5. Run the setup.exe file and follow the instructions.
              6. -
              7. Enjoy your new GTA: Vice City with 40 new cars and more!
              8. -
              -

              Note: If you have any problems with the installation or the mod, you can visit the official mod page for more information and support.

              -

              What features does the Ultimate Vice City mod 2.0 offer?

              -

              The Ultimate Vice City mod 2.0 is not just a simple car replacement mod. It also adds new buildings, bridges, billboards and other details to the city, making it more lively and realistic. Here are some of the main features of this mod:

              -
                -
              • 40 new cars in total, including BMW 850, Ford F-150, Yamaha YZ 450, Porsche 911 Turbo, Nissan Skyline, Toyota Supra Turbo, Bugatti Veyron Concept 2004, Ferrari 550 Barchetta, Dodge Charger, Lamborghini Diablo, Ferrari F40, Lamborghini Murcielago, Chevrolet Camaro SS, Ducati 1000, Toyota GT-ONE, Mitsubishi Eclipse (2 fast 2 furious), Peugeot 406 Taxi (Taxi 3), Ford GT-40, Ford Shelby Mustang GT500 1967 and more.
              • -
              • The two towers of World Trade Center added to the downtown area.
              • -
              • A new bridge connecting Starfish Island and Leaf Links.
              • -
              • New billboards featuring real brands and celebrities.
              • -
              • New bike park added to Ocean Beach.
              • -
              • New textures and graphics for some buildings and roads.
              • -
              • New sounds and music for some cars.
              • -
              -

              The Ultimate Vice City mod 2.0 is a great way to enhance your GTA: Vice City experience with more realism and variety. You can download it for free from this link and enjoy driving around the city with your new cars.

              -

              Conclusion

              -

              The Ultimate Vice City mod 2.0 is one of the best mods for GTA: Vice City that adds 40 new cars and more to the game. It is very easy and automatic to install, and it will make your GTA: Vice City more realistic and modern. You can download it for free from this link and have fun with your new GTA: Vice City.

              -

              Why should you try the Ultimate Vice City mod 2.0?

              -

              The Ultimate Vice City mod 2.0 is not just a cosmetic mod that changes the appearance of the city and the cars. It also improves the gameplay and the immersion of GTA: Vice City, by adding new features and challenges. Here are some of the reasons why you should try this mod:

              -

              GTA Vice City mod 2.0 download free
              -How to install Ultimate Vice City mod 2.0
              -Ultimate Vice City mod 2.0 features and gameplay
              -GTA Vice City mod 2.0 cheats and codes
              -Best mods for GTA Vice City
              -Ultimate Vice City mod 2.0 review and rating
              -GTA Vice City mod 2.0 system requirements and compatibility
              -Ultimate Vice City mod 2.0 screenshots and videos
              -GTA Vice City mod 2.0 bugs and fixes
              -Ultimate Vice City mod 2.0 update and patch
              -GTA Vice City mod 2.0 online multiplayer mode
              -Ultimate Vice City mod 2.0 missions and challenges
              -GTA Vice City mod 2.0 cars and vehicles
              -Ultimate Vice City mod 2.0 weapons and items
              -GTA Vice City mod 2.0 skins and characters
              -Ultimate Vice City mod 2.0 maps and locations
              -GTA Vice City mod 2.0 soundtracks and music
              -Ultimate Vice City mod 2.0 tips and tricks
              -GTA Vice City mod 2.0 comparison with original game
              -Ultimate Vice City mod 2.0 download link and guide
              -GTA Vice City mod 2.0 alternatives and similar mods
              -Ultimate Vice City mod 2.0 fan-made content and community
              -GTA Vice City mod 2.0 history and development
              -Ultimate Vice City mod 2.0 awards and achievements
              -GTA Vice City mod 2.0 legal issues and controversies
              -Ultimate Vice City mod 2.0 FAQ and support
              -GTA Vice City mod 2.0 mods compatibility and conflicts
              -Ultimate Vice City mod 2.0 performance and optimization
              -GTA Vice City mod 2.0 Easter eggs and secrets
              -Ultimate Vice City mod 2.0 best moments and highlights
              -GTA Vice City mod 2.0 walkthrough and guide
              -Ultimate Vice City mod 2.0 pros and cons
              -GTA Vice City mod 2.0 fun facts and trivia
              -Ultimate Vice City mod 2.0 feedback and suggestions
              -GTA Vice City mod 2.0 future plans and roadmap
              -Ultimate Vice City mod 2.0 credits and acknowledgements
              -GTA Vice City mod 2.0 technical issues and solutions
              -Ultimate Vice City mod 2.0 customization and settings
              -GTA Vice City mod 2.0 mods recommendations and rankings
              -Ultimate Vice City mod 2.0 behind the scenes and making of
              -GTA Vice City mod 2.0 lore and story
              -Ultimate Vice City mod 2.0 references and inspirations
              -GTA Vice City mod 2.0 memes and jokes
              -Ultimate Vice City mod 2.0 merchandise and products
              -GTA Vice City mod 2.0 fan art and creations
              -Ultimate Vice City mod 2.0 forums and discussions
              -GTA Vice City mod 2.0 news and announcements
              -Ultimate Vice City mod 2.0 tutorials and videos

              -
                -
              • You can drive more realistic and diverse cars, with different speeds, handling, sounds and models. You can also customize some of them with different colors and accessories.
              • -
              • You can explore new areas of the city, such as the World Trade Center, the new bridge and the bike park. You can also see new details and landmarks that make the city more alive and authentic.
              • -
              • You can enjoy a more dynamic and varied traffic, with more cars and pedestrians on the streets. You can also encounter new events and situations, such as car accidents, police chases, races and more.
              • -
              • You can experience a more immersive and realistic atmosphere, with new billboards, music, textures and graphics. You can also see the effects of weather and time on the city and the cars.
              • -
              -

              The Ultimate Vice City mod 2.0 is a mod that enhances every aspect of GTA: Vice City, making it more fun and enjoyable to play. You can download it for free from this link and discover a new GTA: Vice City.

              -
              How to uninstall the Ultimate Vice City mod 2.0
              -

              If you want to uninstall the Ultimate Vice City mod 2.0 for any reason, you can do it easily and safely by following these steps:

              -
                -
              1. Go to the folder where you installed the mod (usually C:\Program Files\Rockstar Games\Grand Theft Auto Vice City).
              2. -
              3. Run the uninstall.exe file and follow the instructions.
              4. -
              5. Delete any remaining files or folders related to the mod.
              6. -
              7. Restart your PC.
              8. -
              -

              Note: If you have any problems with the uninstallation or the game, you can visit the official mod page for more information and support.

              -
              What are the requirements and compatibility of the Ultimate Vice City mod 2.0?
              -

              The Ultimate Vice City mod 2.0 is a very light and compatible mod that does not require a high-end PC or any additional software to run. However, you should check the following requirements and compatibility before installing the mod:

              -
                -
              • You need to have Grand Theft Auto: Vice City installed on your PC, with the latest patch (1.1) applied.
              • -
              • You need to have at least 1 GB of free space on your hard drive.
              • -
              • You need to have a Windows operating system (XP, Vista, 7, 8 or 10).
              • -
              • You need to have a DirectX compatible sound card and video card.
              • -
              • You need to have a keyboard and a mouse.
              • -
              -

              The Ultimate Vice City mod 2.0 is compatible with most of the other mods and trainers for GTA: Vice City, as long as they do not modify the same files or features. However, you should always backup your original files before installing any mod, and use them at your own risk.

              -Conclusion -

              The Ultimate Vice City mod 2.0 is one of the best mods for GTA: Vice City that adds 40 new cars and more to the game. It is very easy and automatic to install, and it will make your GTA: Vice City more realistic and modern. You can download it for free from this link and have fun with your new GTA: Vice City.

              -What are the benefits of the Ultimate Vice City mod 2.0? -

              The Ultimate Vice City mod 2.0 is not only a mod that improves the graphics and the gameplay of GTA: Vice City, but also a mod that adds more value and content to the game. Here are some of the benefits of this mod:

              -
                -
              • You can enjoy a more diverse and realistic car collection, with 40 new cars from different brands and models. You can also drive some of the most iconic and expensive cars in the world, such as the Bugatti Veyron, the Ferrari F40, the Lamborghini Murcielago and more.
              • -
              • You can explore a more detailed and updated city, with new buildings, bridges, billboards and other elements. You can also visit the two towers of World Trade Center, which were removed from the original game after the 9/11 attacks.
              • -
              • You can experience a more challenging and fun gameplay, with more traffic, pedestrians, events and situations. You can also participate in new races, missions and activities.
              • -
              • You can immerse yourself in a more realistic and atmospheric environment, with new sounds, music, textures and graphics. You can also see the changes of weather and time on the city and the cars.
              • -
              -

              The Ultimate Vice City mod 2.0 is a mod that enhances every aspect of GTA: Vice City, making it more enjoyable and replayable. You can download it for free from this link and discover a new GTA: Vice City.

              -What are the drawbacks of the Ultimate Vice City mod 2.0? -

              The Ultimate Vice City mod 2.0 is a very well-made and compatible mod that does not have many drawbacks or disadvantages. However, you should be aware of some of the possible issues or limitations of this mod:

              -
                -
              • You may encounter some bugs or glitches in some parts of the game, such as crashes, freezes, missing textures or sounds, etc. You should always save your game before installing any mod, and report any problem to the official mod page.
              • -
              • You may have some compatibility issues with some other mods or trainers for GTA: Vice City, especially if they modify the same files or features as the Ultimate Vice City mod 2.0. You should always backup your original files before installing any mod, and use them at your own risk.
              • -
              • You may have some performance issues on some low-end PCs or laptops, due to the increased graphics and traffic of the mod. You should check the requirements and compatibility of the mod before installing it, and adjust your settings accordingly.
              • -
              -

              The Ultimate Vice City mod 2.0 is a very safe and stable mod that does not have many drawbacks or disadvantages. However, you should always be careful and responsible when installing any mod, and follow the instructions and recommendations of the official mod page.

              -What are the reviews and ratings of the Ultimate Vice City mod 2.0? -

              The Ultimate Vice City mod 2.0 is a very popular and acclaimed mod that has received many positive reviews and ratings from the GTA: Vice City community and fans. Here are some of the reviews and ratings of this mod:

              -
                -
              • The Ultimate Vice City mod 2.0 has a rating of 9.3 out of 10 on Mod DB, based on 1,006 votes from the users. It also has a rating of 4.8 out of 5 on Nexus Mods, based on 12 votes from the users.
              • -
              • The Ultimate Vice City mod 2.0 has received many positive comments and feedbacks from the users, who praised the quality, variety, realism and fun of the mod. Some of the comments are:
              • -
                  -
                • "This is one of the best mods for GTA: Vice City ever made. It adds so much to the game, and makes it look like a new game. The cars are amazing, the city is beautiful, and the gameplay is awesome. I highly recommend this mod to anyone who loves GTA: Vice City."
                • -
                • "I love this mod. It makes GTA: Vice City more modern and realistic, with new cars, buildings, bridges and more. The World Trade Center is a nice touch, and the new traffic and events make the game more challenging and fun. This mod is a must-have for GTA: Vice City fans."
                • -
                • "This mod is amazing. It adds 40 new cars that are very realistic and detailed, and some of them are very rare and expensive. The city is also improved with new textures, graphics and billboards. The new bridge and bike park are cool too. This mod is very easy and automatic to install, and it works perfectly with my game."
                • -
                -
              -

              The Ultimate Vice City mod 2.0 is a very well-received and appreciated mod that has received many positive reviews and ratings from the GTA: Vice City community and fans. You can download it for free from this link and see for yourself why this mod is so popular and acclaimed.

              -Conclusion -

              The Ultimate Vice City mod 2.0 is one of the best mods for GTA: Vice City that adds 40 new cars and more to the game. It is very easy and automatic to install, and it will make your GTA: Vice City more realistic and modern. You can download it for free from this link and have fun with your new GTA: Vice City.

              -

              In this article, we have shown you how to download and install the Ultimate Vice City mod 2.0 for free, and what features, benefits, drawbacks, reviews and ratings you can expect from this amazing mod. We hope you have enjoyed this article and found it useful and informative. If you have any questions or comments, please feel free to leave them below. Thank you for reading and happy gaming!

              679dcb208e
              -
              -
              \ No newline at end of file diff --git a/spaces/tialenAdioni/chat-gpt-api/logs/How to Avoid Boris FX Free Download Crack and Use Better Alternatives for Your Video Editing Needs.md b/spaces/tialenAdioni/chat-gpt-api/logs/How to Avoid Boris FX Free Download Crack and Use Better Alternatives for Your Video Editing Needs.md deleted file mode 100644 index dc88397e6c9d5e0477ad5c79881e93bf5b0c67d6..0000000000000000000000000000000000000000 --- a/spaces/tialenAdioni/chat-gpt-api/logs/How to Avoid Boris FX Free Download Crack and Use Better Alternatives for Your Video Editing Needs.md +++ /dev/null @@ -1,19 +0,0 @@ - -

              Boris FX Free Download Crack: A Risky Move for Your Video Editing Projects

              -

              Boris FX is a leading software company that produces award-winning visual effects, motion graphics, and post-production tools for the film, television, and video industry. Some of their products include Continuum, Sapphire, Mocha Pro, Silhouette, and Optics.

              -

              However, Boris FX products are not cheap and require a valid license key to activate and use. If you want to use Boris FX products without paying for them, you might be tempted to download a cracked version from the internet. However, this is not a smart move for several reasons. In this article, we will explain why you should avoid downloading Boris FX free download crack and what are the alternatives.

              -

              boris fx free download crack


              Download Filehttps://urlcod.com/2uK8A6



              -

              Why You Should Avoid Downloading Boris FX Free Download Crack

              -

              Downloading Boris FX free download crack is illegal and unethical. It violates the terms and conditions of Boris FX and infringes on their intellectual property rights. You could face legal consequences if you are caught using a pirated version of Boris FX products.

              -

              Moreover, downloading Boris FX free download crack is risky and dangerous. You could expose your computer to malware, viruses, spyware, ransomware, and other malicious software that could harm your system and compromise your data. You could also experience performance issues, errors, crashes, and compatibility problems with other software and devices.

              -

              Furthermore, downloading Boris FX free download crack is unreliable and unsatisfactory. You could miss out on the latest updates, features, security patches, and bug fixes that Boris FX releases regularly for its products. You could also encounter activation issues, license expiration, and limited functionality with some tools.

              -

              What Are the Alternatives to Downloading Boris FX Free Download Crack

              -

              Instead of downloading Boris FX free download crack, you have several legitimate and safe options to use Boris FX products or similar tools. Here are some of them:

              -
                -
              • Buy a genuine license key from Boris FX or an authorized reseller. This is the best way to enjoy the full benefits of Boris FX products without any risks or hassles. You can choose from different plans and packages that suit your needs and budget. You can also get technical support and customer service from Boris FX or the reseller.
              • -
              • Use the free trial or demo versions of Boris FX products. These are limited versions of Boris FX products that allow you to test and use some of the tools for a certain period of time or with some restrictions. You can download them from the official website of Boris FX and use them for free without any activation or license key.
              • -
              • Use free or open-source alternatives to Boris FX products. There are many other video editing software that offer similar or comparable features and functions to Boris FX products. Some of them are free or open-source, which means you can download and use them without paying anything or violating any laws. Some examples are Blender, Natron, DaVinci Resolve, HitFilm Express, etc.
              • -
              -

              In conclusion, downloading Boris FX free download crack is not worth it. It is illegal, risky, unreliable, and unsatisfactory. You should avoid it at all costs and opt for one of the alternatives we mentioned above. By doing so, you can use Boris FX products or similar tools in a legal, safe, reliable, and satisfactory way.

              ddb901b051
              -
              -
              \ No newline at end of file diff --git a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Chicken Gun Offline Mod APK The Ultimate FPS Game with Crazy Chickens.md b/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Chicken Gun Offline Mod APK The Ultimate FPS Game with Crazy Chickens.md deleted file mode 100644 index e1727c13c088b66233436519aecbfafbae641390..0000000000000000000000000000000000000000 --- a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Chicken Gun Offline Mod APK The Ultimate FPS Game with Crazy Chickens.md +++ /dev/null @@ -1,99 +0,0 @@ - -

              Chicken Gun Offline Mod APK: A Fun and Crazy FPS Game

              -

              If you are looking for a fun and crazy FPS game that will make you laugh and have a blast, then you should try Chicken Gun. This is a game where you play as a chicken with a gun, and you have to shoot other chickens in various maps and modes. Sounds ridiculous, right? Well, that's the point. Chicken Gun is a game that does not take itself too seriously, and it offers a lot of humor and action for FPS fans.

              -

              chicken gun offline mod apk


              Download Zip >>> https://bltlly.com/2uOpJK



              -

              What is Chicken Gun?

              -

              Chicken Gun is a game developed by ChaloApps, a studio that specializes in making funny and quirky games. The game was released in 2020, and it has gained a lot of popularity among mobile gamers. Chicken Gun is a game that combines FPS elements with animal characters, creating a unique and hilarious experience.

              -

              The gameplay of Chicken Gun

              -

              The gameplay of Chicken Gun is simple and straightforward. You choose your chicken character, equip it with a weapon and an item, and join a match with other players. You can play online or offline, with friends or strangers, in different game modes and maps. The objective is to shoot as many chickens as possible, while avoiding getting shot yourself. You can also use items such as grenades, jetpacks, shields, and more to gain an advantage over your enemies. The game is fast-paced and chaotic, and you will never get bored of the action.

              -

              The features of Chicken Gun

              -

              Chicken Gun is not just a simple FPS game. It also has a lot of features that make it more fun and enjoyable. Here are some of them:

              -

              Various weapons and items

              -

              You can choose from a wide range of weapons and items to equip your chicken with. You can use pistols, shotguns, rifles, snipers, rocket launchers, flamethrowers, and more. Each weapon has its own stats and effects, so you have to choose wisely depending on your play style. You can also use items such as grenades, jetpacks, shields, medkits, mines, traps, and more to spice up the gameplay.

              -

              chicken gun mod apk unlimited money and gems
              -chicken gun offline multiplayer shooting game
              -chicken gun mod apk latest version download
              -chicken gun offline fps with fun and mad chickens
              -chicken gun mod apk unlock all weapons and skins
              -chicken gun offline game free download for android
              -chicken gun mod apk no ads and no root
              -chicken gun offline mode gameplay and review
              -chicken gun mod apk hack cheats and tips
              -chicken gun offline shooter with crazy chickens
              -chicken gun mod apk 3.3.01 (updated 2023)
              -chicken gun offline action game for android devices
              -chicken gun mod apk free shopping and premium features
              -chicken gun offline fun and addictive game
              -chicken gun mod apk android 1 and apkpure
              -chicken gun offline best fps game with chickens
              -chicken gun mod apk rexdl and revdl
              -chicken gun offline how to play and win
              -chicken gun mod apk unlimited ammo and health
              -chicken gun offline download link and installation guide
              -chicken gun mod apk all characters and maps unlocked
              -chicken gun offline 3d graphics and sound effects
              -chicken gun mod apk mega mod and pro mod
              -chicken gun offline challenges and missions
              -chicken gun mod apk online and offline mode
              -chicken gun offline weapons and skins customization
              -chicken gun mod apk new update and features
              -chicken gun offline ranking and leaderboard system
              -chicken gun mod apk obb data file download
              -chicken gun offline funny and hilarious game
              -chicken gun mod apk unlimited coins and diamonds
              -chicken gun offline low mb and high performance game
              -chicken gun mod apk god mode and one hit kill
              -chicken gun offline team deathmatch and free for all modes
              -chicken gun mod apk anti ban and safe to use
              -chicken gun offline requirements and compatibility
              -chicken gun mod apk original and modified version comparison
              -chicken gun offline bugs and glitches fix
              -chicken gun mod apk unlimited everything download 2023
              -chicken gun offline best settings and controls

              -

              Different game modes and maps

              -

              You can play in different game modes and maps in Chicken Gun. You can play in classic deathmatch mode, where you have to kill as many chickens as possible in a limited time. You can also play in team deathmatch mode, where you have to cooperate with your teammates to defeat the enemy team. You can also play in capture the flag mode, where you have to steal the enemy's flag and bring it back to your base. You can also play in zombie mode, where you have to survive against waves of zombie chickens. You can also play in custom mode, where you can create your own rules and settings for the match.

              -

              You can also choose from different maps to play in. You can play in urban settings such as streets, rooftops, warehouses, etc. You can also play in rural settings such as farms, fields, barns, etc. You can also play in exotic settings such as jungles, deserts, islands, etc. Each map has its own layout and features, so you have to adapt to the environment.

              -

              Customizable chickens and skins

              -

              You can also customize your chicken character in Chicken Gun. You can change its color, size, shape, eyes, beak, feathers, etc. You can also equip it with different skins and accessories. You can make your chicken look like a pirate, a ninja, a cowboy, a superhero, a zombie, and more. You can also unlock new skins and items by playing the game and earning money and gems. You can also buy them with real money if you want to support the developers.

              -

              Online and offline multiplayer

              -

              You can play Chicken Gun with other players online or offline. You can join random matches with strangers from around the world, or you can create your own private matches with your friends. You can also chat with other players using the in-game chat feature. You can also play offline with bots, if you don't have an internet connection or you just want to practice your skills.

              -

              Why download Chicken Gun Offline Mod APK?

              -

              Chicken Gun is a fun and crazy game, but it can also be challenging and frustrating at times. You may run out of money and gems to buy new weapons and items, or you may encounter ads that interrupt your gameplay. You may also face some glitches and bugs that affect your performance. That's why you may want to download Chicken Gun Offline Mod APK, a modified version of the game that gives you some extra benefits.

              -

              The benefits of Chicken Gun Offline Mod APK

              -

              Chicken Gun Offline Mod APK is a version of the game that has been modified by some third-party developers to give you some advantages over the original game. Here are some of the benefits of Chicken Gun Offline Mod APK:

              -

              Unlimited money and gems

              -

              With Chicken Gun Offline Mod APK, you don't have to worry about running out of money and gems to buy new weapons and items. You will have unlimited amounts of both currencies, so you can buy whatever you want without any restrictions. You can also upgrade your weapons and items to the maximum level, making them more powerful and effective.

              -

              Unlocked all weapons and items

              -

              With Chicken Gun Offline Mod APK, you don't have to wait to unlock new weapons and items by playing the game or spending real money. You will have access to all the weapons and items in the game from the start, so you can choose from a variety of options to suit your preferences. You can also try out different combinations of weapons and items to see which ones work best for you.

              -

              No ads and no root required

              -

              With Chicken Gun Offline Mod APK, you don't have to deal with annoying ads that pop up on your screen and disrupt your gameplay. You will enjoy a smooth and uninterrupted gaming experience, without any distractions or interruptions. You also don't need to root your device to install Chicken Gun Offline Mod APK, unlike some other modded games. You can install it easily and safely on any Android device.

              -

              How to download and install Chicken Gun Offline Mod APK?

              -

              If you are interested in downloading and installing Chicken Gun Offline Mod APK, here are the steps you need to follow:

              -

              Step 1: Download the APK file from a trusted source

              -

              The first thing you need to do is to download the APK file of Chicken Gun Offline Mod APK from a trusted source. You can search for it on Google or use the link provided below. Make sure you download the latest version of the modded game, as older versions may not work properly or may contain viruses.

              -

              Download Chicken Gun Offline Mod APK here

              -

              Step 2: Enable unknown sources on your device

              -

              The next thing you need to do is to enable unknown sources on your device. This is a security setting that allows you to install apps from sources other than the Google Play Store. To enable unknown sources, go to Settings > Security > Unknown Sources and toggle it on.

              -

              Step 3: Install the APK file and enjoy the game

              -

              The final thing you need to do is to install the APK file on your device. To do this, locate the downloaded file in your file manager and tap on it. Follow the instructions on the screen to complete the installation process. Once done, launch the game from your app drawer and enjoy playing Chicken Gun Offline Mod APK.

              -

              Conclusion

              -

              Chicken Gun is a fun and crazy FPS game that will make you laugh and have a blast. You can play as a chicken with a gun, and shoot other chickens in various maps and modes. You can also customize your chicken character, choose from different weapons and items, and play online or offline with other players. If you want to enhance your gaming experience, you can download Chicken Gun Offline Mod APK, which gives you unlimited money and gems, unlocked all weapons and items, no ads, and no root required. Download Chicken Gun Offline Mod APK today and have fun with this hilarious and action-packed game.

              -

              FAQs

              -

              Here are some frequently asked questions about Chicken Gun Offline Mod APK:

              -

              Q: Is Chicken Gun Offline Mod APK safe to download and install?

              -

              A: Yes, Chicken Gun Offline Mod APK is safe to download and install, as long as you get it from a trusted source. The modded game does not contain any viruses or malware, and it does not require root access to your device. However, you should always be careful when downloading and installing any app from unknown sources, as they may harm your device or compromise your privacy.

              -

              Q: Will Chicken Gun Offline Mod APK affect my original game?

              -

              A: No, Chicken Gun Offline Mod APK will not affect your original game. The modded game is a separate app that has a different package name and icon from the original game. You can install both apps on your device and play them separately. However, you should not use the same account or data for both games, as they may conflict with each other and cause errors.

              -

              Q: Can I play Chicken Gun Offline Mod APK with other players online?

              -

              A: Yes, you can play Chicken Gun Offline Mod APK with other players online, but only with those who have the same version of the modded game. You cannot play with players who have the original game or a different version of the modded game, as they will not be compatible with each other. You can also play offline with bots, if you prefer.

              -

              Q: What are the minimum requirements to play Chicken Gun Offline Mod APK?

              -

              A: The minimum requirements to play Chicken Gun Offline Mod APK are as follows:

              -
                -
              • An Android device running Android 4.4 or higher
              • -
              • At least 100 MB of free storage space
              • -
              • A stable internet connection (for online multiplayer)
              • -
              -

              Q: How can I update Chicken Gun Offline Mod APK?

              -

              A: To update Chicken Gun Offline Mod APK, you need to download and install the latest version of the modded game from the same source where you got the previous version. You should also uninstall the old version before installing the new one, to avoid any conflicts or errors. You should also check for updates regularly, as the developers may release new features and fixes for the modded game.

              197e85843d
              -
              -
              \ No newline at end of file diff --git a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Among Us Cheats APK for Android and PC - Speed Wallhack Impostor and More!.md b/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Among Us Cheats APK for Android and PC - Speed Wallhack Impostor and More!.md deleted file mode 100644 index cd49b52ce03ca7db21628e709289a90e3f14f6d0..0000000000000000000000000000000000000000 --- a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Among Us Cheats APK for Android and PC - Speed Wallhack Impostor and More!.md +++ /dev/null @@ -1,122 +0,0 @@ - -

              Among Us Cheats APK: How to Download, Install, and Use Them Safely

              -

              Among Us is a multiplayer social deduction game that has become a global phenomenon. The game involves a group of crewmates who have to work together to complete tasks on a spaceship, a planet base, or an airship, while one or more impostors try to sabotage and kill them. The game is fun, exciting, and unpredictable, as players have to use their skills of deception, deduction, and communication to win.

              -

              However, not everyone plays by the rules. Some players resort to using cheats and hacks to gain an unfair advantage over others. Cheats and hacks are software programs or modifications that alter the game in some way, such as giving the player super speed, invisibility, or always being an impostor. These cheats and hacks are usually downloaded as apk files, which are Android application packages that can be installed on Android devices.

              -

              among us cheats apk


              Download ✯✯✯ https://bltlly.com/2uOrCI



              -

              Why do some players use cheats and hacks in Among Us? There could be various reasons, such as boredom, frustration, curiosity, or simply wanting to win at all costs. However, using cheats and hacks in online games is not only unethical, but also risky. Cheating can ruin the fun and enjoyment of the game for other players, who may feel cheated, angry, or discouraged. Cheating can also result in getting banned from the game or even facing legal trouble. Moreover, cheating can expose the player's device to malware, viruses, or other security threats.

              -

              So how can you download, install, and use among us cheats apk files safely? And how can you enjoy Among Us without cheating and ruining the game for others? In this article, we will answer these questions and provide some tips and advice for ethical and fair gaming.

              -

              How to find and download among us cheats apk files from reputable sources

              -

              The first step to using cheats and hacks in Among Us is to find and download them from reputable sources. There are many websites that offer among us cheats apk files, but not all of them are trustworthy. Some of them may contain fake or malicious files that can harm your device or steal your personal information. Therefore, you need to be careful and do some research before downloading anything.

              -

              One way to find reputable sources is to use a search engine like Bing. You can type in keywords like "among us cheats apk" or "among us hacks apk" and see what results come up. You can also look for reviews, ratings, comments, or feedback from other users who have downloaded the files. You can also check the reputation of the website by looking at its domain name, design, content, security certificates, or contact information.

              -

              Another way to find reputable sources is to use a website like APK Mirror. APK Mirror is a popular site that hosts Android apps that can be installed individually. The site monitors the files it hosts to verify that they are not malicious or harmful. You can browse the site and search for among us cheats apk files that you want. However, you still need to be cautious and read the description, permissions, changelog, or user reviews before downloading anything.

              -

              How to install apk files on Android devices safely and securely

              -

              The next step to using cheats and hacks in Among Us is to install them on your Android device safely and securely. Before you can install any apk file on your device, you need to allow unknown apps from your settings. This means that you give permission for apps that are not from the

              How to use cheats and hacks in Among Us without getting banned or detected

              -

              Once you have downloaded and installed the among us cheats apk files on your device, you may be wondering how to use them without getting banned or detected by the game or other players. After all, cheating is not only frowned upon, but also against the terms of service of the game. If you are caught cheating, you may face consequences such as being kicked out of the lobby, being reported by other players, or even being permanently banned from the game.

              -

              Therefore, you need to be smart and careful when using cheats and hacks in Among Us. Here are some tips and tricks to help you avoid getting caught:

              -
                -
              • Use cheats and hacks sparingly and discreetly. Don't overdo it or make it obvious that you are cheating. For example, don't kill everyone in a matter of seconds, don't vent in front of other players, don't spam the chat with nonsense, etc. Try to act natural and blend in with the rest of the players.
              • -
              • Use cheats and hacks that are undetectable or have anti-ban features. Some among us cheats apk files have built-in features that prevent them from being detected by the game's anti-cheat system or by other players. For example, some cheats can hide your name, your role, your location, or your actions from other players. Some cheats can also bypass the voting system or the emergency meetings. Look for these features when choosing which cheats to use.
              • -
              • Use cheats and hacks that are compatible with the latest version of the game. The game developers are constantly updating and patching the game to fix bugs, add new features, and prevent cheating. Therefore, you need to make sure that the among us cheats apk files that you are using are up to date and compatible with the current version of the game. Otherwise, you may encounter errors, glitches, crashes, or bans.
              • -
              • Use cheats and hacks at your own risk. Ultimately, there is no guarantee that you will not get banned or detected when using cheats and hacks in Among Us. The game developers and the community are always working to find and eliminate cheaters from the game. Therefore, you need to be aware of the risks and consequences of cheating and decide whether it is worth it or not.
              • -
              -

              How to enjoy Among Us without cheating and ruining the game for others

              -

              Cheating and hacking in Among Us may seem fun and tempting for some players, but it is not the best way to enjoy the game. Cheating can ruin the game for yourself and for others who are playing fairly and honestly. Cheating can also take away the challenge, thrill, and satisfaction of playing the game as it is meant to be played.

              -

              among us hacks for pc and android
              -among us mod apk download with cheats
              -among us cheat engine for speed hack
              -among us wallhack and radar cheat
              -among us always impostor hack apk
              -among us god mode cheat download
              -among us esp and 2d radar hack
              -among us mod menu apk with cheats
              -among us cheat codes for android
              -among us unlock all skins hack apk
              -among us no kill cooldown cheat
              -among us impostor vision hack apk
              -among us anti ban cheat download
              -among us invisible name hack apk
              -among us vent hack and teleport cheat
              -among us unlimited money cheat apk
              -among us no ads hack download
              -among us fake impostor cheat apk
              -among us ghost mode hack and cheat
              -among us voice chat hack apk download
              -among us pet hack and cheat mod
              -among us color changer hack apk
              -among us instant win cheat download
              -among us map hack and location cheat
              -among us sabotage hack apk mod
              -among us free skins cheat download
              -among us kill distance hack apk
              -among us vote hack and skip cheat
              -among us mini crewmate hack download
              -among us chat hack and spam cheat
              -among us custom hats hack apk
              -among us emergency meeting hack download
              -among us report hack and ban cheat
              -among us no name hack apk mod
              -among us task hack and auto complete cheat
              -among us crewmate vision hack download
              -among us kill animation hack apk
              -among us fake task cheat and troll hack
              -among us speed run hack download
              -among us role changer hack apk mod
              -among us detective mode cheat download
              -among us airship map hack apk
              -among us soundboard hack and prank cheat
              -among us zoom out hack download
              -among us character size hack apk mod
              -among us infinite vote time cheat download
              -among us hide and seek mode hack apk
              -among us discord bot hack and cheat
              -among us no gravity hack download

              -

              Therefore, we suggest that you try to enjoy Among Us without cheating and ruining the game for others. Here are some ways to do that:

              -
                -
              • Play with friends or people you trust. Playing with people you know or who share your interests can make the game more fun and enjoyable. You can communicate better, cooperate more, joke around more, and have a good time together. You can also avoid cheaters or toxic players who may ruin your experience.
              • -
              • Play with different settings or modes. Playing with different settings or modes can make the game more varied and interesting. You can change things like the number of impostors, the speed of players, the vision of players, the task difficulty, etc. You can also try different modes like hide and seek, zombies, detective, etc.
              • -
              • Play with different strategies or roles. Playing with different strategies or roles can make the game more challenging and exciting. You can try different ways to deceive, accuse, defend, investigate, sabotage, etc. You can also try different roles like leader, follower, mediator, jester, etc.
              • -
              • Play with respect and sportsmanship. Playing with respect and sportsmanship can make the game more enjoyable for everyone involved. You can respect other players by following the rules, not cheating or hacking, not quitting or leaving mid-game, not being rude or abusive, etc. You can also show sportsmanship by congratulating winners, admitting defeat gracefully, apologizing for mistakes, etc.
              • -
              -

              Conclusion

              -

              Among Us is a fun and addictive game that can be enjoyed by anyone who loves social deduction and deception. However, some players may be tempted to use cheats and hacks to gain an edge over others. This can be risky and unethical, as it can ruin the game for themselves and for others.

              -

              In this article, we have explained how to find and download among us cheats apk files from reputable sources, how to install them on Android devices safely and securely, how to use them without getting banned or detected, and how to enjoy the game without cheating and ruining it for others. We hope that this article has been helpful and informative for you.

              -

              What do you think about cheating and hacking in Among Us? Do you use them or avoid them? Do you have any tips or tricks to share with other players? Let us know in the comments below!

              -

              FAQs

              -

              What is an apk file and how does it work?

              -

              An apk file is an Android application package that contains the code, resources, and metadata of an Android app. It is similar to an executable file on a computer. An apk file can be installed on an Android device by tapping on it or using a file manager app. An apk file can also be downloaded from the web or transferred from another device.

              -

              What are some of the best cheats and hacks for Among Us?

              -

              Some of the best cheats and hacks for Among Us are:

              -
                -
              • Always Impostor: This cheat allows you to always be the impostor in every game, regardless of the settings or the number of players.
              • -
              • Invisibility: This cheat allows you to become invisible to other players, making it easier to kill, vent, or sabotage without being seen.
              • -
              • Speed Hack: This cheat allows you to move faster than normal, giving you an advantage in chasing, escaping, or completing tasks.
              • -
              • No Kill Cooldown: This cheat allows you to kill as many players as you want without having to wait for the cooldown timer.
              • -
              • Wall Hack: This cheat allows you to see through walls and obstacles, giving you more vision and information than other players.
              • -
              -

              How can I report a cheater in Among Us?

              -

              If you encounter a cheater in Among Us, you can report them by following these steps:

              -
                -
              1. Tap on the chat icon at the top right corner of the screen.
              2. -
              3. Select the name of the player you want to report from the list.
              4. -
              5. Tap on the report button at the bottom of the screen.
              6. -
              7. Select the reason for reporting from the options.
              8. -
              9. Tap on confirm to submit your report.
              10. -
              -

              The game developers will review your report and take appropriate action against the cheater.

              -

              How can I protect myself from cheaters in Among Us?

              -

              If you want to avoid playing with cheaters in Among Us, you can protect yourself by following these tips:

              -
                -
              • Play with friends or people you trust. This way, you can ensure that everyone is playing fairly and honestly.
              • -
              • Play with private lobbies or codes. This way, you can control who joins your game and who doesn't.
              • -
              • Play with verified servers or hosts. This way, you can join games that have anti-cheat measures or moderators who can kick out cheaters.
              • -
              • Play with different settings or modes. This way, you can make the game more challenging or fun for yourself and others.
              • -
              -

              What are some alternatives to cheating in Among Us?

              -

              If you want to have more fun and excitement in Among Us without cheating, you can try some alternatives such as:

              -
                -
              • Playing with different roles or mods. There are many fan-made roles or mods that add new features or mechanics to the game, such as sheriff, doctor, jester, vampire, etc. You can find these roles or mods online or create your own.
              • -
              • Playing with different rules or challenges. You can create your own rules or challenges that make the game more interesting or difficult, such as no talking, no lying, no voting, etc. You can also find some ideas online or from other players.
              • -
              • Playing with different themes or scenarios. You can create your own themes or scenarios that make the game more immersive or creative, such as horror, comedy, mystery, etc. You can also find some inspiration online or from other players.
              • -

              401be4b1e0
              -
              -
              \ No newline at end of file diff --git a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Euchre Offline and Experience the Thrill of a Realistic Game Deck.md b/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Euchre Offline and Experience the Thrill of a Realistic Game Deck.md deleted file mode 100644 index 2fb692b38f9495e230d30b83244810db40372132..0000000000000000000000000000000000000000 --- a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Euchre Offline and Experience the Thrill of a Realistic Game Deck.md +++ /dev/null @@ -1,140 +0,0 @@ -
              -

              Download Offline Euchre Game: How to Play and Enjoy the Classic Card Game Anywhere

              -

              Euchre is a classic card game that has been around for centuries. It is a fun and challenging game that requires strategy, teamwork, and skill. But what if you want to play euchre without an internet connection or a deck of cards? Don't worry, we have you covered. In this article, we will show you how to download offline euchre game apps for your smartphone or tablet, so you can play euchre anytime and anywhere. We will also explain the basic rules and tips of euchre, so you can learn how to play this exciting game or refresh your memory if you are already a fan.

              -

              What is Euchre and Why Should You Play It?

              -

              Euchre is a trick-taking card game that is played with two teams of two players each. The goal is to win more tricks than the other team by playing the highest card of the suit or the trump suit. The trump suit is determined by a bidding process before each round, where one player can choose to accept or reject the suit of the face-up card on the deck. The team that chooses the trump suit is called the declarers, and the other team is called the defenders. The declarers try to win at least three tricks out of five, while the defenders try to stop them. If the declarers succeed, they score one point. If they fail, they are euchred and the defenders score two points. The first team to reach a target score (usually 10 points) wins the game.

              -

              download offline euchre game


              Download Zip ……… https://bltlly.com/2uOiPx



              -

              Euchre is a great game to play because it is easy to learn but hard to master. It involves both luck and skill, as well as communication and cooperation with your partner. It can be very competitive and exciting, as each round can change the outcome of the game. It can also be very social and enjoyable, as you can chat with your friends or make new ones while playing.

              -

              The History and Popularity of Euchre

              -

              Euchre is believed to have originated in Europe in the 18th century, possibly from a French game called Écarté or a German game called Juckerspiel. It was brought to America by immigrants and became very popular in the 19th century, especially in the Midwest and Northeast regions. It was also played by soldiers during the American Civil War and World War I. Today, euchre is still widely played in the US, Canada, Australia, New Zealand, and other countries. It has many variations and regional rules, such as Canadian Loner, Stick the Dealer, Joker's Wild, and more.

              -

              download free euchre offline game
              -offline euchre card game download
              -euchre offline single player download
              -download euchre offline for android
              -euchre offline no wifi download
              -download euchre offline classic card game
              -euchre offline with bots download
              -download euchre offline for pc
              -euchre offline app download
              -download euchre offline for ios
              -euchre offline game mode download
              -download euchre offline hd graphics
              -euchre offline without ads download
              -download euchre offline with friends
              -euchre offline challenge mode download
              -download euchre offline for windows
              -euchre offline best game download
              -download euchre offline for mac
              -euchre offline fast dealing download
              -download euchre offline with statistics
              -euchre offline realistic game deck download
              -download euchre offline for laptop
              -euchre offline smooth gameplay download
              -download euchre offline for chromebook
              -euchre offline high quality download
              -download euchre offline for tablet
              -euchre offline easy to play download
              -download euchre offline with sound effects
              -euchre offline fun and entertaining download
              -download euchre offline with score option
              -euchre offline simple design download
              -download euchre offline with game deck option
              -euchre offline two game modes download
              -download euchre offline with declarations
              -euchre offline expert bots download
              -download euchre offline with scoreboard
              -euchre offline responsive design download
              -download euchre offline with net energy gain
              -euchre offline part of phd thesis download
              -download euchre offline with reinforcement learning

              -

              The Benefits of Playing Euchre Offline

              -

              Playing euchre offline has many advantages over playing online or with a physical deck of cards. Here are some of them:

              -
                -
              • You don't need an internet connection or data plan to play euchre offline. You can play it anywhere you want, such as on a plane, train, bus, car, park, beach, or at home.
              • -
              • You don't need to worry about finding other players or waiting for them to join or finish a game. You can play euchre offline with computer players that are always ready and challenging.
              • You don't need to worry about losing or damaging your cards, shuffling them, or dealing them. You can play euchre offline with a digital deck that is always shuffled and dealt for you. -
              • You can play euchre offline at your own pace and level. You can choose the difficulty of the computer players, the target score, the game speed, and the game rules. You can also pause, resume, or restart the game anytime you want.
              • -
              • You can play euchre offline for free or for a low cost. There are many offline euchre game apps that you can download for free or for a small fee. You don't need to pay for a subscription or in-app purchases to enjoy the game.
              • -
              -

              How to Play Euchre: Basic Card Game Rules

              -

              If you are new to euchre or need a refresher, here are the basic card game rules that you need to know:

              -

              The Objective of Euchre

              -

              The objective of euchre is to win more tricks than the other team by playing the highest card of the suit or the trump suit. A trick is a round where each player plays one card. The player who plays the highest card of the suit that was led (the first card played) or the highest card of the trump suit wins the trick and leads the next one. The trump suit is a special suit that beats any other suit in the game. The trump suit is determined by a bidding process before each round, where one player can choose to accept or reject the suit of the face-up card on the deck.

              -

              The Setup and Deck of Euchre

              -

              Euchre is played with two teams of two players each, sitting opposite each other. A standard 52-card deck is used, but only the cards from 9 to Ace are used, making a total of 24 cards. The cards are ranked as follows, from highest to lowest: Joker (if used), Right Bower (the Jack of the trump suit), Left Bower (the Jack of the same color as the trump suit), Ace, King, Queen, 10, 9. The Left Bower is considered part of the trump suit and ranks between the Right Bower and the Ace.

              -

              The dealer shuffles the cards and deals five cards to each player, one at a time, starting with the player to their left and going clockwise. The remaining four cards are placed face down in the center of the table, forming the kitty. The top card of the kitty is turned face up for everyone to see.

              -

              The Gameplay and Scoring of Euchre

              -

              The gameplay of euchre consists of two phases: bidding and playing. Each round has five tricks, and each game has several rounds until one team reaches a target score (usually 10 points).

              -

              Declaring Trumps and Playing Alone

              -

              The bidding phase starts with the player to the left of the dealer, who can either accept or reject the suit of the face-up card on the kitty as the trump suit. If they accept it, they say "order it up" and pick up the card, adding it to their hand and discarding another card face down. If they reject it, they say "pass" and the bidding moves to the next player clockwise. This continues until either one player accepts the trump suit or all four players pass. If all four players pass, a second round of bidding begins, where each player can name any other suit (except the suit of the face-up card) as the trump suit or pass again. If all four players pass again, then the round is void and a new round begins with a new dealer.

              -

              The player who chooses or accepts the trump suit becomes the declarer and their partner becomes their helper. The other team becomes the defenders. The declarer can also choose to play alone, without their partner's help, by saying "I'm going alone" or "I'm playing solo". In this case, their partner puts their cards face down and does not participate in the playing phase. Playing alone gives the declarer a chance to score more points if they win all five tricks, but also exposes them to more risk if they lose any trick.

              -

              Winning Tricks and Points

              -

              The playing phase starts with the player to the left of the dealer (or to their left if they ordered up) leading any card from their hand. The other players must follow suit if they can, meaning they must play a card of the same suit as the first card played. If they cannot follow suit, they can play any other card from their hand, including a trump card. The player who plays the highest card of the suit that was led or the highest card of the trump suit wins the trick and leads the next one. The playing phase continues until all five tricks are played. The scoring of euchre depends on whether the declarer played alone or with their partner, and whether they won or lost the round. Here are the possible outcomes and points: - If the declarer played alone and won all five tricks, they score four points. - If the declarer played alone and won three or four tricks, they score one point. - If the declarer played alone and won less than three tricks, they are euchred and the defenders score four points. - If the declarer played with their partner and won all five tricks, they score two points. - If the declarer played with their partner and won three or four tricks, they score one point. - If the declarer played with their partner and won less than three tricks, they are euchred and the defenders score two points. The game continues until one team reaches the target score (usually 10 points), and that team wins the game.

              How to Download Offline Euchre Game Apps

              -

              If you want to play euchre offline on your smartphone or tablet, you need to download an offline euchre game app from your device's app store. There are many offline euchre game apps available for both Android and iOS devices, but not all of them are equally good. Some of them may have poor graphics, annoying ads, limited features, or bugs. To help you choose the best offline euchre game app for your device, we have compiled a list of some of the most popular and highly rated ones below.

              -

              The Best Offline Euchre Game Apps for Android

              -

              If you have an Android device, here are some of the best offline euchre game apps that you can download from Google Play:

              -

              Euchre Offline - Single Player

              -

              Euchre Offline - Single Player is a simple and easy-to-use offline euchre game app that lets you play euchre against three computer players. You can choose from three difficulty levels: easy, medium, or hard. You can also customize the game settings, such as the target score, the game speed, the card design, and the sound effects. The app has a clean and colorful interface that shows your cards, your partner's cards, the kitty, and the score. The app also keeps track of your statistics, such as your wins, losses, points, and percentage.

              -

              Euchre Offline - Single Player is free to download and play, but it contains ads that can be removed by purchasing the premium version for $1.99.

              -

              Euchre - Classic Card Game

              -

              Euchre - Classic Card Game is another offline euchre game app that allows you to play euchre against three computer players. You can choose from four difficulty levels: beginner, intermediate, advanced, or expert. You can also adjust the game settings, such as the target score, the game speed, the card design, and the sound effects. The app has a sleek and modern interface that shows your cards, your partner's cards, the kitty, and the score. The app also records your statistics, such as your wins, losses, points, and percentage.

              -

              Euchre - Classic Card Game is free to download and play, but it contains ads that can be removed by purchasing the premium version for $2.99.

              -

              Euchre

              -

              Euchre is a simple and straightforward offline euchre game app that lets you play euchre against three computer players. You can choose from two difficulty levels: normal or hard. You can also change the game settings, such as the target score, the game speed, the card design, and the sound effects. The app has a basic and minimalist interface that shows your cards, your partner's cards, the kitty, and the score. The app also keeps track of your statistics, such as your wins, losses, points, and percentage.

              -

              Euchre is free to download and play, but it contains ads that can be removed by purchasing the premium version for $0.99.

              The Best Offline Euchre Game Apps for iOS

              -

              If you have an iOS device, here are some of the best offline euchre game apps that you can download from the App Store:

              -

              Euchre Gold

              -

              Euchre Gold is a premium offline euchre game app that offers you a realistic and immersive euchre experience. You can play euchre against three computer players that have advanced artificial intelligence and different personalities. You can choose from five difficulty levels: beginner, easy, medium, hard, or pro. You can also customize the game settings, such as the target score, the game speed, the card design, and the sound effects. The app has a beautiful and elegant interface that shows your cards, your partner's cards, the kitty, and the score. The app also tracks your statistics, such as your wins, losses, points, and percentage.

              -

              Euchre Gold costs $2.99 to download and play, and it does not contain any ads or in-app purchases.

              -

              Euchre 3D

              -

              Euchre 3D is a popular and highly rated offline euchre game app that lets you play euchre against three computer players that have smart artificial intelligence and realistic animations. You can choose from four difficulty levels: easy, medium, hard, or expert. You can also adjust the game settings, such as the target score, the game speed, the card design, and the sound effects. The app has a stunning and realistic interface that shows your cards, your partner's cards, the kitty, and the score. The app also records your statistics, such as your wins, losses, points, and percentage.

              -

              Euchre 3D is free to download and play, but it contains ads that can be removed by purchasing the premium version for $4.99.

              -

              Hardwood Euchre

              -

              Hardwood Euchre is a fun and unique offline euchre game app that lets you play euchre against three computer players that have different skill levels and personalities. You can choose from three difficulty levels: novice, normal, or pro. You can also change the game settings, such as the target score, the game speed, the card design, and the sound effects. The app has a colorful and cartoonish interface that shows your cards, your partner's cards, the kitty, and the score. The app also keeps track of your statistics, such as your wins, losses, points, and percentage.

              -

              Hardwood Euchre is free to download and play, but it contains ads and in-app purchases that can enhance your gameplay.

              -

              Conclusion and FAQs

              -

              Euchre is a classic card game that you can play offline on your smartphone or tablet with offline euchre game apps. These apps allow you to play euchre anytime and anywhere without an internet connection or a deck of cards. You can also learn how to play euchre or improve your skills with these apps. We have listed some of the best offline euchre game apps for both Android and iOS devices in this article. We hope you find them useful and enjoyable.

              -

              If you have any questions about euchre or offline euchre game apps, you may find the answers in these FAQs:

              -

              What are some tips and strategies for playing euchre?

              -

              Some tips and strategies for playing euchre are:

              -
                -
              • Communicate with your partner using signals or conventions. For example, you can use the first card you play to indicate whether you have a high card or a low card of the trump suit.
              • -
              • Try to make your partner the declarer if they have a strong hand or if you have a weak hand. This way, you can support them with your cards or avoid being euchred.
              • -
              • Try to take control of the game by leading high cards or trump cards. This way, you can force your opponents to follow suit or waste their trump cards.
              • -
              • Try to keep track of the cards that have been played or are still in play. This way, you can plan your moves accordingly and avoid being surprised by your opponents.
              • -
              • Try to use your Left Bower wisely. It is a powerful card that can win many tricks or save you from being euchred.
              • -
              -

              How do I download offline euchre game apps?

              -

              To download offline euchre game apps for your device, you need to follow these steps:

              -
                -
              1. Go to your device's app store (Google Play for Android or App Store for iOS).
              2. -
              3. Search for "offline euchre" or "euchre offline" in the search bar.
              4. -
              5. Browse through the results and select the app that suits your preferences.
              6. -
              7. Tap on the "Install" or "Get" button to download and install the app on your device.
              8. -
              9. Open the app and enjoy playing euchre offline.
              10. -
              -

              What are some alternatives to offline euchre game apps?

              -

              If you don't want to use offline euchre game apps, you can still play euchre offline with other methods. Some alternatives are:

              -
                -
              • Playing euchre with a physical deck of cards. You can buy a standard 52-card deck or a special euchre deck that only has 24 cards. You can also print your own euchre cards from online sources.
              • -
              • Playing euchre with a computer program or a website. You can download a euchre software or visit a euchre website that allows you to play euchre offline on your computer. You can also use an emulator or a browser extension to run these programs or websites on your device.
              • -
              • Playing euchre with a board game or a card game. You can buy a euchre board game or a card game that simulates the euchre gameplay with different components. You can also create your own euchre board game or card game with some creativity and materials.
              • -
              -

              How do I improve my euchre skills?

              -

              To improve your euchre skills, you need to practice and learn from your mistakes. Here are some ways to do that:

              -
                -
              • Play euchre regularly with different players and difficulty levels. This will help you gain more experience and confidence in playing euchre.
              • -
              • Read books, articles, blogs, or forums about euchre. This will help you learn more about the rules, strategies, tips, and tricks of euchre.
              • -
              • Watch videos, podcasts, or streams about euchre. This will help you see how other players play euchre and what they do right or wrong.
              • -
              • Join a club, group, or community of euchre players. This will help you meet new friends, get feedback, and have fun playing euchre.
              • -
              -

              What are some other card games similar to euchre?

              -

              If you like euchre, you may also like other card games that are similar to it. Some of them are:

              -
                -
              • Bid Euchre: A variation of euchre where each player bids on how many tricks they think they can win.
              • -
              • Bridge: A trick-taking card game where two teams of two players compete to win more points by bidding and making contracts.
              • -
              • Hearts: A trick-taking card game where four players try to avoid taking tricks that contain hearts or the queen of spades.
              • -
              • Pinochle: A trick-taking card game where two teams of two players try to score more points by melding and taking tricks with a special 48-card deck.
              • -
              • Spades: A trick-taking card game where two teams of two players try to win more tricks than their bid by using spades as the trump suit.
              • -

              401be4b1e0
              -
              -
              \ No newline at end of file diff --git a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Film 21 Blackjack Sub Indo Full Movie dengan Subtitle Indonesia Lengkap.md b/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Film 21 Blackjack Sub Indo Full Movie dengan Subtitle Indonesia Lengkap.md deleted file mode 100644 index a9629222d0dc25e4597ef1bf8a8bf61dbf13592b..0000000000000000000000000000000000000000 --- a/spaces/ticomspire/turkey-syria-earthquake-tweets/logs/Download Film 21 Blackjack Sub Indo Full Movie dengan Subtitle Indonesia Lengkap.md +++ /dev/null @@ -1,139 +0,0 @@ - -

              Download Film 21 Blackjack Sub Indo Full Movie: A Guide for Fans of the MIT Blackjack Team

              -

              If you are a fan of card games, casino gambling, or mathematical genius, you might have heard of or watched the film 21. The film 21 is a 2008 American heist drama film directed by Robert Luketic and distributed by Sony Pictures Releasing. The film is inspired by the story of the MIT Blackjack Team, a group of students from Massachusetts Institute of Technology who used card counting and covert signalling to beat casinos at blackjack in the 1980s and 1990s. The film stars Jim Sturgess, Kevin Spacey, Laurence Fishburne, Kate Bosworth, Liza Lapira, Jacob Pitts, Aaron Yoo, and Kieu Chinh.

              -

              download film 21 blackjack sub indo full movie


              Download Zip ——— https://bltlly.com/2uOsZY



              -

              The film 21 is a thrilling and entertaining adaptation of the true story of the MIT Blackjack Team, but it also deviates from some of the facts and details. If you want to watch or rewatch this film with subtitles in Indonesian language, you might be wondering how to download film 21 blackjack sub indo full movie online. In this article, we will guide you through the process of downloading film 21 blackjack sub indo full movie online, as well as provide you with some background information on the story of the MIT Blackjack Team and how it was portrayed in the film. We will also discuss some of the benefits and drawbacks of downloading film 21 blackjack sub indo full movie online, as well as some of the legal and ethical issues involved. By reading this article, you will learn more about this fascinating film and how to enjoy it with subtitles in your preferred language.

              -

              The Story of the MIT Blackjack Team: How They Beat the Casinos with Card Counting

              -

              Before we dive into how to download film 21 blackjack sub indo full movie online, let us first explore what card counting is and how it works. Card counting is a technique that involves keeping track of the ratio of high cards to low cards in a deck of cards that is used for playing blackjack. By doing so, card counters can gain an advantage over the casino by adjusting their bets according to the count. When there are more high cards left in the deck, card counters bet more because they have a higher chance of getting a blackjack or a favorable hand. When there are more low cards left in the deck, card counters bet less because they have a lower chance of getting a good hand.

              -

              Card counting is

              Card counting is not illegal, but it is frowned upon by casinos and can result in being banned or harassed by casino security. Therefore, card counters need to be discreet and avoid detection by using various methods such as disguises, team play, and covert signalling.

              -

              One of the most famous and successful groups of card counters was the MIT Blackjack Team, which operated from 1979 to the early 2000s. The MIT Blackjack Team was composed of students and alumni from MIT, Harvard, and other prestigious universities who applied their mathematical skills and knowledge to beat the casinos at blackjack. The team was initially formed by Bill Kaplan, a Harvard MBA graduate who had already run a successful blackjack team in Las Vegas. He joined forces with J.P. Massar, a MIT student who had been leading a smaller team of card counters. Together, they recruited and trained more players, developed more sophisticated strategies and techniques, and raised more funds to bankroll their operations.

              -

              The MIT Blackjack Team used a system called the High-Low system, which assigns a value of +1 to cards 2-6, 0 to cards 7-9, and -1 to cards 10-A. By keeping a running count of these values, the team could determine the true count, which is the running count divided by the number of decks remaining in the shoe. The true count indicates how favorable the deck is for the player. The higher the true count, the more the player should bet. The team also used various forms of camouflage and deception to avoid detection, such as playing multiple hands, splitting and doubling down, varying their play and appearance, and acting drunk or careless.

              -

              download film 21 blackjack subtitle indonesia full movie
              -nonton film 21 blackjack sub indo full movie gratis
              -streaming film 21 blackjack sub indo full movie online
              -download film 21 blackjack sub indo full movie mp4
              -download film 21 blackjack sub indo full movie hd
              -download film 21 blackjack sub indo full movie lk21
              -download film 21 blackjack sub indo full movie indoxxi
              -download film 21 blackjack sub indo full movie ganool
              -download film 21 blackjack sub indo full movie terbaru
              -download film 21 blackjack sub indo full movie bluray
              -download film 21 blackjack sub indo full movie 480p
              -download film 21 blackjack sub indo full movie 720p
              -download film 21 blackjack sub indo full movie google drive
              -download film 21 blackjack sub indo full movie bioskopkeren
              -download film 21 blackjack sub indo full movie juraganfilm
              -download film 21 blackjack sub indo full movie dunia21
              -download film 21 blackjack sub indo full movie cinemaindo
              -download film 21 blackjack sub indo full movie layarkaca21
              -download film 21 blackjack sub indo full movie netflix
              -download film 21 blackjack sub indo full movie xxi
              -download film 21 blackjack sub indo full movie kawanfilm
              -download film 21 blackjack sub indo full movie rebahin
              -download film 21 blackjack sub indo full movie filmapik
              -download film 21 blackjack sub indo full movie dramaindo
              -download film 21 blackjack sub indo full movie drakorindo
              -download film 21 blackjack sub indo full movie sobatkeren
              -download film 21 blackjack sub indo full movie nontonkeren
              -download film 21 blackjack sub indo full movie dutafilm
              -download film 21 blackjack sub indo full movie savefilm21
              -download film 21 blackjack sub indo full movie oploverz
              -download film 21 blackjack sub indo full movie animeindo
              -download film 21 blackjack sub indo full movie samehadaku
              -download film 21 blackjack sub indo full movie anoboy
              -download film 21 blackjack sub indo full movie nanime
              -download film 21 blackjack sub indo full movie otakudesu
              -download film 21 blackjack sub indo full movie nekopoi
              -download film 21 blackjack sub indo full movie meownime
              -download film 21 blackjack sub indo full movie awsubs
              -download film 21 blackjack sub indo full movie gomunime
              -download film 21 blackjack sub indo full movie kusonime
              -cara mudah download film 21 blackjack sub indo full movie
              -situs terbaik untuk download film 21 blackjack sub indo full movie
              -link alternatif untuk download film 21 blackjack sub indo full movie
              -tips dan trik untuk download film 21 blackjack sub indo full movie
              -review dan sinopsis untuk download film 21 blackjack sub indo full movie
              -rekomendasi dan rating untuk download film 21 blackjack sub indo full movie
              -daftar pemeran dan sutradara untuk download film 21 blackjack sub indo full movie
              -fakta dan trivia untuk download film 21 blackjack sub indo full movie
              -soundtrack dan lagu tema untuk download film 21 blackjack sub indo full movie

              -

              The MIT Blackjack Team also employed a team approach, which involved having different roles for each member. The main roles were:

              -
                -
              • The spotter: This was the person who counted the cards and kept track of the true count. The spotter would bet the minimum and signal to the other members when the count was high.
              • -
              • The big player: This was the person who joined the table when the count was high and bet large amounts of money. The big player acted as if they were a rich and reckless gambler who did not know how to play blackjack well.
              • -
              • The gorilla: This was the person who also joined the table when the count was high and bet large amounts of money. The gorilla did not count cards but followed a simple set of rules based on the spotter's signals.
              • -
              • The back-spotter: This was the person who watched the tables from a distance and counted the cards. The back-spotter would signal to the other members when a table was hot or when there was a threat from the casino.
              • -
              -

              The MIT Blackjack Team used these roles and strategies to win millions of dollars from casinos around the world, especially in Atlantic City and Las Vegas. They also faced many challenges and risks from the casinos, such as being banned, blacklisted, followed, threatened, or physically assaulted by casino security or private investigators. Some of the team members were also arrested or sued by the casinos for cheating or trespassing.

              -

              The Film 21: How It Adapted the True Story of the MIT Blackjack Team

              -

              Now that we have learned more about the story of the MIT Blackjack Team, let us see how it was adapted into

              Now that we have learned more about the story of the MIT Blackjack Team, let us see how it was adapted into the film 21. The film 21 is loosely based on the book Bringing Down the House by Ben Mezrich, which was published in 2003 and became a bestseller. The book is a fictionalized account of the experiences of one of the former members of the MIT Blackjack Team, who used the pseudonym Kevin Lewis. The book chronicles how Lewis joined the team, learned the skills and techniques of card counting, and participated in various heists and escapades in casinos around the world.

              -

              The film 21 follows a similar plot as the book, but with some changes and additions. The main character is Ben Campbell, played by Jim Sturgess, a brilliant but shy MIT student who needs money to pay for his tuition at Harvard Medical School. He is recruited by his math professor Micky Rosa, played by Kevin Spacey, who leads a secret blackjack team composed of other talented students. The team members are Jill Taylor, played by Kate Bosworth, Choi, played by Aaron Yoo, Kianna, played by Liza Lapira, and Fisher, played by Jacob Pitts. They travel to Las Vegas on weekends and use card counting and covert signalling to win large sums of money from the casinos.

              -

              The film 21 differs from the book and the true story of the MIT Blackjack Team in several ways. For example:

              -
                -
              • The film 21 changes the ethnicity and names of most of the characters. In reality, most of the members of the MIT Blackjack Team were Asian-American, but in the film they are mostly white. The film also uses different names for the characters, such as Ben Campbell instead of Kevin Lewis, Micky Rosa instead of John Chang or Bill Kaplan, and Cole Williams instead of Andy Anderson.
              • -
              • The film 21 exaggerates some of the events and situations that occurred in the book and in reality. For instance, the film depicts Ben Campbell as having a photographic memory and being able to memorize codes and signals in a short time. The film also shows the team using elaborate disguises and gadgets, such as wigs, fake IDs, hidden earpieces, and infrared cameras. The film also adds some scenes that did not happen in reality, such as a chase scene in a casino, a confrontation with a rival team, and a betrayal by Micky Rosa.
              • -
              • The film 21 simplifies some of the aspects and details of card counting and blackjack. For example, the film does not explain how the team calculated the true count or how they adjusted their bets according to different rules and situations. The film also does not show how the team dealt with other factors that could affect their performance, such as casino heat, dealer errors, shuffle tracking, or team play variations.
              • -
              -

              Despite these differences, the film 21 still captures some of the essence and spirit of the story of the MIT Blackjack Team. The film showcases some of the scenes and locations that were featured in the book and in reality, such as the MIT campus, the Las Vegas Strip, and various casinos such as Planet Hollywood, Red Rock Casino Resort & Spa, The Venetian Las Vegas, Hard Rock Hotel and Casino (Las Vegas), and Riviera Hotel and Casino. The film also portrays some of

              Despite these differences, the film 21 still captures some of the essence and spirit of the story of the MIT Blackjack Team. The film showcases some of the scenes and locations that were featured in the book and in reality, such as the MIT campus, the Las Vegas Strip, and various casinos such as Planet Hollywood, Red Rock Casino Resort & Spa, The Venetian Las Vegas, Hard Rock Hotel and Casino (Las Vegas), and Riviera Hotel and Casino. The film also portrays some of the thrill and drama of card counting and casino gambling, such as the excitement of winning big, the tension of avoiding detection, the conflict between loyalty and greed, and the consequences of breaking the rules.

              -

              How to Download Film 21 Blackjack Sub Indo Full Movie: The Best Sites and Platforms

              -

              Now that we have a better understanding of what the film 21 is about and how it relates to the story of the MIT Blackjack Team, let us move on to how to download film 21 blackjack sub indo full movie online. There are many reasons why you might want to download film 21 blackjack sub indo full movie online, such as:

              -
                -
              • You want to watch the film with subtitles in Indonesian language, which might not be available on streaming platforms or DVD releases.
              • -
              • You want to save money and time by not having to pay for a subscription or a rental fee, or by not having to wait for delivery or availability.
              • -
              • You want to have more control and flexibility over when and how you watch the film, such as being able to pause, rewind, fast forward, or skip scenes.
              • -
              • You want to have a backup copy of the film in case you lose access to it or it gets removed from online sources.
              • -
              -

              However, there are also some drawbacks and risks of downloading film 21 blackjack sub indo full movie online, such as:

              -
                -
              • You might violate the intellectual property rights of the filmmakers and distributors, who own the exclusive rights to reproduce, distribute, display, and perform the film. Downloading film 21 blackjack sub indo full movie online without their permission or authorization might constitute piracy or infringement, which could result in legal action or penalties.
              • -
              • You might expose your device or network to malware or viruses, which could harm your data or system. Downloading film 21 blackjack sub indo full movie online from untrusted or illegal sources might contain malicious software or code that could infect your device or network with spyware, ransomware, trojans, worms, or other types of malware.
              • -
              • You might compromise your privacy or security, which could endanger your identity or information. Downloading film 21 blackjack sub indo full movie online from unsecured or unencrypted sources might expose your IP address, location, browsing history, or personal information to third parties who could monitor, track, or steal your data.
              • -
              -

              Therefore, if you decide to download film 21 blackjack sub indo full movie online, you need to be careful and responsible. You need to weigh the pros and cons of downloading film 21 blackjack sub indo full movie online, and respect the rights and interests of the filmmakers and distributors. You also need to choose reliable and reputable sites and platforms to download film 21 blackjack sub indo full movie online safely and securely. Here are some of the best sites and platforms to download film 21 blackjack sub indo full movie online:

              - - - - - - - - - - - - - - - - - - - - - - - - - -
              Site/PlatformFeaturesAdvantagesDisadvantages
              Layarkaca21- A popular Indonesian website that offers a large collection of movies and TV shows in various genres and languages.
              - Provides high-quality video and audio files in different formats and resolutions.
              - Allows users to download film 21 blackjack sub indo full movie online for free with no registration or subscription required.
              - Has a user-friendly interface and a fast download speed.
              - Has a wide range of options for subtitles in different languages.
              - Has a loyal and active community of users who provide feedback and ratings.
              - Has a lot of pop-up ads and redirects that could be annoying or harmful.
              - Has a limited server capacity that could cause buffering or downtime.
              - Has a questionable legality and legitimacy that could raise ethical or legal issues.
              Netflix- A leading global streaming platform that offers a vast library of movies and TV shows in various genres and languages.
              - Provides high-quality video and audio files in different formats and resolutions.
              - Allows users to download film 21 blackjack sub indo full movie online for offline viewing with a paid subscription plan.
              - Has a professional and reputable service that guarantees quality and security.
              - Has a flexible and convenient feature that allows users to watch offline on any device.< - Has a flexible and convenient feature that allows users to watch offline on any device.
              - Has a personalized and customized recommendation system that suggests movies and TV shows based on the user's preferences and interests.
              - Requires a monthly or annual fee to access the content.
              - Has a limited availability and selection of content depending on the region or country.
              - Has a strict policy and terms of service that restricts the use and sharing of the content.
              YouTube- A popular global video-sharing platform that offers a variety of content in various genres and languages.
              - Provides high-quality video and audio files in different formats and resolutions.
              - Allows users to download film 21 blackjack sub indo full movie online for offline viewing with a paid subscription plan or a third-party software or website.
              - Has a simple and easy-to-use interface and a fast download speed.
              - Has a huge and diverse collection of content that caters to different tastes and needs.
              - Has a social and interactive feature that allows users to comment, like, share, and subscribe to the content.
              - Requires a paid subscription plan or a third-party software or website to download the content.
              - Has a low reliability and quality of some of the content that could be pirated, illegal, or inappropriate.
              - Has a potential risk of violating the intellectual property rights of the content creators or owners.
              -

              Conclusion: Why You Should Watch Film 21 Blackjack Sub Indo Full Movie

              -

              In conclusion, film 21 blackjack sub indo full movie is a film that you should watch if you are interested in the story of the MIT Blackjack Team and how they used card counting and covert signalling to beat the casinos at blackjack. The film is a thrilling and entertaining adaptation of the true story, but it also deviates from some of the facts and details. Therefore, you should also do some research on the real story of the MIT Blackjack Team and how it differs from the film. You can also read the book Bringing Down the House by Ben Mezrich, which was the source material for the film.

              -

              If you want to watch film 21 blackjack sub indo full movie with subtitles in Indonesian language, you can download it online from various sites and platforms. However, you need to be careful and responsible when downloading film 21 blackjack sub indo full movie online, as there are some benefits and drawbacks, as well as some legal and ethical issues involved. You need to respect the rights and interests of the filmmakers and distributors, and choose reliable and reputable sources to download film 21 blackjack sub indo full movie online safely and securely.

              -

              Watching film 21 blackjack sub indo full movie can be a fun and educational experience for you. You can learn more about card counting, blackjack, casino gambling, mathematics, and teamwork. You can also enjoy the drama, suspense, action, and romance of the film. You can also compare and contrast the film with the true story of the MIT Blackjack Team and see how they are similar or different. You can also share your thoughts and opinions on the film with your friends or family.

              -

              So what are you waiting for? Download film 21 blackjack sub indo full movie online today and watch it with subtitles in your preferred language. You will not regret it!

              -

              FAQs

              -

              Here are some frequently asked questions about film 21 blackjack sub indo full movie:

              -
                -
              1. Is film 21 blackjack sub indo full movie based on a true story?
              2. -

                Yes, film 21 blackjack sub indo full movie is based on the true story of the MIT Blackjack Team, a group of students from Massachusetts Institute of Technology who used card counting and covert signalling to beat casinos at blackjack in the 1980s and 1990s. However, the film also changes some of the facts and details of the true story, such as the names, ethnicities, events, and situations of the characters.

                -
              3. Who are the actors in film 21 blackjack sub indo full movie?
              4. -

                The main actors in film 21 blackjack sub indo full movie are Jim Sturgess as Ben Campbell, Kevin Spacey as Micky Rosa, Laurence Fishburne as Cole Williams, Kate Bosworth as Jill Taylor, Liza Lapira as Kianna, Jacob Pitts as Fisher, Aaron Yoo as Choi, and Kieu Chinh as Ben's mother.

                -
              5. Where can I watch film 21 blackjack sub indo full movie online?
              6. -

                You can watch film 21 blackjack sub indo full movie online on various sites

                You can watch film 21 blackjack sub indo full movie online on various sites and platforms, such as Layarkaca21, Netflix, and YouTube. However, you need to be careful and responsible when watching film 21 blackjack sub indo full movie online, as there are some benefits and drawbacks, as well as some legal and ethical issues involved. You need to respect the rights and interests of the filmmakers and distributors, and choose reliable and reputable sources to watch film 21 blackjack sub indo full movie online safely and securely.

                -
              7. How long is film 21 blackjack sub indo full movie?
              8. -

                Film 21 blackjack sub indo full movie has a runtime of 123 minutes, or 2 hours and 3 minutes. The film was released on March 28, 2008 in the United States and on April 11, 2008 in Indonesia.

                -
              9. What are some of the reviews and ratings of film 21 blackjack sub indo full movie?
              10. -

                Film 21 blackjack sub indo full movie has received mixed reviews from critics and audiences. The film has a score of 36% on Rotten Tomatoes, based on 165 reviews, with an average rating of 5.1/10. The film also has a score of 48 out of 100 on Metacritic, based on 29 reviews, indicating "mixed or average reviews". The film has a rating of 6.8 out of 10 on IMDb, based on 228,267 votes, and a rating of 4 out of 5 on Layarkaca21, based on 1,234 votes.

                -

                Some of the positive reviews praise the film for its entertaining and thrilling plot, its talented and charismatic cast, its stylish and slick direction, and its captivating and realistic portrayal of card counting and casino gambling. Some of the negative reviews criticize the film for its inaccurate and exaggerated depiction of the true story, its clichéd and predictable script, its lack of depth and character development, and its moral and ethical ambiguity.

                401be4b1e0
                -
                -
                \ No newline at end of file diff --git a/spaces/tioseFevbu/cartoon-converter/scripts/Download Armand Van Helden - My My My Zippy.md b/spaces/tioseFevbu/cartoon-converter/scripts/Download Armand Van Helden - My My My Zippy.md deleted file mode 100644 index cd8bcc3c6b2859f63a15b5697d45624e21af01eb..0000000000000000000000000000000000000000 --- a/spaces/tioseFevbu/cartoon-converter/scripts/Download Armand Van Helden - My My My Zippy.md +++ /dev/null @@ -1,14 +0,0 @@ - -

                Download Armand Van Helden - My My My Zippy: A Classic Dance Track

                -

                If you are looking for a catchy and upbeat dance track, you might want to download Armand Van Helden - My My My Zippy. This song is a hit single by the American producer and DJ Armand Van Helden, released in 2004 as part of his album Nympho. The song features a sample of the song "Comin' Apart" by Gary Wright, and has a funky and groovy vibe that will make you want to move your feet.

                -

                Download Armand Van Helden - My My My Zippy


                Download File »»» https://urlcod.com/2uHxtG



                -

                Armand Van Helden - My My My Zippy was a top-ten success in several countries, including Australia, Belgium, Denmark and Norway. It also reached number 15 on the UK Singles Chart, and number 2 on the US Dance Club Songs chart. The song has been praised for its catchy hook, energetic production and fun lyrics. The song is about enjoying the moment and having a good time with someone you like.

                -

                The song also has an alternative version, featuring vocals from Tara McDonald, which was released in 2006 and peaked at number 12 in the UK. This version has a more pop-oriented sound, and adds some additional lyrics to the original chorus. The music video for this version features a geeky man who fantasizes about being invited to an all-girls' party at a beach house.

                -

                If you want to download Armand Van Helden - My My My Zippy, you can find it on various online platforms, such as YouTube, Spotify, iTunes and Amazon Music. You can also watch the music videos for both versions of the song on YouTube. Whether you prefer the original or the re-release, this song is sure to make you feel good and dance along.

                - -

                Armand Van Helden - My My My Zippy is not only a great song by itself, but also a source of inspiration for many remixes and covers. The song has been remixed by various artists, such as Ashley Beedle, Deekline & Wizard, Stonebridge and DJ Kuba & Neitan. These remixes add different elements and styles to the original track, such as house, breakbeat, electro and bass. Some of these remixes have been released as official singles, while others are available online or on compilations.

                -

                -

                One of the most popular remixes of Armand Van Helden - My My My Zippy is the Original Club Mix, featuring Tara McDonald. This version was released in 2006 as a re-release of the original song, and has a more pop-oriented sound. The remix adds some additional lyrics to the original chorus, sung by Tara McDonald, who is a British singer and songwriter. She has also collaborated with other dance music producers, such as David Guetta, Axwell and Todd Terry.

                -

                Another notable remix of Armand Van Helden - My My My Zippy is the one by DJ Kuba & Neitan, which was released in 2019. This remix has a more modern and energetic sound, with a heavy bassline and catchy drops. The remix also incorporates some vocal samples from the original song, such as "How did we ever get this way?" and "What's it gonna take to do it?". The remix has been supported by many DJs and radio stations around the world.

                e93f5a0c3f
                -
                -
                \ No newline at end of file diff --git a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/pip/_internal/cli/command_context.py b/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/pip/_internal/cli/command_context.py deleted file mode 100644 index 139995ac3f109a82664e4913f7ebc32ecf7617e1..0000000000000000000000000000000000000000 --- a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/pip/_internal/cli/command_context.py +++ /dev/null @@ -1,27 +0,0 @@ -from contextlib import ExitStack, contextmanager -from typing import ContextManager, Generator, TypeVar - -_T = TypeVar("_T", covariant=True) - - -class CommandContextMixIn: - def __init__(self) -> None: - super().__init__() - self._in_main_context = False - self._main_context = ExitStack() - - @contextmanager - def main_context(self) -> Generator[None, None, None]: - assert not self._in_main_context - - self._in_main_context = True - try: - with self._main_context: - yield - finally: - self._in_main_context = False - - def enter_context(self, context_provider: ContextManager[_T]) -> _T: - assert self._in_main_context - - return self._main_context.enter_context(context_provider) diff --git a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/pip/_internal/commands/configuration.py b/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/pip/_internal/commands/configuration.py deleted file mode 100644 index e3837325986140c96a02cd4d3fa746f5796ecc99..0000000000000000000000000000000000000000 --- a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/pip/_internal/commands/configuration.py +++ /dev/null @@ -1,276 +0,0 @@ -import logging -import os -import subprocess -from optparse import Values -from typing import Any, List, Optional - -from pip._internal.cli.base_command import Command -from pip._internal.cli.status_codes import ERROR, SUCCESS -from pip._internal.configuration import ( - Configuration, - Kind, - get_configuration_files, - kinds, -) -from pip._internal.exceptions import PipError -from pip._internal.utils.logging import indent_log -from pip._internal.utils.misc import get_prog, write_output - -logger = logging.getLogger(__name__) - - -class ConfigurationCommand(Command): - """ - Manage local and global configuration. - - Subcommands: - - - list: List the active configuration (or from the file specified) - - edit: Edit the configuration file in an editor - - get: Get the value associated with command.option - - set: Set the command.option=value - - unset: Unset the value associated with command.option - - debug: List the configuration files and values defined under them - - Configuration keys should be dot separated command and option name, - with the special prefix "global" affecting any command. For example, - "pip config set global.index-url https://example.org/" would configure - the index url for all commands, but "pip config set download.timeout 10" - would configure a 10 second timeout only for "pip download" commands. - - If none of --user, --global and --site are passed, a virtual - environment configuration file is used if one is active and the file - exists. Otherwise, all modifications happen to the user file by - default. - """ - - ignore_require_venv = True - usage = """ - %prog [] list - %prog [] [--editor ] edit - - %prog [] get command.option - %prog [] set command.option value - %prog [] unset command.option - %prog [] debug - """ - - def add_options(self) -> None: - self.cmd_opts.add_option( - "--editor", - dest="editor", - action="store", - default=None, - help=( - "Editor to use to edit the file. Uses VISUAL or EDITOR " - "environment variables if not provided." - ), - ) - - self.cmd_opts.add_option( - "--global", - dest="global_file", - action="store_true", - default=False, - help="Use the system-wide configuration file only", - ) - - self.cmd_opts.add_option( - "--user", - dest="user_file", - action="store_true", - default=False, - help="Use the user configuration file only", - ) - - self.cmd_opts.add_option( - "--site", - dest="site_file", - action="store_true", - default=False, - help="Use the current environment configuration file only", - ) - - self.parser.insert_option_group(0, self.cmd_opts) - - def run(self, options: Values, args: List[str]) -> int: - handlers = { - "list": self.list_values, - "edit": self.open_in_editor, - "get": self.get_name, - "set": self.set_name_value, - "unset": self.unset_name, - "debug": self.list_config_values, - } - - # Determine action - if not args or args[0] not in handlers: - logger.error( - "Need an action (%s) to perform.", - ", ".join(sorted(handlers)), - ) - return ERROR - - action = args[0] - - # Determine which configuration files are to be loaded - # Depends on whether the command is modifying. - try: - load_only = self._determine_file( - options, need_value=(action in ["get", "set", "unset", "edit"]) - ) - except PipError as e: - logger.error(e.args[0]) - return ERROR - - # Load a new configuration - self.configuration = Configuration( - isolated=options.isolated_mode, load_only=load_only - ) - self.configuration.load() - - # Error handling happens here, not in the action-handlers. - try: - handlers[action](options, args[1:]) - except PipError as e: - logger.error(e.args[0]) - return ERROR - - return SUCCESS - - def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]: - file_options = [ - key - for key, value in ( - (kinds.USER, options.user_file), - (kinds.GLOBAL, options.global_file), - (kinds.SITE, options.site_file), - ) - if value - ] - - if not file_options: - if not need_value: - return None - # Default to user, unless there's a site file. - elif any( - os.path.exists(site_config_file) - for site_config_file in get_configuration_files()[kinds.SITE] - ): - return kinds.SITE - else: - return kinds.USER - elif len(file_options) == 1: - return file_options[0] - - raise PipError( - "Need exactly one file to operate upon " - "(--user, --site, --global) to perform." - ) - - def list_values(self, options: Values, args: List[str]) -> None: - self._get_n_args(args, "list", n=0) - - for key, value in sorted(self.configuration.items()): - write_output("%s=%r", key, value) - - def get_name(self, options: Values, args: List[str]) -> None: - key = self._get_n_args(args, "get [name]", n=1) - value = self.configuration.get_value(key) - - write_output("%s", value) - - def set_name_value(self, options: Values, args: List[str]) -> None: - key, value = self._get_n_args(args, "set [name] [value]", n=2) - self.configuration.set_value(key, value) - - self._save_configuration() - - def unset_name(self, options: Values, args: List[str]) -> None: - key = self._get_n_args(args, "unset [name]", n=1) - self.configuration.unset_value(key) - - self._save_configuration() - - def list_config_values(self, options: Values, args: List[str]) -> None: - """List config key-value pairs across different config files""" - self._get_n_args(args, "debug", n=0) - - self.print_env_var_values() - # Iterate over config files and print if they exist, and the - # key-value pairs present in them if they do - for variant, files in sorted(self.configuration.iter_config_files()): - write_output("%s:", variant) - for fname in files: - with indent_log(): - file_exists = os.path.exists(fname) - write_output("%s, exists: %r", fname, file_exists) - if file_exists: - self.print_config_file_values(variant) - - def print_config_file_values(self, variant: Kind) -> None: - """Get key-value pairs from the file of a variant""" - for name, value in self.configuration.get_values_in_config(variant).items(): - with indent_log(): - write_output("%s: %s", name, value) - - def print_env_var_values(self) -> None: - """Get key-values pairs present as environment variables""" - write_output("%s:", "env_var") - with indent_log(): - for key, value in sorted(self.configuration.get_environ_vars()): - env_var = f"PIP_{key.upper()}" - write_output("%s=%r", env_var, value) - - def open_in_editor(self, options: Values, args: List[str]) -> None: - editor = self._determine_editor(options) - - fname = self.configuration.get_file_to_edit() - if fname is None: - raise PipError("Could not determine appropriate file.") - - try: - subprocess.check_call([editor, fname]) - except FileNotFoundError as e: - if not e.filename: - e.filename = editor - raise - except subprocess.CalledProcessError as e: - raise PipError( - "Editor Subprocess exited with exit code {}".format(e.returncode) - ) - - def _get_n_args(self, args: List[str], example: str, n: int) -> Any: - """Helper to make sure the command got the right number of arguments""" - if len(args) != n: - msg = ( - "Got unexpected number of arguments, expected {}. " - '(example: "{} config {}")' - ).format(n, get_prog(), example) - raise PipError(msg) - - if n == 1: - return args[0] - else: - return args - - def _save_configuration(self) -> None: - # We successfully ran a modifying command. Need to save the - # configuration. - try: - self.configuration.save() - except Exception: - logger.exception( - "Unable to save configuration. Please report this as a bug." - ) - raise PipError("Internal Error.") - - def _determine_editor(self, options: Values) -> str: - if options.editor is not None: - return options.editor - elif "VISUAL" in os.environ: - return os.environ["VISUAL"] - elif "EDITOR" in os.environ: - return os.environ["EDITOR"] - else: - raise PipError("Could not determine editor to use.") diff --git a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/setuptools/_vendor/packaging/requirements.py b/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/setuptools/_vendor/packaging/requirements.py deleted file mode 100644 index 0d93231b4613b27acd2bf7c1283d4ae99d595bdc..0000000000000000000000000000000000000000 --- a/spaces/tjburns/ask_marcus_aurelius/.venv/lib/python3.10/site-packages/setuptools/_vendor/packaging/requirements.py +++ /dev/null @@ -1,146 +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. - -import re -import string -import urllib.parse -from typing import List, Optional as TOptional, Set - -from setuptools.extern.pyparsing import ( # noqa - Combine, - Literal as L, - Optional, - ParseException, - Regex, - Word, - ZeroOrMore, - originalTextFor, - stringEnd, - stringStart, -) - -from .markers import MARKER_EXPR, Marker -from .specifiers import LegacySpecifier, Specifier, SpecifierSet - - -class InvalidRequirement(ValueError): - """ - An invalid requirement was found, users should refer to PEP 508. - """ - - -ALPHANUM = Word(string.ascii_letters + string.digits) - -LBRACKET = L("[").suppress() -RBRACKET = L("]").suppress() -LPAREN = L("(").suppress() -RPAREN = L(")").suppress() -COMMA = L(",").suppress() -SEMICOLON = L(";").suppress() -AT = L("@").suppress() - -PUNCTUATION = Word("-_.") -IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM) -IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END)) - -NAME = IDENTIFIER("name") -EXTRA = IDENTIFIER - -URI = Regex(r"[^ ]+")("url") -URL = AT + URI - -EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA) -EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras") - -VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE) -VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE) - -VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY -VERSION_MANY = Combine( - VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False -)("_raw_spec") -_VERSION_SPEC = Optional((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY) -_VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or "") - -VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier") -VERSION_SPEC.setParseAction(lambda s, l, t: t[1]) - -MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker") -MARKER_EXPR.setParseAction( - lambda s, l, t: Marker(s[t._original_start : t._original_end]) -) -MARKER_SEPARATOR = SEMICOLON -MARKER = MARKER_SEPARATOR + MARKER_EXPR - -VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER) -URL_AND_MARKER = URL + Optional(MARKER) - -NAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER) - -REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd -# setuptools.extern.pyparsing isn't thread safe during initialization, so we do it eagerly, see -# issue #104 -REQUIREMENT.parseString("x[]") - - -class Requirement: - """Parse a requirement. - - Parse a given requirement string into its parts, such as name, specifier, - URL, and extras. Raises InvalidRequirement on a badly-formed requirement - string. - """ - - # TODO: Can we test whether something is contained within a requirement? - # If so how do we do that? Do we need to test against the _name_ of - # the thing as well as the version? What about the markers? - # TODO: Can we normalize the name and extra name? - - def __init__(self, requirement_string: str) -> None: - try: - req = REQUIREMENT.parseString(requirement_string) - except ParseException as e: - raise InvalidRequirement( - f'Parse error at "{ requirement_string[e.loc : e.loc + 8]!r}": {e.msg}' - ) - - self.name: str = req.name - if req.url: - parsed_url = urllib.parse.urlparse(req.url) - if parsed_url.scheme == "file": - if urllib.parse.urlunparse(parsed_url) != req.url: - raise InvalidRequirement("Invalid URL given") - elif not (parsed_url.scheme and parsed_url.netloc) or ( - not parsed_url.scheme and not parsed_url.netloc - ): - raise InvalidRequirement(f"Invalid URL: {req.url}") - self.url: TOptional[str] = req.url - else: - self.url = None - self.extras: Set[str] = set(req.extras.asList() if req.extras else []) - self.specifier: SpecifierSet = SpecifierSet(req.specifier) - self.marker: TOptional[Marker] = req.marker if req.marker else None - - def __str__(self) -> str: - parts: List[str] = [self.name] - - if self.extras: - formatted_extras = ",".join(sorted(self.extras)) - parts.append(f"[{formatted_extras}]") - - if self.specifier: - parts.append(str(self.specifier)) - - if self.url: - parts.append(f"@ {self.url}") - if self.marker: - parts.append(" ") - - if self.marker: - parts.append(f"; {self.marker}") - - return "".join(parts) - - def __repr__(self) -> str: - return f"" diff --git a/spaces/tobiaspires/ad-image-generation/app_v1.py b/spaces/tobiaspires/ad-image-generation/app_v1.py deleted file mode 100644 index 25cefac4b449d624014c515952c7b3bbed9442e7..0000000000000000000000000000000000000000 --- a/spaces/tobiaspires/ad-image-generation/app_v1.py +++ /dev/null @@ -1,85 +0,0 @@ -import gradio as gr -import torch -from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation -from diffusers import StableDiffusionInpaintPipeline -from PIL import Image, ImageOps -import PIL - -# cuda cpu -device_name = 'cpu' -device = torch.device(device_name) - -processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined") -model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined").to(device) -inpainting_pipeline = StableDiffusionInpaintPipeline.from_pretrained("stabilityai/stable-diffusion-2-inpainting").to(device) - - -def numpy_to_pil(images): - if images.ndim == 3: - images = images[None, ...] - images = (images * 255).round().astype("uint8") - - if images.shape[-1] == 1: - # special case for grayscale (single channel) images - pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images] - else: - pil_images = [Image.fromarray(image) for image in images] - - return pil_images - - -def get_mask(text, image): - inputs = processor( - text=[text], images=[image], padding="max_length", return_tensors="pt" - ).to(device) - - outputs = model(**inputs) - mask = torch.sigmoid(outputs.logits).cpu().detach().unsqueeze(-1).numpy() - - mask_pil = numpy_to_pil(mask)[0].resize(image.size) - #mask_pil.show() - return mask_pil - - -def predict(prompt, negative_prompt, image, obj2mask): - mask = get_mask(obj2mask, image) - image = image.convert("RGB").resize((512, 512)) - mask_image = mask.convert("RGB").resize((512, 512)) - mask_image = ImageOps.invert(mask_image) - images = inpainting_pipeline(prompt=prompt, negative_prompt=negative_prompt, image=image, - mask_image=mask_image).images - mask = mask_image.convert('L') - - PIL.Image.composite(images[0], image, mask) - return (images[0]) - - -def inference(prompt, negative_prompt, obj2mask, image_numpy): - generator = torch.Generator() - generator.manual_seed(int(52362)) - - image = numpy_to_pil(image_numpy)[0].convert("RGB").resize((512, 512)) - img = predict(prompt, negative_prompt, image, obj2mask) - return img - - -with gr.Blocks() as demo: - with gr.Row(): - with gr.Column(): - prompt = gr.Textbox(label="Prompt", value="cinematic, landscape, sharpe focus") - negative_prompt = gr.Textbox(label="Negative Prompt", value="illustration, 3d render") - mask = gr.Textbox(label="Mask", value="shoe") - intput_img = gr.Image() - run = gr.Button(value="Generate") - with gr.Column(): - output_img = gr.Image() - - run.click( - inference, - inputs=[prompt, negative_prompt, mask, intput_img - ], - outputs=output_img, - ) - -demo.queue(concurrency_count=1) -demo.launch() diff --git a/spaces/tomofi/MMOCR/configs/_base_/recog_models/crnn.py b/spaces/tomofi/MMOCR/configs/_base_/recog_models/crnn.py deleted file mode 100644 index b316c6a8a7f4f79c0cff3062583391b746f3cad8..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/configs/_base_/recog_models/crnn.py +++ /dev/null @@ -1,12 +0,0 @@ -label_convertor = dict( - type='CTCConvertor', dict_type='DICT36', with_unknown=False, lower=True) - -model = dict( - type='CRNNNet', - preprocessor=None, - backbone=dict(type='VeryDeepVgg', leaky_relu=False, input_channels=1), - encoder=None, - decoder=dict(type='CRNNDecoder', in_channels=512, rnn_flag=True), - loss=dict(type='CTCLoss'), - label_convertor=label_convertor, - pretrained=None) diff --git a/spaces/tomofi/MMOCR/mmocr/core/visualize.py b/spaces/tomofi/MMOCR/mmocr/core/visualize.py deleted file mode 100644 index 35ccdaf523c60f331b5541fd21e460bfb2d59870..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/mmocr/core/visualize.py +++ /dev/null @@ -1,888 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import math -import os -import shutil -import urllib -import warnings - -import cv2 -import mmcv -import numpy as np -import torch -from matplotlib import pyplot as plt -from PIL import Image, ImageDraw, ImageFont - -import mmocr.utils as utils - - -def overlay_mask_img(img, mask): - """Draw mask boundaries on image for visualization. - - Args: - img (ndarray): The input image. - mask (ndarray): The instance mask. - - Returns: - img (ndarray): The output image with instance boundaries on it. - """ - assert isinstance(img, np.ndarray) - assert isinstance(mask, np.ndarray) - - contours, _ = cv2.findContours( - mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) - - cv2.drawContours(img, contours, -1, (0, 255, 0), 1) - - return img - - -def show_feature(features, names, to_uint8, out_file=None): - """Visualize a list of feature maps. - - Args: - features (list(ndarray)): The feature map list. - names (list(str)): The visualized title list. - to_uint8 (list(1|0)): The list indicating whether to convent - feature maps to uint8. - out_file (str): The output file name. If set to None, - the output image will be shown without saving. - """ - assert utils.is_type_list(features, np.ndarray) - assert utils.is_type_list(names, str) - assert utils.is_type_list(to_uint8, int) - assert utils.is_none_or_type(out_file, str) - assert utils.equal_len(features, names, to_uint8) - - num = len(features) - row = col = math.ceil(math.sqrt(num)) - - for i, (f, n) in enumerate(zip(features, names)): - plt.subplot(row, col, i + 1) - plt.title(n) - if to_uint8[i]: - f = f.astype(np.uint8) - plt.imshow(f) - if out_file is None: - plt.show() - else: - plt.savefig(out_file) - - -def show_img_boundary(img, boundary): - """Show image and instance boundaires. - - Args: - img (ndarray): The input image. - boundary (list[float or int]): The input boundary. - """ - assert isinstance(img, np.ndarray) - assert utils.is_type_list(boundary, (int, float)) - - cv2.polylines( - img, [np.array(boundary).astype(np.int32).reshape(-1, 1, 2)], - True, - color=(0, 255, 0), - thickness=1) - plt.imshow(img) - plt.show() - - -def show_pred_gt(preds, - gts, - show=False, - win_name='', - wait_time=0, - out_file=None): - """Show detection and ground truth for one image. - - Args: - preds (list[list[float]]): The detection boundary list. - gts (list[list[float]]): The ground truth boundary list. - show (bool): Whether to show the image. - win_name (str): The window name. - wait_time (int): The value of waitKey param. - out_file (str): The filename of the output. - """ - assert utils.is_2dlist(preds) - assert utils.is_2dlist(gts) - assert isinstance(show, bool) - assert isinstance(win_name, str) - assert isinstance(wait_time, int) - assert utils.is_none_or_type(out_file, str) - - p_xy = [p for boundary in preds for p in boundary] - gt_xy = [g for gt in gts for g in gt] - - max_xy = np.max(np.array(p_xy + gt_xy).reshape(-1, 2), axis=0) - - width = int(max_xy[0]) + 100 - height = int(max_xy[1]) + 100 - - img = np.ones((height, width, 3), np.int8) * 255 - pred_color = mmcv.color_val('red') - gt_color = mmcv.color_val('blue') - thickness = 1 - - for boundary in preds: - cv2.polylines( - img, [np.array(boundary).astype(np.int32).reshape(-1, 1, 2)], - True, - color=pred_color, - thickness=thickness) - for gt in gts: - cv2.polylines( - img, [np.array(gt).astype(np.int32).reshape(-1, 1, 2)], - True, - color=gt_color, - thickness=thickness) - if show: - mmcv.imshow(img, win_name, wait_time) - if out_file is not None: - mmcv.imwrite(img, out_file) - - return img - - -def imshow_pred_boundary(img, - boundaries_with_scores, - labels, - score_thr=0, - boundary_color='blue', - text_color='blue', - thickness=1, - font_scale=0.5, - show=True, - win_name='', - wait_time=0, - out_file=None, - show_score=False): - """Draw boundaries and class labels (with scores) on an image. - - Args: - img (str or ndarray): The image to be displayed. - boundaries_with_scores (list[list[float]]): Boundaries with scores. - labels (list[int]): Labels of boundaries. - score_thr (float): Minimum score of boundaries to be shown. - boundary_color (str or tuple or :obj:`Color`): Color of boundaries. - text_color (str or tuple or :obj:`Color`): Color of texts. - thickness (int): Thickness of lines. - font_scale (float): Font scales of texts. - show (bool): Whether to show the image. - win_name (str): The window name. - wait_time (int): Value of waitKey param. - out_file (str or None): The filename of the output. - show_score (bool): Whether to show text instance score. - """ - assert isinstance(img, (str, np.ndarray)) - assert utils.is_2dlist(boundaries_with_scores) - assert utils.is_type_list(labels, int) - assert utils.equal_len(boundaries_with_scores, labels) - if len(boundaries_with_scores) == 0: - warnings.warn('0 text found in ' + out_file) - return None - - utils.valid_boundary(boundaries_with_scores[0]) - img = mmcv.imread(img) - - scores = np.array([b[-1] for b in boundaries_with_scores]) - inds = scores > score_thr - boundaries = [boundaries_with_scores[i][:-1] for i in np.where(inds)[0]] - scores = [scores[i] for i in np.where(inds)[0]] - labels = [labels[i] for i in np.where(inds)[0]] - - boundary_color = mmcv.color_val(boundary_color) - text_color = mmcv.color_val(text_color) - font_scale = 0.5 - - for boundary, score in zip(boundaries, scores): - boundary_int = np.array(boundary).astype(np.int32) - - cv2.polylines( - img, [boundary_int.reshape(-1, 1, 2)], - True, - color=boundary_color, - thickness=thickness) - - if show_score: - label_text = f'{score:.02f}' - cv2.putText(img, label_text, - (boundary_int[0], boundary_int[1] - 2), - cv2.FONT_HERSHEY_COMPLEX, font_scale, text_color) - if show: - mmcv.imshow(img, win_name, wait_time) - if out_file is not None: - mmcv.imwrite(img, out_file) - - return img - - -def imshow_text_char_boundary(img, - text_quads, - boundaries, - char_quads, - chars, - show=False, - thickness=1, - font_scale=0.5, - win_name='', - wait_time=-1, - out_file=None): - """Draw text boxes and char boxes on img. - - Args: - img (str or ndarray): The img to be displayed. - text_quads (list[list[int|float]]): The text boxes. - boundaries (list[list[int|float]]): The boundary list. - char_quads (list[list[list[int|float]]]): A 2d list of char boxes. - char_quads[i] is for the ith text, and char_quads[i][j] is the jth - char of the ith text. - chars (list[list[char]]). The string for each text box. - thickness (int): Thickness of lines. - font_scale (float): Font scales of texts. - show (bool): Whether to show the image. - win_name (str): The window name. - wait_time (int): Value of waitKey param. - out_file (str or None): The filename of the output. - """ - assert isinstance(img, (np.ndarray, str)) - assert utils.is_2dlist(text_quads) - assert utils.is_2dlist(boundaries) - assert utils.is_3dlist(char_quads) - assert utils.is_2dlist(chars) - assert utils.equal_len(text_quads, char_quads, boundaries) - - img = mmcv.imread(img) - char_color = [mmcv.color_val('blue'), mmcv.color_val('green')] - text_color = mmcv.color_val('red') - text_inx = 0 - for text_box, boundary, char_box, txt in zip(text_quads, boundaries, - char_quads, chars): - text_box = np.array(text_box) - boundary = np.array(boundary) - - text_box = text_box.reshape(-1, 2).astype(np.int32) - cv2.polylines( - img, [text_box.reshape(-1, 1, 2)], - True, - color=text_color, - thickness=thickness) - if boundary.shape[0] > 0: - cv2.polylines( - img, [boundary.reshape(-1, 1, 2)], - True, - color=text_color, - thickness=thickness) - - for b in char_box: - b = np.array(b) - c = char_color[text_inx % 2] - b = b.astype(np.int32) - cv2.polylines( - img, [b.reshape(-1, 1, 2)], True, color=c, thickness=thickness) - - label_text = ''.join(txt) - cv2.putText(img, label_text, (text_box[0, 0], text_box[0, 1] - 2), - cv2.FONT_HERSHEY_COMPLEX, font_scale, text_color) - text_inx = text_inx + 1 - - if show: - mmcv.imshow(img, win_name, wait_time) - if out_file is not None: - mmcv.imwrite(img, out_file) - - return img - - -def tile_image(images): - """Combined multiple images to one vertically. - - Args: - images (list[np.ndarray]): Images to be combined. - """ - assert isinstance(images, list) - assert len(images) > 0 - - for i, _ in enumerate(images): - if len(images[i].shape) == 2: - images[i] = cv2.cvtColor(images[i], cv2.COLOR_GRAY2BGR) - - widths = [img.shape[1] for img in images] - heights = [img.shape[0] for img in images] - h, w = sum(heights), max(widths) - vis_img = np.zeros((h, w, 3), dtype=np.uint8) - - offset_y = 0 - for image in images: - img_h, img_w = image.shape[:2] - vis_img[offset_y:(offset_y + img_h), 0:img_w, :] = image - offset_y += img_h - - return vis_img - - -def imshow_text_label(img, - pred_label, - gt_label, - show=False, - win_name='', - wait_time=-1, - out_file=None): - """Draw predicted texts and ground truth texts on images. - - Args: - img (str or np.ndarray): Image filename or loaded image. - pred_label (str): Predicted texts. - gt_label (str): Ground truth texts. - show (bool): Whether to show the image. - win_name (str): The window name. - wait_time (int): Value of waitKey param. - out_file (str): The filename of the output. - """ - assert isinstance(img, (np.ndarray, str)) - assert isinstance(pred_label, str) - assert isinstance(gt_label, str) - assert isinstance(show, bool) - assert isinstance(win_name, str) - assert isinstance(wait_time, int) - - img = mmcv.imread(img) - - src_h, src_w = img.shape[:2] - resize_height = 64 - resize_width = int(1.0 * src_w / src_h * resize_height) - img = cv2.resize(img, (resize_width, resize_height)) - h, w = img.shape[:2] - - if is_contain_chinese(pred_label): - pred_img = draw_texts_by_pil(img, [pred_label], None) - else: - pred_img = np.ones((h, w, 3), dtype=np.uint8) * 255 - cv2.putText(pred_img, pred_label, (5, 40), cv2.FONT_HERSHEY_SIMPLEX, - 0.9, (0, 0, 255), 2) - images = [pred_img, img] - - if gt_label != '': - if is_contain_chinese(gt_label): - gt_img = draw_texts_by_pil(img, [gt_label], None) - else: - gt_img = np.ones((h, w, 3), dtype=np.uint8) * 255 - cv2.putText(gt_img, gt_label, (5, 40), cv2.FONT_HERSHEY_SIMPLEX, - 0.9, (255, 0, 0), 2) - images.append(gt_img) - - img = tile_image(images) - - if show: - mmcv.imshow(img, win_name, wait_time) - if out_file is not None: - mmcv.imwrite(img, out_file) - - return img - - -def imshow_node(img, - result, - boxes, - idx_to_cls={}, - show=False, - win_name='', - wait_time=-1, - out_file=None): - - img = mmcv.imread(img) - h, w = img.shape[:2] - - max_value, max_idx = torch.max(result['nodes'].detach().cpu(), -1) - node_pred_label = max_idx.numpy().tolist() - node_pred_score = max_value.numpy().tolist() - - texts, text_boxes = [], [] - for i, box in enumerate(boxes): - new_box = [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], - [box[0], box[3]]] - Pts = np.array([new_box], np.int32) - cv2.polylines( - img, [Pts.reshape((-1, 1, 2))], - True, - color=(255, 255, 0), - thickness=1) - x_min = int(min([point[0] for point in new_box])) - y_min = int(min([point[1] for point in new_box])) - - # text - pred_label = str(node_pred_label[i]) - if pred_label in idx_to_cls: - pred_label = idx_to_cls[pred_label] - pred_score = '{:.2f}'.format(node_pred_score[i]) - text = pred_label + '(' + pred_score + ')' - texts.append(text) - - # text box - font_size = int( - min( - abs(new_box[3][1] - new_box[0][1]), - abs(new_box[1][0] - new_box[0][0]))) - char_num = len(text) - text_box = [ - x_min * 2, y_min, x_min * 2 + font_size * char_num, y_min, - x_min * 2 + font_size * char_num, y_min + font_size, x_min * 2, - y_min + font_size - ] - text_boxes.append(text_box) - - pred_img = np.ones((h, w * 2, 3), dtype=np.uint8) * 255 - pred_img = draw_texts_by_pil( - pred_img, texts, text_boxes, draw_box=False, on_ori_img=True) - - vis_img = np.ones((h, w * 3, 3), dtype=np.uint8) * 255 - vis_img[:, :w] = img - vis_img[:, w:] = pred_img - - if show: - mmcv.imshow(vis_img, win_name, wait_time) - if out_file is not None: - mmcv.imwrite(vis_img, out_file) - - return vis_img - - -def gen_color(): - """Generate BGR color schemes.""" - color_list = [(101, 67, 254), (154, 157, 252), (173, 205, 249), - (123, 151, 138), (187, 200, 178), (148, 137, 69), - (169, 200, 200), (155, 175, 131), (154, 194, 182), - (178, 190, 137), (140, 211, 222), (83, 156, 222)] - return color_list - - -def draw_polygons(img, polys): - """Draw polygons on image. - - Args: - img (np.ndarray): The original image. - polys (list[list[float]]): Detected polygons. - Return: - out_img (np.ndarray): Visualized image. - """ - dst_img = img.copy() - color_list = gen_color() - out_img = dst_img - for idx, poly in enumerate(polys): - poly = np.array(poly).reshape((-1, 1, 2)).astype(np.int32) - cv2.drawContours( - img, - np.array([poly]), - -1, - color_list[idx % len(color_list)], - thickness=cv2.FILLED) - out_img = cv2.addWeighted(dst_img, 0.5, img, 0.5, 0) - return out_img - - -def get_optimal_font_scale(text, width): - """Get optimal font scale for cv2.putText. - - Args: - text (str): Text in one box. - width (int): The box width. - """ - for scale in reversed(range(0, 60, 1)): - textSize = cv2.getTextSize( - text, - fontFace=cv2.FONT_HERSHEY_SIMPLEX, - fontScale=scale / 10, - thickness=1) - new_width = textSize[0][0] - if new_width <= width: - return scale / 10 - return 1 - - -def draw_texts(img, texts, boxes=None, draw_box=True, on_ori_img=False): - """Draw boxes and texts on empty img. - - Args: - img (np.ndarray): The original image. - texts (list[str]): Recognized texts. - boxes (list[list[float]]): Detected bounding boxes. - draw_box (bool): Whether draw box or not. If False, draw text only. - on_ori_img (bool): If True, draw box and text on input image, - else, on a new empty image. - Return: - out_img (np.ndarray): Visualized image. - """ - color_list = gen_color() - h, w = img.shape[:2] - if boxes is None: - boxes = [[0, 0, w, 0, w, h, 0, h]] - assert len(texts) == len(boxes) - - if on_ori_img: - out_img = img - else: - out_img = np.ones((h, w, 3), dtype=np.uint8) * 255 - for idx, (box, text) in enumerate(zip(boxes, texts)): - if draw_box: - new_box = [[x, y] for x, y in zip(box[0::2], box[1::2])] - Pts = np.array([new_box], np.int32) - cv2.polylines( - out_img, [Pts.reshape((-1, 1, 2))], - True, - color=color_list[idx % len(color_list)], - thickness=1) - min_x = int(min(box[0::2])) - max_y = int( - np.mean(np.array(box[1::2])) + 0.2 * - (max(box[1::2]) - min(box[1::2]))) - font_scale = get_optimal_font_scale( - text, int(max(box[0::2]) - min(box[0::2]))) - cv2.putText(out_img, text, (min_x, max_y), cv2.FONT_HERSHEY_SIMPLEX, - font_scale, (0, 0, 0), 1) - - return out_img - - -def draw_texts_by_pil(img, - texts, - boxes=None, - draw_box=True, - on_ori_img=False, - font_size=None, - fill_color=None, - draw_pos=None, - return_text_size=False): - """Draw boxes and texts on empty image, especially for Chinese. - - Args: - img (np.ndarray): The original image. - texts (list[str]): Recognized texts. - boxes (list[list[float]]): Detected bounding boxes. - draw_box (bool): Whether draw box or not. If False, draw text only. - on_ori_img (bool): If True, draw box and text on input image, - else on a new empty image. - font_size (int, optional): Size to create a font object for a font. - fill_color (tuple(int), optional): Fill color for text. - draw_pos (list[tuple(int)], optional): Start point to draw each text. - return_text_size (bool): If True, return the list of text size. - - Returns: - (np.ndarray, list[tuple]) or np.ndarray: Return a tuple - ``(out_img, text_sizes)``, where ``out_img`` is the output image - with texts drawn on it and ``text_sizes`` are the size of drawing - texts. If ``return_text_size`` is False, only the output image will be - returned. - """ - - color_list = gen_color() - h, w = img.shape[:2] - if boxes is None: - boxes = [[0, 0, w, 0, w, h, 0, h]] - if draw_pos is None: - draw_pos = [None for _ in texts] - assert len(boxes) == len(texts) == len(draw_pos) - - if fill_color is None: - fill_color = (0, 0, 0) - - if on_ori_img: - out_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) - else: - out_img = Image.new('RGB', (w, h), color=(255, 255, 255)) - out_draw = ImageDraw.Draw(out_img) - - text_sizes = [] - for idx, (box, text, ori_point) in enumerate(zip(boxes, texts, draw_pos)): - if len(text) == 0: - continue - min_x, max_x = min(box[0::2]), max(box[0::2]) - min_y, max_y = min(box[1::2]), max(box[1::2]) - color = tuple(list(color_list[idx % len(color_list)])[::-1]) - if draw_box: - out_draw.line(box, fill=color, width=1) - dirname, _ = os.path.split(os.path.abspath(__file__)) - font_path = os.path.join(dirname, 'font.TTF') - if not os.path.exists(font_path): - url = ('https://download.openmmlab.com/mmocr/data/font.TTF') - print(f'Downloading {url} ...') - local_filename, _ = urllib.request.urlretrieve(url) - shutil.move(local_filename, font_path) - tmp_font_size = font_size - if tmp_font_size is None: - box_width = max(max_x - min_x, max_y - min_y) - tmp_font_size = int(0.9 * box_width / len(text)) - fnt = ImageFont.truetype(font_path, tmp_font_size) - if ori_point is None: - ori_point = (min_x + 1, min_y + 1) - out_draw.text(ori_point, text, font=fnt, fill=fill_color) - text_sizes.append(fnt.getsize(text)) - - del out_draw - - out_img = cv2.cvtColor(np.asarray(out_img), cv2.COLOR_RGB2BGR) - - if return_text_size: - return out_img, text_sizes - - return out_img - - -def is_contain_chinese(check_str): - """Check whether string contains Chinese or not. - - Args: - check_str (str): String to be checked. - - Return True if contains Chinese, else False. - """ - for ch in check_str: - if u'\u4e00' <= ch <= u'\u9fff': - return True - return False - - -def det_recog_show_result(img, end2end_res, out_file=None): - """Draw `result`(boxes and texts) on `img`. - - Args: - img (str or np.ndarray): The image to be displayed. - end2end_res (dict): Text detect and recognize results. - out_file (str): Image path where the visualized image should be saved. - Return: - out_img (np.ndarray): Visualized image. - """ - img = mmcv.imread(img) - boxes, texts = [], [] - for res in end2end_res['result']: - boxes.append(res['box']) - texts.append(res['text']) - box_vis_img = draw_polygons(img, boxes) - - if is_contain_chinese(''.join(texts)): - text_vis_img = draw_texts_by_pil(img, texts, boxes) - else: - text_vis_img = draw_texts(img, texts, boxes) - - h, w = img.shape[:2] - out_img = np.ones((h, w * 2, 3), dtype=np.uint8) - out_img[:, :w, :] = box_vis_img - out_img[:, w:, :] = text_vis_img - - if out_file: - mmcv.imwrite(out_img, out_file) - - return out_img - - -def draw_edge_result(img, result, edge_thresh=0.5, keynode_thresh=0.5): - """Draw text and their relationship on empty images. - - Args: - img (np.ndarray): The original image. - result (dict): The result of model forward_test, including: - - img_metas (list[dict]): List of meta information dictionary. - - nodes (Tensor): Node prediction with size: - number_node * node_classes. - - edges (Tensor): Edge prediction with size: number_edge * 2. - edge_thresh (float): Score threshold for edge classification. - keynode_thresh (float): Score threshold for node - (``key``) classification. - - Returns: - np.ndarray: The image with key, value and relation drawn on it. - """ - - h, w = img.shape[:2] - - vis_area_width = w // 3 * 2 - vis_area_height = h - dist_key_to_value = vis_area_width // 2 - dist_pair_to_pair = 30 - - bbox_x1 = dist_pair_to_pair - bbox_y1 = 0 - - new_w = vis_area_width - new_h = vis_area_height - pred_edge_img = np.ones((new_h, new_w, 3), dtype=np.uint8) * 255 - - nodes = result['nodes'].detach().cpu() - texts = result['img_metas'][0]['ori_texts'] - num_nodes = result['nodes'].size(0) - edges = result['edges'].detach().cpu()[:, -1].view(num_nodes, num_nodes) - - # (i, j) will be a valid pair - # either edge_score(node_i->node_j) > edge_thresh - # or edge_score(node_j->node_i) > edge_thresh - pairs = (torch.max(edges, edges.T) > edge_thresh).nonzero(as_tuple=True) - pairs = (pairs[0].numpy().tolist(), pairs[1].numpy().tolist()) - - # 1. "for n1, n2 in zip(*pairs) if n1 < n2": - # Only (n1, n2) will be included if n1 < n2 but not (n2, n1), to - # avoid duplication. - # 2. "(n1, n2) if nodes[n1, 1] > nodes[n1, 2]": - # nodes[n1, 1] is the score that this node is predicted as key, - # nodes[n1, 2] is the score that this node is predicted as value. - # If nodes[n1, 1] > nodes[n1, 2], n1 will be the index of key, - # so that n2 will be the index of value. - result_pairs = [(n1, n2) if nodes[n1, 1] > nodes[n1, 2] else (n2, n1) - for n1, n2 in zip(*pairs) if n1 < n2] - - result_pairs.sort() - result_pairs_score = [ - torch.max(edges[n1, n2], edges[n2, n1]) for n1, n2 in result_pairs - ] - - key_current_idx = -1 - pos_current = (-1, -1) - newline_flag = False - - key_font_size = 15 - value_font_size = 15 - key_font_color = (0, 0, 0) - value_font_color = (0, 0, 255) - arrow_color = (0, 0, 255) - score_color = (0, 255, 0) - for pair, pair_score in zip(result_pairs, result_pairs_score): - key_idx = pair[0] - if nodes[key_idx, 1] < keynode_thresh: - continue - if key_idx != key_current_idx: - # move y-coords down for a new key - bbox_y1 += 10 - # enlarge blank area to show key-value info - if newline_flag: - bbox_x1 += vis_area_width - tmp_img = np.ones( - (new_h, new_w + vis_area_width, 3), dtype=np.uint8) * 255 - tmp_img[:new_h, :new_w] = pred_edge_img - pred_edge_img = tmp_img - new_w += vis_area_width - newline_flag = False - bbox_y1 = 10 - key_text = texts[key_idx] - key_pos = (bbox_x1, bbox_y1) - value_idx = pair[1] - value_text = texts[value_idx] - value_pos = (bbox_x1 + dist_key_to_value, bbox_y1) - if key_idx != key_current_idx: - # draw text for a new key - key_current_idx = key_idx - pred_edge_img, text_sizes = draw_texts_by_pil( - pred_edge_img, [key_text], - draw_box=False, - on_ori_img=True, - font_size=key_font_size, - fill_color=key_font_color, - draw_pos=[key_pos], - return_text_size=True) - pos_right_bottom = (key_pos[0] + text_sizes[0][0], - key_pos[1] + text_sizes[0][1]) - pos_current = (pos_right_bottom[0] + 5, bbox_y1 + 10) - pred_edge_img = cv2.arrowedLine( - pred_edge_img, (pos_right_bottom[0] + 5, bbox_y1 + 10), - (bbox_x1 + dist_key_to_value - 5, bbox_y1 + 10), arrow_color, - 1) - score_pos_x = int( - (pos_right_bottom[0] + bbox_x1 + dist_key_to_value) / 2.) - score_pos_y = bbox_y1 + 10 - int(key_font_size * 0.3) - else: - # draw arrow from key to value - if newline_flag: - tmp_img = np.ones((new_h + dist_pair_to_pair, new_w, 3), - dtype=np.uint8) * 255 - tmp_img[:new_h, :new_w] = pred_edge_img - pred_edge_img = tmp_img - new_h += dist_pair_to_pair - pred_edge_img = cv2.arrowedLine(pred_edge_img, pos_current, - (bbox_x1 + dist_key_to_value - 5, - bbox_y1 + 10), arrow_color, 1) - score_pos_x = int( - (pos_current[0] + bbox_x1 + dist_key_to_value - 5) / 2.) - score_pos_y = int((pos_current[1] + bbox_y1 + 10) / 2.) - # draw edge score - cv2.putText(pred_edge_img, '{:.2f}'.format(pair_score), - (score_pos_x, score_pos_y), cv2.FONT_HERSHEY_COMPLEX, 0.4, - score_color) - # draw text for value - pred_edge_img = draw_texts_by_pil( - pred_edge_img, [value_text], - draw_box=False, - on_ori_img=True, - font_size=value_font_size, - fill_color=value_font_color, - draw_pos=[value_pos], - return_text_size=False) - bbox_y1 += dist_pair_to_pair - if bbox_y1 + dist_pair_to_pair >= new_h: - newline_flag = True - - return pred_edge_img - - -def imshow_edge(img, - result, - boxes, - show=False, - win_name='', - wait_time=-1, - out_file=None): - """Display the prediction results of the nodes and edges of the KIE model. - - Args: - img (np.ndarray): The original image. - result (dict): The result of model forward_test, including: - - img_metas (list[dict]): List of meta information dictionary. - - nodes (Tensor): Node prediction with size: \ - number_node * node_classes. - - edges (Tensor): Edge prediction with size: number_edge * 2. - boxes (list): The text boxes corresponding to the nodes. - show (bool): Whether to show the image. Default: False. - win_name (str): The window name. Default: '' - wait_time (float): Value of waitKey param. Default: 0. - out_file (str or None): The filename to write the image. - Default: None. - - Returns: - np.ndarray: The image with key, value and relation drawn on it. - """ - img = mmcv.imread(img) - h, w = img.shape[:2] - color_list = gen_color() - - for i, box in enumerate(boxes): - new_box = [[box[0], box[1]], [box[2], box[1]], [box[2], box[3]], - [box[0], box[3]]] - Pts = np.array([new_box], np.int32) - cv2.polylines( - img, [Pts.reshape((-1, 1, 2))], - True, - color=color_list[i % len(color_list)], - thickness=1) - - pred_img_h = h - pred_img_w = w - - pred_edge_img = draw_edge_result(img, result) - pred_img_h = max(pred_img_h, pred_edge_img.shape[0]) - pred_img_w += pred_edge_img.shape[1] - - vis_img = np.zeros((pred_img_h, pred_img_w, 3), dtype=np.uint8) - vis_img[:h, :w] = img - vis_img[:, w:] = 255 - - height_t, width_t = pred_edge_img.shape[:2] - vis_img[:height_t, w:(w + width_t)] = pred_edge_img - - if show: - mmcv.imshow(vis_img, win_name, wait_time) - if out_file is not None: - mmcv.imwrite(vis_img, out_file) - res_dic = { - 'boxes': boxes, - 'nodes': result['nodes'].detach().cpu(), - 'edges': result['edges'].detach().cpu(), - 'metas': result['img_metas'][0] - } - mmcv.dump(res_dic, f'{out_file}_res.pkl') - - return vis_img diff --git a/spaces/tomofi/MMOCR/tests/test_apis/test_utils.py b/spaces/tomofi/MMOCR/tests/test_apis/test_utils.py deleted file mode 100644 index 9d015512e272cd6696c95bbde14c6a52de567163..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MMOCR/tests/test_apis/test_utils.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import copy -import os - -import pytest -from mmcv import Config - -from mmocr.apis.utils import (disable_text_recog_aug_test, - replace_image_to_tensor) - - -@pytest.mark.parametrize('cfg_file', [ - '../configs/textrecog/sar/sar_r31_parallel_decoder_academic.py', -]) -def test_disable_text_recog_aug_test(cfg_file): - tmp_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) - config_file = os.path.join(tmp_dir, cfg_file) - - cfg = Config.fromfile(config_file) - test = cfg.data.test.datasets[0] - - # cfg.data.test.type is 'OCRDataset' - cfg1 = copy.deepcopy(cfg) - test1 = copy.deepcopy(test) - test1.pipeline = cfg1.data.test.pipeline - cfg1.data.test = test1 - cfg1 = disable_text_recog_aug_test(cfg1, set_types=['test']) - assert cfg1.data.test.pipeline[1].type != 'MultiRotateAugOCR' - - # cfg.data.test.type is 'UniformConcatDataset' - # and cfg.data.test.pipeline is list[dict] - cfg2 = copy.deepcopy(cfg) - test2 = copy.deepcopy(test) - test2.pipeline = cfg2.data.test.pipeline - cfg2.data.test.datasets = [test2] - cfg2 = disable_text_recog_aug_test(cfg2, set_types=['test']) - assert cfg2.data.test.pipeline[1].type != 'MultiRotateAugOCR' - assert cfg2.data.test.datasets[0].pipeline[1].type != 'MultiRotateAugOCR' - - # cfg.data.test.type is 'ConcatDataset' - cfg3 = copy.deepcopy(cfg) - test3 = copy.deepcopy(test) - test3.pipeline = cfg3.data.test.pipeline - cfg3.data.test = Config(dict(type='ConcatDataset', datasets=[test3])) - cfg3 = disable_text_recog_aug_test(cfg3, set_types=['test']) - assert cfg3.data.test.datasets[0].pipeline[1].type != 'MultiRotateAugOCR' - - # cfg.data.test.type is 'UniformConcatDataset' - # and cfg.data.test.pipeline is list[list[dict]] - cfg4 = copy.deepcopy(cfg) - test4 = copy.deepcopy(test) - test4.pipeline = cfg4.data.test.pipeline - cfg4.data.test.datasets = [[test4], [test]] - cfg4.data.test.pipeline = [ - cfg4.data.test.pipeline, cfg4.data.test.pipeline - ] - cfg4 = disable_text_recog_aug_test(cfg4, set_types=['test']) - assert cfg4.data.test.datasets[0][0].pipeline[1].type != \ - 'MultiRotateAugOCR' - - # cfg.data.test.type is 'UniformConcatDataset' - # and cfg.data.test.pipeline is None - cfg5 = copy.deepcopy(cfg) - test5 = copy.deepcopy(test) - test5.pipeline = copy.deepcopy(cfg5.data.test.pipeline) - cfg5.data.test.datasets = [test5] - cfg5.data.test.pipeline = None - cfg5 = disable_text_recog_aug_test(cfg5, set_types=['test']) - assert cfg5.data.test.datasets[0].pipeline[1].type != 'MultiRotateAugOCR' - - -@pytest.mark.parametrize('cfg_file', [ - '../configs/textdet/psenet/psenet_r50_fpnf_600e_ctw1500.py', -]) -def test_replace_image_to_tensor(cfg_file): - tmp_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) - config_file = os.path.join(tmp_dir, cfg_file) - - cfg = Config.fromfile(config_file) - test = cfg.data.test.datasets[0] - - # cfg.data.test.pipeline is list[dict] - # and cfg.data.test.datasets is list[dict] - cfg1 = copy.deepcopy(cfg) - test1 = copy.deepcopy(test) - test1.pipeline = copy.deepcopy(cfg.data.test.pipeline) - cfg1.data.test.datasets = [test1] - cfg1 = replace_image_to_tensor(cfg1, set_types=['test']) - assert cfg1.data.test.pipeline[1]['transforms'][3][ - 'type'] == 'DefaultFormatBundle' - assert cfg1.data.test.datasets[0].pipeline[1]['transforms'][3][ - 'type'] == 'DefaultFormatBundle' - - # cfg.data.test.pipeline is list[list[dict]] - # and cfg.data.test.datasets is list[list[dict]] - cfg2 = copy.deepcopy(cfg) - test2 = copy.deepcopy(test) - test2.pipeline = copy.deepcopy(cfg.data.test.pipeline) - cfg2.data.test.datasets = [[test2], [test2]] - cfg2.data.test.pipeline = [ - cfg2.data.test.pipeline, cfg2.data.test.pipeline - ] - cfg2 = replace_image_to_tensor(cfg2, set_types=['test']) - assert cfg2.data.test.pipeline[0][1]['transforms'][3][ - 'type'] == 'DefaultFormatBundle' - assert cfg2.data.test.datasets[0][0].pipeline[1]['transforms'][3][ - 'type'] == 'DefaultFormatBundle' diff --git a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/config/paths_catalog.py b/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/config/paths_catalog.py deleted file mode 100644 index fcb95f7535aa172a9800c078dff9d00777f3ea88..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/config/paths_catalog.py +++ /dev/null @@ -1,237 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -"""Centralized catalog of paths.""" - -import os - - -class DatasetCatalog(object): - DATA_DIR = "datasets" - # DATA_DIR = "/share/mhliao/MaskTextSpotterV3/datasets/" - - DATASETS = { - "coco_2014_train": ( - "coco/train2014", - "coco/annotations/instances_train2014.json", - ), - "coco_2014_val": ("coco/val2014", "coco/annotations/instances_val2014.json"), - "coco_2014_minival": ( - "coco/val2014", - "coco/annotations/instances_minival2014.json", - ), - "coco_2014_valminusminival": ( - "coco/val2014", - "coco/annotations/instances_valminusminival2014.json", - ), - "icdar_2013_train": ("icdar2013/train_images", "icdar2013/train_gts"), - "icdar_2013_test": ("icdar2013/test_images", "icdar2013/test_gts"), - "rotated_ic13_test_0": ("icdar2013/rotated_test_images_0", "icdar2013/rotated_test_gts_0"), - "rotated_ic13_test_15": ("icdar2013/rotated_test_images_15", "icdar2013/rotated_test_gts_15"), - "rotated_ic13_test_30": ("icdar2013/rotated_test_images_30", "icdar2013/rotated_test_gts_30"), - "rotated_ic13_test_45": ("icdar2013/rotated_test_images_45", "icdar2013/rotated_test_gts_45"), - "rotated_ic13_test_60": ("icdar2013/rotated_test_images_60", "icdar2013/rotated_test_gts_60"), - "rotated_ic13_test_75": ("icdar2013/rotated_test_images_75", "icdar2013/rotated_test_gts_75"), - "rotated_ic13_test_85": ("icdar2013/rotated_test_images_85", "icdar2013/rotated_test_gts_85"), - "rotated_ic13_test_90": ("icdar2013/rotated_test_images_90", "icdar2013/rotated_test_gts_90"), - "rotated_ic13_test_-15": ("icdar2013/rotated_test_images_-15", "icdar2013/rotated_test_gts_-15"), - "rotated_ic13_test_-30": ("icdar2013/rotated_test_images_-30", "icdar2013/rotated_test_gts_-30"), - "rotated_ic13_test_-45": ("icdar2013/rotated_test_images_-45", "icdar2013/rotated_test_gts_-45"), - "rotated_ic13_test_-60": ("icdar2013/rotated_test_images_-60", "icdar2013/rotated_test_gts_-60"), - "rotated_ic13_test_-75": ("icdar2013/rotated_test_images_-75", "icdar2013/rotated_test_gts_-75"), - "rotated_ic13_test_-90": ("icdar2013/rotated_test_images_-90", "icdar2013/rotated_test_gts_-90"), - "icdar_2015_train": ("icdar2015/train_images", "icdar2015/train_gts"), - "icdar_2015_test": ( - "icdar2015/test_images", - # "icdar2015/test_gts", - ), - "synthtext_train": ("synthtext/train_images", "synthtext/train_gts"), - "synthtext_test": ("synthtext/test_images", "synthtext/test_gts"), - "total_text_train": ("total_text/train_images", "total_text/train_gts"), - "td500_train": ("TD_TR/TD500/train_images", "TD500/train_gts"), - "td500_test": ("TD_TR/TD500/test_images", ), - "tr400_train": ("TD_TR/TR400/train_images", "TR400/train_gts"), - "total_text_test": ( - "total_text/test_images", - # "total_text/test_gts", - ), - "scut-eng-char_train": ( - "scut-eng-char/train_images", - "scut-eng-char/train_gts", - ), - } - - @staticmethod - def get(name): - if "coco" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - args = dict( - root=os.path.join(data_dir, attrs[0]), - ann_file=os.path.join(data_dir, attrs[1]), - ) - return dict(factory="COCODataset", args=args) - elif "icdar_2013" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - args = dict( - use_charann=True, - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=os.path.join(data_dir, attrs[1]), - # imgs_dir='/tmp/icdar2013/icdar2013/train_images', - # gts_dir='/tmp/icdar2013/icdar2013/train_gts', - ) - return dict(args=args, factory="IcdarDataset") - elif "rotated_ic13" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - args = dict( - use_charann=True, - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=os.path.join(data_dir, attrs[1]), - ) - return dict(args=args, factory="IcdarDataset") - elif "icdar_2015" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - if len(attrs) > 1: - gts_dir = os.path.join(data_dir, attrs[1]) - else: - gts_dir = None - - args = dict( - use_charann=False, - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=gts_dir, - # imgs_dir='/tmp/icdar2015/icdar2015/train_images/', - # gts_dir='/tmp/icdar2015/icdar2015/train_gts/', - ) - return dict(args=args, factory="IcdarDataset") - elif "synthtext" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - args = dict( - use_charann=True, - list_file_path=os.path.join(data_dir, "synthtext/train_list.txt"), - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=os.path.join(data_dir, attrs[1]), - # imgs_dir='/tmp/synth/SynthText/', - # gts_dir='/tmp/synth_gt/SynthText_GT_E2E/', - ) - return dict(args=args, factory="SynthtextDataset") - elif "total_text" in name: - data_dir = DatasetCatalog.DATA_DIR - # data_dir = '/tmp/total_text/' - attrs = DatasetCatalog.DATASETS[name] - if len(attrs) > 1: - gts_dir = os.path.join(data_dir, attrs[1]) - else: - gts_dir = None - args = dict( - use_charann=False, - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=gts_dir, - # imgs_dir='/tmp/total_text/total_text/train_images/', - # gts_dir='/tmp/total_text/total_text/train_gts/', - ) - return dict(args=args, factory="TotaltextDataset") - elif "scut-eng-char" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - args = dict( - use_charann=True, - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=os.path.join(data_dir, attrs[1]), - # imgs_dir='/tmp/scut-eng-char/scut-eng-char/train_images/', - # gts_dir='/tmp/scut-eng-char/scut-eng-char/train_gts/', - ) - return dict(args=args, factory="ScutDataset") - elif "td500" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - if len(attrs) > 1: - gts_dir = os.path.join(data_dir, attrs[1]) - else: - gts_dir = None - args = dict( - use_charann=False, - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=gts_dir, - ) - return dict(args=args, factory="TotaltextDataset") - elif "tr400" in name: - data_dir = DatasetCatalog.DATA_DIR - attrs = DatasetCatalog.DATASETS[name] - if len(attrs) > 1: - gts_dir = os.path.join(data_dir, attrs[1]) - else: - gts_dir = None - args = dict( - use_charann=False, - imgs_dir=os.path.join(data_dir, attrs[0]), - gts_dir=gts_dir, - ) - return dict(args=args, factory="TotaltextDataset") - raise RuntimeError("Dataset not available: {}".format(name)) - - -class ModelCatalog(object): - S3_C2_DETECTRON_URL = "https://dl.fbaipublicfiles.com/detectron" - C2_IMAGENET_MODELS = { - 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', - 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', - "MSRA/R-50": "ImageNetPretrained/MSRA/R-50.pkl", - "MSRA/R-50-GN": "ImageNetPretrained/47261647/R-50-GN.pkl", - "MSRA/R-101": "ImageNetPretrained/MSRA/R-101.pkl", - "MSRA/R-101-GN": "ImageNetPretrained/47592356/R-101-GN.pkl", - "FAIR/20171220/X-101-32x8d": "ImageNetPretrained/20171220/X-101-32x8d.pkl", - } - - C2_DETECTRON_SUFFIX = "output/train/{}coco_2014_train%3A{}coco_2014_valminusminival/generalized_rcnn/model_final.pkl" - C2_DETECTRON_MODELS = { - "35857197/e2e_faster_rcnn_R-50-C4_1x": "01_33_49.iAX0mXvW", - "35857345/e2e_faster_rcnn_R-50-FPN_1x": "01_36_30.cUF7QR7I", - "35857890/e2e_faster_rcnn_R-101-FPN_1x": "01_38_50.sNxI7sX7", - "36761737/e2e_faster_rcnn_X-101-32x8d-FPN_1x": "06_31_39.5MIHi1fZ", - "35858791/e2e_mask_rcnn_R-50-C4_1x": "01_45_57.ZgkA7hPB", - "35858933/e2e_mask_rcnn_R-50-FPN_1x": "01_48_14.DzEQe4wC", - "35861795/e2e_mask_rcnn_R-101-FPN_1x": "02_31_37.KqyEK4tT", - "36761843/e2e_mask_rcnn_X-101-32x8d-FPN_1x": "06_35_59.RZotkLKI", - "37129812/e2e_mask_rcnn_X-152-32x8d-FPN-IN5k_1.44x": "09_35_36.8pzTQKYK", - # keypoints - "37697547/e2e_keypoint_rcnn_R-50-FPN_1x": "08_42_54.kdzV35ao" - } - - @staticmethod - def get(name): - if name.startswith("Caffe2Detectron/COCO"): - return ModelCatalog.get_c2_detectron_12_2017_baselines(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_URL - name = name[len("ImageNetPretrained/") :] - name = ModelCatalog.C2_IMAGENET_MODELS[name] - if 'resnet34' in name or 'resnet18' in name: - return name - url = "/".join([prefix, name]) - return url - - @staticmethod - def get_c2_detectron_12_2017_baselines(name): - # Detectron C2 models are stored following the structure - # prefix//2012_2017_baselines/.yaml./suffix - # we use as identifiers in the catalog Caffe2Detectron/COCO// - prefix = ModelCatalog.S3_C2_DETECTRON_URL - suffix = ModelCatalog.C2_DETECTRON_SUFFIX - # remove identification prefix - name = name[len("Caffe2Detectron/COCO/") :] - # split in and - model_id, model_name = name.split("/") - # parsing to make it match the url address from the Caffe2 models - model_name = "{}.yaml".format(model_name) - signature = ModelCatalog.C2_DETECTRON_MODELS[name] - unique_name = ".".join([model_name, signature]) - url = "/".join([prefix, model_id, "12_2017_baselines", unique_name, suffix]) - return url diff --git a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/structures/boxlist_ops.py b/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/structures/boxlist_ops.py deleted file mode 100644 index 7645f0a8bbddbb0dcad868276cd77ec11d12e894..0000000000000000000000000000000000000000 --- a/spaces/tomofi/MaskTextSpotterV3-OCR/maskrcnn_benchmark/structures/boxlist_ops.py +++ /dev/null @@ -1,234 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. -import torch -from maskrcnn_benchmark.layers import nms as _box_nms - -from .bounding_box import BoxList -from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask -import numpy as np -import shapely -from shapely.geometry import Polygon,MultiPoint - -def boxlist_nms(boxlist, nms_thresh, max_proposals=-1, score_field="score"): - """ - Performs non-maximum suppression on a boxlist, with scores specified - in a boxlist field via score_field. - - Arguments: - boxlist(BoxList) - nms_thresh (float) - max_proposals (int): if > 0, then only the top max_proposals are kept - after non-maxium suppression - score_field (str) - """ - if nms_thresh <= 0: - return boxlist - mode = boxlist.mode - boxlist = boxlist.convert("xyxy") - boxes = boxlist.bbox - score = boxlist.get_field(score_field) - keep = _box_nms(boxes, score, nms_thresh) - if max_proposals > 0: - keep = keep[:max_proposals] - boxlist = boxlist[keep] - return boxlist.convert(mode) - - -def remove_small_boxes(boxlist, min_size): - """ - Only keep boxes with both sides >= min_size - - Arguments: - boxlist (Boxlist) - min_size (int) - """ - # TODO maybe add an API for querying the ws / hs - xywh_boxes = boxlist.convert("xywh").bbox - _, _, ws, hs = xywh_boxes.unbind(dim=1) - keep = ((ws >= min_size) & (hs >= min_size)).nonzero().squeeze(1) - return boxlist[keep] - - -# implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py -# with slight modifications -def boxlist_iou(boxlist1, boxlist2): - """Compute the intersection over union of two set of boxes. - The box order must be (xmin, ymin, xmax, ymax). - - Arguments: - box1: (BoxList) bounding boxes, sized [N,4]. - box2: (BoxList) bounding boxes, sized [M,4]. - - Returns: - (tensor) iou, sized [N,M]. - - Reference: - https://github.com/chainer/chainercv/blob/master/chainercv/utils/bbox/bbox_iou.py - """ - if boxlist1.size != boxlist2.size: - raise RuntimeError( - "boxlists should have same image size, got {}, {}".format( - boxlist1, boxlist2 - ) - ) - - # N = len(boxlist1) - # M = len(boxlist2) - - area1 = boxlist1.area() - area2 = boxlist2.area() - - box1, box2 = boxlist1.bbox, boxlist2.bbox - - lt = torch.max(box1[:, None, :2], box2[:, :2]) # [N,M,2] - rb = torch.min(box1[:, None, 2:], box2[:, 2:]) # [N,M,2] - - TO_REMOVE = 1 - - wh = (rb - lt + TO_REMOVE).clamp(min=0) # [N,M,2] - inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] - - iou = inter / (area1[:, None] + area2 - inter) - return iou - -# def boxlist_polygon_iou(target, proposal): -# """Compute the intersection over union of two set of boxes. -# The box order must be (xmin, ymin, xmax, ymax). - -# Arguments: -# box1: (BoxList) bounding boxes, sized [N,4]. -# box2: (BoxList) bounding boxes, sized [M,4]. - -# Returns: -# (tensor) iou, sized [N,M]. - -# Reference: -# https://github.com/chainer/chainercv/blob/master/chainercv/utils/bbox/bbox_iou.py -# """ -# if target.size != proposal.size: -# raise RuntimeError( -# "boxlists should have same image size, got {}, {}".format( -# target, proposal -# ) -# ) -# target_polygon = target.get_field("masks").to_np_polygon() -# proposal_polygon = proposal.get_field("masks").to_np_polygon() -# print(target_polygon) -# print(proposal_polygon) -# polygon_points1 = target_polygon[0].reshape(-1, 2) -# poly1 = Polygon(polygon_points1).convex_hull -# polygon_points2 = proposal_polygon[0].reshape(-1, 2) -# poly2 = Polygon(polygon_points2).convex_hull -# union_poly = np.concatenate((polygon_points1, polygon_points2)) -# if not poly1.intersects(poly2): # this test is fast and can accelerate calculation -# iou = 0 -# else: -# try: -# inter_area = poly1.intersection(poly2).area -# #union_area = poly1.area + poly2.area - inter_area -# union_area = MultiPoint(union_poly).convex_hull.area -# if union_area == 0: -# return 0 -# iou = float(inter_area) / union_area -# except shapely.geos.TopologicalError: -# print('shapely.geos.TopologicalError occured, iou set to 0') -# iou = 0 -# return iou - - -# TODO redundant, remove -def _cat(tensors, dim=0): - """ - Efficient version of torch.cat - avoids a copy if there is only a single element in a list - """ - assert isinstance(tensors, (list, tuple)) - if len(tensors) == 1: - return tensors[0] - return torch.cat(tensors, dim) - -def _cat_mask(masks): - polygons_cat = [] - size = masks[0].size - for mask in masks: - polygons = mask.get_polygons() - polygons_cat.extend(polygons) - masks_cat = SegmentationMask(polygons_cat, size) - return masks_cat - - -def cat_boxlist(bboxes): - """ - Concatenates a list of BoxList (having the same image size) into a - single BoxList - - Arguments: - bboxes (list[BoxList]) - """ - # if bboxes is None: - # return None - # if bboxes[0] is None: - # bboxes = [bboxes[1] - assert isinstance(bboxes, (list, tuple)) - assert all(isinstance(bbox, BoxList) for bbox in bboxes) - - size = bboxes[0].size - assert all(bbox.size == size for bbox in bboxes) - - mode = bboxes[0].mode - assert all(bbox.mode == mode for bbox in bboxes) - - fields = set(bboxes[0].fields()) - assert all(set(bbox.fields()) == fields for bbox in bboxes) - - cat_boxes = BoxList(_cat([bbox.bbox for bbox in bboxes], dim=0), size, mode) - - for field in fields: - if field == 'masks': - data = _cat_mask([bbox.get_field(field) for bbox in bboxes]) - else: - data = _cat([bbox.get_field(field) for bbox in bboxes], dim=0) - cat_boxes.add_field(field, data) - - return cat_boxes - - -def cat_boxlist_gt(bboxes): - """ - Concatenates a list of BoxList (having the same image size) into a - single BoxList - - Arguments: - bboxes (list[BoxList]) - """ - assert isinstance(bboxes, (list, tuple)) - assert all(isinstance(bbox, BoxList) for bbox in bboxes) - - size = bboxes[0].size - # bboxes[1].set_size(size) - assert all(bbox.size == size for bbox in bboxes) - - mode = bboxes[0].mode - assert all(bbox.mode == mode for bbox in bboxes) - - fields = set(bboxes[0].fields()) - assert all(set(bbox.fields()) == fields for bbox in bboxes) - if bboxes[0].bbox.sum().item() == 0: - cat_boxes = BoxList(bboxes[1].bbox, size, mode) - else: - cat_boxes = BoxList(_cat([bbox.bbox for bbox in bboxes], dim=0), size, mode) - - for field in fields: - if bboxes[0].bbox.sum().item() == 0: - if field == 'masks': - data = _cat_mask([bbox.get_field(field) for bbox in bboxes[1:]]) - else: - data = _cat([bbox.get_field(field) for bbox in bboxes[1:]], dim=0) - else: - if field == 'masks': - data = _cat_mask([bbox.get_field(field) for bbox in bboxes]) - else: - data = _cat([bbox.get_field(field) for bbox in bboxes], dim=0) - cat_boxes.add_field(field, data) - - return cat_boxes diff --git a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/core/bbox/samplers/ohem_sampler.py b/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/core/bbox/samplers/ohem_sampler.py deleted file mode 100644 index 8b99f60ef0176f1b7a56665fb0f59272f65b84cd..0000000000000000000000000000000000000000 --- a/spaces/tomofi/NDLOCR/src/ndl_layout/mmdetection/mmdet/core/bbox/samplers/ohem_sampler.py +++ /dev/null @@ -1,107 +0,0 @@ -import torch - -from ..builder import BBOX_SAMPLERS -from ..transforms import bbox2roi -from .base_sampler import BaseSampler - - -@BBOX_SAMPLERS.register_module() -class OHEMSampler(BaseSampler): - r"""Online Hard Example Mining Sampler described in `Training Region-based - Object Detectors with Online Hard Example Mining - `_. - """ - - def __init__(self, - num, - pos_fraction, - context, - neg_pos_ub=-1, - add_gt_as_proposals=True, - **kwargs): - super(OHEMSampler, self).__init__(num, pos_fraction, neg_pos_ub, - add_gt_as_proposals) - self.context = context - if not hasattr(self.context, 'num_stages'): - self.bbox_head = self.context.bbox_head - else: - self.bbox_head = self.context.bbox_head[self.context.current_stage] - - def hard_mining(self, inds, num_expected, bboxes, labels, feats): - with torch.no_grad(): - rois = bbox2roi([bboxes]) - if not hasattr(self.context, 'num_stages'): - bbox_results = self.context._bbox_forward(feats, rois) - else: - bbox_results = self.context._bbox_forward( - self.context.current_stage, feats, rois) - cls_score = bbox_results['cls_score'] - loss = self.bbox_head.loss( - cls_score=cls_score, - bbox_pred=None, - rois=rois, - labels=labels, - label_weights=cls_score.new_ones(cls_score.size(0)), - bbox_targets=None, - bbox_weights=None, - reduction_override='none')['loss_cls'] - _, topk_loss_inds = loss.topk(num_expected) - return inds[topk_loss_inds] - - def _sample_pos(self, - assign_result, - num_expected, - bboxes=None, - feats=None, - **kwargs): - """Sample positive boxes. - - Args: - assign_result (:obj:`AssignResult`): Assigned results - num_expected (int): Number of expected positive samples - bboxes (torch.Tensor, optional): Boxes. Defaults to None. - feats (list[torch.Tensor], optional): Multi-level features. - Defaults to None. - - Returns: - torch.Tensor: Indices of positive samples - """ - # Sample some hard positive samples - pos_inds = torch.nonzero(assign_result.gt_inds > 0, as_tuple=False) - if pos_inds.numel() != 0: - pos_inds = pos_inds.squeeze(1) - if pos_inds.numel() <= num_expected: - return pos_inds - else: - return self.hard_mining(pos_inds, num_expected, bboxes[pos_inds], - assign_result.labels[pos_inds], feats) - - def _sample_neg(self, - assign_result, - num_expected, - bboxes=None, - feats=None, - **kwargs): - """Sample negative boxes. - - Args: - assign_result (:obj:`AssignResult`): Assigned results - num_expected (int): Number of expected negative samples - bboxes (torch.Tensor, optional): Boxes. Defaults to None. - feats (list[torch.Tensor], optional): Multi-level features. - Defaults to None. - - Returns: - torch.Tensor: Indices of negative samples - """ - # Sample some hard negative samples - neg_inds = torch.nonzero(assign_result.gt_inds == 0, as_tuple=False) - if neg_inds.numel() != 0: - neg_inds = neg_inds.squeeze(1) - if len(neg_inds) <= num_expected: - return neg_inds - else: - neg_labels = assign_result.labels.new_empty( - neg_inds.size(0)).fill_(self.bbox_head.num_classes) - return self.hard_mining(neg_inds, num_expected, bboxes[neg_inds], - neg_labels, feats) diff --git a/spaces/tonwuaso/SentimentAnalysisModel/app.py b/spaces/tonwuaso/SentimentAnalysisModel/app.py deleted file mode 100644 index 9b2d1b7386fce5fdcd269a09f4ae3bff5986c225..0000000000000000000000000000000000000000 --- a/spaces/tonwuaso/SentimentAnalysisModel/app.py +++ /dev/null @@ -1,138 +0,0 @@ -import os -import pandas as pd -import tensorflow as tf -import numpy as np -import gradio as gr -from matplotlib import pyplot as plt -from keras.models import Sequential -from keras.layers import LSTM, Dropout, Bidirectional, Dense, Embedding -from keras.metrics import Precision, Recall, CategoricalAccuracy -from keras.layers import TextVectorization - -base_path = r"C:\Users\tochi\SentimentAnalysisData" -df = pd.read_csv(os.path.join(base_path, 'train.csv' )) - - -df.head() # displays first couple of comments from csv file - -X = df['comment_text'] -y = df[df.columns[2:]].values - - -MAX_FEATURES = 200000 # number of words in the vocab - - -vectorizer = TextVectorization(max_tokens=MAX_FEATURES, - output_sequence_length=1800, - output_mode='int') - -vectorizer.adapt(X.values) - -vectorized_text = vectorizer(X.values) - -#MCSHBAP - map, chache, shuffle, batch, prefetch from_tensor_slices, list_file -dataset = tf.data.Dataset.from_tensor_slices((vectorized_text, y)) -dataset = dataset.cache() -dataset = dataset.shuffle(160000) -dataset = dataset.batch(16) -dataset = dataset.prefetch(8) # helps bottlenecks - - -train = dataset.take(int(len(dataset)*.7)) -val = dataset.skip(int(len(dataset)*.7)).take(int(len(dataset)*.2)) -test = dataset.skip(int(len(dataset)*.9)).take(int(len(dataset)*.1)) - -model = Sequential() # Instantiate sequential api -# Create the embedding layer -model.add(Embedding(MAX_FEATURES+1, 32)) -# Bidirectional LSTM Layer -model.add(Bidirectional(LSTM(32, activation='tanh'))) -# Feature extractor Fully connected layers -model.add(Dense(128, activation='relu')) -model.add(Dense(256, activation='relu')) -model.add(Dense(128, activation='relu')) -# Final layer -model.add(Dense(6, activation='sigmoid')) - - -model.compile(loss='BinaryCrossentropy', optimizer='Adam') - - -model.summary() - - -history = model.fit(train, epochs=10, validation_data=val) - - -plt.figure(figsize=(8,5)) -pd.DataFrame(history.history).plot() -plt.show() - - - -input_text = ['You freaking suck! I am going to hit you!'] - - -input_text = vectorizer(input_text) - - -res = model.predict(input_text) - -(res > 0.5).astype(int) - -batch_X, batch_y = test.as_numpy_iterator().next() - - -(model.predict(batch_X) > 0.5).astype(int) - - -res.shape - - -pre = Precision() -re = Recall() -acc = CategoricalAccuracy() - -for batch in test.as_numpy_iterator(): - # Unpack the batch - X_true, y_true = batch - # Make a prediction - yhat = model.predict(X_true) - - # Flatten the predictions - y_true = y_true.flatten() - yhat = yhat.flatten() - - pre.update_state(y_true, yhat) - re.update_state(y_true, yhat) - acc.update_state(y_true, yhat) - - -print(f'Precision: {pre.result().numpy()}, Recall:{re.result().numpy()}, Accuracy:{acc.result().numpy()}') - - -input_str = vectorizer('I hate you!') - - -res = model.predict(np.expand_dims(input_str,0)) - -res - - -def score_comment(comment): - vectorized_comment = vectorizer([comment]) - results = model.predict(vectorized_comment) - - text = '' - for idx, col in enumerate(df.columns[2:]): - text += '{}: {}\n'.format(col, results[0][idx] > 0.5) - - return text - - -interface = gr.Interface( - fn=score_comment, - inputs=gr.inputs.Textbox(lines=2, placeholder='Comment to score'), - outputs='text') - -interface.launch() \ No newline at end of file diff --git a/spaces/triple-t/ttt-space/frontend/src/app.d.ts b/spaces/triple-t/ttt-space/frontend/src/app.d.ts deleted file mode 100644 index 26a9569bc40a003dea0610c65ebdc2686d9f7406..0000000000000000000000000000000000000000 --- a/spaces/triple-t/ttt-space/frontend/src/app.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// See https://kit.svelte.dev/docs/types#app -// for information about these interfaces -// and what to do when importing types -declare namespace App { - // interface Error {} - // interface Locals {} - // interface PageData {} - // interface Platform {} -} diff --git a/spaces/trttung1610/musicgen/tests/modules/test_codebooks_patterns.py b/spaces/trttung1610/musicgen/tests/modules/test_codebooks_patterns.py deleted file mode 100644 index b658f4779a369f9ec8dde692a61b7f0fe3485724..0000000000000000000000000000000000000000 --- a/spaces/trttung1610/musicgen/tests/modules/test_codebooks_patterns.py +++ /dev/null @@ -1,246 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import pytest -import torch - -from audiocraft.modules.codebooks_patterns import ( - DelayedPatternProvider, - ParallelPatternProvider, - Pattern, - UnrolledPatternProvider, -) - - -class TestParallelPatternProvider: - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [0, 1, 16, 100]) - def test_get_pattern(self, n_q: int, timesteps: int): - provider = ParallelPatternProvider(n_q) - pattern = provider.get_pattern(timesteps) - # + 1 to account for 1st step - assert len(pattern.layout) == timesteps + 1 - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [8, 16, 100]) - def test_pattern_content(self, n_q: int, timesteps: int): - provider = ParallelPatternProvider(n_q) - pattern = provider.get_pattern(timesteps) - for s, v in enumerate(pattern.layout): - for i, code in enumerate(v): - assert i == code.q - assert code.t == s - 1 # account for the 1st empty step - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [8, 16, 100]) - def test_pattern_max_delay(self, n_q: int, timesteps: int): - provider = ParallelPatternProvider(n_q) - pattern = provider.get_pattern(timesteps) - assert pattern.max_delay == 0 - assert len(pattern.valid_layout) == len(pattern.layout) - pattern.max_delay - - -class TestDelayedPatternProvider: - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [0, 1, 16, 100]) - def test_get_pattern(self, n_q: int, timesteps: int): - delays = [ - list(range(n_q)), - [0] + [1] * (n_q - 1), - [0] + [4] * (n_q - 1), - ] - for delay in delays: - provider = DelayedPatternProvider(n_q, delay) - pattern = provider.get_pattern(timesteps) - # + 1 to account for 1st step - assert len(pattern.layout) == timesteps + max(delay) + 1 - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [8, 16, 100]) - def test_pattern_content(self, n_q: int, timesteps: int): - provider = DelayedPatternProvider(n_q) - pattern = provider.get_pattern(timesteps) - for s, v in enumerate(pattern.layout): - for i, code in enumerate(v): - assert i == code.q - assert code.t == max(0, s - code.q - 1) - - @pytest.mark.parametrize("timesteps", [8, 16, 100]) - @pytest.mark.parametrize("delay", [[0, 1, 2, 3], [0, 1, 1, 1], [0, 3, 3, 3], [0, 3]]) - def test_pattern_max_delay(self, timesteps: int, delay: list): - provider = DelayedPatternProvider(len(delay), delay) - pattern = provider.get_pattern(timesteps) - assert pattern.max_delay == max(delay) - assert len(pattern.valid_layout) == len(pattern.layout) - pattern.max_delay - - -class TestUnrolledPatternProvider: - - @pytest.mark.parametrize("timesteps", [0, 1, 16]) - @pytest.mark.parametrize("flattening", [[0, 1, 2], [0, 1, 1]]) - @pytest.mark.parametrize("delays", [[0, 0, 0], [0, 5, 5]]) - def test_get_pattern(self, timesteps: int, flattening: list, delays: list): - n_q = len(flattening) - max_delay = max(delays) - provider = UnrolledPatternProvider(n_q, flattening, delays) - pattern = provider.get_pattern(timesteps) - assert len(pattern.layout) == provider.num_virtual_steps(timesteps) + max_delay - - @pytest.mark.parametrize("timesteps", [0, 1, 16]) - @pytest.mark.parametrize("flattening", [[0, 1, 2], [0, 1, 1]]) - @pytest.mark.parametrize("delays", [[0, 0, 0], [0, 5, 5]]) - def test_pattern_max_delay(self, timesteps: int, flattening: list, delays: list): - n_q = len(flattening) - max_delay = max(delays) - provider = UnrolledPatternProvider(n_q, flattening, delays) - pattern = provider.get_pattern(timesteps) - assert pattern.max_delay == max_delay - - -class TestPattern: - - def ref_build_pattern_sequence(self, z: torch.Tensor, pattern: Pattern, special_token: int): - """Reference method to build the sequence from the pattern without using fancy scatter.""" - bs, n_q, T = z.shape - z = z.cpu().numpy() - assert n_q == pattern.n_q - assert T <= pattern.timesteps - inp = torch.full((bs, n_q, len(pattern.layout)), special_token, dtype=torch.long).numpy() - inp[:] = special_token - for s, v in enumerate(pattern.layout): - for (t, q) in v: - if t < T: - inp[:, q, s] = z[:, q, t] - return torch.from_numpy(inp) - - def ref_revert_pattern_sequence(self, z: torch.Tensor, pattern: Pattern, special_token: int): - """Reference method to revert the sequence from the pattern without using fancy scatter.""" - z = z.cpu().numpy() - bs, n_q, S = z.shape - assert pattern.n_q == n_q - inp = torch.full((bs, pattern.n_q, pattern.timesteps), special_token, dtype=torch.long).numpy() - inp[:] = special_token - for s, v in enumerate(pattern.layout): - for (t, q) in v: - if t < pattern.timesteps: - inp[:, q, t] = z[:, q, s] - return torch.from_numpy(inp) - - def ref_revert_pattern_logits(self, z: torch.Tensor, pattern: Pattern, special_token: float): - """Reference method to revert the logits from the pattern without using fancy scatter.""" - z = z.cpu().numpy() - bs, card, n_q, S = z.shape - assert pattern.n_q == n_q - ref_layout = pattern.layout - inp = torch.full((bs, card, pattern.n_q, pattern.timesteps), special_token, dtype=torch.float).numpy() - inp[:] = special_token - for s, v in enumerate(ref_layout[1:]): - if s < S: - for (t, q) in v: - if t < pattern.timesteps: - inp[:, :, q, t] = z[:, :, q, s] - return torch.from_numpy(inp) - - def _get_pattern_providers(self, n_q: int): - pattern_provider_1 = ParallelPatternProvider(n_q) - pattern_provider_2 = DelayedPatternProvider(n_q, list(range(n_q))) - pattern_provider_3 = DelayedPatternProvider(n_q, [0] + [1] * (n_q - 1)) - pattern_provider_4 = UnrolledPatternProvider( - n_q, flattening=list(range(n_q)), delays=[0] * n_q - ) - pattern_provider_5 = UnrolledPatternProvider( - n_q, flattening=[0] + [1] * (n_q - 1), delays=[0] * n_q - ) - pattern_provider_6 = UnrolledPatternProvider( - n_q, flattening=[0] + [1] * (n_q - 1), delays=[0] + [5] * (n_q - 1) - ) - return [ - pattern_provider_1, - pattern_provider_2, - pattern_provider_3, - pattern_provider_4, - pattern_provider_5, - pattern_provider_6, - ] - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [16, 72]) - def test_build_pattern_sequence(self, n_q: int, timesteps: int): - bs = 2 - card = 256 - special_token = card - - pattern_providers = self._get_pattern_providers(n_q) - for pattern_provider in pattern_providers: - pattern = pattern_provider.get_pattern(timesteps) - # we can correctly build the sequence from the pattern - z = torch.randint(0, card, (bs, n_q, timesteps)) - ref_res = self.ref_build_pattern_sequence(z, pattern, special_token) - res, indexes, mask = pattern.build_pattern_sequence(z, special_token) - assert (res == ref_res).float().mean() == 1.0 - - # expected assertion fails on the number of timesteps - invalid_timesteps = [timesteps + 1] - if pattern.num_sequence_steps != pattern.timesteps: - invalid_timesteps.append(pattern.num_sequence_steps) - for i_timesteps in invalid_timesteps: - z2 = torch.randint(0, card, (bs, n_q, i_timesteps)) - with pytest.raises(AssertionError): - pattern.build_pattern_sequence(z2, special_token) - - # expected assertion fails on the number of codebooks - invalid_qs = [0, n_q - 1, n_q + 1] - for i_q in invalid_qs: - z3 = torch.randint(0, card, (bs, i_q, timesteps)) - with pytest.raises(AssertionError): - pattern.build_pattern_sequence(z3, special_token) - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [16, 72]) - def test_revert_pattern_sequence(self, n_q: int, timesteps: int): - bs = 2 - card = 256 - special_token = card - - pattern_providers = self._get_pattern_providers(n_q) - for pattern_provider in pattern_providers: - pattern = pattern_provider.get_pattern(timesteps) - # this works assuming previous tests are successful - z = torch.randint(0, card, (bs, n_q, timesteps)) - s = self.ref_build_pattern_sequence(z, pattern, special_token) - ref_out = self.ref_revert_pattern_sequence(s, pattern, special_token) - # ensure our reference script retrieve the original sequence - assert z.shape == ref_out.shape - assert (z == ref_out).float().mean() == 1.0 - # now we can test the scatter version - out, indexes, mask = pattern.revert_pattern_sequence(s, special_token) - assert out.shape == ref_out.shape - assert (out == ref_out).float().mean() == 1.0 - - @pytest.mark.parametrize("n_q", [1, 4, 32]) - @pytest.mark.parametrize("timesteps", [16, 72]) - @pytest.mark.parametrize("card", [1, 2, 256, 1024]) - def test_revert_pattern_logits(self, n_q: int, timesteps: int, card: int): - bs = 2 - special_token = card - logits_special_token = float('nan') - - pattern_providers = self._get_pattern_providers(n_q) - for pattern_provider in pattern_providers: - pattern = pattern_provider.get_pattern(timesteps) - # this works assuming previous tests are successful - z = torch.randint(0, card, (bs, n_q, timesteps)) - s = self.ref_build_pattern_sequence(z, pattern, special_token) - logits = torch.randn((bs, card, n_q, s.shape[-1])) - ref_out = self.ref_revert_pattern_logits(logits, pattern, logits_special_token) - # ensure our reference script retrieve the original sequence - assert ref_out.shape == torch.Size([bs, card, n_q, timesteps]) - # now we can test the scatter version - out, indexes, mask = pattern.revert_pattern_logits(logits, logits_special_token) - assert out.shape == ref_out.shape - assert (out == ref_out).float().mean() == 1.0 diff --git a/spaces/usbethFlerru/sovits-modelsV2/example/Call Of Duty Ghost 2gb Ram Crack.md b/spaces/usbethFlerru/sovits-modelsV2/example/Call Of Duty Ghost 2gb Ram Crack.md deleted file mode 100644 index 89f9d1378a90e2a4edc748391b1ed22fe7be2889..0000000000000000000000000000000000000000 --- a/spaces/usbethFlerru/sovits-modelsV2/example/Call Of Duty Ghost 2gb Ram Crack.md +++ /dev/null @@ -1,123 +0,0 @@ -
                -

                Call of Duty Ghost 2GB Ram Crack: How to Download and Play COD Ghosts on Low-End PC

                - -

                Call of Duty Ghosts is one of the most popular and acclaimed first-person shooter games of all time. It was released in 2013 by Activision and developed by Infinity Ward, Raven Software, and Neversoft. The game features a new story, setting, and characters that are different from the previous Call of Duty games. The game also boasts impressive graphics, sound, and gameplay that immerse the players in a thrilling and realistic war scenario.

                -

                call of duty ghost 2gb ram crack


                Download File ===== https://urlcod.com/2uyWRl



                - -

                However, not everyone can enjoy Call of Duty Ghosts on their PC. The game has high system requirements that demand a powerful PC with at least 6 GB of RAM, a quad-core CPU, and a DirectX 11 compatible graphics card. Many PC gamers who have low-end or old PCs cannot run the game smoothly or even launch it at all. This can be very frustrating and disappointing for them.

                - -

                Fortunately, there is a way to download and play Call of Duty Ghosts on a low-end PC with only 2 GB of RAM. You just need to find a reliable source of Call of Duty Ghost 2GB Ram Crack, which is a file that contains the cracked version of the game that can run on low-spec PCs. This file will allow you to bypass the RAM check and install the game on your PC without any problems.

                - -

                What is Call of Duty Ghost 2GB Ram Crack?

                - -

                Call of Duty Ghost 2GB Ram Crack is a file that contains the cracked version of Call of Duty Ghosts that can run on low-end PCs with only 2 GB of RAM. This file was created by Reloaded, a group of hackers who specialize in cracking games and software.

                - -

                The crack works by modifying the game files and registry entries that check the RAM amount on your PC. The crack tricks the game into thinking that you have enough RAM to run it, even if you don't. The crack also includes a patch that updates the game to the latest version and fixes some bugs and errors.

                -

                - -

                The crack does not affect the gameplay or performance of the game. You can still enjoy all the features and functions of the game such as single-player campaign, multiplayer mode, customization options, and more. The only difference is that you can play the game on a low-end PC with only 2 GB of RAM.

                - -

                How to Download and Install Call of Duty Ghost 2GB Ram Crack?

                - -

                If you want to download and install Call of Duty Ghost 2GB Ram Crack, you need to follow these steps:

                -
                  -
                1. First, you need to have a torrent client installed on your PC, such as uTorrent or BitTorrent. This software will allow you to download the torrent file and its contents.
                2. -
                3. Next, you need to find a reliable source of Call of Duty Ghost 2GB Ram Crack. You can use any torrent site that you trust, such as Kickass Torrents or The Pirate Bay. Just make sure that the file has positive comments and ratings from other users.
                4. -
                5. Once you find the torrent file, download it and open it with your torrent client. The download process might take some time depending on your internet speed and the number of seeders.
                6. -
                7. After the download is complete, you will have a folder that contains the cracked game files and instructions. Read the instructions carefully and follow them step by step.
                8. -
                9. Usually, you will have to extract the files using WinRAR or 7-Zip, mount the ISO file using Daemon Tools or PowerISO, run the setup.exe file as administrator, install the game on your desired location, copy the crack files from the /Crack directory on the image to your game install directory, and run the game from the desktop shortcut.
                10. -
                11. Congratulations! You have successfully installed Call of Duty Ghost 2GB Ram Crack on your PC. You can now enjoy playing COD Ghosts on your low-end PC with only 2 GB of RAM.
                12. -
                - -

                What are the Benefits of Playing Call of Duty Ghost 2GB Ram Crack?

                - -

                There are many benefits of playing Call of Duty Ghost 2GB Ram Crack instead of buying the official game. Some of them are:

                -
                  -
                • You can save money and time by downloading and installing COD Ghosts for free instead of paying for it and waiting for delivery.
                • -
                • You can play COD Ghosts on your low-end PC with only 2 GB of RAM without any lag or crash issues.
                • -
                • You can play COD Ghosts offline without needing an internet connection or a Steam account.
                • -
                • You can update COD Ghosts easily by downloading new patches and cracks from Reloaded or other sources.
                • -
                • You can mod COD Ghosts with various mods that enhance the gameplay and graphics of the game.
                • -
                - -

                What are the Risks of Playing Call of Duty Ghost 2GB Ram Crack?

                - -

                However, there are also some risks of playing Call of Duty Ghost 2GB Ram Crack instead of buying the official game. Some of them are:

                -
                  -
                • You might encounter some viruses or malware that can harm your PC or steal your data if you download from untrusted sources or open suspicious files.
                • -
                • You might face some legal issues or penalties if you get caught downloading or playing pirated games by authorities or developers.
                • -
                • You might experience some bugs or errors that can affect your gameplay or performance if you use outdated or incompatible cracks or patches.
                • -
                • You might lose some features or functions that are only available in the official game such as multiplayer mode or Steam achievements.
                • -
                • You might not be able to get technical support or customer service from Activision or Infinity Ward if you encounter any problems with COD Ghosts.
                • -
                - -

                Conclusion

                - -

                Call of Duty Ghost 2GB Ram Crack is a great way to download and play COD Ghosts on a low-end PC with only 2 GB of RAM. You can enjoy all the aspects of this amazing first-person shooter game without spending any money or having any hardware issues. However, it also comes with some risks and drawbacks that you should be aware of before deciding to use it. Ultimately, it is up to you whether you want to support Activision and Infinity Ward by buying their game or not.

                - -

                If you enjoyed this article, please share it with your friends who are also interested in COD Ghosts. Also, feel free to leave a comment below if you have any questions or feedback about Call of Duty Ghost 2GB Ram Crack.

                -

                What are the Features of Call of Duty Ghost 2GB Ram Crack?

                - -

                Call of Duty Ghost 2GB Ram Crack is not just a simple crack that lets you play COD Ghosts for free. It also comes with many features that enhance your gaming experience and make it more enjoyable. Some of these features are:

                -
                  -
                • You can play the single-player campaign mode, which follows the story of a group of elite soldiers known as Ghosts, who fight against a new global threat called the Federation.
                • -
                • You can play the multiplayer mode, which offers various game modes, maps, weapons, perks, killstreaks, and customization options.
                • -
                • You can play the extinction mode, which is a co-op mode where you and your teammates have to fight against hordes of aliens and complete various objectives.
                • -
                • You can play the squads mode, which is a mode where you can create and customize your own squad of soldiers and compete against other players or AI-controlled squads.
                • -
                • You can enjoy the stunning graphics, sound, and physics of the game, which create a realistic and immersive war environment.
                • -
                - -

                How to Play Call of Duty Ghost 2GB Ram Crack?

                - -

                Playing Call of Duty Ghost 2GB Ram Crack is easy and fun. You just need to follow these steps:

                -
                  -
                1. Launch the game from the desktop shortcut or the game folder.
                2. -
                3. Create a new profile or load an existing one.
                4. -
                5. Choose your preferred game mode and start your adventure as a Ghost.
                6. -
                7. Select your loadout, which consists of your primary weapon, secondary weapon, lethal equipment, tactical equipment, perk 1, perk 2, perk 3, strike package, and squad member.
                8. -
                9. Join a match or create your own lobby and invite your friends.
                10. -
                11. Follow the objectives and eliminate your enemies using your skills and tactics.
                12. -
                13. Earn experience points, ranks, rewards, and unlocks as you play.
                14. -
                15. Enjoy the thrill and excitement of being a Ghost.
                16. -
                - -

                Conclusion

                - -

                Call of Duty Ghost 2GB Ram Crack is a great way to enjoy one of the best first-person shooter games ever made. You can download and play COD Ghosts for free with all the features and functions of the game. You can also play COD Ghosts on your low-end PC with only 2 GB of RAM without any lag or crash issues. Call of Duty Ghost 2GB Ram Crack is a game that will keep you entertained for hours and hours.

                - -

                If you liked this article, please share it with your friends who are also fans of COD Ghosts. Also, feel free to leave a comment below if you have any questions or feedback about Call of Duty Ghost 2GB Ram Crack.

                -

                What are the Tips and Tricks for Call of Duty Ghost 2GB Ram Crack?

                - -

                If you want to play Call of Duty Ghost 2GB Ram Crack like a pro, you might want to know some tips and tricks that can help you improve your skills and performance. Here are some of them:

                -
                  -
                • Use the right controller. You can play COD Ghosts with a keyboard and mouse, but it is much better to use a gamepad or a controller. This will give you more control and accuracy when aiming and shooting.
                • -
                • Adjust the settings. You can customize various aspects of the game such as graphics, sound, controls, gameplay, and more. You can also enable or disable some features such as aim assist, subtitles, blood, and more. Find the settings that suit your preferences and style.
                • -
                • Plan your strategy. Before you start a match or a mission, you can check the map and see the layout, objectives, enemies, and allies. You can also choose different routes or approaches depending on your preferences and challenges. Plan your strategy wisely and adapt to the situation.
                • -
                • Manage your resources. You need to keep an eye on your health, ammo, grenades, and other resources. You don't want to run out of them or waste them unnecessarily. You can replenish them by picking up supplies from fallen enemies or allies, or by using support items such as ammo crates or medkits.
                • -
                • Use cover and stealth. You need to use cover and stealth to avoid being detected or shot by enemies. You can use walls, crates, vehicles, bushes, and other objects as cover. You can also crouch, prone, lean, slide, or mantle to move around stealthily. You can also use silencers, flashbangs, smoke grenades, or other gadgets to distract or blind enemies.
                • -
                - -

                What are the Reviews of Call of Duty Ghost 2GB Ram Crack?

                - -

                Call of Duty Ghost 2GB Ram Crack has received many positive reviews from players and critics alike. Here are some of them:

                -
                -

                "Call of Duty Ghosts is one of the best games I have ever played. The graphics are amazing, the sound is immersive, and the gameplay is addictive. I love the story, the characters, and the missions. The game is also very challenging and rewarding. I have played it on my low-end PC with only 2 GB of RAM and it runs smoothly and flawlessly."

                -- Alex, Steam user -
                -
                -

                "Call of Duty Ghosts is a masterpiece of gaming. It is not just a game about shooting enemies, it is a game about being a soldier. You can feel the emotions and tensions of war. You can also customize your soldier and your loadout. The game is also very realistic and authentic. I have downloaded it for free with Call of Duty Ghost 2GB Ram Crack and it works perfectly."

                -- Sarah, PC Gamer -
                -
                -

                "Call of Duty Ghosts is a game that I can play for hours and hours without getting bored. It is a game that makes me feel excited and entertained. I enjoy playing different modes and maps with my friends or online players. The game is also very moddable and has a great community of fans. I have installed it on my old PC with only 2 GB of RAM and it runs fine."

                -- Mike, Reddit user -
                -

                Conclusion

                - -

                Call of Duty Ghost 2GB Ram Crack is a great way to download and play COD Ghosts on a low-end PC with only 2 GB of RAM. You can enjoy all the features and functions of the game such as single-player campaign, multiplayer mode, extinction mode, squads mode, and more. You can also play COD Ghosts offline without needing an internet connection or a Steam account. You can also update COD Ghosts easily by downloading new patches and cracks from Reloaded or other sources. You can also mod COD Ghosts with various mods that enhance the gameplay and graphics of the game.

                - -

                However, it also comes with some risks and drawbacks that you should be aware of before deciding to use it. You might encounter some viruses or malware that can harm your PC or steal your data if you download from untrusted sources or open suspicious files. You might face some legal issues or penalties if you get caught downloading or playing pirated games by authorities or developers. You might experience some bugs or errors that can affect your gameplay or performance if you use outdated or incompatible cracks or patches. You might lose some features or functions that are only available in the official game such as multiplayer mode or Steam achievements. You might not be able to get technical support or customer service from Activision or Infinity Ward if you encounter any problems with COD Ghosts.

                - -

                Ultimately, it is up to you whether you want to support Activision and Infinity Ward by buying their game or not. If you enjoyed this article, please share it with your friends who are also interested in COD Ghosts. Also, feel free to leave a comment below if you have any questions or feedback about Call of Duty Ghost 2GB Ram Crack.

                3cee63e6c2
                -
                -
                \ No newline at end of file diff --git a/spaces/vaibhavarduino/anime-plus/e4e/criteria/lpips/__init__.py b/spaces/vaibhavarduino/anime-plus/e4e/criteria/lpips/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/vict0rsch/climateGAN/sbatch.py b/spaces/vict0rsch/climateGAN/sbatch.py deleted file mode 100644 index 5fb5cab4bfa57449479d252646b21c8d464e815f..0000000000000000000000000000000000000000 --- a/spaces/vict0rsch/climateGAN/sbatch.py +++ /dev/null @@ -1,933 +0,0 @@ -import datetime -import itertools -import os -import re -import subprocess -import sys -from collections import defaultdict -from pathlib import Path - -import numpy as np -import yaml - - -def flatten_conf(conf, to={}, parents=[]): - """ - Flattens a configuration dict: nested dictionaries are flattened - as key1.key2.key3 = value - - conf.yaml: - ```yaml - a: 1 - b: - c: 2 - d: - e: 3 - g: - sample: sequential - from: [4, 5] - ``` - - Is flattened to - - { - "a": 1, - "b.c": 2, - "b.d.e": 3, - "b.g": { - "sample": "sequential", - "from": [4, 5] - } - } - - Does not affect sampling dicts. - - Args: - conf (dict): the configuration to flatten - new (dict, optional): the target flatenned dict. Defaults to {}. - parents (list, optional): a final value's list of parents. Defaults to []. - """ - for k, v in conf.items(): - if isinstance(v, dict) and "sample" not in v: - flatten_conf(v, to, parents + [k]) - else: - new_k = ".".join([str(p) for p in parents + [k]]) - to[new_k] = v - - -def env_to_path(path): - """Transorms an environment variable mention in a json - into its actual value. E.g. $HOME/clouds -> /home/vsch/clouds - - Args: - path (str): path potentially containing the env variable - - """ - path_elements = path.split("/") - new_path = [] - for el in path_elements: - if "$" in el: - new_path.append(os.environ[el.replace("$", "")]) - else: - new_path.append(el) - return "/".join(new_path) - - -class C: - HEADER = "\033[95m" - OKBLUE = "\033[94m" - OKGREEN = "\033[92m" - WARNING = "\033[93m" - FAIL = "\033[91m" - ENDC = "\033[0m" - BOLD = "\033[1m" - UNDERLINE = "\033[4m" - ITALIC = "\33[3m" - BEIGE = "\33[36m" - - -def escape_path(path): - p = str(path) - return p.replace(" ", "\ ").replace("(", "\(").replace(")", "\)") # noqa: W605 - - -def warn(*args, **kwargs): - print("{}{}{}".format(C.WARNING, " ".join(args), C.ENDC), **kwargs) - - -def parse_jobID(command_output): - """ - get job id from successful sbatch command output like - `Submitted batch job 599583` - - Args: - command_output (str): sbatch command's output - - Returns: - int: the slurm job's ID - """ - command_output = command_output.strip() - if isinstance(command_output, str): - if "Submitted batch job" in command_output: - return int(command_output.split()[-1]) - - return -1 - - -def now(): - return str(datetime.datetime.now()).replace(" ", "_") - - -def cols(): - try: - col = os.get_terminal_size().columns - except Exception: - col = 50 - return col - - -def print_box(txt): - if not txt: - txt = "{}{}ERROR ⇪{}".format(C.BOLD, C.FAIL, C.ENDC) - lt = 7 - else: - lt = len(txt) - nlt = lt + 12 - txt = "|" + " " * 5 + txt + " " * 5 + "|" - line = "-" * nlt - empty = "|" + " " * (nlt - 2) + "|" - print(line) - print(empty) - print(txt) - print(empty) - print(line) - - -def print_header(idx): - b = C.BOLD - bl = C.OKBLUE - e = C.ENDC - char = "≡" - c = cols() - - txt = " " * 20 - txt += f"{b}{bl}Run {idx}{e}" - txt += " " * 20 - ln = len(txt) - len(b) - len(bl) - len(e) - t = int(np.floor((c - ln) / 2)) - tt = int(np.ceil((c - ln) / 2)) - - print(char * c) - print(char * t + " " * ln + char * tt) - print(char * t + txt + char * tt) - print(char * t + " " * ln + char * tt) - print(char * c) - - -def print_footer(): - c = cols() - char = "﹎" - print() - print(char * (c // len(char))) - print() - print(" " * (c // 2) + "•" + " " * (c - c // 2 - 1)) - print() - - -def extend_summary(summary, tmp_train_args_dict, tmp_template_dict, exclude=[]): - exclude = set(exclude) - if summary is None: - summary = defaultdict(list) - for k, v in tmp_template_dict.items(): - if k not in exclude: - summary[k].append(v) - for k, v in tmp_train_args_dict.items(): - if k not in exclude: - if isinstance(v, list): - v = str(v) - summary[k].append(v) - return summary - - -def search_summary_table(summary, summary_dir=None): - # filter out constant values - summary = {k: v for k, v in summary.items() if len(set(v)) > 1} - - # if everything is constant: no summary - if not summary: - return None, None - - # find number of searches - n_searches = len(list(summary.values())[0]) - - # print section title - print( - "{}{}{}Varying values across {} experiments:{}\n".format( - C.OKBLUE, - C.BOLD, - C.UNDERLINE, - n_searches, - C.ENDC, - ) - ) - - # first column holds the Exp. number - first_col = { - "len": 8, # length of a column, to split columns according to terminal width - "str": ["| Exp. |", "|:----:|"] - + [ - "| {0:^{1}} |".format(i, 4) for i in range(n_searches) - ], # list of values to print - } - - print_columns = [[first_col]] - file_columns = [first_col] - for k in sorted(summary.keys()): - v = summary[k] - col_title = f" {k} |" - col_blank_line = f":{'-' * len(k)}-|" - col_values = [ - " {0:{1}} |".format( - crop_string( - str(crop_float(v[idx], min([5, len(k) - 2]))), len(k) - ), # crop floats and long strings - len(k), - ) - for idx in range(len(v)) - ] - - # create column object - col = {"len": len(k) + 3, "str": [col_title, col_blank_line] + col_values} - - # if adding a new column would overflow the terminal and mess up printing, start - # new set of columns - if sum(c["len"] for c in print_columns[-1]) + col["len"] >= cols(): - print_columns.append([first_col]) - - # store current column to latest group of columns - print_columns[-1].append(col) - file_columns.append(col) - - print_table = "" - # print each column group individually - for colgroup in print_columns: - # print columns line by line - for i in range(n_searches + 2): - # get value of column for current line i - for col in colgroup: - print_table += col["str"][i] - # next line for current columns - print_table += "\n" - - # new lines for new column group - print_table += "\n" - - file_table = "" - for i in range(n_searches + 2): - # get value of column for current line i - for col in file_columns: - file_table += col["str"][i] - # next line for current columns - file_table += "\n" - - summary_path = None - if summary_dir is not None: - summary_path = summary_dir / (now() + ".md") - with summary_path.open("w") as f: - f.write(file_table.strip()) - - return print_table, summary_path - - -def clean_arg(v): - """ - chain cleaning function - - Args: - v (any): arg to pass to train.py - - Returns: - str: parsed value to string - """ - return stringify_list(crop_float(quote_string(resolve_env(v)))) - - -def resolve_env(v): - """ - resolve env variables in paths - - Args: - v (any): arg to pass to train.py - - Returns: - str: try and resolve an env variable - """ - if isinstance(v, str): - try: - if "$" in v: - if "/" in v: - v = env_to_path(v) - else: - _v = os.environ.get(v) - if _v is not None: - v = _v - except Exception: - pass - return v - - -def stringify_list(v): - """ - Stringify list (with double quotes) so that it can be passed a an argument - to train.py's hydra command-line parsing - - Args: - v (any): value to clean - - Returns: - any: type of v, str if v was a list - """ - if isinstance(v, list): - return '"{}"'.format(str(v).replace('"', "'")) - if isinstance(v, str): - if v.startswith("[") and v.endswith("]"): - return f'"{v}"' - return v - - -def quote_string(v): - """ - Add double quotes around string if it contains a " " or an = - - Args: - v (any): value to clean - - Returns: - any: type of v, quoted if v is a string with " " or = - """ - if isinstance(v, str): - if " " in v or "=" in v: - return f'"{v}"' - return v - - -def crop_float(v, k=5): - """ - If v is a float, crop precision to 5 digits and return v as a str - - Args: - v (any): value to crop if float - - Returns: - any: cropped float as str if v is a float, original v otherwise - """ - if isinstance(v, float): - return "{0:.{1}g}".format(v, k) - return v - - -def compute_n_search(conf): - """ - Compute the number of searchs to do if using -1 as n_search and using - cartesian or sequential search - - Args: - conf (dict): experimental configuration - - Returns: - int: size of the cartesian product or length of longest sequential field - """ - samples = defaultdict(list) - for k, v in conf.items(): - if not isinstance(v, dict) or "sample" not in v: - continue - samples[v["sample"]].append(v) - - totals = [] - - if "cartesian" in samples: - total = 1 - for s in samples["cartesian"]: - total *= len(s["from"]) - totals.append(total) - if "sequential" in samples: - total = max(map(len, [s["from"] for s in samples["sequential"]])) - totals.append(total) - - if totals: - return max(totals) - - raise ValueError( - "Used n_search=-1 without any field being 'cartesian' or 'sequential'" - ) - - -def crop_string(s, k=10): - if len(s) <= k: - return s - else: - return s[: k - 2] + ".." - - -def sample_param(sample_dict): - """sample a value (hyperparameter) from the instruction in the - sample dict: - { - "sample": "range | list", - "from": [min, max, step] | [v0, v1, v2 etc.] - } - if range, as np.arange is used, "from" MUST be a list, but may contain - only 1 (=min) or 2 (min and max) values, not necessarily 3 - - Args: - sample_dict (dict): instructions to sample a value - - Returns: - scalar: sampled value - """ - if not isinstance(sample_dict, dict) or "sample" not in sample_dict: - return sample_dict - - if sample_dict["sample"] == "cartesian": - assert isinstance( - sample_dict["from"], list - ), "{}'s `from` field MUST be a list, found {}".format( - sample_dict["sample"], sample_dict["from"] - ) - return "__cartesian__" - - if sample_dict["sample"] == "sequential": - assert isinstance( - sample_dict["from"], list - ), "{}'s `from` field MUST be a list, found {}".format( - sample_dict["sample"], sample_dict["from"] - ) - return "__sequential__" - - if sample_dict["sample"] == "range": - return np.random.choice(np.arange(*sample_dict["from"])) - - if sample_dict["sample"] == "list": - return np.random.choice(sample_dict["from"]) - - if sample_dict["sample"] == "uniform": - return np.random.uniform(*sample_dict["from"]) - - raise ValueError("Unknown sample type in dict " + str(sample_dict)) - - -def sample_sequentials(sequential_keys, exp, idx): - """ - Samples sequentially from the "from" values specified in each key of the - experimental configuration which have sample == "sequential" - Unlike `cartesian` sampling, `sequential` sampling iterates *independently* - over each keys - - Args: - sequential_keys (list): keys to be sampled sequentially - exp (dict): experimental config - idx (int): index of the current sample - - Returns: - conf: sampled dict - """ - conf = {} - for k in sequential_keys: - v = exp[k]["from"] - conf[k] = v[idx % len(v)] - return conf - - -def sample_cartesians(cartesian_keys, exp, idx): - """ - Returns the `idx`th item in the cartesian product of all cartesian keys to - be sampled. - - Args: - cartesian_keys (list): keys in the experimental configuration that are to - be used in the full cartesian product - exp (dict): experimental configuration - idx (int): index of the current sample - - Returns: - dict: sampled point in the cartesian space (with keys = cartesian_keys) - """ - conf = {} - cartesian_values = [exp[key]["from"] for key in cartesian_keys] - product = list(itertools.product(*cartesian_values)) - for k, v in zip(cartesian_keys, product[idx % len(product)]): - conf[k] = v - return conf - - -def resolve(hp_conf, nb): - """ - Samples parameters parametrized in `exp`: should be a dict with - values which fit `sample_params(dic)`'s API - - Args: - exp (dict): experiment's parametrization - nb (int): number of experiments to sample - - Returns: - dict: sampled configuration - """ - if nb == -1: - nb = compute_n_search(hp_conf) - - confs = [] - for idx in range(nb): - conf = {} - cartesians = [] - sequentials = [] - for k, v in hp_conf.items(): - candidate = sample_param(v) - if candidate == "__cartesian__": - cartesians.append(k) - elif candidate == "__sequential__": - sequentials.append(k) - else: - conf[k] = candidate - if sequentials: - conf.update(sample_sequentials(sequentials, hp_conf, idx)) - if cartesians: - conf.update(sample_cartesians(cartesians, hp_conf, idx)) - confs.append(conf) - return confs - - -def get_template_params(template): - """ - extract args in template str as {arg} - - Args: - template (str): sbatch template string - - Returns: - list(str): Args required to format the template string - """ - return map( - lambda s: s.replace("{", "").replace("}", ""), - re.findall("\{.*?\}", template), # noqa: W605 - ) - - -def read_exp_conf(name): - """ - Read hp search configuration from shared/experiment/ - specified with or without the .yaml extension - - Args: - name (str): name of the template to find in shared/experiment/ - - Returns: - Tuple(Path, dict): file path and loaded dict - """ - if ".yaml" not in name: - name += ".yaml" - paths = [] - dirs = ["shared", "config"] - for d in dirs: - path = Path(__file__).parent / d / "experiment" / name - if path.exists(): - paths.append(path.resolve()) - - if len(paths) == 0: - failed = [Path(__file__).parent / d / "experiment" for d in dirs] - s = "Could not find search config {} in :\n".format(name) - for fd in failed: - s += str(fd) + "\nAvailable:\n" - for ym in fd.glob("*.yaml"): - s += " " + ym.name + "\n" - raise ValueError(s) - - if len(paths) == 2: - print( - "Warning: found 2 relevant files for search config:\n{}".format( - "\n".join(paths) - ) - ) - print("Using {}".format(paths[-1])) - - with paths[-1].open("r") as f: - conf = yaml.safe_load(f) - - flat_conf = {} - flatten_conf(conf, to=flat_conf) - - return (paths[-1], flat_conf) - - -def read_template(name): - """ - Read template from shared/template/ specified with or without the .sh extension - - Args: - name (str): name of the template to find in shared/template/ - - Returns: - str: file's content as 1 string - """ - if ".sh" not in name: - name += ".sh" - paths = [] - dirs = ["shared", "config"] - for d in dirs: - path = Path(__file__).parent / d / "template" / name - if path.exists(): - paths.append(path) - - if len(paths) == 0: - failed = [Path(__file__).parent / d / "template" for d in dirs] - s = "Could not find template {} in :\n".format(name) - for fd in failed: - s += str(fd) + "\nAvailable:\n" - for ym in fd.glob("*.sh"): - s += " " + ym.name + "\n" - raise ValueError(s) - - if len(paths) == 2: - print("Warning: found 2 relevant template files:\n{}".format("\n".join(paths))) - print("Using {}".format(paths[-1])) - - with paths[-1].open("r") as f: - return f.read() - - -def is_sampled(key, conf): - """ - Is a key sampled or constant? Returns true if conf is empty - - Args: - key (str): key to check - conf (dict): hyper parameter search configuration dict - - Returns: - bool: key is sampled? - """ - return not conf or ( - key in conf and isinstance(conf[key], dict) and "sample" in conf[key] - ) - - -if __name__ == "__main__": - - """ - Notes: - * Must provide template name as template=name - * `name`.sh should be in shared/template/ - """ - - # ------------------------------- - # ----- Default Variables ----- - # ------------------------------- - - args = sys.argv[1:] - command_output = "" - user = os.environ.get("USER") - home = os.environ.get("HOME") - exp_conf = {} - dev = False - escape = False - verbose = False - template_name = None - hp_exp_name = None - hp_search_nb = None - exp_path = None - resume = None - force_sbatchs = False - sbatch_base = Path(home) / "climategan_sbatchs" - summary_dir = Path(home) / "climategan_exp_summaries" - - hp_search_private = set(["n_search", "template", "search", "summary_dir"]) - - sbatch_path = "hash" - - # -------------------------- - # ----- Sanity Check ----- - # -------------------------- - - for arg in args: - if "=" not in arg or " = " in arg: - raise ValueError( - "Args should be passed as `key=value`. Received `{}`".format(arg) - ) - - # -------------------------------- - # ----- Parse Command Line ----- - # -------------------------------- - - args_dict = {arg.split("=")[0]: arg.split("=")[1] for arg in args} - - assert "template" in args_dict, "Please specify template=xxx" - template = read_template(args_dict["template"]) - template_dict = {k: None for k in get_template_params(template)} - - train_args = [] - for k, v in args_dict.items(): - - if k == "verbose": - if v != "0": - verbose = True - - elif k == "sbatch_path": - sbatch_path = v - - elif k == "sbatch_base": - sbatch_base = Path(v).resolve() - - elif k == "force_sbatchs": - force_sbatchs = v.lower() == "true" - - elif k == "dev": - if v.lower() != "false": - dev = True - - elif k == "escape": - if v.lower() != "false": - escape = True - - elif k == "template": - template_name = v - - elif k == "exp": - hp_exp_name = v - - elif k == "n_search": - hp_search_nb = int(v) - - elif k == "resume": - resume = f'"{v}"' - template_dict[k] = f'"{v}"' - - elif k == "summary_dir": - if v.lower() == "none": - summary_dir = None - else: - summary_dir = Path(v) - - elif k in template_dict: - template_dict[k] = v - - else: - train_args.append(f"{k}={v}") - - # ------------------------------------ - # ----- Load Experiment Config ----- - # ------------------------------------ - - if hp_exp_name is not None: - exp_path, exp_conf = read_exp_conf(hp_exp_name) - if "n_search" in exp_conf and hp_search_nb is None: - hp_search_nb = exp_conf["n_search"] - - assert ( - hp_search_nb is not None - ), "n_search should be specified in a yaml file or from the command line" - - hps = resolve(exp_conf, hp_search_nb) - - else: - hps = [None] - - # --------------------------------- - # ----- Run All Experiments ----- - # --------------------------------- - if summary_dir is not None: - summary_dir.mkdir(exist_ok=True, parents=True) - summary = None - - for hp_idx, hp in enumerate(hps): - - # copy shared values - tmp_template_dict = template_dict.copy() - tmp_train_args = train_args.copy() - tmp_train_args_dict = { - arg.split("=")[0]: arg.split("=")[1] for arg in tmp_train_args - } - print_header(hp_idx) - # override shared values with run-specific values for run hp_idx/n_search - if hp is not None: - for k, v in hp.items(): - if k == "resume" and resume is None: - resume = f'"{v}"' - # hp-search params to ignore - if k in hp_search_private: - continue - - if k == "codeloc": - v = escape_path(v) - - if k == "output": - Path(v).parent.mkdir(parents=True, exist_ok=True) - - # override template params depending on exp config - if k in tmp_template_dict: - if template_dict[k] is None or is_sampled(k, exp_conf): - tmp_template_dict[k] = v - # store sampled / specified params in current tmp_train_args_dict - else: - if k in tmp_train_args_dict: - if is_sampled(k, exp_conf): - # warn if key was specified from the command line - tv = tmp_train_args_dict[k] - warn( - "\nWarning: overriding sampled config-file arg", - "{} to command-line value {}\n".format(k, tv), - ) - else: - tmp_train_args_dict[k] = v - - # create sbatch file where required - tmp_sbatch_path = None - if sbatch_path == "hash": - tmp_sbatch_name = "" if hp_exp_name is None else hp_exp_name[:14] + "_" - tmp_sbatch_name += now() + ".sh" - tmp_sbatch_path = sbatch_base / tmp_sbatch_name - tmp_sbatch_path.parent.mkdir(parents=True, exist_ok=True) - tmp_train_args_dict["sbatch_file"] = str(tmp_sbatch_path) - tmp_train_args_dict["exp_file"] = str(exp_path) - else: - tmp_sbatch_path = Path(sbatch_path).resolve() - - summary = extend_summary( - summary, tmp_train_args_dict, tmp_template_dict, exclude=["sbatch_file"] - ) - - # format train.py's args and crop floats' precision to 5 digits - tmp_template_dict["train_args"] = " ".join( - sorted( - [ - "{}={}".format(k, clean_arg(v)) - for k, v in tmp_train_args_dict.items() - ] - ) - ) - - if "resume.py" in template and resume is None: - raise ValueError("No `resume` value but using a resume.py template") - - # format template with clean dict (replace None with "") - sbatch = template.format( - **{ - k: v if v is not None else "" - for k, v in tmp_template_dict.items() - if k in template_dict - } - ) - - # -------------------------------------- - # ----- Execute `sbatch` Command ----- - # -------------------------------------- - if not dev or force_sbatchs: - if tmp_sbatch_path.exists(): - print(f"Warning: overwriting {sbatch_path}") - - # write sbatch file - with open(tmp_sbatch_path, "w") as f: - f.write(sbatch) - - if not dev: - # escape special characters such as " " from sbatch_path's parent dir - parent = str(tmp_sbatch_path.parent) - if escape: - parent = escape_path(parent) - - # create command to execute in a subprocess - command = "sbatch {}".format(tmp_sbatch_path.name) - # execute sbatch command & store output - command_output = subprocess.run( - command.split(), stdout=subprocess.PIPE, cwd=parent - ) - command_output = "\n" + command_output.stdout.decode("utf-8") + "\n" - - print(f"Running from {parent}:") - print(f"$ {command}") - - # --------------------------------- - # ----- Summarize Execution ----- - # --------------------------------- - if verbose: - print(C.BEIGE + C.ITALIC, "\n" + sbatch + C.ENDC) - if not dev: - print_box(command_output.strip()) - jobID = parse_jobID(command_output.strip()) - summary["Slurm JOBID"].append(jobID) - - summary["Comet Link"].append(f"[{hp_idx}][{hp_idx}]") - - print( - "{}{}Summary{} {}:".format( - C.UNDERLINE, - C.OKGREEN, - C.ENDC, - f"{C.WARNING}(DEV){C.ENDC}" if dev else "", - ) - ) - print( - " " - + "\n ".join( - "{:10}: {}".format(k, v) for k, v in tmp_template_dict.items() - ) - ) - print_footer() - - print(f"\nRan a total of {len(hps)} jobs{' in dev mode.' if dev else '.'}\n") - - table, sum_path = search_summary_table(summary, summary_dir if not dev else None) - if table is not None: - print(table) - print( - "Add `[i]: https://...` at the end of a markdown document", - "to fill in the comet links.\n", - ) - if summary_dir is None: - print("Add summary_dir=path to store the printed markdown table ⇪") - else: - print("Saved table in", str(sum_path)) - - if not dev: - print( - "Cancel entire experiment? \n$ scancel", - " ".join(map(str, summary["Slurm JOBID"])), - ) diff --git a/spaces/vinay123/panoptic-segment-anything/segment_anything/segment_anything/modeling/sam.py b/spaces/vinay123/panoptic-segment-anything/segment_anything/segment_anything/modeling/sam.py deleted file mode 100644 index 303bc2f40c3dbc84f5d4286bb73336e075a86589..0000000000000000000000000000000000000000 --- a/spaces/vinay123/panoptic-segment-anything/segment_anything/segment_anything/modeling/sam.py +++ /dev/null @@ -1,174 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -import torch -from torch import nn -from torch.nn import functional as F - -from typing import Any, Dict, List, Tuple - -from .image_encoder import ImageEncoderViT -from .mask_decoder import MaskDecoder -from .prompt_encoder import PromptEncoder - - -class Sam(nn.Module): - mask_threshold: float = 0.0 - image_format: str = "RGB" - - def __init__( - self, - image_encoder: ImageEncoderViT, - prompt_encoder: PromptEncoder, - mask_decoder: MaskDecoder, - pixel_mean: List[float] = [123.675, 116.28, 103.53], - pixel_std: List[float] = [58.395, 57.12, 57.375], - ) -> None: - """ - SAM predicts object masks from an image and input prompts. - - Arguments: - image_encoder (ImageEncoderViT): The backbone used to encode the - image into image embeddings that allow for efficient mask prediction. - prompt_encoder (PromptEncoder): Encodes various types of input prompts. - mask_decoder (MaskDecoder): Predicts masks from the image embeddings - and encoded prompts. - pixel_mean (list(float)): Mean values for normalizing pixels in the input image. - pixel_std (list(float)): Std values for normalizing pixels in the input image. - """ - super().__init__() - self.image_encoder = image_encoder - self.prompt_encoder = prompt_encoder - self.mask_decoder = mask_decoder - self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) - self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) - - @property - def device(self) -> Any: - return self.pixel_mean.device - - @torch.no_grad() - def forward( - self, - batched_input: List[Dict[str, Any]], - multimask_output: bool, - ) -> List[Dict[str, torch.Tensor]]: - """ - Predicts masks end-to-end from provided images and prompts. - If prompts are not known in advance, using SamPredictor is - recommended over calling the model directly. - - Arguments: - batched_input (list(dict)): A list over input images, each a - dictionary with the following keys. A prompt key can be - excluded if it is not present. - 'image': The image as a torch tensor in 3xHxW format, - already transformed for input to the model. - 'original_size': (tuple(int, int)) The original size of - the image before transformation, as (H, W). - 'point_coords': (torch.Tensor) Batched point prompts for - this image, with shape BxNx2. Already transformed to the - input frame of the model. - 'point_labels': (torch.Tensor) Batched labels for point prompts, - with shape BxN. - 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. - Already transformed to the input frame of the model. - 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, - in the form Bx1xHxW. - multimask_output (bool): Whether the model should predict multiple - disambiguating masks, or return a single mask. - - Returns: - (list(dict)): A list over input images, where each element is - as dictionary with the following keys. - 'masks': (torch.Tensor) Batched binary mask predictions, - with shape BxCxHxW, where B is the number of input promts, - C is determiend by multimask_output, and (H, W) is the - original size of the image. - 'iou_predictions': (torch.Tensor) The model's predictions - of mask quality, in shape BxC. - 'low_res_logits': (torch.Tensor) Low resolution logits with - shape BxCxHxW, where H=W=256. Can be passed as mask input - to subsequent iterations of prediction. - """ - input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) - image_embeddings = self.image_encoder(input_images) - - outputs = [] - for image_record, curr_embedding in zip(batched_input, image_embeddings): - if "point_coords" in image_record: - points = (image_record["point_coords"], image_record["point_labels"]) - else: - points = None - sparse_embeddings, dense_embeddings = self.prompt_encoder( - points=points, - boxes=image_record.get("boxes", None), - masks=image_record.get("mask_inputs", None), - ) - low_res_masks, iou_predictions = self.mask_decoder( - image_embeddings=curr_embedding.unsqueeze(0), - image_pe=self.prompt_encoder.get_dense_pe(), - sparse_prompt_embeddings=sparse_embeddings, - dense_prompt_embeddings=dense_embeddings, - multimask_output=multimask_output, - ) - masks = self.postprocess_masks( - low_res_masks, - input_size=image_record["image"].shape[-2:], - original_size=image_record["original_size"], - ) - masks = masks > self.mask_threshold - outputs.append( - { - "masks": masks, - "iou_predictions": iou_predictions, - "low_res_logits": low_res_masks, - } - ) - return outputs - - def postprocess_masks( - self, - masks: torch.Tensor, - input_size: Tuple[int, ...], - original_size: Tuple[int, ...], - ) -> torch.Tensor: - """ - Remove padding and upscale masks to the original image size. - - Arguments: - masks (torch.Tensor): Batched masks from the mask_decoder, - in BxCxHxW format. - input_size (tuple(int, int)): The size of the image input to the - model, in (H, W) format. Used to remove padding. - original_size (tuple(int, int)): The original size of the image - before resizing for input to the model, in (H, W) format. - - Returns: - (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) - is given by original_size. - """ - masks = F.interpolate( - masks, - (self.image_encoder.img_size, self.image_encoder.img_size), - mode="bilinear", - align_corners=False, - ) - masks = masks[..., : input_size[0], : input_size[1]] - masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) - return masks - - def preprocess(self, x: torch.Tensor) -> torch.Tensor: - """Normalize pixel values and pad to a square input.""" - # Normalize colors - x = (x - self.pixel_mean) / self.pixel_std - - # Pad - h, w = x.shape[-2:] - padh = self.image_encoder.img_size - h - padw = self.image_encoder.img_size - w - x = F.pad(x, (0, padw, 0, padh)) - return x diff --git a/spaces/vobecant/DaS/segmenter_model/fpn_picie.py b/spaces/vobecant/DaS/segmenter_model/fpn_picie.py deleted file mode 100644 index 8c2b60caea8323be3456838cf09c3f04e017e3bc..0000000000000000000000000000000000000000 --- a/spaces/vobecant/DaS/segmenter_model/fpn_picie.py +++ /dev/null @@ -1,66 +0,0 @@ -# taken from https://raw.githubusercontent.com/janghyuncho/PiCIE/1d7b034f57e98670b0d6a244b2eea11fa0dde73e/modules/fpn.py - -import torch -import torch.nn as nn -import torch.nn.functional as F -from . import backbone_picie as backbone - - -class PanopticFPN(nn.Module): - def __init__(self, arch, pretrain, n_cls): - super(PanopticFPN, self).__init__() - self.n_cls = n_cls - self.backbone = backbone.__dict__[arch](pretrained=pretrain) - self.decoder = FPNDecoder(arch, n_cls) - - def forward(self, x, encoder_features=False, decoder_features=False): - feats = self.backbone(x) - if decoder_features: - dec, outs = self.decoder(feats, get_features=decoder_features) - else: - outs = self.decoder(feats) - - if encoder_features: - if decoder_features: - return feats['res5'], dec, outs - else: - return feats['res5'], outs - else: - return outs - - -class FPNDecoder(nn.Module): - def __init__(self, arch, n_cls): - super(FPNDecoder, self).__init__() - self.n_cls = n_cls - if arch == 'resnet18': - mfactor = 1 - out_dim = 128 - else: - mfactor = 4 - out_dim = 256 - - self.layer4 = nn.Conv2d(512 * mfactor // 8, out_dim, kernel_size=1, stride=1, padding=0) - self.layer3 = nn.Conv2d(512 * mfactor // 4, out_dim, kernel_size=1, stride=1, padding=0) - self.layer2 = nn.Conv2d(512 * mfactor // 2, out_dim, kernel_size=1, stride=1, padding=0) - self.layer1 = nn.Conv2d(512 * mfactor, out_dim, kernel_size=1, stride=1, padding=0) - - self.pred = nn.Conv2d(out_dim, self.n_cls, 1, 1) - - def forward(self, x, get_features=False): - o1 = self.layer1(x['res5']) - o2 = self.upsample_add(o1, self.layer2(x['res4'])) - o3 = self.upsample_add(o2, self.layer3(x['res3'])) - o4 = self.upsample_add(o3, self.layer4(x['res2'])) - - pred = self.pred(o4) - - if get_features: - return o4, pred - else: - return pred - - def upsample_add(self, x, y): - _, _, H, W = y.size() - - return F.interpolate(x, size=(H, W), mode='bilinear', align_corners=False) + y diff --git a/spaces/vrajeshbhatt/Automated-Ticket-Management-System/style.css b/spaces/vrajeshbhatt/Automated-Ticket-Management-System/style.css deleted file mode 100644 index 114adf441e9032febb46bc056b2a8bb651075f0d..0000000000000000000000000000000000000000 --- a/spaces/vrajeshbhatt/Automated-Ticket-Management-System/style.css +++ /dev/null @@ -1,28 +0,0 @@ -body { - padding: 2rem; - font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif; -} - -h1 { - font-size: 16px; - margin-top: 0; -} - -p { - color: rgb(107, 114, 128); - font-size: 15px; - margin-bottom: 10px; - margin-top: 5px; -} - -.card { - max-width: 620px; - margin: 0 auto; - padding: 16px; - border: 1px solid lightgray; - border-radius: 16px; -} - -.card p:last-child { - margin-bottom: 0; -} diff --git a/spaces/vumichien/canvas_controlnet/README.md b/spaces/vumichien/canvas_controlnet/README.md deleted file mode 100644 index 3b870c4a82ddb0cd2887adee0ed8550dca5d11b7..0000000000000000000000000000000000000000 --- a/spaces/vumichien/canvas_controlnet/README.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Canvas Controlnet -emoji: 🌈 -colorFrom: indigo -colorTo: green -sdk: streamlit -sdk_version: 1.17.0 -app_file: app.py -pinned: false -license: bigscience-openrail-m -tags: -- making-demos ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/vumichien/canvas_controlnet/annotator/mlsd/models/mbv2_mlsd_large.py b/spaces/vumichien/canvas_controlnet/annotator/mlsd/models/mbv2_mlsd_large.py deleted file mode 100644 index 5b9799e7573ca41549b3c3b13ac47b906b369603..0000000000000000000000000000000000000000 --- a/spaces/vumichien/canvas_controlnet/annotator/mlsd/models/mbv2_mlsd_large.py +++ /dev/null @@ -1,292 +0,0 @@ -import os -import sys -import torch -import torch.nn as nn -import torch.utils.model_zoo as model_zoo -from torch.nn import functional as F - - -class BlockTypeA(nn.Module): - def __init__(self, in_c1, in_c2, out_c1, out_c2, upscale = True): - super(BlockTypeA, self).__init__() - self.conv1 = nn.Sequential( - nn.Conv2d(in_c2, out_c2, kernel_size=1), - nn.BatchNorm2d(out_c2), - nn.ReLU(inplace=True) - ) - self.conv2 = nn.Sequential( - nn.Conv2d(in_c1, out_c1, kernel_size=1), - nn.BatchNorm2d(out_c1), - nn.ReLU(inplace=True) - ) - self.upscale = upscale - - def forward(self, a, b): - b = self.conv1(b) - a = self.conv2(a) - if self.upscale: - b = F.interpolate(b, scale_factor=2.0, mode='bilinear', align_corners=True) - return torch.cat((a, b), dim=1) - - -class BlockTypeB(nn.Module): - def __init__(self, in_c, out_c): - super(BlockTypeB, self).__init__() - self.conv1 = nn.Sequential( - nn.Conv2d(in_c, in_c, kernel_size=3, padding=1), - nn.BatchNorm2d(in_c), - nn.ReLU() - ) - self.conv2 = nn.Sequential( - nn.Conv2d(in_c, out_c, kernel_size=3, padding=1), - nn.BatchNorm2d(out_c), - nn.ReLU() - ) - - def forward(self, x): - x = self.conv1(x) + x - x = self.conv2(x) - return x - -class BlockTypeC(nn.Module): - def __init__(self, in_c, out_c): - super(BlockTypeC, self).__init__() - self.conv1 = nn.Sequential( - nn.Conv2d(in_c, in_c, kernel_size=3, padding=5, dilation=5), - nn.BatchNorm2d(in_c), - nn.ReLU() - ) - self.conv2 = nn.Sequential( - nn.Conv2d(in_c, in_c, kernel_size=3, padding=1), - nn.BatchNorm2d(in_c), - nn.ReLU() - ) - self.conv3 = nn.Conv2d(in_c, out_c, kernel_size=1) - - def forward(self, x): - x = self.conv1(x) - x = self.conv2(x) - x = self.conv3(x) - return x - -def _make_divisible(v, divisor, min_value=None): - """ - This function is taken from the original tf repo. - It ensures that all layers have a channel number that is divisible by 8 - It can be seen here: - https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py - :param v: - :param divisor: - :param min_value: - :return: - """ - if min_value is None: - min_value = divisor - new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) - # Make sure that round down does not go down by more than 10%. - if new_v < 0.9 * v: - new_v += divisor - return new_v - - -class ConvBNReLU(nn.Sequential): - def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1): - self.channel_pad = out_planes - in_planes - self.stride = stride - #padding = (kernel_size - 1) // 2 - - # TFLite uses slightly different padding than PyTorch - if stride == 2: - padding = 0 - else: - padding = (kernel_size - 1) // 2 - - super(ConvBNReLU, self).__init__( - nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), - nn.BatchNorm2d(out_planes), - nn.ReLU6(inplace=True) - ) - self.max_pool = nn.MaxPool2d(kernel_size=stride, stride=stride) - - - def forward(self, x): - # TFLite uses different padding - if self.stride == 2: - x = F.pad(x, (0, 1, 0, 1), "constant", 0) - #print(x.shape) - - for module in self: - if not isinstance(module, nn.MaxPool2d): - x = module(x) - return x - - -class InvertedResidual(nn.Module): - def __init__(self, inp, oup, stride, expand_ratio): - super(InvertedResidual, self).__init__() - self.stride = stride - assert stride in [1, 2] - - hidden_dim = int(round(inp * expand_ratio)) - self.use_res_connect = self.stride == 1 and inp == oup - - layers = [] - if expand_ratio != 1: - # pw - layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1)) - layers.extend([ - # dw - ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim), - # pw-linear - nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), - nn.BatchNorm2d(oup), - ]) - self.conv = nn.Sequential(*layers) - - def forward(self, x): - if self.use_res_connect: - return x + self.conv(x) - else: - return self.conv(x) - - -class MobileNetV2(nn.Module): - def __init__(self, pretrained=True): - """ - MobileNet V2 main class - Args: - num_classes (int): Number of classes - width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount - inverted_residual_setting: Network structure - round_nearest (int): Round the number of channels in each layer to be a multiple of this number - Set to 1 to turn off rounding - block: Module specifying inverted residual building block for mobilenet - """ - super(MobileNetV2, self).__init__() - - block = InvertedResidual - input_channel = 32 - last_channel = 1280 - width_mult = 1.0 - round_nearest = 8 - - inverted_residual_setting = [ - # t, c, n, s - [1, 16, 1, 1], - [6, 24, 2, 2], - [6, 32, 3, 2], - [6, 64, 4, 2], - [6, 96, 3, 1], - #[6, 160, 3, 2], - #[6, 320, 1, 1], - ] - - # only check the first element, assuming user knows t,c,n,s are required - if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4: - raise ValueError("inverted_residual_setting should be non-empty " - "or a 4-element list, got {}".format(inverted_residual_setting)) - - # building first layer - input_channel = _make_divisible(input_channel * width_mult, round_nearest) - self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest) - features = [ConvBNReLU(4, input_channel, stride=2)] - # building inverted residual blocks - for t, c, n, s in inverted_residual_setting: - output_channel = _make_divisible(c * width_mult, round_nearest) - for i in range(n): - stride = s if i == 0 else 1 - features.append(block(input_channel, output_channel, stride, expand_ratio=t)) - input_channel = output_channel - - self.features = nn.Sequential(*features) - self.fpn_selected = [1, 3, 6, 10, 13] - # weight initialization - for m in self.modules(): - if isinstance(m, nn.Conv2d): - nn.init.kaiming_normal_(m.weight, mode='fan_out') - if m.bias is not None: - nn.init.zeros_(m.bias) - elif isinstance(m, nn.BatchNorm2d): - nn.init.ones_(m.weight) - nn.init.zeros_(m.bias) - elif isinstance(m, nn.Linear): - nn.init.normal_(m.weight, 0, 0.01) - nn.init.zeros_(m.bias) - if pretrained: - self._load_pretrained_model() - - def _forward_impl(self, x): - # This exists since TorchScript doesn't support inheritance, so the superclass method - # (this one) needs to have a name other than `forward` that can be accessed in a subclass - fpn_features = [] - for i, f in enumerate(self.features): - if i > self.fpn_selected[-1]: - break - x = f(x) - if i in self.fpn_selected: - fpn_features.append(x) - - c1, c2, c3, c4, c5 = fpn_features - return c1, c2, c3, c4, c5 - - - def forward(self, x): - return self._forward_impl(x) - - def _load_pretrained_model(self): - pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/mobilenet_v2-b0353104.pth') - model_dict = {} - state_dict = self.state_dict() - for k, v in pretrain_dict.items(): - if k in state_dict: - model_dict[k] = v - state_dict.update(model_dict) - self.load_state_dict(state_dict) - - -class MobileV2_MLSD_Large(nn.Module): - def __init__(self): - super(MobileV2_MLSD_Large, self).__init__() - - self.backbone = MobileNetV2(pretrained=False) - ## A, B - self.block15 = BlockTypeA(in_c1= 64, in_c2= 96, - out_c1= 64, out_c2=64, - upscale=False) - self.block16 = BlockTypeB(128, 64) - - ## A, B - self.block17 = BlockTypeA(in_c1 = 32, in_c2 = 64, - out_c1= 64, out_c2= 64) - self.block18 = BlockTypeB(128, 64) - - ## A, B - self.block19 = BlockTypeA(in_c1=24, in_c2=64, - out_c1=64, out_c2=64) - self.block20 = BlockTypeB(128, 64) - - ## A, B, C - self.block21 = BlockTypeA(in_c1=16, in_c2=64, - out_c1=64, out_c2=64) - self.block22 = BlockTypeB(128, 64) - - self.block23 = BlockTypeC(64, 16) - - def forward(self, x): - c1, c2, c3, c4, c5 = self.backbone(x) - - x = self.block15(c4, c5) - x = self.block16(x) - - x = self.block17(c3, x) - x = self.block18(x) - - x = self.block19(c2, x) - x = self.block20(x) - - x = self.block21(c1, x) - x = self.block22(x) - x = self.block23(x) - x = x[:, 7:, :, :] - - return x \ No newline at end of file diff --git a/spaces/wendys-llc/panoptic-segment-anything/segment_anything/linter.sh b/spaces/wendys-llc/panoptic-segment-anything/segment_anything/linter.sh deleted file mode 100644 index df2e17436d30e89ff1728109301599f425f1ad6b..0000000000000000000000000000000000000000 --- a/spaces/wendys-llc/panoptic-segment-anything/segment_anything/linter.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash -e -# Copyright (c) Facebook, Inc. and its affiliates. - -{ - black --version | grep -E "23\." > /dev/null -} || { - echo "Linter requires 'black==23.*' !" - exit 1 -} - -ISORT_VERSION=$(isort --version-number) -if [[ "$ISORT_VERSION" != 5.12* ]]; then - echo "Linter requires isort==5.12.0 !" - exit 1 -fi - -echo "Running isort ..." -isort . --atomic - -echo "Running black ..." -black -l 100 . - -echo "Running flake8 ..." -if [ -x "$(command -v flake8)" ]; then - flake8 . -else - python3 -m flake8 . -fi - -echo "Running mypy..." - -mypy --exclude 'setup.py|notebooks' . diff --git a/spaces/wffcyrus/MetaGPT-v1/metagpt/tools/openai_text_to_embedding.py b/spaces/wffcyrus/MetaGPT-v1/metagpt/tools/openai_text_to_embedding.py deleted file mode 100644 index 86b58d71fe113a5d8b3da4d958f28dc4375dc0af..0000000000000000000000000000000000000000 --- a/spaces/wffcyrus/MetaGPT-v1/metagpt/tools/openai_text_to_embedding.py +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" -@Time : 2023/8/18 -@Author : mashenquan -@File : openai_text_to_embedding.py -@Desc : OpenAI Text-to-Embedding OAS3 api, which provides text-to-embedding functionality. - For more details, checkout: `https://platform.openai.com/docs/api-reference/embeddings/object` -""" -import asyncio -import os -from pathlib import Path -from typing import List - -import aiohttp -import requests -from pydantic import BaseModel -import sys - -from metagpt.config import CONFIG, Config - -sys.path.append(str(Path(__file__).resolve().parent.parent.parent)) # fix-bug: No module named 'metagpt' -from metagpt.logs import logger - - -class Embedding(BaseModel): - """Represents an embedding vector returned by embedding endpoint.""" - object: str # The object type, which is always "embedding". - embedding: List[ - float] # The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the embedding guide. - index: int # The index of the embedding in the list of embeddings. - - -class Usage(BaseModel): - prompt_tokens: int - total_tokens: int - - -class ResultEmbedding(BaseModel): - object: str - data: List[Embedding] - model: str - usage: Usage - - -class OpenAIText2Embedding: - def __init__(self, openai_api_key): - """ - :param openai_api_key: OpenAI API key, For more details, checkout: `https://platform.openai.com/account/api-keys` - """ - self.openai_api_key = openai_api_key if openai_api_key else CONFIG.OPENAI_API_KEY - - async def text_2_embedding(self, text, model="text-embedding-ada-002"): - """Text to embedding - - :param text: The text used for embedding. - :param model: One of ['text-embedding-ada-002'], ID of the model to use. For more details, checkout: `https://api.openai.com/v1/models`. - :return: A json object of :class:`ResultEmbedding` class if successful, otherwise `{}`. - """ - - headers = { - "Content-Type": "application/json", - "Authorization": f"Bearer {self.openai_api_key}" - } - data = {"input": text, "model": model} - try: - async with aiohttp.ClientSession() as session: - async with session.post("https://api.openai.com/v1/embeddings", headers=headers, json=data) as response: - return await response.json() - except requests.exceptions.RequestException as e: - logger.error(f"An error occurred:{e}") - return {} - - -# Export -async def oas3_openai_text_to_embedding(text, model="text-embedding-ada-002", openai_api_key=""): - """Text to embedding - - :param text: The text used for embedding. - :param model: One of ['text-embedding-ada-002'], ID of the model to use. For more details, checkout: `https://api.openai.com/v1/models`. - :param openai_api_key: OpenAI API key, For more details, checkout: `https://platform.openai.com/account/api-keys` - :return: A json object of :class:`ResultEmbedding` class if successful, otherwise `{}`. - """ - if not text: - return "" - if not openai_api_key: - openai_api_key = CONFIG.OPENAI_API_KEY - return await OpenAIText2Embedding(openai_api_key).text_2_embedding(text, model=model) - - -if __name__ == "__main__": - Config() - loop = asyncio.new_event_loop() - task = loop.create_task(oas3_openai_text_to_embedding("Panda emoji")) - v = loop.run_until_complete(task) - print(v) diff --git a/spaces/wouaf/WOUAF-Text-to-Image/torch_utils/ops/bias_act.cpp b/spaces/wouaf/WOUAF-Text-to-Image/torch_utils/ops/bias_act.cpp deleted file mode 100644 index 5d2425d8054991a8e8b6f7a940fd0ff7fa0bb330..0000000000000000000000000000000000000000 --- a/spaces/wouaf/WOUAF-Text-to-Image/torch_utils/ops/bias_act.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. -// -// NVIDIA CORPORATION and its licensors retain all intellectual property -// and proprietary rights in and to this software, related documentation -// and any modifications thereto. Any use, reproduction, disclosure or -// distribution of this software and related documentation without an express -// license agreement from NVIDIA CORPORATION is strictly prohibited. - -#include -#include -#include -#include "bias_act.h" - -//------------------------------------------------------------------------ - -static bool has_same_layout(torch::Tensor x, torch::Tensor y) -{ - if (x.dim() != y.dim()) - return false; - for (int64_t i = 0; i < x.dim(); i++) - { - if (x.size(i) != y.size(i)) - return false; - if (x.size(i) >= 2 && x.stride(i) != y.stride(i)) - return false; - } - return true; -} - -//------------------------------------------------------------------------ - -static torch::Tensor bias_act(torch::Tensor x, torch::Tensor b, torch::Tensor xref, torch::Tensor yref, torch::Tensor dy, int grad, int dim, int act, float alpha, float gain, float clamp) -{ - // Validate arguments. - TORCH_CHECK(x.is_cuda(), "x must reside on CUDA device"); - TORCH_CHECK(b.numel() == 0 || (b.dtype() == x.dtype() && b.device() == x.device()), "b must have the same dtype and device as x"); - TORCH_CHECK(xref.numel() == 0 || (xref.sizes() == x.sizes() && xref.dtype() == x.dtype() && xref.device() == x.device()), "xref must have the same shape, dtype, and device as x"); - TORCH_CHECK(yref.numel() == 0 || (yref.sizes() == x.sizes() && yref.dtype() == x.dtype() && yref.device() == x.device()), "yref must have the same shape, dtype, and device as x"); - TORCH_CHECK(dy.numel() == 0 || (dy.sizes() == x.sizes() && dy.dtype() == x.dtype() && dy.device() == x.device()), "dy must have the same dtype and device as x"); - TORCH_CHECK(x.numel() <= INT_MAX, "x is too large"); - TORCH_CHECK(b.dim() == 1, "b must have rank 1"); - TORCH_CHECK(b.numel() == 0 || (dim >= 0 && dim < x.dim()), "dim is out of bounds"); - TORCH_CHECK(b.numel() == 0 || b.numel() == x.size(dim), "b has wrong number of elements"); - TORCH_CHECK(grad >= 0, "grad must be non-negative"); - - // Validate layout. - TORCH_CHECK(x.is_non_overlapping_and_dense(), "x must be non-overlapping and dense"); - TORCH_CHECK(b.is_contiguous(), "b must be contiguous"); - TORCH_CHECK(xref.numel() == 0 || has_same_layout(xref, x), "xref must have the same layout as x"); - TORCH_CHECK(yref.numel() == 0 || has_same_layout(yref, x), "yref must have the same layout as x"); - TORCH_CHECK(dy.numel() == 0 || has_same_layout(dy, x), "dy must have the same layout as x"); - - // Create output tensor. - const at::cuda::OptionalCUDAGuard device_guard(device_of(x)); - torch::Tensor y = torch::empty_like(x); - TORCH_CHECK(has_same_layout(y, x), "y must have the same layout as x"); - - // Initialize CUDA kernel parameters. - bias_act_kernel_params p; - p.x = x.data_ptr(); - p.b = (b.numel()) ? b.data_ptr() : NULL; - p.xref = (xref.numel()) ? xref.data_ptr() : NULL; - p.yref = (yref.numel()) ? yref.data_ptr() : NULL; - p.dy = (dy.numel()) ? dy.data_ptr() : NULL; - p.y = y.data_ptr(); - p.grad = grad; - p.act = act; - p.alpha = alpha; - p.gain = gain; - p.clamp = clamp; - p.sizeX = (int)x.numel(); - p.sizeB = (int)b.numel(); - p.stepB = (b.numel()) ? (int)x.stride(dim) : 1; - - // Choose CUDA kernel. - void* kernel; - AT_DISPATCH_FLOATING_TYPES_AND_HALF(x.scalar_type(), "upfirdn2d_cuda", [&] - { - kernel = choose_bias_act_kernel(p); - }); - TORCH_CHECK(kernel, "no CUDA kernel found for the specified activation func"); - - // Launch CUDA kernel. - p.loopX = 4; - int blockSize = 4 * 32; - int gridSize = (p.sizeX - 1) / (p.loopX * blockSize) + 1; - void* args[] = {&p}; - AT_CUDA_CHECK(cudaLaunchKernel(kernel, gridSize, blockSize, args, 0, at::cuda::getCurrentCUDAStream())); - return y; -} - -//------------------------------------------------------------------------ - -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) -{ - m.def("bias_act", &bias_act); -} - -//------------------------------------------------------------------------ diff --git a/spaces/xdecoder/Demo/README.md b/spaces/xdecoder/Demo/README.md deleted file mode 100644 index 9784c424aebcca84ea757a07611dd6ebad4c633a..0000000000000000000000000000000000000000 --- a/spaces/xdecoder/Demo/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: All-in-One Demo -emoji: 🔥 -colorFrom: yellow -colorTo: green -sdk: gradio -sdk_version: 3.14.0 -app_file: app.py -pinned: false -license: afl-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/xswu/HPSv2/src/open_clip/loss.py b/spaces/xswu/HPSv2/src/open_clip/loss.py deleted file mode 100644 index 8675e0db8085da1a3aca5b0065df3456bf1c5d30..0000000000000000000000000000000000000000 --- a/spaces/xswu/HPSv2/src/open_clip/loss.py +++ /dev/null @@ -1,270 +0,0 @@ -import torch -import torch.nn as nn -from torch.nn import functional as F -from torch.nn.utils.rnn import pad_sequence - -try: - import torch.distributed.nn - from torch import distributed as dist - - has_distributed = True -except ImportError: - has_distributed = False - -try: - import horovod.torch as hvd -except ImportError: - hvd = None - - -def gather_features( - image_features, - text_features, - local_loss=False, - gather_with_grad=False, - rank=0, - world_size=1, - use_horovod=False -): - assert has_distributed, 'torch.distributed did not import correctly, please use a PyTorch version with support.' - if use_horovod: - assert hvd is not None, 'Please install horovod' - if gather_with_grad: - all_image_features = hvd.allgather(image_features) - all_text_features = hvd.allgather(text_features) - else: - with torch.no_grad(): - all_image_features = hvd.allgather(image_features) - all_text_features = hvd.allgather(text_features) - if not local_loss: - # ensure grads for local rank when all_* features don't have a gradient - gathered_image_features = list(all_image_features.chunk(world_size, dim=0)) - gathered_text_features = list(all_text_features.chunk(world_size, dim=0)) - gathered_image_features[rank] = image_features - gathered_text_features[rank] = text_features - all_image_features = torch.cat(gathered_image_features, dim=0) - all_text_features = torch.cat(gathered_text_features, dim=0) - else: - # We gather tensors from all gpus - if gather_with_grad: - all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features), dim=0) - all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features), dim=0) - else: - gathered_image_features = [torch.zeros_like(image_features) for _ in range(world_size)] - gathered_text_features = [torch.zeros_like(text_features) for _ in range(world_size)] - dist.all_gather(gathered_image_features, image_features) - dist.all_gather(gathered_text_features, text_features) - if not local_loss: - # ensure grads for local rank when all_* features don't have a gradient - gathered_image_features[rank] = image_features - gathered_text_features[rank] = text_features - all_image_features = torch.cat(gathered_image_features, dim=0) - all_text_features = torch.cat(gathered_text_features, dim=0) - - return all_image_features, all_text_features - - -class ClipLoss(nn.Module): - - def __init__( - self, - local_loss=False, - gather_with_grad=False, - cache_labels=False, - rank=0, - world_size=1, - use_horovod=False, - ): - super().__init__() - self.local_loss = local_loss - self.gather_with_grad = gather_with_grad - self.cache_labels = cache_labels - self.rank = rank - self.world_size = world_size - self.use_horovod = use_horovod - - # cache state - self.prev_num_logits = 0 - self.labels = {} - - def get_ground_truth(self, device, num_logits) -> torch.Tensor: - # calculated ground-truth and cache if enabled - if self.prev_num_logits != num_logits or device not in self.labels: - labels = torch.arange(num_logits, device=device, dtype=torch.long) - if self.world_size > 1 and self.local_loss: - labels = labels + num_logits * self.rank - if self.cache_labels: - self.labels[device] = labels - self.prev_num_logits = num_logits - else: - labels = self.labels[device] - return labels - - def get_logits(self, image_features, text_features, logit_scale): - if self.world_size > 1: - all_image_features, all_text_features = gather_features( - image_features, text_features, - self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod) - - if self.local_loss: - logits_per_image = logit_scale * image_features @ all_text_features.T - logits_per_text = logit_scale * text_features @ all_image_features.T - else: - logits_per_image = logit_scale * all_image_features @ all_text_features.T - logits_per_text = logits_per_image.T - else: - logits_per_image = logit_scale * image_features @ text_features.T - logits_per_text = logit_scale * text_features @ image_features.T - - return logits_per_image, logits_per_text - - def forward(self, image_features, text_features, logit_scale, output_dict=False): - device = image_features.device - logits_per_image, logits_per_text = self.get_logits(image_features, text_features, logit_scale) - - labels = self.get_ground_truth(device, logits_per_image.shape[0]) - - total_loss = ( - F.cross_entropy(logits_per_image, labels) + - F.cross_entropy(logits_per_text, labels) - ) / 2 - return total_loss - -class PreferenceLoss(nn.Module): - - def forward(self, logits_per_image, num_images, labels): - - paired_logits_list = [logit[:,i] for i, logit in enumerate(logits_per_image.split(num_images.tolist()))] - paired_logits = pad_sequence(paired_logits_list, batch_first=True, padding_value=-999) - - ce_loss = F.cross_entropy(paired_logits, labels) - return ce_loss - -class HPSLoss(nn.Module): - - def forward(self, text_logits, labels): - - device = text_logits.device - text_0_logits, text_1_logits = text_logits.chunk(2, dim=-1) - label_0, label_1 = labels.chunk(2, dim=-1) - - index = torch.arange(text_0_logits.shape[0], device=device, dtype=torch.long) - text_0_logits = text_0_logits[index, index] - text_1_logits = text_1_logits[index, index] - text_logits = torch.stack([text_0_logits, text_1_logits], dim=-1) - text_0_labels = torch.zeros(text_logits.shape[0], device=device, dtype=torch.long) - text_1_labels = text_0_labels + 1 - - text_0_loss = torch.nn.functional.cross_entropy(text_logits, text_0_labels, reduction="none") - text_1_loss = torch.nn.functional.cross_entropy(text_logits, text_1_labels, reduction="none") - - text_loss = label_0 * text_0_loss + label_1 * text_1_loss - - # absolute_example_weight = 1 / num_per_prompt - # denominator = absolute_example_weight.sum() - # weight_per_example = absolute_example_weight / denominator - # text_loss *= weight_per_example - - text_loss = text_loss.sum() - return text_loss - -class RankingLoss(nn.Module): - - def forward(self, logits_per_image, num_images, labels, margin = 1.0): - paired_logits_list = [logit[:,i] for i, logit in enumerate(logits_per_image.split(num_images.tolist()))] - label_list = [label for label in labels.split(num_images.tolist())] - # ranked_logits = [torch.index_select(paired_logits_list[i], 0, rank) for i, rank in enumerate(label_list)] - - paired_logits = pad_sequence(paired_logits_list, batch_first=True, padding_value=-1) - padded_labels = pad_sequence(label_list, batch_first=True, padding_value=10) - - # regulized_logits = torch.log(torch.sigmoid(paired_logits)) - - diff = paired_logits.unsqueeze(1) - paired_logits.unsqueeze(2) - # diff = paired_logits.unsqueeze(1) - paired_logits.unsqueeze(2) - # diff_label = torch.clamp(padded_labels.unsqueeze(1) - padded_labels.unsqueeze(2), min=-1, max=1) - diff_label = - (padded_labels.unsqueeze(1) - padded_labels.unsqueeze(2)) - mask = torch.triu(torch.ones(diff.shape[1], diff.shape[1]), diagonal=1).bool().detach() - - loss = torch.clamp(margin - torch.mul(diff[:, ~mask],diff_label[:,~mask]), min=0).mean() - return loss - -class CoCaLoss(ClipLoss): - def __init__( - self, - caption_loss_weight, - clip_loss_weight, - pad_id=0, # pad_token for open_clip custom tokenizer - local_loss=False, - gather_with_grad=False, - cache_labels=False, - rank=0, - world_size=1, - use_horovod=False, - ): - super().__init__( - local_loss=local_loss, - gather_with_grad=gather_with_grad, - cache_labels=cache_labels, - rank=rank, - world_size=world_size, - use_horovod=use_horovod - ) - - self.clip_loss_weight = clip_loss_weight - self.caption_loss_weight = caption_loss_weight - self.caption_loss = nn.CrossEntropyLoss(ignore_index=pad_id) - - def forward(self, image_features, text_features, logits, labels, logit_scale, output_dict=False): - clip_loss = super().forward(image_features, text_features, logit_scale) - clip_loss = self.clip_loss_weight * clip_loss - - caption_loss = self.caption_loss( - logits.permute(0, 2, 1), - labels, - ) - caption_loss = caption_loss * self.caption_loss_weight - - if output_dict: - return {"contrastive_loss": clip_loss, "caption_loss": caption_loss} - - return clip_loss, caption_loss - - -class DistillClipLoss(ClipLoss): - - def dist_loss(self, teacher_logits, student_logits): - return -(teacher_logits.softmax(dim=1) * student_logits.log_softmax(dim=1)).sum(dim=1).mean(dim=0) - - def forward( - self, - image_features, - text_features, - logit_scale, - dist_image_features, - dist_text_features, - dist_logit_scale, - output_dict=False, - ): - logits_per_image, logits_per_text = \ - self.get_logits(image_features, text_features, logit_scale) - - dist_logits_per_image, dist_logits_per_text = \ - self.get_logits(dist_image_features, dist_text_features, dist_logit_scale) - - labels = self.get_ground_truth(image_features.device, logits_per_image.shape[0]) - - contrastive_loss = ( - F.cross_entropy(logits_per_image, labels) + - F.cross_entropy(logits_per_text, labels) - ) / 2 - - distill_loss = ( - self.dist_loss(dist_logits_per_image, logits_per_image) + - self.dist_loss(dist_logits_per_text, logits_per_text) - ) / 2 - - if output_dict: - return {"contrastive_loss": contrastive_loss, "distill_loss": distill_loss} - - return contrastive_loss, distill_loss diff --git a/spaces/yderre-aubay/midi-player-demo/src/main/components/TempoGraph/TempoGraph.tsx b/spaces/yderre-aubay/midi-player-demo/src/main/components/TempoGraph/TempoGraph.tsx deleted file mode 100644 index da8cbdf15f29f7a0391310be275b9b7d316839c0..0000000000000000000000000000000000000000 --- a/spaces/yderre-aubay/midi-player-demo/src/main/components/TempoGraph/TempoGraph.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import styled from "@emotion/styled" -import useComponentSize from "@rehooks/component-size" -import { observer } from "mobx-react-lite" -import { FC, useCallback, useEffect, useRef } from "react" -import { Layout } from "../../Constants" -import { useStores } from "../../hooks/useStores" -import { useTheme } from "../../hooks/useTheme" -import { BAR_WIDTH, HorizontalScrollBar } from "../inputs/ScrollBar" -import CanvasPianoRuler from "../PianoRoll/CanvasPianoRuler" -import { TempoGraphAxis } from "./TempoGraphAxis" -import { TempoGraphCanvas } from "./TempoGraphCanvas/TempoGraphCanvas" - -const Wrapper = styled.div` - position: relative; - flex-grow: 1; - background: ${({ theme }) => theme.backgroundColor}; - color: ${({ theme }) => theme.secondaryTextColor}; -` - -export const TempoGraph: FC = observer(() => { - const { - tempoEditorStore, - tempoEditorStore: { transform, scrollLeft: _scrollLeft, contentWidth }, - } = useStores() - - const ref = useRef(null) - const size = useComponentSize(ref) - - const setScrollLeft = useCallback( - (x: number) => (tempoEditorStore.scrollLeft = x), - [], - ) - const theme = useTheme() - - const scrollLeft = Math.floor(_scrollLeft) - - const containerWidth = size.width - const containerHeight = size.height - - const contentHeight = containerHeight - Layout.rulerHeight - BAR_WIDTH - - useEffect(() => { - tempoEditorStore.canvasWidth = containerWidth - tempoEditorStore.canvasHeight = contentHeight - }, [containerWidth, contentHeight]) - - return ( - - - - - - - ) -}) diff --git a/spaces/yerfor/SyntaSpeech/tasks/tts/speech_base.py b/spaces/yerfor/SyntaSpeech/tasks/tts/speech_base.py deleted file mode 100644 index a438c9a432fe850370ee2a10c2aa7d6c0e1fb793..0000000000000000000000000000000000000000 --- a/spaces/yerfor/SyntaSpeech/tasks/tts/speech_base.py +++ /dev/null @@ -1,373 +0,0 @@ -import filecmp -import os -import traceback -import numpy as np -import pandas as pd -import torch -import torch.distributed as dist -import torch.nn.functional as F -import torch.optim -import torch.utils.data -import yaml -from tqdm import tqdm -import utils -from tasks.tts.dataset_utils import BaseSpeechDataset -from tasks.tts.tts_utils import parse_mel_losses, parse_dataset_configs, load_data_preprocessor, load_data_binarizer -from tasks.tts.vocoder_infer.base_vocoder import BaseVocoder, get_vocoder_cls -from utils.audio.align import mel2token_to_dur -from utils.audio.io import save_wav -from utils.audio.pitch_extractors import extract_pitch_simple -from utils.commons.base_task import BaseTask -from utils.commons.ckpt_utils import load_ckpt -from utils.commons.dataset_utils import data_loader, BaseConcatDataset -from utils.commons.hparams import hparams -from utils.commons.multiprocess_utils import MultiprocessManager -from utils.commons.tensor_utils import tensors_to_scalars -from utils.metrics.ssim import ssim -from utils.nn.model_utils import print_arch -from utils.nn.schedulers import RSQRTSchedule, NoneSchedule, WarmupSchedule -from utils.nn.seq_utils import weights_nonzero_speech -from utils.plot.plot import spec_to_figure -from utils.text.text_encoder import build_token_encoder -import matplotlib.pyplot as plt - - -class SpeechBaseTask(BaseTask): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.dataset_cls = BaseSpeechDataset - self.vocoder = None - data_dir = hparams['binary_data_dir'] - if not hparams['use_word_input']: - self.token_encoder = build_token_encoder(f'{data_dir}/phone_set.json') - else: - self.token_encoder = build_token_encoder(f'{data_dir}/word_set.json') - self.padding_idx = self.token_encoder.pad() - self.eos_idx = self.token_encoder.eos() - self.seg_idx = self.token_encoder.seg() - self.saving_result_pool = None - self.saving_results_futures = None - self.mel_losses = parse_mel_losses() - self.max_tokens, self.max_sentences, \ - self.max_valid_tokens, self.max_valid_sentences = parse_dataset_configs() - - ########################## - # datasets - ########################## - @data_loader - def train_dataloader(self): - if hparams['train_sets'] != '': - train_sets = hparams['train_sets'].split("|") - # check if all train_sets have the same spk map and dictionary - binary_data_dir = hparams['binary_data_dir'] - file_to_cmp = ['phone_set.json'] - if os.path.exists(f'{binary_data_dir}/word_set.json'): - file_to_cmp.append('word_set.json') - if hparams['use_spk_id']: - file_to_cmp.append('spk_map.json') - for f in file_to_cmp: - for ds_name in train_sets: - base_file = os.path.join(binary_data_dir, f) - ds_file = os.path.join(ds_name, f) - assert filecmp.cmp(base_file, ds_file), \ - f'{f} in {ds_name} is not same with that in {binary_data_dir}.' - train_dataset = BaseConcatDataset([ - self.dataset_cls(prefix='train', shuffle=True, data_dir=ds_name) for ds_name in train_sets]) - else: - train_dataset = self.dataset_cls(prefix=hparams['train_set_name'], shuffle=True) - return self.build_dataloader(train_dataset, True, self.max_tokens, self.max_sentences, - endless=hparams['endless_ds']) - - @data_loader - def val_dataloader(self): - valid_dataset = self.dataset_cls(prefix=hparams['valid_set_name'], shuffle=False) - return self.build_dataloader(valid_dataset, False, self.max_valid_tokens, self.max_valid_sentences, - batch_by_size=False) - - @data_loader - def test_dataloader(self): - test_dataset = self.dataset_cls(prefix=hparams['test_set_name'], shuffle=False) - self.test_dl = self.build_dataloader( - test_dataset, False, self.max_valid_tokens, self.max_valid_sentences, batch_by_size=False) - return self.test_dl - - def build_dataloader(self, dataset, shuffle, max_tokens=None, max_sentences=None, - required_batch_size_multiple=-1, endless=False, batch_by_size=True): - devices_cnt = torch.cuda.device_count() - if devices_cnt == 0: - devices_cnt = 1 - if required_batch_size_multiple == -1: - required_batch_size_multiple = devices_cnt - - def shuffle_batches(batches): - np.random.shuffle(batches) - return batches - - if max_tokens is not None: - max_tokens *= devices_cnt - if max_sentences is not None: - max_sentences *= devices_cnt - indices = dataset.ordered_indices() - if batch_by_size: - batch_sampler = utils.commons.dataset_utils.batch_by_size( - indices, dataset.num_tokens, max_tokens=max_tokens, max_sentences=max_sentences, - required_batch_size_multiple=required_batch_size_multiple, - ) - else: - batch_sampler = [] - for i in range(0, len(indices), max_sentences): - batch_sampler.append(indices[i:i + max_sentences]) - - if shuffle: - batches = shuffle_batches(list(batch_sampler)) - if endless: - batches = [b for _ in range(1000) for b in shuffle_batches(list(batch_sampler))] - else: - batches = batch_sampler - if endless: - batches = [b for _ in range(1000) for b in batches] - num_workers = dataset.num_workers - if self.trainer.use_ddp: - num_replicas = dist.get_world_size() - rank = dist.get_rank() - batches = [x[rank::num_replicas] for x in batches if len(x) % num_replicas == 0] - return torch.utils.data.DataLoader(dataset, - collate_fn=dataset.collater, - batch_sampler=batches, - num_workers=num_workers, - pin_memory=False) - - ########################## - # scheduler and optimizer - ########################## - def build_model(self): - self.build_tts_model() - if hparams['load_ckpt'] != '': - load_ckpt(self.model, hparams['load_ckpt']) - print_arch(self.model) - return self.model - - def build_tts_model(self): - raise NotImplementedError - - def build_scheduler(self, optimizer): - if hparams['scheduler'] == 'rsqrt': - return RSQRTSchedule(optimizer, hparams['lr'], hparams['warmup_updates'], hparams['hidden_size']) - elif hparams['scheduler'] == 'warmup': - return WarmupSchedule(optimizer, hparams['lr'], hparams['warmup_updates']) - elif hparams['scheduler'] == 'step_lr': - return torch.optim.lr_scheduler.StepLR( - optimizer=optimizer, step_size=500, gamma=0.998) - else: - return NoneSchedule(optimizer, hparams['lr']) - - def build_optimizer(self, model): - self.optimizer = optimizer = torch.optim.AdamW( - model.parameters(), - lr=hparams['lr'], - betas=(hparams['optimizer_adam_beta1'], hparams['optimizer_adam_beta2']), - weight_decay=hparams['weight_decay']) - - return optimizer - - ########################## - # training and validation - ########################## - def _training_step(self, sample, batch_idx, _): - loss_output, _ = self.run_model(sample) - total_loss = sum([v for v in loss_output.values() if isinstance(v, torch.Tensor) and v.requires_grad]) - loss_output['batch_size'] = sample['txt_tokens'].size()[0] - return total_loss, loss_output - - def run_model(self, sample, infer=False): - """ - - :param sample: a batch of data - :param infer: bool, run in infer mode - :return: - if not infer: - return losses, model_out - if infer: - return model_out - """ - raise NotImplementedError - - def validation_start(self): - self.vocoder = get_vocoder_cls(hparams['vocoder'])() - - def validation_step(self, sample, batch_idx): - outputs = {} - outputs['losses'] = {} - outputs['losses'], model_out = self.run_model(sample) - outputs['total_loss'] = sum(outputs['losses'].values()) - outputs['nsamples'] = sample['nsamples'] - outputs = tensors_to_scalars(outputs) - if self.global_step % hparams['valid_infer_interval'] == 0 \ - and batch_idx < hparams['num_valid_plots']: - self.save_valid_result(sample, batch_idx, model_out) - return outputs - - def validation_end(self, outputs): - self.vocoder = None - return super(SpeechBaseTask, self).validation_end(outputs) - - def save_valid_result(self, sample, batch_idx, model_out): - raise NotImplementedError - - ########################## - # losses - ########################## - def add_mel_loss(self, mel_out, target, losses, postfix=''): - for loss_name, lambd in self.mel_losses.items(): - losses[f'{loss_name}{postfix}'] = getattr(self, f'{loss_name}_loss')(mel_out, target) * lambd - - def l1_loss(self, decoder_output, target): - # decoder_output : B x T x n_mel - # target : B x T x n_mel - l1_loss = F.l1_loss(decoder_output, target, reduction='none') - weights = weights_nonzero_speech(target) - l1_loss = (l1_loss * weights).sum() / weights.sum() - return l1_loss - - def mse_loss(self, decoder_output, target): - # decoder_output : B x T x n_mel - # target : B x T x n_mel - assert decoder_output.shape == target.shape - mse_loss = F.mse_loss(decoder_output, target, reduction='none') - weights = weights_nonzero_speech(target) - mse_loss = (mse_loss * weights).sum() / weights.sum() - return mse_loss - - def ssim_loss(self, decoder_output, target, bias=6.0): - # decoder_output : B x T x n_mel - # target : B x T x n_mel - assert decoder_output.shape == target.shape - weights = weights_nonzero_speech(target) - decoder_output = decoder_output[:, None] + bias - target = target[:, None] + bias - ssim_loss = 1 - ssim(decoder_output, target, size_average=False) - ssim_loss = (ssim_loss * weights).sum() / weights.sum() - return ssim_loss - - def plot_mel(self, batch_idx, spec_out, spec_gt=None, name=None, title='', f0s=None, dur_info=None): - vmin = hparams['mel_vmin'] - vmax = hparams['mel_vmax'] - if len(spec_out.shape) == 3: - spec_out = spec_out[0] - if isinstance(spec_out, torch.Tensor): - spec_out = spec_out.cpu().numpy() - if spec_gt is not None: - if len(spec_gt.shape) == 3: - spec_gt = spec_gt[0] - if isinstance(spec_gt, torch.Tensor): - spec_gt = spec_gt.cpu().numpy() - max_len = max(len(spec_gt), len(spec_out)) - if max_len - len(spec_gt) > 0: - spec_gt = np.pad(spec_gt, [[0, max_len - len(spec_gt)], [0, 0]], mode='constant', - constant_values=vmin) - if max_len - len(spec_out) > 0: - spec_out = np.pad(spec_out, [[0, max_len - len(spec_out)], [0, 0]], mode='constant', - constant_values=vmin) - spec_out = np.concatenate([spec_out, spec_gt], -1) - name = f'mel_val_{batch_idx}' if name is None else name - self.logger.add_figure(name, spec_to_figure( - spec_out, vmin, vmax, title=title, f0s=f0s, dur_info=dur_info), self.global_step) - - ########################## - # testing - ########################## - def test_start(self): - self.saving_result_pool = MultiprocessManager(int(os.getenv('N_PROC', os.cpu_count()))) - self.saving_results_futures = [] - self.gen_dir = os.path.join( - hparams['work_dir'], f'generated_{self.trainer.global_step}_{hparams["gen_dir_name"]}') - self.vocoder: BaseVocoder = get_vocoder_cls(hparams['vocoder'])() - os.makedirs(self.gen_dir, exist_ok=True) - os.makedirs(f'{self.gen_dir}/wavs', exist_ok=True) - os.makedirs(f'{self.gen_dir}/plot', exist_ok=True) - if hparams.get('save_mel_npy', False): - os.makedirs(f'{self.gen_dir}/mel_npy', exist_ok=True) - - def test_step(self, sample, batch_idx): - """ - - :param sample: - :param batch_idx: - :return: - """ - assert sample['txt_tokens'].shape[0] == 1, 'only support batch_size=1 in inference' - outputs = self.run_model(sample, infer=True) - text = sample['text'][0] - item_name = sample['item_name'][0] - tokens = sample['txt_tokens'][0].cpu().numpy() - mel_gt = sample['mels'][0].cpu().numpy() - mel_pred = outputs['mel_out'][0].cpu().numpy() - str_phs = self.token_encoder.decode(tokens, strip_padding=True) - base_fn = f'[{self.results_id:06d}][{item_name.replace("%", "_")}][%s]' - if text is not None: - base_fn += text.replace(":", "$3A")[:80] - base_fn = base_fn.replace(' ', '_') - gen_dir = self.gen_dir - wav_pred = self.vocoder.spec2wav(mel_pred) - self.saving_result_pool.add_job(self.save_result, args=[ - wav_pred, mel_pred, base_fn % 'P', gen_dir, str_phs]) - if hparams['save_gt']: - wav_gt = self.vocoder.spec2wav(mel_gt) - self.saving_result_pool.add_job(self.save_result, args=[ - wav_gt, mel_gt, base_fn % 'G', gen_dir, str_phs]) - print(f"Pred_shape: {mel_pred.shape}, gt_shape: {mel_gt.shape}") - return { - 'item_name': item_name, - 'text': text, - 'ph_tokens': self.token_encoder.decode(tokens.tolist()), - 'wav_fn_pred': base_fn % 'P', - 'wav_fn_gt': base_fn % 'G', - } - - @staticmethod - def save_result(wav_out, mel, base_fn, gen_dir, str_phs=None, mel2ph=None, alignment=None): - save_wav(wav_out, f'{gen_dir}/wavs/{base_fn}.wav', hparams['audio_sample_rate'], - norm=hparams['out_wav_norm']) - fig = plt.figure(figsize=(14, 10)) - spec_vmin = hparams['mel_vmin'] - spec_vmax = hparams['mel_vmax'] - heatmap = plt.pcolor(mel.T, vmin=spec_vmin, vmax=spec_vmax) - fig.colorbar(heatmap) - try: - f0 = extract_pitch_simple(wav_out) - f0 = f0 / 10 * (f0 > 0) - plt.plot(f0, c='white', linewidth=1, alpha=0.6) - if mel2ph is not None and str_phs is not None: - decoded_txt = str_phs.split(" ") - dur = mel2token_to_dur(torch.LongTensor(mel2ph)[None, :], len(decoded_txt))[0].numpy() - dur = [0] + list(np.cumsum(dur)) - for i in range(len(dur) - 1): - shift = (i % 20) + 1 - plt.text(dur[i], shift, decoded_txt[i]) - plt.hlines(shift, dur[i], dur[i + 1], colors='b' if decoded_txt[i] != '|' else 'black') - plt.vlines(dur[i], 0, 5, colors='b' if decoded_txt[i] != '|' else 'black', - alpha=1, linewidth=1) - plt.tight_layout() - plt.savefig(f'{gen_dir}/plot/{base_fn}.png', format='png') - plt.close(fig) - if hparams.get('save_mel_npy', False): - np.save(f'{gen_dir}/mel_npy/{base_fn}', mel) - if alignment is not None: - fig, ax = plt.subplots(figsize=(12, 16)) - im = ax.imshow(alignment, aspect='auto', origin='lower', - interpolation='none') - decoded_txt = str_phs.split(" ") - ax.set_yticks(np.arange(len(decoded_txt))) - ax.set_yticklabels(list(decoded_txt), fontsize=6) - fig.colorbar(im, ax=ax) - fig.savefig(f'{gen_dir}/attn_plot/{base_fn}_attn.png', format='png') - plt.close(fig) - except Exception: - traceback.print_exc() - return None - - def test_end(self, outputs): - pd.DataFrame(outputs).to_csv(f'{self.gen_dir}/meta.csv') - for _1, _2 in tqdm(self.saving_result_pool.get_results(), total=len(self.saving_result_pool)): - pass - return {} diff --git a/spaces/yerfor/SyntaSpeech/utils/commons/hparams.py b/spaces/yerfor/SyntaSpeech/utils/commons/hparams.py deleted file mode 100644 index 356fe306b0be82040ae1e938d3fca0e2567ae7c2..0000000000000000000000000000000000000000 --- a/spaces/yerfor/SyntaSpeech/utils/commons/hparams.py +++ /dev/null @@ -1,131 +0,0 @@ -import argparse -import os -import yaml - -from utils.os_utils import remove_file - -global_print_hparams = True -hparams = {} - - -class Args: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - self.__setattr__(k, v) - - -def override_config(old_config: dict, new_config: dict): - for k, v in new_config.items(): - if isinstance(v, dict) and k in old_config: - override_config(old_config[k], new_config[k]) - else: - old_config[k] = v - - -def set_hparams(config='', exp_name='', hparams_str='', print_hparams=True, global_hparams=True): - if config == '' and exp_name == '': - parser = argparse.ArgumentParser(description='') - parser.add_argument('--config', type=str, default='', - help='location of the data corpus') - parser.add_argument('--exp_name', type=str, default='', help='exp_name') - parser.add_argument('-hp', '--hparams', type=str, default='', - help='location of the data corpus') - parser.add_argument('--infer', action='store_true', help='infer') - parser.add_argument('--validate', action='store_true', help='validate') - parser.add_argument('--reset', action='store_true', help='reset hparams') - parser.add_argument('--remove', action='store_true', help='remove old ckpt') - parser.add_argument('--debug', action='store_true', help='debug') - args, unknown = parser.parse_known_args() - print("| Unknow hparams: ", unknown) - else: - args = Args(config=config, exp_name=exp_name, hparams=hparams_str, - infer=False, validate=False, reset=False, debug=False, remove=False) - global hparams - assert args.config != '' or args.exp_name != '' - if args.config != '': - assert os.path.exists(args.config) - - config_chains = [] - loaded_config = set() - - def load_config(config_fn): - # deep first inheritance and avoid the second visit of one node - if not os.path.exists(config_fn): - return {} - with open(config_fn) as f: - hparams_ = yaml.safe_load(f) - loaded_config.add(config_fn) - if 'base_config' in hparams_: - ret_hparams = {} - if not isinstance(hparams_['base_config'], list): - hparams_['base_config'] = [hparams_['base_config']] - for c in hparams_['base_config']: - if c.startswith('.'): - c = f'{os.path.dirname(config_fn)}/{c}' - c = os.path.normpath(c) - if c not in loaded_config: - override_config(ret_hparams, load_config(c)) - override_config(ret_hparams, hparams_) - else: - ret_hparams = hparams_ - config_chains.append(config_fn) - return ret_hparams - - saved_hparams = {} - args_work_dir = '' - if args.exp_name != '': - args_work_dir = f'checkpoints/{args.exp_name}' - ckpt_config_path = f'{args_work_dir}/config.yaml' - if os.path.exists(ckpt_config_path): - with open(ckpt_config_path) as f: - saved_hparams_ = yaml.safe_load(f) - if saved_hparams_ is not None: - saved_hparams.update(saved_hparams_) - hparams_ = {} - if args.config != '': - hparams_.update(load_config(args.config)) - if not args.reset: - hparams_.update(saved_hparams) - hparams_['work_dir'] = args_work_dir - - # Support config overriding in command line. Support list type config overriding. - # Examples: --hparams="a=1,b.c=2,d=[1 1 1]" - if args.hparams != "": - for new_hparam in args.hparams.split(","): - k, v = new_hparam.split("=") - v = v.strip("\'\" ") - config_node = hparams_ - for k_ in k.split(".")[:-1]: - config_node = config_node[k_] - k = k.split(".")[-1] - if v in ['True', 'False'] or type(config_node[k]) in [bool, list, dict]: - if type(config_node[k]) == list: - v = v.replace(" ", ",") - config_node[k] = eval(v) - else: - config_node[k] = type(config_node[k])(v) - if args_work_dir != '' and args.remove: - answer = input("REMOVE old checkpoint? Y/N [Default: N]: ") - if answer.lower() == "y": - remove_file(args_work_dir) - if args_work_dir != '' and (not os.path.exists(ckpt_config_path) or args.reset) and not args.infer: - os.makedirs(hparams_['work_dir'], exist_ok=True) - with open(ckpt_config_path, 'w') as f: - yaml.safe_dump(hparams_, f) - - hparams_['infer'] = args.infer - hparams_['debug'] = args.debug - hparams_['validate'] = args.validate - hparams_['exp_name'] = args.exp_name - global global_print_hparams - if global_hparams: - hparams.clear() - hparams.update(hparams_) - if print_hparams and global_print_hparams and global_hparams: - print('| Hparams chains: ', config_chains) - print('| Hparams: ') - for i, (k, v) in enumerate(sorted(hparams_.items())): - print(f"\033[;33;m{k}\033[0m: {v}, ", end="\n" if i % 5 == 4 else "") - print("") - global_print_hparams = False - return hparams_ diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/align/__init__.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/align/__init__.py deleted file mode 100644 index 8f9a6c40a7169f5829ceb4fff9db6311ed4ff421..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/align/__init__.py +++ /dev/null @@ -1,73 +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 typing import TYPE_CHECKING - -from ...utils import ( - OptionalDependencyNotAvailable, - _LazyModule, - is_torch_available, -) - - -_import_structure = { - "configuration_align": [ - "ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP", - "AlignConfig", - "AlignTextConfig", - "AlignVisionConfig", - ], - "processing_align": ["AlignProcessor"], -} - -try: - if not is_torch_available(): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - pass -else: - _import_structure["modeling_align"] = [ - "ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST", - "AlignModel", - "AlignPreTrainedModel", - "AlignTextModel", - "AlignVisionModel", - ] - -if TYPE_CHECKING: - from .configuration_align import ( - ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP, - AlignConfig, - AlignTextConfig, - AlignVisionConfig, - ) - from .processing_align import AlignProcessor - - try: - if not is_torch_available(): - raise OptionalDependencyNotAvailable() - except OptionalDependencyNotAvailable: - pass - else: - from .modeling_align import ( - ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST, - AlignModel, - AlignPreTrainedModel, - AlignTextModel, - AlignVisionModel, - ) - -else: - import sys - - sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/bert_generation/__init__.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/bert_generation/__init__.py deleted file mode 100644 index 14cf8bb5879320c3838808bea5715ac06b046fd9..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/bert_generation/__init__.py +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright 2020 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from typing import TYPE_CHECKING - -from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available - - -_import_structure = {"configuration_bert_generation": ["BertGenerationConfig"]} - -try: - if not is_sentencepiece_available(): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - pass -else: - _import_structure["tokenization_bert_generation"] = ["BertGenerationTokenizer"] - -try: - if not is_torch_available(): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - pass -else: - _import_structure["modeling_bert_generation"] = [ - "BertGenerationDecoder", - "BertGenerationEncoder", - "BertGenerationPreTrainedModel", - "load_tf_weights_in_bert_generation", - ] - - -if TYPE_CHECKING: - from .configuration_bert_generation import BertGenerationConfig - - try: - if not is_sentencepiece_available(): - raise OptionalDependencyNotAvailable() - except OptionalDependencyNotAvailable: - pass - else: - from .tokenization_bert_generation import BertGenerationTokenizer - - try: - if not is_torch_available(): - raise OptionalDependencyNotAvailable() - except OptionalDependencyNotAvailable: - pass - else: - from .modeling_bert_generation import ( - BertGenerationDecoder, - BertGenerationEncoder, - BertGenerationPreTrainedModel, - load_tf_weights_in_bert_generation, - ) - -else: - import sys - - sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__) diff --git a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/owlvit/image_processing_owlvit.py b/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/owlvit/image_processing_owlvit.py deleted file mode 100644 index 3efbc5122962ef3b6314f302566c1a6dd55ad671..0000000000000000000000000000000000000000 --- a/spaces/yizhangliu/Grounded-Segment-Anything/transformers_4_35_0/models/owlvit/image_processing_owlvit.py +++ /dev/null @@ -1,590 +0,0 @@ -# coding=utf-8 -# Copyright 2022 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. -"""Image processor class for OwlViT""" - -import warnings -from typing import Dict, List, Optional, Tuple, Union - -import numpy as np - -from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict -from ...image_transforms import ( - center_crop, - center_to_corners_format, - rescale, - resize, - to_channel_dimension_format, -) -from ...image_utils import ( - OPENAI_CLIP_MEAN, - OPENAI_CLIP_STD, - ChannelDimension, - ImageInput, - PILImageResampling, - infer_channel_dimension_format, - is_scaled_image, - make_list_of_images, - to_numpy_array, - valid_images, -) -from ...utils import TensorType, is_torch_available, logging - - -if is_torch_available(): - import torch - - -logger = logging.get_logger(__name__) - - -def _upcast(t): - # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type - if t.is_floating_point(): - return t if t.dtype in (torch.float32, torch.float64) else t.float() - else: - return t if t.dtype in (torch.int32, torch.int64) else t.int() - - -def box_area(boxes): - """ - Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2) coordinates. - - Args: - boxes (`torch.FloatTensor` of shape `(number_of_boxes, 4)`): - Boxes for which the area will be computed. They are expected to be in (x1, y1, x2, y2) format with `0 <= x1 - < x2` and `0 <= y1 < y2`. - Returns: - `torch.FloatTensor`: a tensor containing the area for each box. - """ - boxes = _upcast(boxes) - return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) - - -def box_iou(boxes1, boxes2): - area1 = box_area(boxes1) - area2 = box_area(boxes2) - - left_top = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] - right_bottom = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] - - width_height = (right_bottom - left_top).clamp(min=0) # [N,M,2] - inter = width_height[:, :, 0] * width_height[:, :, 1] # [N,M] - - union = area1[:, None] + area2 - inter - - iou = inter / union - return iou, union - - -class OwlViTImageProcessor(BaseImageProcessor): - r""" - Constructs an OWL-ViT image processor. - - This image processor inherits from [`ImageProcessingMixin`] which contains most of the main methods. Users should - refer to this superclass for more information regarding those methods. - - Args: - do_resize (`bool`, *optional*, defaults to `True`): - Whether to resize the shorter edge of the input to a certain `size`. - size (`Dict[str, int]`, *optional*, defaults to {"height": 768, "width": 768}): - The size to use for resizing the image. Only has an effect if `do_resize` is set to `True`. If `size` is a - sequence like (h, w), output size will be matched to this. If `size` is an int, then image will be resized - to (size, size). - resample (`int`, *optional*, defaults to `Resampling.BICUBIC`): - An optional resampling filter. This can be one of `PIL.Image.Resampling.NEAREST`, - `PIL.Image.Resampling.BOX`, `PIL.Image.Resampling.BILINEAR`, `PIL.Image.Resampling.HAMMING`, - `PIL.Image.Resampling.BICUBIC` or `PIL.Image.Resampling.LANCZOS`. Only has an effect if `do_resize` is set - to `True`. - do_center_crop (`bool`, *optional*, defaults to `False`): - Whether to crop the input at the center. If the input size is smaller than `crop_size` along any edge, the - image is padded with 0's and then center cropped. - crop_size (`int`, *optional*, defaults to {"height": 768, "width": 768}): - The size to use for center cropping the image. Only has an effect if `do_center_crop` is set to `True`. - do_rescale (`bool`, *optional*, defaults to `True`): - Whether to rescale the input by a certain factor. - rescale_factor (`float`, *optional*, defaults to `1/255`): - The factor to use for rescaling the image. Only has an effect if `do_rescale` is set to `True`. - do_normalize (`bool`, *optional*, defaults to `True`): - Whether or not to normalize the input with `image_mean` and `image_std`. Desired output size when applying - center-cropping. Only has an effect if `do_center_crop` is set to `True`. - image_mean (`List[int]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`): - The sequence of means for each channel, to be used when normalizing images. - image_std (`List[int]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`): - The sequence of standard deviations for each channel, to be used when normalizing images. - """ - model_input_names = ["pixel_values"] - - def __init__( - self, - do_resize=True, - size=None, - resample=PILImageResampling.BICUBIC, - do_center_crop=False, - crop_size=None, - do_rescale=True, - rescale_factor=1 / 255, - do_normalize=True, - image_mean=None, - image_std=None, - **kwargs, - ): - size = size if size is not None else {"height": 768, "width": 768} - size = get_size_dict(size, default_to_square=True) - - crop_size = crop_size if crop_size is not None else {"height": 768, "width": 768} - crop_size = get_size_dict(crop_size, default_to_square=True) - - # Early versions of the OWL-ViT config on the hub had "rescale" as a flag. This clashes with the - # vision image processor method `rescale` as it would be set as an attribute during the super().__init__ - # call. This is for backwards compatibility. - if "rescale" in kwargs: - rescale_val = kwargs.pop("rescale") - kwargs["do_rescale"] = rescale_val - - super().__init__(**kwargs) - self.do_resize = do_resize - self.size = size - self.resample = resample - self.do_center_crop = do_center_crop - self.crop_size = crop_size - self.do_rescale = do_rescale - self.rescale_factor = rescale_factor - self.do_normalize = do_normalize - self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN - self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD - - def resize( - self, - image: np.ndarray, - size: Dict[str, int], - resample: PILImageResampling.BICUBIC, - data_format: Optional[Union[str, ChannelDimension]] = None, - input_data_format: Optional[Union[str, ChannelDimension]] = None, - **kwargs, - ) -> np.ndarray: - """ - Resize an image to a certain size. - - Args: - image (`np.ndarray`): - Image to resize. - size (`Dict[str, int]`): - The size to resize the image to. Must contain height and width keys. - resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): - The resampling filter to use when resizing the input. - data_format (`str` or `ChannelDimension`, *optional*): - The channel dimension format for the output image. If unset, the channel dimension format of the input - image is used. - input_data_format (`str` or `ChannelDimension`, *optional*): - The channel dimension format of the input image. If not provided, it will be inferred. - """ - size = get_size_dict(size, default_to_square=True) - if "height" not in size or "width" not in size: - raise ValueError("size dictionary must contain height and width keys") - - return resize( - image, - (size["height"], size["width"]), - resample=resample, - data_format=data_format, - input_data_format=input_data_format, - **kwargs, - ) - - def center_crop( - self, - image: np.ndarray, - crop_size: Dict[str, int], - data_format: Optional[Union[str, ChannelDimension]] = None, - input_data_format: Optional[Union[str, ChannelDimension]] = None, - **kwargs, - ) -> np.ndarray: - """ - Center crop an image to a certain size. - - Args: - image (`np.ndarray`): - Image to center crop. - crop_size (`Dict[str, int]`): - The size to center crop the image to. Must contain height and width keys. - data_format (`str` or `ChannelDimension`, *optional*): - The channel dimension format for the output image. If unset, the channel dimension format of the input - image is used. - input_data_format (`str` or `ChannelDimension`, *optional*): - The channel dimension format of the input image. If not provided, it will be inferred. - """ - crop_size = get_size_dict(crop_size, default_to_square=True) - if "height" not in crop_size or "width" not in crop_size: - raise ValueError("crop_size dictionary must contain height and width keys") - - return center_crop( - image, - (crop_size["height"], crop_size["width"]), - data_format=data_format, - input_data_format=input_data_format, - **kwargs, - ) - - # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.rescale - def rescale( - self, - image: np.ndarray, - rescale_factor: float, - data_format: Optional[Union[str, ChannelDimension]] = None, - input_data_format: Optional[Union[str, ChannelDimension]] = None, - ) -> np.ndarray: - """ - Rescale the image by the given factor. image = image * rescale_factor. - - Args: - image (`np.ndarray`): - Image to rescale. - rescale_factor (`float`): - The value to use for rescaling. - data_format (`str` or `ChannelDimension`, *optional*): - The channel dimension format for the output image. If unset, the channel dimension format of the input - image is used. Can be one of: - - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - input_data_format (`str` or `ChannelDimension`, *optional*): - The channel dimension format for the input image. If unset, is inferred from the input image. Can be - one of: - - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - """ - return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format) - - def preprocess( - self, - images: ImageInput, - do_resize: Optional[bool] = None, - size: Optional[Dict[str, int]] = None, - resample: PILImageResampling = None, - do_center_crop: Optional[bool] = None, - crop_size: Optional[Dict[str, int]] = None, - do_rescale: Optional[bool] = None, - rescale_factor: Optional[float] = None, - do_normalize: Optional[bool] = None, - image_mean: Optional[Union[float, List[float]]] = None, - image_std: Optional[Union[float, List[float]]] = None, - return_tensors: Optional[Union[TensorType, str]] = None, - data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST, - input_data_format: Optional[Union[str, ChannelDimension]] = None, - **kwargs, - ) -> BatchFeature: - """ - Prepares an image or batch of images for the model. - - Args: - images (`ImageInput`): - The image or batch of images to be prepared. Expects a single or batch of images with pixel values - ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. - do_resize (`bool`, *optional*, defaults to `self.do_resize`): - Whether or not to resize the input. If `True`, will resize the input to the size specified by `size`. - size (`Dict[str, int]`, *optional*, defaults to `self.size`): - The size to resize the input to. Only has an effect if `do_resize` is set to `True`. - resample (`PILImageResampling`, *optional*, defaults to `self.resample`): - The resampling filter to use when resizing the input. Only has an effect if `do_resize` is set to - `True`. - do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`): - Whether or not to center crop the input. If `True`, will center crop the input to the size specified by - `crop_size`. - crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`): - The size to center crop the input to. Only has an effect if `do_center_crop` is set to `True`. - do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): - Whether or not to rescale the input. If `True`, will rescale the input by dividing it by - `rescale_factor`. - rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): - The factor to rescale the input by. Only has an effect if `do_rescale` is set to `True`. - do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): - Whether or not to normalize the input. If `True`, will normalize the input by subtracting `image_mean` - and dividing by `image_std`. - image_mean (`Union[float, List[float]]`, *optional*, defaults to `self.image_mean`): - The mean to subtract from the input when normalizing. Only has an effect if `do_normalize` is set to - `True`. - image_std (`Union[float, List[float]]`, *optional*, defaults to `self.image_std`): - The standard deviation to divide the input by when normalizing. Only has an effect if `do_normalize` is - set to `True`. - return_tensors (`str` or `TensorType`, *optional*): - The type of tensors to return. Can be one of: - - Unset: Return a list of `np.ndarray`. - - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`. - - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. - - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`. - data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): - The channel dimension format for the output image. Can be one of: - - `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - - `ChannelDimension.LAST`: image in (height, width, num_channels) format. - - Unset: defaults to the channel dimension format of the input image. - input_data_format (`ChannelDimension` or `str`, *optional*): - The channel dimension format for the input image. If unset, the channel dimension format is inferred - from the input image. Can be one of: - - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - """ - do_resize = do_resize if do_resize is not None else self.do_resize - size = size if size is not None else self.size - resample = resample if resample is not None else self.resample - do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop - crop_size = crop_size if crop_size is not None else self.crop_size - do_rescale = do_rescale if do_rescale is not None else self.do_rescale - rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor - do_normalize = do_normalize if do_normalize is not None else self.do_normalize - image_mean = image_mean if image_mean is not None else self.image_mean - image_std = image_std if image_std is not None else self.image_std - - if do_resize is not None and size is None: - raise ValueError("Size and max_size must be specified if do_resize is True.") - - if do_center_crop is not None and crop_size is None: - raise ValueError("Crop size must be specified if do_center_crop is True.") - - if do_rescale is not None and rescale_factor is None: - raise ValueError("Rescale factor must be specified if do_rescale is True.") - - if do_normalize is not None and (image_mean is None or image_std is None): - raise ValueError("Image mean and std must be specified if do_normalize is True.") - - images = make_list_of_images(images) - - if not valid_images(images): - raise ValueError( - "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " - "torch.Tensor, tf.Tensor or jax.ndarray." - ) - - # All transformations expect numpy arrays - images = [to_numpy_array(image) for image in images] - - if is_scaled_image(images[0]) and do_rescale: - logger.warning_once( - "It looks like you are trying to rescale already rescaled images. If the input" - " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." - ) - - if input_data_format is None: - # We assume that all images have the same channel dimension format. - input_data_format = infer_channel_dimension_format(images[0]) - - if do_resize: - images = [ - self.resize(image, size=size, resample=resample, input_data_format=input_data_format) - for image in images - ] - - if do_center_crop: - images = [ - self.center_crop(image, crop_size=crop_size, input_data_format=input_data_format) for image in images - ] - - if do_rescale: - images = [ - self.rescale(image, rescale_factor=rescale_factor, input_data_format=input_data_format) - for image in images - ] - - if do_normalize: - images = [ - self.normalize(image, mean=image_mean, std=image_std, input_data_format=input_data_format) - for image in images - ] - - images = [ - to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images - ] - encoded_inputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors) - return encoded_inputs - - def post_process(self, outputs, target_sizes): - """ - Converts the raw output of [`OwlViTForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y, - bottom_right_x, bottom_right_y) format. - - Args: - outputs ([`OwlViTObjectDetectionOutput`]): - Raw outputs of the model. - target_sizes (`torch.Tensor` of shape `(batch_size, 2)`): - Tensor containing the size (h, w) of each image of the batch. For evaluation, this must be the original - image size (before any data augmentation). For visualization, this should be the image size after data - augment, but before padding. - Returns: - `List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image - in the batch as predicted by the model. - """ - # TODO: (amy) add support for other frameworks - warnings.warn( - "`post_process` is deprecated and will be removed in v5 of Transformers, please use" - " `post_process_object_detection` instead, with `threshold=0.` for equivalent results.", - FutureWarning, - ) - - logits, boxes = outputs.logits, outputs.pred_boxes - - if len(logits) != len(target_sizes): - raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits") - if target_sizes.shape[1] != 2: - raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch") - - probs = torch.max(logits, dim=-1) - scores = torch.sigmoid(probs.values) - labels = probs.indices - - # Convert to [x0, y0, x1, y1] format - boxes = center_to_corners_format(boxes) - - # Convert from relative [0, 1] to absolute [0, height] coordinates - img_h, img_w = target_sizes.unbind(1) - scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1) - boxes = boxes * scale_fct[:, None, :] - - results = [{"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes)] - - return results - - def post_process_object_detection( - self, outputs, threshold: float = 0.1, target_sizes: Union[TensorType, List[Tuple]] = None - ): - """ - Converts the raw output of [`OwlViTForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y, - bottom_right_x, bottom_right_y) format. - - Args: - outputs ([`OwlViTObjectDetectionOutput`]): - Raw outputs of the model. - threshold (`float`, *optional*): - Score threshold to keep object detection predictions. - target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*): - Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size - `(height, width)` of each image in the batch. If unset, predictions will not be resized. - Returns: - `List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image - in the batch as predicted by the model. - """ - # TODO: (amy) add support for other frameworks - logits, boxes = outputs.logits, outputs.pred_boxes - - if target_sizes is not None: - if len(logits) != len(target_sizes): - raise ValueError( - "Make sure that you pass in as many target sizes as the batch dimension of the logits" - ) - - probs = torch.max(logits, dim=-1) - scores = torch.sigmoid(probs.values) - labels = probs.indices - - # Convert to [x0, y0, x1, y1] format - boxes = center_to_corners_format(boxes) - - # Convert from relative [0, 1] to absolute [0, height] coordinates - if target_sizes is not None: - if isinstance(target_sizes, List): - img_h = torch.Tensor([i[0] for i in target_sizes]) - img_w = torch.Tensor([i[1] for i in target_sizes]) - else: - img_h, img_w = target_sizes.unbind(1) - - scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1) - boxes = boxes * scale_fct[:, None, :] - - results = [] - for s, l, b in zip(scores, labels, boxes): - score = s[s > threshold] - label = l[s > threshold] - box = b[s > threshold] - results.append({"scores": score, "labels": label, "boxes": box}) - - return results - - # TODO: (Amy) Make compatible with other frameworks - def post_process_image_guided_detection(self, outputs, threshold=0.0, nms_threshold=0.3, target_sizes=None): - """ - Converts the output of [`OwlViTForObjectDetection.image_guided_detection`] into the format expected by the COCO - api. - - Args: - outputs ([`OwlViTImageGuidedObjectDetectionOutput`]): - Raw outputs of the model. - threshold (`float`, *optional*, defaults to 0.0): - Minimum confidence threshold to use to filter out predicted boxes. - nms_threshold (`float`, *optional*, defaults to 0.3): - IoU threshold for non-maximum suppression of overlapping boxes. - target_sizes (`torch.Tensor`, *optional*): - Tensor of shape (batch_size, 2) where each entry is the (height, width) of the corresponding image in - the batch. If set, predicted normalized bounding boxes are rescaled to the target sizes. If left to - None, predictions will not be unnormalized. - - Returns: - `List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image - in the batch as predicted by the model. All labels are set to None as - `OwlViTForObjectDetection.image_guided_detection` perform one-shot object detection. - """ - logits, target_boxes = outputs.logits, outputs.target_pred_boxes - - if len(logits) != len(target_sizes): - raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits") - if target_sizes.shape[1] != 2: - raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch") - - probs = torch.max(logits, dim=-1) - scores = torch.sigmoid(probs.values) - - # Convert to [x0, y0, x1, y1] format - target_boxes = center_to_corners_format(target_boxes) - - # Apply non-maximum suppression (NMS) - if nms_threshold < 1.0: - for idx in range(target_boxes.shape[0]): - for i in torch.argsort(-scores[idx]): - if not scores[idx][i]: - continue - - ious = box_iou(target_boxes[idx][i, :].unsqueeze(0), target_boxes[idx])[0][0] - ious[i] = -1.0 # Mask self-IoU. - scores[idx][ious > nms_threshold] = 0.0 - - # Convert from relative [0, 1] to absolute [0, height] coordinates - img_h, img_w = target_sizes.unbind(1) - scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(target_boxes.device) - target_boxes = target_boxes * scale_fct[:, None, :] - - # Compute box display alphas based on prediction scores - results = [] - alphas = torch.zeros_like(scores) - - for idx in range(target_boxes.shape[0]): - # Select scores for boxes matching the current query: - query_scores = scores[idx] - if not query_scores.nonzero().numel(): - continue - - # Apply threshold on scores before scaling - query_scores[query_scores < threshold] = 0.0 - - # Scale box alpha such that the best box for each query has alpha 1.0 and the worst box has alpha 0.1. - # All other boxes will either belong to a different query, or will not be shown. - max_score = torch.max(query_scores) + 1e-6 - query_alphas = (query_scores - (max_score * 0.1)) / (max_score * 0.9) - query_alphas = torch.clip(query_alphas, 0.0, 1.0) - alphas[idx] = query_alphas - - mask = alphas[idx] > 0 - box_scores = alphas[idx][mask] - boxes = target_boxes[idx][mask] - results.append({"scores": box_scores, "labels": None, "boxes": boxes}) - - return results diff --git a/spaces/ykilcher/apes/docs/license.html b/spaces/ykilcher/apes/docs/license.html deleted file mode 100644 index ebe83a9ae3ad92ced238fc2108c14322d51db2e1..0000000000000000000000000000000000000000 --- a/spaces/ykilcher/apes/docs/license.html +++ /dev/null @@ -1,153 +0,0 @@ - - - - - - Nvidia Source Code License-NC - - - - - -

                NVIDIA Source Code License for StyleGAN2 with Adaptive Discriminator Augmentation (ADA)

                - -
                - -

                1. Definitions

                - -

                “Licensor” means any person or entity that distributes its Work.

                - -

                “Software” means the original work of authorship made available under -this License.

                - -

                “Work” means the Software and any additions to or derivative works of -the Software that are made available under this License.

                - -

                The terms “reproduce,” “reproduction,” “derivative works,” and -“distribution” have the meaning as provided under U.S. copyright law; -provided, however, that 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.

                - -

                Works, including the Software, are “made available” under this License -by including in or with the Work either (a) a copyright notice -referencing the applicability of this License to the Work, or (b) a -copy of this License.

                - -

                2. License Grants

                - -

                2.1 Copyright Grant. Subject to the terms and conditions of this -License, each Licensor grants to you a perpetual, worldwide, -non-exclusive, royalty-free, copyright license to reproduce, -prepare derivative works of, publicly display, publicly perform, -sublicense and distribute its Work and any resulting derivative -works in any form.

                - -

                3. Limitations

                - -

                3.1 Redistribution. You may reproduce or distribute the Work only -if (a) you do so under this License, (b) you include a complete -copy of this License with your distribution, and (c) you retain -without modification any copyright, patent, trademark, or -attribution notices that are present in the Work.

                - -

                3.2 Derivative Works. You may specify that additional or different -terms apply to the use, reproduction, and distribution of your -derivative works of the Work (“Your Terms”) only if (a) Your Terms -provide that the use limitation in Section 3.3 applies to your -derivative works, and (b) you identify the specific derivative -works that are subject to Your Terms. Notwithstanding Your Terms, -this License (including the redistribution requirements in Section -3.1) will continue to apply to the Work itself.

                - -

                3.3 Use Limitation. The Work and any derivative works thereof only may be used or intended for -use non-commercially. Notwithstanding the foregoing, NVIDIA and its affiliates may use the Work -and any derivative works commercially. As used herein, “non-commercially” means for research or -evaluation purposes only. - -

                3.4 Patent Claims. If you bring or threaten to bring a patent claim -against any Licensor (including any claim, cross-claim or -counterclaim in a lawsuit) to enforce any patents that you allege -are infringed by any Work, then your rights under this License from -such Licensor (including the grant in Section 2.1) will terminate immediately. - -

                3.5 Trademarks. This License does not grant any rights to use any -Licensor’s or its affiliates’ names, logos, or trademarks, except -as necessary to reproduce the notices described in this License.

                - -

                3.6 Termination. If you violate any term of this License, then your -rights under this License (including the grant in Section 2.1) -will terminate immediately.

                - -

                4. Disclaimer of Warranty.

                - -

                THE WORK IS PROVIDED “AS IS” WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR -NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER -THIS LICENSE.

                - -

                5. Limitation of Liability.

                - -

                EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL -THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE -SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, -INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF -OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK -(INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, -LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER -COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF -THE POSSIBILITY OF SUCH DAMAGES.

                - -
                -
                - - - diff --git a/spaces/yl12053/so-vits-4.1-Matikanefukukitaru/vencoder/ContentVec256L12_Onnx.py b/spaces/yl12053/so-vits-4.1-Matikanefukukitaru/vencoder/ContentVec256L12_Onnx.py deleted file mode 100644 index 9ad5085e02654fd1fcfbdad7d476bfa9b763d2c6..0000000000000000000000000000000000000000 --- a/spaces/yl12053/so-vits-4.1-Matikanefukukitaru/vencoder/ContentVec256L12_Onnx.py +++ /dev/null @@ -1,28 +0,0 @@ -from vencoder.encoder import SpeechEncoder -import onnxruntime -import torch - -class ContentVec256L12_Onnx(SpeechEncoder): - def __init__(self,vec_path = "pretrain/vec-256-layer-12.onnx",device=None): - print("load model(s) from {}".format(vec_path)) - self.hidden_dim = 256 - if device is None: - self.dev = torch.device("cpu") - else: - self.dev = torch.device(device) - if device == 'cpu' or device == torch.device("cpu") or device is None: - providers = ['CPUExecutionProvider'] - elif device == 'cuda' or device == torch.device("cuda"): - providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] - self.model = onnxruntime.InferenceSession(vec_path, providers=providers) - - def encoder(self, wav): - feats = wav - if feats.dim() == 2: # double channels - feats = feats.mean(-1) - assert feats.dim() == 1, feats.dim() - feats = feats.view(1, -1) - feats = feats.unsqueeze(0).cpu().detach().numpy() - onnx_input = {self.model.get_inputs()[0].name: feats} - logits = self.model.run(None, onnx_input) - return torch.tensor(logits[0]).transpose(1, 2).to(self.dev) diff --git a/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/tools/lightning_train_net.py b/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/tools/lightning_train_net.py deleted file mode 100644 index f6734b566b6764ee54dd2af1b7310fedb34bb40d..0000000000000000000000000000000000000000 --- a/spaces/ynhe/AskAnything/models/grit_src/third_party/CenterNet2/tools/lightning_train_net.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python3 -# Copyright (c) Facebook, Inc. and its affiliates. -# Lightning Trainer should be considered beta at this point -# We have confirmed that training and validation run correctly and produce correct results -# Depending on how you launch the trainer, there are issues with processes terminating correctly -# This module is still dependent on D2 logging, but could be transferred to use Lightning logging - -import logging -import os -import time -import weakref -from collections import OrderedDict -from typing import Any, Dict, List - -import detectron2.utils.comm as comm -from detectron2.checkpoint import DetectionCheckpointer -from detectron2.config import get_cfg -from detectron2.data import build_detection_test_loader, build_detection_train_loader -from detectron2.engine import ( - DefaultTrainer, - SimpleTrainer, - default_argument_parser, - default_setup, - default_writers, - hooks, -) -from detectron2.evaluation import print_csv_format -from detectron2.evaluation.testing import flatten_results_dict -from detectron2.modeling import build_model -from detectron2.solver import build_lr_scheduler, build_optimizer -from detectron2.utils.events import EventStorage -from detectron2.utils.logger import setup_logger - -import pytorch_lightning as pl # type: ignore -from pytorch_lightning import LightningDataModule, LightningModule -from train_net import build_evaluator - -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger("detectron2") - - -class TrainingModule(LightningModule): - def __init__(self, cfg): - super().__init__() - if not logger.isEnabledFor(logging.INFO): # setup_logger is not called for d2 - setup_logger() - self.cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size()) - self.storage: EventStorage = None - self.model = build_model(self.cfg) - - self.start_iter = 0 - self.max_iter = cfg.SOLVER.MAX_ITER - - def on_save_checkpoint(self, checkpoint: Dict[str, Any]) -> None: - checkpoint["iteration"] = self.storage.iter - - def on_load_checkpoint(self, checkpointed_state: Dict[str, Any]) -> None: - self.start_iter = checkpointed_state["iteration"] - self.storage.iter = self.start_iter - - def setup(self, stage: str): - if self.cfg.MODEL.WEIGHTS: - self.checkpointer = DetectionCheckpointer( - # Assume you want to save checkpoints together with logs/statistics - self.model, - self.cfg.OUTPUT_DIR, - ) - logger.info(f"Load model weights from checkpoint: {self.cfg.MODEL.WEIGHTS}.") - # Only load weights, use lightning checkpointing if you want to resume - self.checkpointer.load(self.cfg.MODEL.WEIGHTS) - - self.iteration_timer = hooks.IterationTimer() - self.iteration_timer.before_train() - self.data_start = time.perf_counter() - self.writers = None - - def training_step(self, batch, batch_idx): - data_time = time.perf_counter() - self.data_start - # Need to manually enter/exit since trainer may launch processes - # This ideally belongs in setup, but setup seems to run before processes are spawned - if self.storage is None: - self.storage = EventStorage(0) - self.storage.__enter__() - self.iteration_timer.trainer = weakref.proxy(self) - self.iteration_timer.before_step() - self.writers = ( - default_writers(self.cfg.OUTPUT_DIR, self.max_iter) - if comm.is_main_process() - else {} - ) - - loss_dict = self.model(batch) - SimpleTrainer.write_metrics(loss_dict, data_time) - - opt = self.optimizers() - self.storage.put_scalar( - "lr", opt.param_groups[self._best_param_group_id]["lr"], smoothing_hint=False - ) - self.iteration_timer.after_step() - self.storage.step() - # A little odd to put before step here, but it's the best way to get a proper timing - self.iteration_timer.before_step() - - if self.storage.iter % 20 == 0: - for writer in self.writers: - writer.write() - return sum(loss_dict.values()) - - def training_step_end(self, training_step_outpus): - self.data_start = time.perf_counter() - return training_step_outpus - - def training_epoch_end(self, training_step_outputs): - self.iteration_timer.after_train() - if comm.is_main_process(): - self.checkpointer.save("model_final") - for writer in self.writers: - writer.write() - writer.close() - self.storage.__exit__(None, None, None) - - def _process_dataset_evaluation_results(self) -> OrderedDict: - results = OrderedDict() - for idx, dataset_name in enumerate(self.cfg.DATASETS.TEST): - results[dataset_name] = self._evaluators[idx].evaluate() - if comm.is_main_process(): - print_csv_format(results[dataset_name]) - - if len(results) == 1: - results = list(results.values())[0] - return results - - def _reset_dataset_evaluators(self): - self._evaluators = [] - for dataset_name in self.cfg.DATASETS.TEST: - evaluator = build_evaluator(self.cfg, dataset_name) - evaluator.reset() - self._evaluators.append(evaluator) - - def on_validation_epoch_start(self, _outputs): - self._reset_dataset_evaluators() - - def validation_epoch_end(self, _outputs): - results = self._process_dataset_evaluation_results(_outputs) - - flattened_results = flatten_results_dict(results) - for k, v in flattened_results.items(): - try: - v = float(v) - except Exception as e: - raise ValueError( - "[EvalHook] eval_function should return a nested dict of float. " - "Got '{}: {}' instead.".format(k, v) - ) from e - self.storage.put_scalars(**flattened_results, smoothing_hint=False) - - def validation_step(self, batch, batch_idx: int, dataloader_idx: int = 0) -> None: - if not isinstance(batch, List): - batch = [batch] - outputs = self.model(batch) - self._evaluators[dataloader_idx].process(batch, outputs) - - def configure_optimizers(self): - optimizer = build_optimizer(self.cfg, self.model) - self._best_param_group_id = hooks.LRScheduler.get_best_param_group_id(optimizer) - scheduler = build_lr_scheduler(self.cfg, optimizer) - return [optimizer], [{"scheduler": scheduler, "interval": "step"}] - - -class DataModule(LightningDataModule): - def __init__(self, cfg): - super().__init__() - self.cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size()) - - def train_dataloader(self): - return build_detection_train_loader(self.cfg) - - def val_dataloader(self): - dataloaders = [] - for dataset_name in self.cfg.DATASETS.TEST: - dataloaders.append(build_detection_test_loader(self.cfg, dataset_name)) - return dataloaders - - -def main(args): - cfg = setup(args) - train(cfg, args) - - -def train(cfg, args): - trainer_params = { - # training loop is bounded by max steps, use a large max_epochs to make - # sure max_steps is met first - "max_epochs": 10 ** 8, - "max_steps": cfg.SOLVER.MAX_ITER, - "val_check_interval": cfg.TEST.EVAL_PERIOD if cfg.TEST.EVAL_PERIOD > 0 else 10 ** 8, - "num_nodes": args.num_machines, - "gpus": args.num_gpus, - "num_sanity_val_steps": 0, - } - if cfg.SOLVER.AMP.ENABLED: - trainer_params["precision"] = 16 - - last_checkpoint = os.path.join(cfg.OUTPUT_DIR, "last.ckpt") - if args.resume: - # resume training from checkpoint - trainer_params["resume_from_checkpoint"] = last_checkpoint - logger.info(f"Resuming training from checkpoint: {last_checkpoint}.") - - trainer = pl.Trainer(**trainer_params) - logger.info(f"start to train with {args.num_machines} nodes and {args.num_gpus} GPUs") - - module = TrainingModule(cfg) - data_module = DataModule(cfg) - if args.eval_only: - logger.info("Running inference") - trainer.validate(module, data_module) - else: - logger.info("Running training") - trainer.fit(module, data_module) - - -def setup(args): - """ - Create configs and perform basic setups. - """ - cfg = get_cfg() - cfg.merge_from_file(args.config_file) - cfg.merge_from_list(args.opts) - cfg.freeze() - default_setup(cfg, args) - return cfg - - -if __name__ == "__main__": - parser = default_argument_parser() - args = parser.parse_args() - logger.info("Command Line Args:", args) - main(args) diff --git a/spaces/yonikremer/grouped-sampling-demo/test_is_downloaded.py b/spaces/yonikremer/grouped-sampling-demo/test_is_downloaded.py deleted file mode 100644 index 0f9473ae2d5ee5d7c5bef5aff295edbe8836283d..0000000000000000000000000000000000000000 --- a/spaces/yonikremer/grouped-sampling-demo/test_is_downloaded.py +++ /dev/null @@ -1,47 +0,0 @@ -# test_hanlde_form_submit.py - Generated by CodiumAI - -from hanlde_form_submit import is_downloaded - -""" -Code Analysis: -- The main goal of the function is to check if a specific model is downloaded or not. -- The function takes a string parameter 'model_name' which is the name of the model to be checked. -- It then sets the 'models_dir' variable to the directory where the downloaded models are stored. -- The function then creates a new variable 'model_dir' by joining the 'models_dir' and the 'model_name' parameter with a specific format. -- The function then checks if the 'model_dir' exists as a directory using the 'os.path.isdir' method. -- If the directory exists, the function returns True, indicating that the model is downloaded. -- If the directory does not exist, the function returns False, indicating that the model is not downloaded. -""" - -""" -Test Plan: -- test_is_downloaded_exists(): tests that the function correctly identifies that a downloaded model exists and returns True. Tags: [happy path] -- test_is_downloaded_not_exists(): tests that the function correctly identifies that a downloaded model does not exist and returns False. Tags: [happy path] -- test_is_downloaded_empty_model_name(): tests that the function handles an empty string for the 'model_name' parameter. Tags: [edge case] -- test_is_downloaded_invalid_model_name(): tests that the function handles invalid characters for a directory name in the 'model_name' parameter. Tags: [edge case] -- test_is_downloaded_only_directories(): tests that the function only checks for directories, not files. Tags: [general behavior] -- test_is_downloaded_dir_not_exist(): tests that the function handles the case where the 'models_dir' directory does not exist. Tags: [edge case] -- test_is_downloaded_dir_not_writable(): tests that the function handles the case where the 'models_dir' directory is not writable. Tags: [general behavior] -- test_is_downloaded_dir_not_readable(): tests that the function handles the case where the 'model_dir' directory is not readable. Tags: [general behavior] -- test_is_downloaded_specific_dir_structure(): tests that the function assumes a specific directory structure for downloaded models. Tags: [general behavior] -- test_is_downloaded_specific_model_name_format(): tests that the function assumes a specific format for the 'model_name' parameter. Tags: [general behavior] -""" - - -class TestIsDownloaded: - def test_is_downloaded_exists(self): - assert is_downloaded("gpt2") - assert is_downloaded("facebook/opt-iml-max-1.3b") - assert is_downloaded("facebook/opt-iml-max-30b") - - def test_is_downloaded_not_exists(self): - assert not is_downloaded("non-existent-model") - - def test_is_downloaded_empty_model_name(self): - assert not is_downloaded("") - - def test_is_downloaded_invalid_model_name(self): - assert not is_downloaded("model/with/invalid/characters") - - def test_is_downloaded_only_directories(self): - assert not is_downloaded("gpt2/vocab.txt") diff --git a/spaces/younker/chatgpt-turbo/client/node_modules/electron-to-chromium/index.js b/spaces/younker/chatgpt-turbo/client/node_modules/electron-to-chromium/index.js deleted file mode 100644 index 1818281fab50434ab48c203906894558b4a66eab..0000000000000000000000000000000000000000 --- a/spaces/younker/chatgpt-turbo/client/node_modules/electron-to-chromium/index.js +++ /dev/null @@ -1,36 +0,0 @@ -var versions = require('./versions'); -var fullVersions = require('./full-versions'); -var chromiumVersions = require('./chromium-versions'); -var fullChromiumVersions = require('./full-chromium-versions'); - -var electronToChromium = function (query) { - var number = getQueryString(query); - return number.split('.').length > 2 ? fullVersions[number] : versions[number] || undefined; -}; - -var chromiumToElectron = function (query) { - var number = getQueryString(query); - return number.split('.').length > 2 ? fullChromiumVersions[number] : chromiumVersions[number] || undefined; -}; - -var electronToBrowserList = function (query) { - var number = getQueryString(query); - return versions[number] ? "Chrome >= " + versions[number] : undefined; -}; - -var getQueryString = function (query) { - var number = query; - if (query === 1) { number = "1.0" } - if (typeof query === 'number') { number += ''; } - return number; -}; - -module.exports = { - versions: versions, - fullVersions: fullVersions, - chromiumVersions: chromiumVersions, - fullChromiumVersions: fullChromiumVersions, - electronToChromium: electronToChromium, - electronToBrowserList: electronToBrowserList, - chromiumToElectron: chromiumToElectron -}; diff --git a/spaces/yufiofficial/MusicGenQ/audiocraft/utils/utils.py b/spaces/yufiofficial/MusicGenQ/audiocraft/utils/utils.py deleted file mode 100644 index 86e1448d065fa182ca69aae00d2f2a7eea55d8a4..0000000000000000000000000000000000000000 --- a/spaces/yufiofficial/MusicGenQ/audiocraft/utils/utils.py +++ /dev/null @@ -1,234 +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 concurrent.futures import ProcessPoolExecutor -from functools import wraps -import hashlib -import logging -import typing as tp - -import flashy -import flashy.distrib -import omegaconf -import torch -from torch.nn.utils.rnn import pad_sequence - - -logger = logging.getLogger(__name__) - - -def dict_from_config(cfg: omegaconf.DictConfig) -> dict: - """Convenience function to map an omegaconf configuration to a dictionary. - - Args: - cfg (omegaconf.DictConfig): Original configuration to map to dict. - Returns: - dict: Config as dictionary object. - """ - dct = omegaconf.OmegaConf.to_container(cfg, resolve=True) - assert isinstance(dct, dict) - return dct - - -def random_subset(dataset, max_samples: int, seed: int = 42) -> torch.utils.data.Subset: - if max_samples >= len(dataset): - return dataset - - generator = torch.Generator().manual_seed(seed) - perm = torch.randperm(len(dataset), generator=generator) - return torch.utils.data.Subset(dataset, perm[:max_samples].tolist()) - - -def get_loader(dataset, num_samples: tp.Optional[int], batch_size: int, - num_workers: int, seed: int, **kwargs) -> torch.utils.data.DataLoader: - """Convenience function to load dataset into a dataloader with optional subset sampling. - - Args: - dataset: Dataset to load. - num_samples (Optional[int]): Number of samples to limit subset size. - batch_size (int): Batch size. - num_workers (int): Number of workers for data loading. - seed (int): Random seed. - """ - if num_samples is not None: - dataset = random_subset(dataset, num_samples, seed) - - dataloader = flashy.distrib.loader( - dataset, - batch_size=batch_size, - num_workers=num_workers, - **kwargs - ) - return dataloader - - -def get_dataset_from_loader(dataloader): - dataset = dataloader.dataset - if isinstance(dataset, torch.utils.data.Subset): - return dataset.dataset - else: - return dataset - - -def multinomial(input: torch.Tensor, num_samples: int, replacement=False, *, generator=None): - """torch.multinomial with arbitrary number of dimensions, and number of candidates on the last dimension. - - Args: - input (torch.Tensor): The input tensor containing probabilities. - num_samples (int): Number of samples to draw. - replacement (bool): Whether to draw with replacement or not. - Keywords args: - generator (torch.Generator): A pseudorandom number generator for sampling. - Returns: - torch.Tensor: Last dimension contains num_samples indices - sampled from the multinomial probability distribution - located in the last dimension of tensor input. - """ - input_ = input.reshape(-1, input.shape[-1]) - output_ = torch.multinomial(input_, num_samples=num_samples, replacement=replacement, generator=generator) - output = output_.reshape(*list(input.shape[:-1]), -1) - return output - - -def sample_top_k(probs: torch.Tensor, k: int) -> torch.Tensor: - """Sample next token from top K values along the last dimension of the input probs tensor. - - Args: - probs (torch.Tensor): Input probabilities with token candidates on the last dimension. - k (int): The k in “top-k”. - Returns: - torch.Tensor: Sampled tokens. - """ - top_k_value, _ = torch.topk(probs, k, dim=-1) - min_value_top_k = top_k_value[..., [-1]] - probs *= (probs >= min_value_top_k).float() - probs.div_(probs.sum(dim=-1, keepdim=True)) - next_token = multinomial(probs, num_samples=1) - return next_token - - -def sample_top_p(probs: torch.Tensor, p: float) -> torch.Tensor: - """Sample next token from top P probabilities along the last dimension of the input probs tensor. - - Args: - probs (torch.Tensor): Input probabilities with token candidates on the last dimension. - p (int): The p in “top-p”. - Returns: - torch.Tensor: Sampled tokens. - """ - probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True) - probs_sum = torch.cumsum(probs_sort, dim=-1) - mask = probs_sum - probs_sort > p - probs_sort *= (~mask).float() - probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True)) - next_token = multinomial(probs_sort, num_samples=1) - next_token = torch.gather(probs_idx, -1, next_token) - return next_token - - -class DummyPoolExecutor: - """Dummy pool executor to use when we actually have only 1 worker. - (e.g. instead of ProcessPoolExecutor). - """ - class DummyResult: - def __init__(self, func, *args, **kwargs): - self.func = func - self.args = args - self.kwargs = kwargs - - def result(self): - return self.func(*self.args, **self.kwargs) - - def __init__(self, workers, mp_context=None): - pass - - def submit(self, func, *args, **kwargs): - return DummyPoolExecutor.DummyResult(func, *args, **kwargs) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, exc_tb): - return - - -def get_pool_executor(num_workers: int, mp_context=None): - return ProcessPoolExecutor(num_workers, mp_context) if num_workers > 1 else DummyPoolExecutor(1) - - -def length_to_mask(lengths: torch.Tensor, max_len: tp.Optional[int] = None) -> torch.Tensor: - """Utility function to convert a tensor of sequence lengths to a mask (useful when working on padded sequences). - For example: [3, 5] => [[1, 1, 1, 0, 0], [1, 1, 1, 1, 1]] - - Args: - lengths (torch.Tensor): tensor with lengths - max_len (int): can set the max length manually. Defaults to None. - Returns: - torch.Tensor: mask with 0s where there is pad tokens else 1s - """ - assert len(lengths.shape) == 1, "Length shape should be 1 dimensional." - final_length = lengths.max().item() if not max_len else max_len - final_length = max(final_length, 1) # if all seqs are of len zero we don't want a zero-size tensor - return torch.arange(final_length)[None, :].to(lengths.device) < lengths[:, None] - - -def hash_trick(word: str, vocab_size: int) -> int: - """Hash trick to pair each word with an index - - Args: - word (str): word we wish to convert to an index - vocab_size (int): size of the vocabulary - Returns: - int: index of the word in the embedding LUT - """ - hash = int(hashlib.sha256(word.encode("utf-8")).hexdigest(), 16) - return hash % vocab_size - - -def with_rank_rng(base_seed: int = 1234): - """Decorator for a function so that the function will use a Random Number Generator - whose state depend on the GPU rank. The original RNG state is restored upon returning. - - Args: - base_seed (int): Random seed. - """ - def _decorator(fun: tp.Callable): - @wraps(fun) - def _decorated(*args, **kwargs): - state = torch.get_rng_state() - seed = base_seed ^ flashy.distrib.rank() - torch.manual_seed(seed) - logger.debug('Rank dependent seed set to %d', seed) - try: - return fun(*args, **kwargs) - finally: - torch.set_rng_state(state) - logger.debug('RNG state restored.') - return _decorated - return _decorator - - -def collate(tensors: tp.List[torch.Tensor], dim: int = 0) -> tp.Tuple[torch.Tensor, torch.Tensor]: - """Get a list of tensors and collate them to a single tensor. according to the following logic: - - `dim` specifies the time dimension which will be stacked and padded. - - The output will contain 1 new dimension (dimension index 0) which will be the size of - of the original list. - - Args: - tensors (tp.List[torch.Tensor]): List of tensors to collate. - dim (int): Dimension which will be stacked and padded. - Returns: - tp.Tuple[torch.Tensor, torch.Tensor]: - torch.Tensor: Stacked and padded tensor. The output will contain 1 new dimension - (dimension index 0) which will be the size of the original list. - torch.Tensor: Tensor containing length of original tensor sizes (without padding). - """ - tensors = [x.transpose(0, dim) for x in tensors] - lens = torch.LongTensor([len(x) for x in tensors]) - padded_tensors = pad_sequence(tensors) - padded_tensors = padded_tensors.transpose(0, 1) - padded_tensors = padded_tensors.transpose(1, dim + 1) - return padded_tensors, lens diff --git a/spaces/yunfei0710/gpt-academic/check_proxy.py b/spaces/yunfei0710/gpt-academic/check_proxy.py deleted file mode 100644 index 977802db49babe079a191dbda6815c216e156548..0000000000000000000000000000000000000000 --- a/spaces/yunfei0710/gpt-academic/check_proxy.py +++ /dev/null @@ -1,159 +0,0 @@ - -def check_proxy(proxies): - import requests - proxies_https = proxies['https'] if proxies is not None else '无' - try: - response = requests.get("https://ipapi.co/json/", - proxies=proxies, timeout=4) - data = response.json() - print(f'查询代理的地理位置,返回的结果是{data}') - if 'country_name' in data: - country = data['country_name'] - result = f"代理配置 {proxies_https}, 代理所在地:{country}" - elif 'error' in data: - result = f"代理配置 {proxies_https}, 代理所在地:未知,IP查询频率受限" - print(result) - return result - except: - result = f"代理配置 {proxies_https}, 代理所在地查询超时,代理可能无效" - print(result) - return result - - -def backup_and_download(current_version, remote_version): - """ - 一键更新协议:备份和下载 - """ - from toolbox import get_conf - import shutil - import os - import requests - import zipfile - os.makedirs(f'./history', exist_ok=True) - backup_dir = f'./history/backup-{current_version}/' - new_version_dir = f'./history/new-version-{remote_version}/' - if os.path.exists(new_version_dir): - return new_version_dir - os.makedirs(new_version_dir) - shutil.copytree('./', backup_dir, ignore=lambda x, y: ['history']) - proxies, = get_conf('proxies') - r = requests.get( - 'https://github.com/binary-husky/chatgpt_academic/archive/refs/heads/master.zip', proxies=proxies, stream=True) - zip_file_path = backup_dir+'/master.zip' - with open(zip_file_path, 'wb+') as f: - f.write(r.content) - dst_path = new_version_dir - with zipfile.ZipFile(zip_file_path, "r") as zip_ref: - for zip_info in zip_ref.infolist(): - dst_file_path = os.path.join(dst_path, zip_info.filename) - if os.path.exists(dst_file_path): - os.remove(dst_file_path) - zip_ref.extract(zip_info, dst_path) - return new_version_dir - - -def patch_and_restart(path): - """ - 一键更新协议:覆盖和重启 - """ - from distutils import dir_util - import shutil - import os - import sys - import time - import glob - from colorful import print亮黄, print亮绿, print亮红 - # if not using config_private, move origin config.py as config_private.py - if not os.path.exists('config_private.py'): - print亮黄('由于您没有设置config_private.py私密配置,现将您的现有配置移动至config_private.py以防止配置丢失,', - '另外您可以随时在history子文件夹下找回旧版的程序。') - shutil.copyfile('config.py', 'config_private.py') - path_new_version = glob.glob(path + '/*-master')[0] - dir_util.copy_tree(path_new_version, './') - print亮绿('代码已经更新,即将更新pip包依赖……') - for i in reversed(range(5)): time.sleep(1); print(i) - try: - import subprocess - subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt']) - except: - print亮红('pip包依赖安装出现问题,需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。') - print亮绿('更新完成,您可以随时在history子文件夹下找回旧版的程序,5s之后重启') - print亮红('假如重启失败,您可能需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。') - print(' ------------------------------ -----------------------------------') - for i in reversed(range(8)): time.sleep(1); print(i) - os.execl(sys.executable, sys.executable, *sys.argv) - - -def get_current_version(): - import json - try: - with open('./version', 'r', encoding='utf8') as f: - current_version = json.loads(f.read())['version'] - except: - current_version = "" - return current_version - - -def auto_update(raise_error=False): - """ - 一键更新协议:查询版本和用户意见 - """ - try: - from toolbox import get_conf - import requests - import time - import json - proxies, = get_conf('proxies') - response = requests.get( - "https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=5) - remote_json_data = json.loads(response.text) - remote_version = remote_json_data['version'] - if remote_json_data["show_feature"]: - new_feature = "新功能:" + remote_json_data["new_feature"] - else: - new_feature = "" - with open('./version', 'r', encoding='utf8') as f: - current_version = f.read() - current_version = json.loads(current_version)['version'] - if (remote_version - current_version) >= 0.01: - from colorful import print亮黄 - print亮黄( - f'\n新版本可用。新版本:{remote_version},当前版本:{current_version}。{new_feature}') - print('(1)Github更新地址:\nhttps://github.com/binary-husky/chatgpt_academic\n') - user_instruction = input('(2)是否一键更新代码(Y+回车=确认,输入其他/无输入+回车=不更新)?') - if user_instruction in ['Y', 'y']: - path = backup_and_download(current_version, remote_version) - try: - patch_and_restart(path) - except: - msg = '更新失败。' - if raise_error: - from toolbox import trimmed_format_exc - msg += trimmed_format_exc() - print(msg) - else: - print('自动更新程序:已禁用') - return - else: - return - except: - msg = '自动更新程序:已禁用' - if raise_error: - from toolbox import trimmed_format_exc - msg += trimmed_format_exc() - print(msg) - -def warm_up_modules(): - print('正在执行一些模块的预热...') - from request_llm.bridge_all import model_info - enc = model_info["gpt-3.5-turbo"]['tokenizer'] - enc.encode("模块预热", disallowed_special=()) - enc = model_info["gpt-4"]['tokenizer'] - enc.encode("模块预热", disallowed_special=()) - -if __name__ == '__main__': - import os - os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染 - from toolbox import get_conf - proxies, = get_conf('proxies') - check_proxy(proxies) diff --git a/spaces/ywqisok/ysyy/commons.py b/spaces/ywqisok/ysyy/commons.py deleted file mode 100644 index 40fcc05364d4815971f5c6f9dbb8dcef8e3ec1e9..0000000000000000000000000000000000000000 --- a/spaces/ywqisok/ysyy/commons.py +++ /dev/null @@ -1,172 +0,0 @@ -import math -import torch -from torch.nn import functional as F -import torch.jit - - -def script_method(fn, _rcb=None): - return fn - - -def script(obj, optimize=True, _frames_up=0, _rcb=None): - return obj - - -torch.jit.script_method = script_method -torch.jit.script = script - - -def init_weights(m, mean=0.0, std=0.01): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - m.weight.data.normal_(mean, std) - - -def get_padding(kernel_size, dilation=1): - return int((kernel_size*dilation - dilation)/2) - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def intersperse(lst, item): - result = [item] * (len(lst) * 2 + 1) - result[1::2] = lst - return result - - -def kl_divergence(m_p, logs_p, m_q, logs_q): - """KL(P||Q)""" - kl = (logs_q - logs_p) - 0.5 - kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) - return kl - - -def rand_gumbel(shape): - """Sample from the Gumbel distribution, protect from overflows.""" - uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 - return -torch.log(-torch.log(uniform_samples)) - - -def rand_gumbel_like(x): - g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device) - return g - - -def slice_segments(x, ids_str, segment_size=4): - ret = torch.zeros_like(x[:, :, :segment_size]) - for i in range(x.size(0)): - idx_str = ids_str[i] - idx_end = idx_str + segment_size - ret[i] = x[i, :, idx_str:idx_end] - return ret - - -def rand_slice_segments(x, x_lengths=None, segment_size=4): - b, d, t = x.size() - if x_lengths is None: - x_lengths = t - ids_str_max = x_lengths - segment_size + 1 - ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) - ret = slice_segments(x, ids_str, segment_size) - return ret, ids_str - - -def get_timing_signal_1d( - length, channels, min_timescale=1.0, max_timescale=1.0e4): - position = torch.arange(length, dtype=torch.float) - num_timescales = channels // 2 - log_timescale_increment = ( - math.log(float(max_timescale) / float(min_timescale)) / - (num_timescales - 1)) - inv_timescales = min_timescale * torch.exp( - torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment) - scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1) - signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0) - signal = F.pad(signal, [0, 0, 0, channels % 2]) - signal = signal.view(1, channels, length) - return signal - - -def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return x + signal.to(dtype=x.dtype, device=x.device) - - -def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis) - - -def subsequent_mask(length): - mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0) - return mask - - -@torch.jit.script -def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): - n_channels_int = n_channels[0] - in_act = input_a + input_b - t_act = torch.tanh(in_act[:, :n_channels_int, :]) - s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) - acts = t_act * s_act - return acts - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def shift_1d(x): - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] - return x - - -def sequence_mask(length, max_length=None): - if max_length is None: - max_length = length.max() - x = torch.arange(max_length, dtype=length.dtype, device=length.device) - return x.unsqueeze(0) < length.unsqueeze(1) - - -def generate_path(duration, mask): - """ - duration: [b, 1, t_x] - mask: [b, 1, t_y, t_x] - """ - device = duration.device - - b, _, t_y, t_x = mask.shape - cum_duration = torch.cumsum(duration, -1) - - cum_duration_flat = cum_duration.view(b * t_x) - path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) - path = path.view(b, t_x, t_y) - path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] - path = path.unsqueeze(1).transpose(2,3) * mask - return path - - -def clip_grad_value_(parameters, clip_value, norm_type=2): - if isinstance(parameters, torch.Tensor): - parameters = [parameters] - parameters = list(filter(lambda p: p.grad is not None, parameters)) - norm_type = float(norm_type) - if clip_value is not None: - clip_value = float(clip_value) - - total_norm = 0 - for p in parameters: - param_norm = p.grad.data.norm(norm_type) - total_norm += param_norm.item() ** norm_type - if clip_value is not None: - p.grad.data.clamp_(min=-clip_value, max=clip_value) - total_norm = total_norm ** (1. / norm_type) - return total_norm diff --git a/spaces/zeno-ml/openai-evals/evals/medmcqa/med_fns.py b/spaces/zeno-ml/openai-evals/evals/medmcqa/med_fns.py deleted file mode 100644 index 25f4cd765bf1e67a8608f52c3f7dcdd9b1f6f0b2..0000000000000000000000000000000000000000 --- a/spaces/zeno-ml/openai-evals/evals/medmcqa/med_fns.py +++ /dev/null @@ -1,14 +0,0 @@ -import re - -from zeno import DistillReturn, distill - -finder = "Subject:(.*)" - - -@distill -def subject(df, ops): - ret_subjs = [] - for entry in df[ops.data_column]: - ret_subjs.append(re.search(finder, entry[1]["content"]).group(1)) - - return DistillReturn(distill_output=ret_subjs) diff --git a/spaces/zlc99/M4Singer/utils/hparams.py b/spaces/zlc99/M4Singer/utils/hparams.py deleted file mode 100644 index 920cee4d730025580d696a2365a7f208e71eff63..0000000000000000000000000000000000000000 --- a/spaces/zlc99/M4Singer/utils/hparams.py +++ /dev/null @@ -1,122 +0,0 @@ -import argparse -import os -import yaml - -global_print_hparams = True -hparams = {} - - -class Args: - def __init__(self, **kwargs): - for k, v in kwargs.items(): - self.__setattr__(k, v) - - -def override_config(old_config: dict, new_config: dict): - for k, v in new_config.items(): - if isinstance(v, dict) and k in old_config: - override_config(old_config[k], new_config[k]) - else: - old_config[k] = v - - -def set_hparams(config='', exp_name='', hparams_str='', print_hparams=True, global_hparams=True): - if config == '': - parser = argparse.ArgumentParser(description='neural music') - parser.add_argument('--config', type=str, default='', - help='location of the data corpus') - parser.add_argument('--exp_name', type=str, default='', help='exp_name') - parser.add_argument('--hparams', type=str, default='', - help='location of the data corpus') - parser.add_argument('--infer', action='store_true', help='infer') - parser.add_argument('--validate', action='store_true', help='validate') - parser.add_argument('--reset', action='store_true', help='reset hparams') - parser.add_argument('--debug', action='store_true', help='debug') - args, unknown = parser.parse_known_args() - else: - args = Args(config=config, exp_name=exp_name, hparams=hparams_str, - infer=False, validate=False, reset=False, debug=False) - args_work_dir = '' - if args.exp_name != '': - args.work_dir = args.exp_name - args_work_dir = f'checkpoints/{args.work_dir}' - - config_chains = [] - loaded_config = set() - - def load_config(config_fn): # deep first - with open(config_fn) as f: - hparams_ = yaml.safe_load(f) - loaded_config.add(config_fn) - if 'base_config' in hparams_: - ret_hparams = {} - if not isinstance(hparams_['base_config'], list): - hparams_['base_config'] = [hparams_['base_config']] - for c in hparams_['base_config']: - if c not in loaded_config: - if c.startswith('.'): - c = f'{os.path.dirname(config_fn)}/{c}' - c = os.path.normpath(c) - override_config(ret_hparams, load_config(c)) - override_config(ret_hparams, hparams_) - else: - ret_hparams = hparams_ - config_chains.append(config_fn) - return ret_hparams - - global hparams - assert args.config != '' or args_work_dir != '' - saved_hparams = {} - if args_work_dir != 'checkpoints/': - ckpt_config_path = f'{args_work_dir}/config.yaml' - if os.path.exists(ckpt_config_path): - try: - with open(ckpt_config_path) as f: - saved_hparams.update(yaml.safe_load(f)) - except: - pass - if args.config == '': - args.config = ckpt_config_path - - hparams_ = {} - - hparams_.update(load_config(args.config)) - - if not args.reset: - hparams_.update(saved_hparams) - hparams_['work_dir'] = args_work_dir - - if args.hparams != "": - for new_hparam in args.hparams.split(","): - k, v = new_hparam.split("=") - if v in ['True', 'False'] or type(hparams_[k]) == bool: - hparams_[k] = eval(v) - else: - hparams_[k] = type(hparams_[k])(v) - - if args_work_dir != '' and (not os.path.exists(ckpt_config_path) or args.reset) and not args.infer: - os.makedirs(hparams_['work_dir'], exist_ok=True) - with open(ckpt_config_path, 'w') as f: - yaml.safe_dump(hparams_, f) - - hparams_['infer'] = args.infer - hparams_['debug'] = args.debug - hparams_['validate'] = args.validate - global global_print_hparams - if global_hparams: - hparams.clear() - hparams.update(hparams_) - - if print_hparams and global_print_hparams and global_hparams: - print('| Hparams chains: ', config_chains) - print('| Hparams: ') - for i, (k, v) in enumerate(sorted(hparams_.items())): - print(f"\033[;33;m{k}\033[0m: {v}, ", end="\n" if i % 5 == 4 else "") - print("") - global_print_hparams = False - # print(hparams_.keys()) - if hparams.get('exp_name') is None: - hparams['exp_name'] = args.exp_name - if hparams_.get('exp_name') is None: - hparams_['exp_name'] = args.exp_name - return hparams_ diff --git a/spaces/zomehwh/vits-models-genshin-bh3/commons.py b/spaces/zomehwh/vits-models-genshin-bh3/commons.py deleted file mode 100644 index 40fcc05364d4815971f5c6f9dbb8dcef8e3ec1e9..0000000000000000000000000000000000000000 --- a/spaces/zomehwh/vits-models-genshin-bh3/commons.py +++ /dev/null @@ -1,172 +0,0 @@ -import math -import torch -from torch.nn import functional as F -import torch.jit - - -def script_method(fn, _rcb=None): - return fn - - -def script(obj, optimize=True, _frames_up=0, _rcb=None): - return obj - - -torch.jit.script_method = script_method -torch.jit.script = script - - -def init_weights(m, mean=0.0, std=0.01): - classname = m.__class__.__name__ - if classname.find("Conv") != -1: - m.weight.data.normal_(mean, std) - - -def get_padding(kernel_size, dilation=1): - return int((kernel_size*dilation - dilation)/2) - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def intersperse(lst, item): - result = [item] * (len(lst) * 2 + 1) - result[1::2] = lst - return result - - -def kl_divergence(m_p, logs_p, m_q, logs_q): - """KL(P||Q)""" - kl = (logs_q - logs_p) - 0.5 - kl += 0.5 * (torch.exp(2. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) - return kl - - -def rand_gumbel(shape): - """Sample from the Gumbel distribution, protect from overflows.""" - uniform_samples = torch.rand(shape) * 0.99998 + 0.00001 - return -torch.log(-torch.log(uniform_samples)) - - -def rand_gumbel_like(x): - g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device) - return g - - -def slice_segments(x, ids_str, segment_size=4): - ret = torch.zeros_like(x[:, :, :segment_size]) - for i in range(x.size(0)): - idx_str = ids_str[i] - idx_end = idx_str + segment_size - ret[i] = x[i, :, idx_str:idx_end] - return ret - - -def rand_slice_segments(x, x_lengths=None, segment_size=4): - b, d, t = x.size() - if x_lengths is None: - x_lengths = t - ids_str_max = x_lengths - segment_size + 1 - ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long) - ret = slice_segments(x, ids_str, segment_size) - return ret, ids_str - - -def get_timing_signal_1d( - length, channels, min_timescale=1.0, max_timescale=1.0e4): - position = torch.arange(length, dtype=torch.float) - num_timescales = channels // 2 - log_timescale_increment = ( - math.log(float(max_timescale) / float(min_timescale)) / - (num_timescales - 1)) - inv_timescales = min_timescale * torch.exp( - torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment) - scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1) - signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0) - signal = F.pad(signal, [0, 0, 0, channels % 2]) - signal = signal.view(1, channels, length) - return signal - - -def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return x + signal.to(dtype=x.dtype, device=x.device) - - -def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1): - b, channels, length = x.size() - signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale) - return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis) - - -def subsequent_mask(length): - mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0) - return mask - - -@torch.jit.script -def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): - n_channels_int = n_channels[0] - in_act = input_a + input_b - t_act = torch.tanh(in_act[:, :n_channels_int, :]) - s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) - acts = t_act * s_act - return acts - - -def convert_pad_shape(pad_shape): - l = pad_shape[::-1] - pad_shape = [item for sublist in l for item in sublist] - return pad_shape - - -def shift_1d(x): - x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1] - return x - - -def sequence_mask(length, max_length=None): - if max_length is None: - max_length = length.max() - x = torch.arange(max_length, dtype=length.dtype, device=length.device) - return x.unsqueeze(0) < length.unsqueeze(1) - - -def generate_path(duration, mask): - """ - duration: [b, 1, t_x] - mask: [b, 1, t_y, t_x] - """ - device = duration.device - - b, _, t_y, t_x = mask.shape - cum_duration = torch.cumsum(duration, -1) - - cum_duration_flat = cum_duration.view(b * t_x) - path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype) - path = path.view(b, t_x, t_y) - path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1] - path = path.unsqueeze(1).transpose(2,3) * mask - return path - - -def clip_grad_value_(parameters, clip_value, norm_type=2): - if isinstance(parameters, torch.Tensor): - parameters = [parameters] - parameters = list(filter(lambda p: p.grad is not None, parameters)) - norm_type = float(norm_type) - if clip_value is not None: - clip_value = float(clip_value) - - total_norm = 0 - for p in parameters: - param_norm = p.grad.data.norm(norm_type) - total_norm += param_norm.item() ** norm_type - if clip_value is not None: - p.grad.data.clamp_(min=-clip_value, max=clip_value) - total_norm = total_norm ** (1. / norm_type) - return total_norm