diff --git a/spaces/0x90e/ESRGAN-MANGA/app.py b/spaces/0x90e/ESRGAN-MANGA/app.py deleted file mode 100644 index 7fe27d451342e1850a523ffab46d1f279ea3a300..0000000000000000000000000000000000000000 --- a/spaces/0x90e/ESRGAN-MANGA/app.py +++ /dev/null @@ -1,86 +0,0 @@ -import gradio as gr -import util -import process_image -from run_cmd import run_cmd - -is_colab = util.is_google_colab() - -css = ''' - .file-preview { - overflow: hidden !important; - margin: 5px 0 !important; - padding: 0 10px !important; - } - - .file-preview div div:nth-child(2) { - flex-grow: 1 !important; - } - - .file-preview div div:nth-child(3) { - text-align: right !important; - padding: 0.5rem 0; - width: auto; - } - - #preview_file .h-full.min-h-\[15rem\].flex.justify-center.items-center { - min-height: initial !important; - padding: 10px 0; - } - - #preview_file a { - border-radius: 0.5rem; - padding-top: 0.5rem; - padding-bottom: 0.5rem; - padding-left: 1rem; - padding-right: 1rem; - font-size: 1rem; - line-height: 1.5rem; - font-weight: 600; - color: white; - background-color: gray; - } - - .colab_img { - margin: 10px 0; - display: inline-block; - margin: 0 10px; - } -''' - -title = "ESRGAN Upscaling With Custom Models" - -with gr.Blocks(title=title, css=css) as demo: - gr.Markdown( - f""" - # {title} - This space uses old ESRGAN architecture to upscale images, using models made by the community. - - Once the photo upscaled (*it can take a long time, this space only uses CPU*). - """) - - gr.HTML(value="For faster upscaling using GPU: Open In Colab buy me a coffee (beer) if this helped 🍺😁") - - gr.HTML(value="Buy Me a Coffee at ko-fi.com") - - with gr.Box(): - with gr.Row(): - with gr.Column(): - input_image = gr.Image(type="pil", label="Input") - upscale_size = gr.Radio(["x4", "x2"], label="Upscale by:", value="x4") - upscale_type = gr.Radio(["Manga", "Anime", "Photo", "General"], label="Select the type of picture you want to upscale:", value="Manga") - - with gr.Row(): - upscale_btn = gr.Button(value="Upscale", variant="primary") - - with gr.Column(): - output_image = gr.Image(type="filepath", interactive=False, label="Upscaled image", elem_id="preview_img") - - with gr.Row(): - out_file = gr.File(interactive=False, show_label=False, elem_id="preview_file") - - gr.HTML(value="

Model Database

") - - upscale_btn.click(process_image.inference, inputs=[input_image, upscale_size, upscale_type], outputs=[output_image, out_file]) - -demo.queue() -demo.launch(debug=is_colab, share=is_colab, inline=is_colab) \ No newline at end of file diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Descargarfisiologiamedicaboronespanol Descubre la obra maestra de Boron en espaol.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Descargarfisiologiamedicaboronespanol Descubre la obra maestra de Boron en espaol.md deleted file mode 100644 index 9356f5dc5f6682ac117fc3ea259d611e60571c4d..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Descargarfisiologiamedicaboronespanol Descubre la obra maestra de Boron en espaol.md +++ /dev/null @@ -1,92 +0,0 @@ - -

Descargar Fisiología Médica Boron Español: Una Guía Completa

-

¿Te interesa aprender sobre la fisiología humana de una forma rigurosa y actualizada? ¿Quieres tener acceso a uno de los libros más recomendados y utilizados en el ámbito académico y profesional? ¿Te gustaría poder leerlo en tu idioma y en formato digital? Si tu respuesta es sí, entonces este artículo es para ti.

-

En este artículo te vamos a explicar todo lo que necesitas saber sobre el libro Fisiología Médica de Boron, una obra de referencia en el mundo de la fisiología que te ayudará a comprender el funcionamiento del cuerpo humano desde un nivel molecular y celular hasta un nivel sistémico y clínico.

-

descargarfisiologiamedicaboronespanol


DOWNLOAD ————— https://byltly.com/2uKv64



-

También te vamos a mostrar las ventajas de descargar el libro en español y en formato digital, así como los pasos que debes seguir para hacerlo de forma gratuita y legal. Al final del artículo te daremos nuestra opinión sobre el libro y te invitaremos a dejar la tuya.

-

Así que no esperes más y sigue leyendo para descubrir cómo descargar fisiología médica boron español gratis.

-

descargar fisiologia medica boron español pdf
-descargar gratis libro de fisiologia boron en español
-descargar fisiologia de boron 3ra edicion español
-descargar fisiologia humana boron español
-descargar fisiologia medica boron y boulpaep español
-descargar fisiologia medica boron 2da edicion español
-descargar fisiologia medica boron 4ta edicion español
-descargar fisiologia medica boron 5ta edicion español
-descargar fisiologia medica boron 6ta edicion español
-descargar fisiologia medica boron 7ma edicion español
-descargar fisiologia medica boron 8va edicion español
-descargar fisiologia medica boron 9na edicion español
-descargar fisiologia medica boron 10ma edicion español
-descargar libro de fisiologia medica boron español mega
-descargar libro de fisiologia medica boron español gratis
-descargar libro de fisiologia medica boron español pdf gratis
-descargar libro de fisiologia medica boron español online
-descargar libro de fisiologia medica boron español completo
-descargar libro de fisiologia medica boron español epub
-descargar libro de fisiologia medica boron español mobi
-como descargar el libro de fisiologia medica boron en español
-donde puedo descargar el libro de fisiologia medica boron en español
-donde descargar el libro de fisiologia medica boron en español
-para que sirve el libro de fisiologia medica boron en español
-que es el libro de fisiologia medica boron en español
-que contiene el libro de fisiologia medica boron en español
-que aprender con el libro de fisiologia medica boron en español
-que estudiar con el libro de fisiologia medica boron en español
-que enseña el libro de fisiologia medica boron en español
-que aporta el libro de fisiologia medica boron en español
-que ventajas tiene el libro de fisiologia medica boron en español
-que desventajas tiene el libro de fisiologia medica boron en español
-que opiniones tiene el libro de fisiologia medica boron en español
-que valoracion tiene el libro de fisiologia medica boron en español
-que precio tiene el libro de fisiologia medica boron en español
-que formato tiene el libro de fisiologia medica boron en español
-que tamaño tiene el libro de fisiologia medica boron en español
-que paginas tiene el libro de fisiologia medica boron en español
-que capitulos tiene el libro de fisiologia medica boron en español
-que secciones tiene el libro de fisiologia medica boron en español
-que temas tiene el libro de fisiologia medica boron en español
-que subtemas tiene el libro de fisiologia medica boron en español
-que autores tiene el libro de fisiologia medica boron en español
-que editorial tiene el libro de fisiologia medica boron en español
-que año tiene el libro de fisiologia medica boron en español
-que edicion tiene el libro de fisiologia medica boron en español
-que isbn tiene el libro de fisiologia medica boron en español
-que idioma tiene el libro de fisiologia medica boron en español
-que traduccion tiene el libro de fisiologia medica boron en español

-

Características del libro Fisiología Médica de Boron

-

Antes de explicarte cómo descargar el libro, vamos a repasar sus principales características para que sepas qué puedes esperar de él.

-

Autoría

-

El libro Fisiología Médica es una obra colectiva escrita por más de 40 expertos en diferentes áreas de la fisiología. Los editores principales son Walter F. Boron y Emile L. Boulpaep, dos reconocidos profesores e investigadores que han dedicado su carrera al estudio de la fisiología celular y molecular.

-

Boron es profesor y director del Departamento de Fisiología y Biofísica de la Escuela de Medicina de la Universidad Case Western Reserve en Cleveland, Ohio. Boulpaep es profesor emérito del Departamento de Medicina Celular y Molecular de la Escuela de Medicina de la Universidad Yale en New Haven, Connecticut.

-

Ambos editores cuentan con una amplia experiencia docente y han recibido numerosos premios y distinciones por su labor científica y educativa.

-

Contenido

-

El libro está organizado en 8 secciones que abarcan los principales aspectos de la fisiología humana. Cada sección contiene varios capítulos que tratan temas específicos relacionados con el funcionamiento de un órgano o un sistema.

-

Las secciones son las siguientes:

- -

En total, el libro contiene 62 capítulos que suman más de 1300 páginas de contenido actualizado y riguroso.

-

Enfoque

-

El libro tiene un enfoque único en la disciplina por su forma de explicar la fisiología partiendo de un nivel molecular y celular que sirve de base para entender el funcionamiento de un órgano o un sistema. Así mismo, a lo largo del texto se hace referencia constante a la correlación clínica y por tanto se estudia también las bases fisiológicas de la enfermedad, lo que le confiere un enfoque fisiopatológico.

-

El libro combina la exposición teórica con ejemplos prácticos que ilustran los conceptos clave y facilitan su comprensión. Además, utiliza un lenguaje claro y preciso que evita las ambigüedades y los errores conceptuales.

-

Elementos didácticos

-

El libro cuenta con numerosos elementos didácticos que ayudan al lector a aprender y repasar los contenidos. Entre ellos se destacan:

- -

Ventajas de descargar el libro Fisiología Médica de Boron en español

-

Ahora que ya conoc

0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Epson WF 7511 Adjustment Program Download What You Need to Know About This Service Tool.md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Epson WF 7511 Adjustment Program Download What You Need to Know About This Service Tool.md deleted file mode 100644 index d30e82019b4a15b54f84735365fd89aa80e08fde..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Epson WF 7511 Adjustment Program Download What You Need to Know About This Service Tool.md +++ /dev/null @@ -1,194 +0,0 @@ -
-

Epson WF 7511 Adjustment Program Download Hit 5: A Guide for Epson Printer Users

-

If you own an Epson WF 7011 or WF 7511 printer, you might have encountered some problems with your device, such as waste ink pad overflow, print head error, or printer initialization failure. These problems can affect the performance and quality of your printer, and sometimes even prevent it from working at all. Fortunately, there is a solution for these issues: Epson WF 7511 Adjustment Program.

-

epson wf 7511 adjustment program download hit 5


Download 🗹 https://byltly.com/2uKA9r



-

Epson WF 7511 Adjustment Program is a utility program that allows you to reset the waste ink pad counter, prescribe the print head ID, do printer initialization, and other functions for your Epson WF 7011 or WF 7511 printer. This program can help you fix your printer problems and extend its lifespan. In this article, we will show you what Epson WF 7511 Adjustment Program is, how to download and install it, how to use it, and some tips and tricks for using it effectively.

-

What is Epson WF 7511 Adjustment Program?

-

Epson WF 7511 Adjustment Program is a service adjustment program that is designed for the specified printer models: Epson WorkForce WF-7011 and WF-7511. It is a utility program that enables you to perform various functions on your printer, such as:

- -

Features and benefits of Epson WF 7511 Adjustment Program

-

Epson WF 7511 Adjustment Program has many features and benefits that make it a useful tool for Epson printer users. Some of them are:

-

epson wf 7511 resetter software free download
-epson wf 7511 printer adjustment program
-how to use epson wf 7511 adjustment tool
-epson wf 7511 service required solution
-epson wf 7511 waste ink pad reset
-epson wf 7511 maintenance mode
-epson wf 7511 firmware update download
-epson wf 7511 driver for windows 10
-epson wf 7511 scanner software download
-epson wf 7511 manual pdf
-epson wf 7511 ink cartridge refill
-epson wf 7511 print head cleaning
-epson wf 7511 paper jam error
-epson wf 7511 duplex printing
-epson wf 7511 wireless setup
-epson wf 7511 scan to email
-epson wf 7511 fax setup
-epson wf 7511 price in india
-epson wf 7511 review and ratings
-epson wf 7511 specifications and features
-epson wf 7511 vs hp officejet pro 8600
-epson wf 7511 compatible toner and ink
-epson wf 7511 spare parts and accessories
-epson wf 7511 troubleshooting and error codes
-epson wf 7511 warranty and service center
-best buy epson wf 7511 online
-cheap and discounted epson wf 7511 deals
-how to install epson wf 7511 on mac
-how to connect epson wf 7511 to wifi
-how to scan multiple pages with epson wf 7511
-how to print borderless with epson wf 7511
-how to fix epson wf 7511 offline problem
-how to replace epson wf 7511 printhead
-how to reset epson wf 7511 ink level
-how to align epson wf 7511 print head
-how to calibrate epson wf 7511 scanner
-how to clean epson wf 7511 rollers and feeders
-how to change epson wf 7511 language settings
-how to set up epson wf 7511 for airprint
-how to enable epson wf 7511 cloud print
-how to disable epson wf 7511 ink monitor
-how to update epson wf 7511 software and drivers
-how to remove epson wf 7511 from network
-how to factory reset epson wf 7511 printer
-how to contact epson wf 7511 customer support
-how to register epson wf 7511 product online
-how to get free samples of epson wf 7511 ink and paper
-how to recycle epson wf 7511 cartridges and parts
-how to join epson wf 7511 loyalty program and rewards

- -

How to download and install Epson WF 7511 Adjustment Program

-

To download and install Epson WF 7511 Adjustment Program, you need to follow these steps:

-
    -
  1. Go to this website, which is one of the sources where you can find the program.
  2. -
  3. Select the quantity of the program you want to buy and click on "Add to cart". The price of the program is $7.50 per unit.
  4. -
  5. Proceed to checkout and enter your payment details. You can pay with PayPal or credit card.
  6. -
  7. After completing your payment, you will receive an email with a link to download the program and a license key.
  8. -
  9. Download the program from the link and save it on your computer.
  10. -
  11. Extract the zip file and run the setup.exe file.
  12. -
  13. Enter your license key when prompted and follow the installation wizard.
  14. -
  15. After installing the program, you can launch it from your desktop or start menu.
  16. -
-

How to use Epson WF 7511 Adjustment Program

-

To use Epson WF 7511 Adjustment Program, you need to follow these steps:

-
    -
  1. Connect your printer to your computer with a USB cable.
  2. -
  3. Turn on your printer and make sure it is in service mode. To enter service mode, press and hold the Power button while pressing these buttons in sequence: Paper Source - Cut/Eject - Paper Source - Cut/Eject - Paper Source - Cut/Eject.
  4. -
  5. Launch Epson WF 7511 Adjustment Program from your desktop or start menu.
  6. -
  7. Select your printer model from the drop-down menu.
  8. -
  9. Select "Particular adjustment mode" from the main menu.
  10. -
  11. Select the function you want to perform from the list of functions.
  12. -
  13. Follow the instructions on the screen for each function.
  14. -
  15. When you are done with using the program, close it and turn off your printer.
  16. -
-

How to reset the waste ink pad counter

-

To reset the waste ink pad counter of your printer, you need to follow these steps:

-
    -
  1. Select "Waste ink pad counter" from the list of functions in Particular adjustment mode.
  2. -
  3. Click on "OK" in the pop-up window that appears.
  4. -
  5. Select "Main pad counter" and "Platen pad counter" from the list of counters in Check and Initialization tab.
  6. -
  7. Click on "Check" button to see the current values of each counter.
  8. -
  9. If any of them reaches or exceeds its limit (100%), click on "Initialization" button to reset them to zero.
  10. -
  11. A confirmation message will appear. Click on "OK" button.
  12. -
  13. The program will ask you to turn off your printer. Do so and then turn it back on again.
  14. -
  15. The waste ink pad counter has been reset successfully.
  16. -
-

How to prescribe the print head ID

-

To prescribe the print head ID of your printer, you need to follow these steps:

-
    -
  1. Select "Print head ID input" from the list of functions in Particular adjustment mode.
  2. -
  3. A pop-up window will appear with instructions on how to find out your print head ID. Follow them carefully.
  4. -
  5. Type in your print head ID in the text box below "Input Print Head ID". Make sure it matches exactly with the one printed on your print head label.
  6. -
  7. Click on "OK" button.
  8. -
  9. The program will ask you to turn off your printer. Do so and then turn it back on again.
  10. -
  11. The print head ID has been prescribed successfully.
  12. -
-

How to do printer initialization

-

To do printer initialization for your printer, you need to follow these steps:

-
  1. Select "Initialization" from
  2. Click on "OK" in the pop-up window that appears.
  3. -
  4. The program will start initializing your printer. This may take a few minutes.
  5. -
  6. When the initialization is done, a confirmation message will appear. Click on "OK" button.
  7. -
  8. The program will ask you to turn off your printer. Do so and then turn it back on again.
  9. -
  10. The printer initialization has been done successfully.
  11. -
-

Tips and tricks for using Epson WF 7511 Adjustment Program

-

Epson WF 7511 Adjustment Program is a powerful and useful tool for Epson printer users, but it also has some limitations and precautions that you need to be aware of. Here are some tips and tricks for using Epson WF 7511 Adjustment Program effectively and safely:

-

How to avoid compatibility issues

-

Epson WF 7511 Adjustment Program is compatible with Windows operating systems only. It does not work with MacOSX or Linux operating systems. If you are using a different operating system, you need to use a terminal-based installation or a virtual machine to run the program.

-

Also, the program works only with USB connection. It does not work with wireless or network connection. Make sure you connect your printer to your computer with a USB cable before using the program.

-

How to update the program to the latest version

-

Epson WF 7511 Adjustment Program is updated regularly to fix bugs and improve performance. The latest version of the program is Ver.1.1.0, which was released in 2020. To update the program to the latest version, you need to follow these steps:

-
    -
  1. Go to this website, which is one of the sources where you can find the program.
  2. -
  3. Select "Free updates (to latest version program)" from the product options and click on "Add to cart". The update is free for regular customers who have bought the program before.
  4. -
  5. Proceed to checkout and enter your payment details. You can pay with PayPal or credit card.
  6. -
  7. After completing your payment, you will receive an email with a link to download the updated program and a new license key.
  8. -
  9. Download the updated program from the link and save it on your computer.
  10. -
  11. Extract the zip file and run the setup.exe file.
  12. -
  13. Enter your new license key when prompted and follow the installation wizard.
  14. -
  15. After installing the updated program, you can launch it from your desktop or start menu.
  16. -
-

How to disable antivirus software while working with the program

-

Some antivirus software may detect Epson WF 7511 Adjustment Program as a malicious or suspicious program and block it from running or accessing your printer. This can cause errors or failures when using the program. To avoid this problem, you need to disable your antivirus software while working with the program or add the program to the exceptions list of your antivirus software.

-

To disable your antivirus software, you need to follow these steps:

-
    -
  1. Find your antivirus software icon on your taskbar or system tray and right-click on it.
  2. -
  3. Select "Disable" or "Turn off" or similar option from the menu that appears.
  4. -
  5. Select how long you want to disable your antivirus software for. You can choose from a few minutes to permanently.
  6. -
  7. Click on "OK" or "Yes" or similar button to confirm your choice.
  8. -
  9. Your antivirus software is now disabled and will not interfere with Epson WF 7511 Adjustment Program.
  10. -
-

To add Epson WF 7511 Adjustment Program to the exceptions list of your antivirus software, you need to follow these steps:

-
    -
  1. Find your antivirus software icon on your taskbar or system tray and right-click on it.
  2. -
  3. Select "Settings" or "Options" or similar option from the menu that appears.
  4. -
  5. Select "Exceptions" or "Exclusions" or similar option from the settings menu.
  6. -
  7. Select "Add" or "Browse" or similar button to add a new exception.
  8. -
  9. Select the folder where you have installed Epson WF 7511 Adjustment Program and click on "OK" or "Open" or similar button.
  10. -
  11. Your antivirus software will now allow Epson WF 7511 Adjustment Program to run and access your printer without any problems.
  12. -
-

Conclusion

-

Epson WF 7511 Adjustment Program is a service adjustment program that can help you fix various problems with your Epson WF 7011 or WF 7511 printer, such as waste ink pad overflow, print head error, or printer initialization failure. It can also help you reset the waste ink pad counter, prescribe the print head ID, do printer initialization, and other functions for your printer. It is an original, full version, and updated program that has a simple user interface and easy-to-use features. It is compatible with Windows operating systems and works only with USB connection.

-

If you are looking for a solution for your Epson printer problems, Epson WF 7511 Adjustment Program is a great choice for you. You can download and install it from this website, which offers free updates and discounts for regular customers. You can also follow our guide on how to use it effectively and safely, and enjoy its features and benefits.

-

Epson WF 7511 Adjustment Program can help you extend the lifespan of your printer and improve its performance and quality. It is a must-have tool for every Epson printer user. Don't hesitate and get it today!

-

Summary of the main points

- -

Call to action

-

If you want to download and install Epson WF 7511 Adjustment Program, you can click on the button below and get it from this website. You will also get free updates and discounts for regular customers. Don't miss this opportunity and get your Epson printer fixed today!

-

-

FAQs

-

Here are some frequently asked questions about Epson WF 7511 Adjustment Program:

-

Q: Is Epson WF 7511 Adjustment Program safe to use?

-

A: Yes, Epson WF 7511 Adjustment Program is safe to use. It is an original program that does not contain any viruses or malware. However, some antivirus software may detect it as a suspicious program and block it from running or accessing your printer. To avoid this problem, you need to disable your antivirus software while working with the program or add the program to the exceptions list of your antivirus software.

-

Q: Does Epson WF 7511 Adjustment Program work with other printer models?

-

A: No, Epson WF 7511 Adjustment Program works only with Epson WorkForce WF-7011 and WF-7511 printer models. It does not work with other printer models. If you have a different printer model, you need to find a different adjustment program that is compatible with your printer model.

-

Q: How often do I need to use Epson WF 7511 Adjustment Program?

-

A: You need to use Epson WF 7511 Adjustment Program whenever you encounter a problem with your printer that can be solved by using the program. For example, if your printer displays an error message about waste ink pad overflow, you need to use the program to reset the waste ink pad counter. If your printer does not recognize your print head, you need to use the program to prescribe the print head ID. If your printer settings are corrupted or incorrect, you need to use the program to do printer initialization.

-

Q: How long does it take to use Epson WF 7511 Adjustment Program?

-

A: It depends on the function you want to perform and the speed of your computer and printer. Generally, it takes a few minutes to use Epson WF 7511 Adjustment Program for each function. For example, it takes about 2 minutes to reset the waste ink pad counter, about 3 minutes to prescribe the print head ID, and about 5 minutes to do printer initialization.

-

Q: What are the advantages of using Epson WF 7511 Adjustment Program?

-

A: There are many advantages of using Epson WF 7511 Adjustment Program for your printer. Some of them are:

- -

0a6ba089eb
-
-
\ No newline at end of file diff --git a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Family Tree Maker For Mac 2 Torrent ((INSTALL)).md b/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Family Tree Maker For Mac 2 Torrent ((INSTALL)).md deleted file mode 100644 index e6ff2a425b2fa55c9cabeb6ddd503e5548d8a741..0000000000000000000000000000000000000000 --- a/spaces/1acneusushi/gradio-2dmoleculeeditor/data/Family Tree Maker For Mac 2 Torrent ((INSTALL)).md +++ /dev/null @@ -1,111 +0,0 @@ -
-

Family Tree Maker For Mac 2 Torrent: How to Download and Use It

-

If you are interested in tracing your roots and creating a family tree, you might have heard of Family Tree Maker, one of the most popular genealogy software in the market. But what if you have a Mac computer and you don't want to pay for the software? Is there a way to get it for free? The answer is yes, if you use a torrent file. In this article, we will explain what Family Tree Maker is, what a torrent file is, why you might want to use Family Tree Maker For Mac 2 Torrent, and how to download and use it. Read on to find out more.

-

Introduction

-

What is Family Tree Maker?

-

Family Tree Maker is a software that helps you create and share your family tree. It allows you to add information about your ancestors and relatives, such as names, dates, places, events, photos, documents, stories, and more. You can also import data from historical records and official archives, such as census records, birth certificates, marriage licenses, death certificates, military records, immigration records, etc. You can also collaborate with other family history enthusiasts online and compare notes and discover more together. Family Tree Maker also lets you share and print your family tree in various formats, such as charts, reports, books, slideshows, etc.

-

Family Tree Maker For Mac 2 Torrent


Download https://byltly.com/2uKwHA



-

What is a torrent file?

-

A torrent file is a small file that contains information about a larger file or a group of files that you want to download from the internet. It does not contain the actual files themselves, but rather the metadata, such as the file names, sizes, locations, checksums, etc. A torrent file also contains information about the peers or sources that have the files or parts of the files that you want to download. To download a torrent file, you need a torrent client, which is a software that connects you to the peers and downloads the files for you.

-

Why use Family Tree Maker For Mac 2 Torrent?

-

There are several reasons why you might want to use Family Tree Maker For Mac 2 Torrent instead of buying the software from the official website. Here are some of them:

- -

How to download Family Tree Maker For Mac 2 Torrent

-

Now that you know what Family Tree Maker For Mac 2 Torrent is and why you might want to use it, let's see how you can download it. Here are the steps you need to follow:

-

Step 1: Find a reliable torrent site

-

The first thing you need to do is to find a torrent site that has the Family Tree Maker For Mac 2 Torrent file that you want. A torrent site is a website that hosts and indexes torrent files from various sources. There are many torrent sites on the internet, but not all of them are safe and trustworthy. Some of them might have malware, viruses, fake files, or illegal content. Therefore, you need to be careful and choose a reputable and reliable torrent site. Here are some of the factors you should consider when choosing a torrent site:

- -

Some examples of reliable torrent sites that might have Family Tree Maker For Mac 2 Torrent are The Pirate Bay, RARBG, 1337x, etc. However, these sites might be blocked or banned in some countries or regions due to legal issues or censorship. Therefore, you might need to use a VPN (virtual private network) service to access them. A VPN service is a software that creates a secure and encrypted connection between your device and a server in another location, allowing you to bypass geo-restrictions and access any website you want.

-

Step 2: Search for Family Tree Maker For Mac 2 Torrent

-

Once you have found a reliable torrent site, the next thing you need to do is to search for Family Tree Maker For Mac 2 Torrent on it. You can use the search bar or the filters on the torrent site to find the torrent file that matches your criteria. You can type in keywords such as "Family Tree Maker", "Mac", "version 2", "torrent", etc. You can also filter by category, genre, language, format, size, date, etc.

-

When you see the list of results, you should look at the details of each torrent file before downloading it. Here are some of the details you should pay attention to:

-

- -

Some examples of Family Tree Maker For Mac 2 Torrent files that you might find on a torrent site are:

- | Name | Size | Type | Seeders | Leechers | Rating | Comments | | --- | --- | --- | --- | --- | --- | --- | Name | Size | Type | Seeders | Leechers | Rating | Comments | | --- | --- | --- | --- | --- | --- | --- | | Family Tree Maker for Mac 2 (2011) - Full Version [Mac OSX] | 1.2 GB | .dmg | 125 | 12 | 4.5/5 | "Works great, easy to install, no problems" | | Family Tree Maker for Mac 2 (2011) - Crack Only [Mac OSX] | 12 MB | .zip | 87 | 9 | 4/5 | "You need to disable your antivirus before running the crack, otherwise it won't work" | | Family Tree Maker for Mac 2 (2011) - Update Only [Mac OSX] | 150 MB | .dmg | 65 | 7 | 3.5/5 | "This update fixes some bugs and improves performance, but you need to have the full version installed first" |

Choose the torrent file that suits your needs and preferences, and click on the download button or link to get it.

-

Step 3: Download the torrent file

-

After you click on the download button or link, you will be prompted to save the torrent file on your device. Choose a location where you want to save it, such as your desktop or downloads folder. The torrent file should be very small and quick to download, usually less than a few megabytes.

-

Step 4: Open the torrent file with a torrent client

-

Once you have downloaded the torrent file, you need to open it with a torrent client. A torrent client is a software that connects you to the peers or sources that have the files or parts of the files that you want to download. It also manages the download process and ensures that you get the complete and correct files. There are many torrent clients available for Mac, such as uTorrent, BitTorrent, Transmission, qBittorrent, etc. You can choose one that suits your needs and preferences, and download and install it on your device.

-

After you have installed a torrent client, you need to open the torrent file with it. You can do this by double-clicking on the torrent file, or by dragging and dropping it into the torrent client window, or by clicking on File > Open Torrent in the torrent client menu. The torrent client will then scan the torrent file and show you the details of the files that you are about to download, such as the name, size, type, progress, speed, etc. You can also choose which files you want to download or skip, and where you want to save them on your device.

-

Click on the start or play button to begin the download. The torrent client will then connect you to the peers or sources that have the files or parts of the files that you want to download. It will also show you the status of the download, such as the number of seeders and leechers, the download and upload speed, the estimated time remaining, etc. You can pause or resume the download at any time, or cancel it if you change your mind.

-

Wait until the download is complete. The time it takes to download depends on various factors, such as the size and quality of the files, the number and availability of peers or sources, the speed and stability of your internet connection, etc. It might take from a few minutes to a few hours or even days.

-

How to use Family Tree Maker For Mac 2 Torrent

-

Now that you have downloaded Family Tree Maker For Mac 2 Torrent, let's see how you can use it. Here are the steps you need to follow:

-

Step 1: Install Family Tree Maker on your Mac

-

The first thing you need to do is to install Family Tree Maker on your Mac. To do this, you need to locate the installation file that you downloaded via torrent. It should be in .dmg format, which is a disk image file that contains the software and its components. Double-click on the .dmg file to open it. You will see a window that shows the contents of the disk image file, such as an icon of Family Tree Maker and a shortcut to your Applications folder.

-

Drag and drop the icon of Family Tree Maker into your Applications folder. This will copy the software into your Applications folder and create a shortcut for it. Alternatively, you can run the installer program that is included in the disk image file and follow the instructions on screen.

-

If you downloaded a crack file or an update file via torrent, you might need to apply them before or after installing Family Tree Maker. A crack file is a file that modifies or bypasses the security features of a software, such as activation codes or serial numbers, allowing you to use the software for free or without limitations. An update file is a file that improves or fixes the software, such as adding new features or resolving bugs or errors. To apply a crack file or an update file, you need to locate them on your device and follow the instructions that are usually included in a text file or a readme file. You might need to copy and paste the crack file or the update file into the installation folder of Family Tree Maker, or run them as administrator, or restart your Mac, etc.

-

Step 2: Create or import your family tree

-

After you have installed Family Tree Maker on your Mac, you can launch it from your Applications folder or from your Dock. You will see a welcome screen that gives you two options: create a new family tree or import an existing family tree.

-

If you want to create a new family tree, you can click on the New button and enter a name for your family tree. You can also choose a template for your family tree, such as standard, extended, fan, bow tie, etc. You can also customize the appearance of your family tree, such as the color, font, style, etc.

-

If you want to import an existing family tree, you can click on the Import button and browse for the file that contains your family tree data. Family Tree Maker supports various file formats, such as .ftm, .ftmb, .ftw, .ged, etc. You can also import data from online sources, such as Ancestry.com, FamilySearch.org, etc. You will need to sign in with your account and grant permission to Family Tree Maker to access your data.

-

Step 3: Add and edit information about your ancestors and relatives

-

Once you have created or imported your family tree, you can start adding and editing information about your ancestors and relatives. You can do this by clicking on the People tab and selecting the person you want to work on. You will see a panel that shows the details of the person, such as name, birth date and place, death date and place, gender, occupation, etc. You can also see the relationships of the person with other people in your family tree, such as parents, spouse, children, siblings, etc.

-

To add information about a person, you can click on the Add button and choose what kind of information you want to add. For example, you can add facts, events, notes, sources, media, etc. You can also add new people to your family tree by clicking on the Add button and choosing what kind of relationship you want to add. For example, you can add parents, spouse, children, siblings, etc.

-

To edit information about a person, you can click on the Edit button and make changes to the existing information. For example, you can change the name, date, place, source, media, etc. of the person. You can also delete information or people from your family tree by clicking on the Delete button and confirming your action.

-

Step 4: Attach photos, documents, and stories to your family tree

-

One of the best features of Family Tree Maker is that it allows you to attach photos, documents, and stories to your family tree. This can help you enrich your family history and make it more personal and memorable. You can do this by clicking on the Media tab and selecting the person you want to work on. You will see a panel that shows the media items that are attached to the person, such as photos, documents, audio files, video files, etc.

-

To attach a photo or a document to a person, you can click on the Add button and choose what kind of media item you want to add. For example, you can add a photo from your computer, from your camera, from a scanner, from a web address, etc. You can also add a document from your computer, from a scanner, from a web address, etc. You can also drag and drop media items from your computer or other sources into the panel.

-

To attach a story to a person, you can click on the Add button and choose Story. You will see a window where you can write or paste your story. You can also format your story using various tools, such as font, size, color, alignment, bullet points, etc. You can also add photos or documents to your story by clicking on the Insert button and choosing what kind of media item you want to add.

-

To edit or delete a media item or a story that is attached to a person, you can click on the Edit or Delete button and make changes or confirm your action.

-

Step 5: Share and print your family tree

-

After you have added and edited information and media items to your family tree, you might want to share and print it. Family Tree Maker offers various options for sharing and printing your family tree. You can do this by clicking on the Publish tab and selecting what kind of output you want to create. For example, you can create charts, reports, books, slideshows, etc.

-

To create a chart of your family tree, you can click on the Chart button and choose what kind of chart you want to create. For example, you can create a pedigree chart, a descendant chart, a fan chart, a bow tie chart, etc. You can also customize the appearance of your chart, such as the size, shape, color, font, style, etc. You can also add or remove information and media items from your chart, such as names, dates, places, photos, etc.

-

To create a report of your family tree, you can click on the Report button and choose what kind of report you want to create. For example, you can create a family group sheet, a kinship report, a timeline report, a source report, etc. You can also customize the content and format of your report, such as the fields, filters, sorting, layout, etc. You can also add or remove information and media items from your report, such as names, dates, places, photos, etc.

-

To create a book of your family tree, you can click on the Book button and choose what kind of book you want to create. For example, you can create a narrative book, a scrapbook, a photo book, etc. You can also customize the design and layout of your book, such as the cover, title page, table of contents, chapters, sections, pages, etc. You can also add or remove information and media items from your book, such as names, dates, places, photos, stories, etc.

-

To create a slideshow of your family tree, you can click on the Slideshow button and choose what kind of slideshow you want to create. For example, you can create a standard slideshow, a photo slideshow, a video slideshow, etc. You can also customize the settings and effects of your slideshow, such as the duration, transition, music, narration, etc. You can also add or remove information and media items from your slideshow, such as names, dates, places, photos, stories, etc.

-

After you have created your output, you can preview it on your screen and make any adjustments if needed. You can also share it online or print it on paper or other materials. To share your output online, you can click on the Share button and choose what kind of platform you want to use. For example, you can share your output on Ancestry.com, FamilySearch.org, Facebook, Twitter, email, etc. You will need to sign in with your account and grant permission to Family Tree Maker to access your data. To print your output on paper or other materials, you can click on the Print button and choose what kind of printer and settings you want to use. For example, you can print your output on letter size paper, legal size paper, poster size paper, canvas, t-shirt, mug, etc.

-

Conclusion

-

In conclusion, Family Tree Maker For Mac 2 Torrent is a great way to create and share your family tree without paying for the software or worrying about compatibility issues. You can download and use it by following these steps:

-
    -
  1. Find a reliable torrent site that has the Family Tree Maker For Mac 2 Torrent file that you want.
  2. -
  3. Search for Family Tree Maker For Mac 2 Torrent on the torrent site and download the torrent file.
  4. -
  5. Open the torrent file with a torrent client and download the files that you want.
  6. -
  7. Install Family Tree Maker on your Mac and apply any crack or update files if needed.
  8. -
  9. Create or import your family tree and add and edit information and media items about your ancestors and relatives.
  10. -
  11. Share and print your family tree in various formats, such as charts, reports, books, slideshows, etc.
  12. -
-

We hope this article has helped you understand how to download and use Family Tree Maker For Mac 2 Torrent. If you have any questions or comments, please feel free to leave them below. Happy genealogy!

-

FAQs

-

Here are some of the frequently asked questions about Family Tree Maker For Mac 2 Torrent:

-

Is Family Tree Maker For Mac 2 Torrent legal?

-

Family Tree Maker For Mac 2 Torrent is not legal in most countries or regions. It is considered a form of piracy or intellectual property theft, as it violates the rights of the software developers and distributors. Downloading and using Family Tree Maker For Mac 2 Torrent might expose you to legal risks or penalties, such as fines, lawsuits, or even jail time. Therefore, we do not recommend or endorse using Family Tree Maker For Mac 2 Torrent, and we advise you to use it at your own risk and discretion.

-

Is Family Tree Maker For Mac 2 Torrent safe?

-

Family Tree Maker For Mac 2 Torrent is not safe in most cases. It might contain malware, viruses, spyware, adware, or other harmful programs that can damage your device or compromise your privacy and security. Downloading and using Family Tree Maker For Mac 2 Torrent might expose you to cyber risks or threats, such as hacking, phishing, identity theft, data loss, etc. Therefore, we do not recommend or endorse using Family Tree Maker For Mac 2 Torrent, and we advise you to use it at your own risk and discretion.

-

How to update Family Tree Maker For Mac 2 Torrent?

-

Family Tree Maker For Mac 2 Torrent is an outdated version of the software that was released in 2011. It might not have the latest features, functions, or improvements that the current version of Family Tree Maker has. It might also have some bugs, errors, or compatibility issues that affect its performance or usability. To update Family Tree Maker For Mac 2 Torrent, you might need to download and apply an update file via torrent. However, this might not be easy or possible, as the update file might not be available or reliable on torrent sites. Therefore, we do not recommend or endorse using Family Tree Maker For Mac 2 Torrent, and we advise you to use the latest version of Family Tree Maker instead.

-

How to uninstall Family Tree Maker For Mac 2 Torrent?

-

If you want to uninstall Family Tree Maker For Mac 2 Torrent from your Mac, you can follow these steps:

-
    -
  1. Open your Applications folder and find the icon of Family Tree Maker.
  2. -
  3. Drag and drop the icon of Family Tree Maker into the Trash bin.
  4. -
  5. Empty the Trash bin to delete the software and its components.
  6. -
  7. Open your Finder and go to the Library folder.
  8. -
  9. Search for any files or folders that are related to Family Tree Maker and delete them.
  10. -
-

This should remove Family Tree Maker For Mac 2 Torrent from your Mac. However, this might not remove all the traces or remnants of the software from your device. To completely uninstall Family Tree Maker For Mac 2 Torrent from your Mac, you might need to use a third-party uninstaller program that can scan and delete any leftover files or registry entries of the software.

-

What are some alternatives to Family Tree Maker For Mac 2 Torrent?

-

If you are looking for some alternatives to Family Tree Maker For Mac 2 Torrent, here are some of them:

- -

These are some of the alternatives to Family Tree Maker For Mac 2 Torrent that you can try. However, none of them can replace the original and official version of Family Tree Maker, which has the best quality, support, and updates. Therefore, we recommend that you buy Family Tree Maker from the official website if you can afford it and enjoy its full benefits.

b2dd77e56b
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Deluxe Ski Jump 3 V1.7.1 Keygen !!EXCLUSIVE!!.md b/spaces/1gistliPinn/ChatGPT4/Examples/Deluxe Ski Jump 3 V1.7.1 Keygen !!EXCLUSIVE!!.md deleted file mode 100644 index 72c72aad2437a844927c4bb023d88f90287aa3bb..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Deluxe Ski Jump 3 V1.7.1 Keygen !!EXCLUSIVE!!.md +++ /dev/null @@ -1,7 +0,0 @@ -
-

deluxe ski jump 3 v1.7.1 keygen

Other reviews:
The Legend of Zelda: Breath of the Wild lets you go anywhere and do anything. Throw a rock, find a new path, explore. The freedom the game offers is exhausting, and I don't know how many times I had to pause to catch my breath. Sure, collecting the Master Sword and fighting Ganon wasn't challenging, but a rich world full of secrets, opportunities, and hidden treasures is a lot more rewarding.

-

deluxe ski jump 3 v1.7.1 keygen

This version comes with a brand new story and nine brand new modes to play. For an action game, it's not bad at all. None of the modes are replayable, so they're only there to give you something to do. As a matter of fact, I couldn't even finish the story because I needed to stop to check out the different modes and achievements. Unfortunately, the time I spent playing these modes couldn't be easily returned.

-

deluxe ski jump 3 v1.7.1 keygen


DOWNLOADhttps://imgfil.com/2uy0py



-

deluxe ski jump 3 v1.7.1 keygen

My only complaint is that the game seems to repeat sections that got me far enough into the story. It's a minor issue, but I had to beat a bunch of story cutscenes twice because I couldn't make it through them the first time. Also, it seems that the game is never really "over" until I start a new game and try again, and that's a bit of a turn-off. All of that said, this game is a great game. The story, music, and visuals are top-notch, and the hack and slash action is even better than in the previous games.

899543212b
-
-
\ No newline at end of file diff --git a/spaces/1gistliPinn/ChatGPT4/Examples/Free Acme Id Card Maker 5.0 Serial Keygen !!EXCLUSIVE!!.md b/spaces/1gistliPinn/ChatGPT4/Examples/Free Acme Id Card Maker 5.0 Serial Keygen !!EXCLUSIVE!!.md deleted file mode 100644 index a67de50df8d1c2307d91d96ce0707c85515c660c..0000000000000000000000000000000000000000 --- a/spaces/1gistliPinn/ChatGPT4/Examples/Free Acme Id Card Maker 5.0 Serial Keygen !!EXCLUSIVE!!.md +++ /dev/null @@ -1,6 +0,0 @@ -

free acme id card maker 5.0 serial keygen


Download ►►► https://imgfil.com/2uy1EY



-
-Free Photo Card Workshop Download, Photo Card Workshop 1.5 ... Please be aware that Brothersoft do not supply any crack, patches, serial numbers or keygen for Photo Card ... Acme Id Card Maker V5.0 Crack ->Shutdown. 1fdad05405
-
-
-

diff --git a/spaces/1line/AutoGPT/autogpt/commands/file_operations.py b/spaces/1line/AutoGPT/autogpt/commands/file_operations.py deleted file mode 100644 index ad145ec956dd9dafd39e09c2244d001cf5febd2f..0000000000000000000000000000000000000000 --- a/spaces/1line/AutoGPT/autogpt/commands/file_operations.py +++ /dev/null @@ -1,267 +0,0 @@ -"""File operations for AutoGPT""" -from __future__ import annotations - -import os -import os.path -from typing import Generator - -import requests -from colorama import Back, Fore -from requests.adapters import HTTPAdapter, Retry - -from autogpt.spinner import Spinner -from autogpt.utils import readable_file_size -from autogpt.workspace import WORKSPACE_PATH, path_in_workspace - -LOG_FILE = "file_logger.txt" -LOG_FILE_PATH = WORKSPACE_PATH / LOG_FILE - - -def check_duplicate_operation(operation: str, filename: str) -> bool: - """Check if the operation has already been performed on the given file - - Args: - operation (str): The operation to check for - filename (str): The name of the file to check for - - Returns: - bool: True if the operation has already been performed on the file - """ - log_content = read_file(LOG_FILE) - log_entry = f"{operation}: {filename}\n" - return log_entry in log_content - - -def log_operation(operation: str, filename: str) -> None: - """Log the file operation to the file_logger.txt - - Args: - operation (str): The operation to log - filename (str): The name of the file the operation was performed on - """ - log_entry = f"{operation}: {filename}\n" - - # Create the log file if it doesn't exist - if not os.path.exists(LOG_FILE_PATH): - with open(LOG_FILE_PATH, "w", encoding="utf-8") as f: - f.write("File Operation Logger ") - - append_to_file(LOG_FILE, log_entry, shouldLog=False) - - -def split_file( - content: str, max_length: int = 4000, overlap: int = 0 -) -> Generator[str, None, None]: - """ - Split text into chunks of a specified maximum length with a specified overlap - between chunks. - - :param content: The input text to be split into chunks - :param max_length: The maximum length of each chunk, - default is 4000 (about 1k token) - :param overlap: The number of overlapping characters between chunks, - default is no overlap - :return: A generator yielding chunks of text - """ - start = 0 - content_length = len(content) - - while start < content_length: - end = start + max_length - if end + overlap < content_length: - chunk = content[start : end + overlap - 1] - else: - chunk = content[start:content_length] - - # Account for the case where the last chunk is shorter than the overlap, so it has already been consumed - if len(chunk) <= overlap: - break - - yield chunk - start += max_length - overlap - - -def read_file(filename: str) -> str: - """Read a file and return the contents - - Args: - filename (str): The name of the file to read - - Returns: - str: The contents of the file - """ - try: - filepath = path_in_workspace(filename) - with open(filepath, "r", encoding="utf-8") as f: - content = f.read() - return content - except Exception as e: - return f"Error: {str(e)}" - - -def ingest_file( - filename: str, memory, max_length: int = 4000, overlap: int = 200 -) -> None: - """ - Ingest a file by reading its content, splitting it into chunks with a specified - maximum length and overlap, and adding the chunks to the memory storage. - - :param filename: The name of the file to ingest - :param memory: An object with an add() method to store the chunks in memory - :param max_length: The maximum length of each chunk, default is 4000 - :param overlap: The number of overlapping characters between chunks, default is 200 - """ - try: - print(f"Working with file {filename}") - content = read_file(filename) - content_length = len(content) - print(f"File length: {content_length} characters") - - chunks = list(split_file(content, max_length=max_length, overlap=overlap)) - - num_chunks = len(chunks) - for i, chunk in enumerate(chunks): - print(f"Ingesting chunk {i + 1} / {num_chunks} into memory") - memory_to_add = ( - f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}" - ) - - memory.add(memory_to_add) - - print(f"Done ingesting {num_chunks} chunks from {filename}.") - except Exception as e: - print(f"Error while ingesting file '{filename}': {str(e)}") - - -def write_to_file(filename: str, text: str) -> str: - """Write text to a file - - Args: - filename (str): The name of the file to write to - text (str): The text to write to the file - - Returns: - str: A message indicating success or failure - """ - if check_duplicate_operation("write", filename): - return "Error: File has already been updated." - try: - filepath = path_in_workspace(filename) - directory = os.path.dirname(filepath) - if not os.path.exists(directory): - os.makedirs(directory) - with open(filepath, "w", encoding="utf-8") as f: - f.write(text) - log_operation("write", filename) - return "File written to successfully." - except Exception as e: - return f"Error: {str(e)}" - - -def append_to_file(filename: str, text: str, shouldLog: bool = True) -> str: - """Append text to a file - - Args: - filename (str): The name of the file to append to - text (str): The text to append to the file - - Returns: - str: A message indicating success or failure - """ - try: - filepath = path_in_workspace(filename) - with open(filepath, "a") as f: - f.write(text) - - if shouldLog: - log_operation("append", filename) - - return "Text appended successfully." - except Exception as e: - return f"Error: {str(e)}" - - -def delete_file(filename: str) -> str: - """Delete a file - - Args: - filename (str): The name of the file to delete - - Returns: - str: A message indicating success or failure - """ - if check_duplicate_operation("delete", filename): - return "Error: File has already been deleted." - try: - filepath = path_in_workspace(filename) - os.remove(filepath) - log_operation("delete", filename) - return "File deleted successfully." - except Exception as e: - return f"Error: {str(e)}" - - -def search_files(directory: str) -> list[str]: - """Search for files in a directory - - Args: - directory (str): The directory to search in - - Returns: - list[str]: A list of files found in the directory - """ - found_files = [] - - if directory in {"", "/"}: - search_directory = WORKSPACE_PATH - else: - search_directory = path_in_workspace(directory) - - for root, _, files in os.walk(search_directory): - for file in files: - if file.startswith("."): - continue - relative_path = os.path.relpath(os.path.join(root, file), WORKSPACE_PATH) - found_files.append(relative_path) - - return found_files - - -def download_file(url, filename): - """Downloads a file - Args: - url (str): URL of the file to download - filename (str): Filename to save the file as - """ - safe_filename = path_in_workspace(filename) - try: - message = f"{Fore.YELLOW}Downloading file from {Back.LIGHTBLUE_EX}{url}{Back.RESET}{Fore.RESET}" - with Spinner(message) as spinner: - session = requests.Session() - retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504]) - adapter = HTTPAdapter(max_retries=retry) - session.mount("http://", adapter) - session.mount("https://", adapter) - - total_size = 0 - downloaded_size = 0 - - with session.get(url, allow_redirects=True, stream=True) as r: - r.raise_for_status() - total_size = int(r.headers.get("Content-Length", 0)) - downloaded_size = 0 - - with open(safe_filename, "wb") as f: - for chunk in r.iter_content(chunk_size=8192): - f.write(chunk) - downloaded_size += len(chunk) - - # Update the progress message - progress = f"{readable_file_size(downloaded_size)} / {readable_file_size(total_size)}" - spinner.update_message(f"{message} {progress}") - - return f'Successfully downloaded and locally stored file: "{filename}"! (Size: {readable_file_size(total_size)})' - except requests.HTTPError as e: - return f"Got an HTTP Error whilst trying to download file: {e}" - except Exception as e: - return "Error: " + str(e) diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/All-in-One Solitaire APK - The Ultimate Solitaire Collection for Android.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/All-in-One Solitaire APK - The Ultimate Solitaire Collection for Android.md deleted file mode 100644 index a98cd1774cfb052f3d558bd91d79a56e6a835d7b..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/All-in-One Solitaire APK - The Ultimate Solitaire Collection for Android.md +++ /dev/null @@ -1,93 +0,0 @@ - -

All-in-One Solitaire APK Download: Play Solitaire Games on Your Android Device

-

If you love playing solitaire games, you will love All-in-One Solitaire APK. This is an amazing app that lets you enjoy over 50 different solitaire games on your Android device. Whether you prefer classic solitaire games like Klondike, Spider, or FreeCell, or you want to try something new like Pyramid, Tri-Peaks, or Wasp, you will find them all in this app. You can also customize your cards and backgrounds, use unlimited undos and hints, and play offline or online. In this article, we will tell you more about All-in-One Solitaire APK, how to download and install it, how to play it, and why you should play it.

-

all in one solitaire apk download


Download File ⇒⇒⇒ https://urlin.us/2uSUgc



-

What is All-in-One Solitaire APK?

-

All-in-One Solitaire APK is an Android game app that offers you a collection of over 50 solitaire games in one place. It is developed by Pozirk Games Inc., a company that specializes in creating casual games for mobile devices. The app has been downloaded over 1 million times on Google Play Store and has received positive reviews from users. The app is compatible with Android 5.0 and up and requires 20 MB of storage space.

-

Features of All-in-One Solitaire APK

-

Over 50 solitaire games in one app

-

One of the best features of All-in-One Solitaire APK is that it gives you access to over 50 solitaire games in one app. You can choose from popular solitaire games like Klondike, Spider, FreeCell, Pyramid, Tri-Peaks, Crescent, Scorpion, Gaps, and more. You can also discover new solitaire games like Algerian, Calculation, Canfield, Flower Garden, Golf, Penguin, Terrace, Wasp, and more. Each game has its own rules and instructions that you can read before playing.

-

Unlimited undos and hints

-

Another great feature of All-in-One Solitaire APK is that it allows you to use unlimited undos and hints. If you make a mistake or get stuck, you can use the undo button to go back to your previous move. If you need some help or guidance, you can use the hint button to get a suggestion for your next move. These features make the game more enjoyable and less frustrating.

-

High quality cards and backgrounds

-

All-in-One Solitaire APK also offers you high quality cards and backgrounds that make the game more attractive and appealing. You can customize your cards by choosing from different designs, colors, sizes, and fonts. You can also change your backgrounds by selecting from various themes, patterns, and images. You can even use your own photos as backgrounds if you want.

-

Easy card movement with one tap

All-in-One Solitaire APK also makes the card movement easy and smooth with one tap. You don't have to drag and drop cards to move them, you can just tap on them and they will automatically move to the best possible place. This feature saves you time and effort and makes the game more convenient and user-friendly.

-

All-in-One Solitaire Android Game Free Download
-Download All in One Solitaire APK for Android Aptoide
-All-in-One Solitaire 1.14.2 APK by Pozirk Games Inc.
-Solitaire All-in-One Card Games APK Download
-All in One Solitaire Free APK for Android Devices
-All-in-One Solitaire APKCombo Games Card
-All-in-One Solitaire Latest Version APK Update
-Download All-in-One Solitaire 1.3.3 APK Aptoide
-All-in-One Solitaire Game Features and Description
-How to Install All-in-One Solitaire APK on Android
-All-in-One Solitaire User Ratings and Reviews
-All-in-One Solitaire Available Games and Modes
-All-in-One Solitaire Unlimited Undos and Hints
-All-in-One Solitaire Background Music and Sound Effects
-All-in-One Solitaire Bigger and Better Cards
-All-in-One Solitaire Easy Cards Movement with One Tap
-All-in-One Solitaire Old Versions and History
-All-in-One Solitaire Category and Google Play ID
-All-in-One Solitaire Installs and Downloads Statistics
-All-in-One Solitaire App APKs and Languages
-All-in-One Solitaire Crescent Solitaire Game Mode
-All-in-One Solitaire Cruel Solitaire Game Mode
-All-in-One Solitaire Tri-Peaks Solitaire Game Mode
-All-in-One Solitaire Pyramid Solitaire Game Mode
-All-in-One Solitaire Klondike Solitaire Game Mode
-All-in-One Solitaire Gaps Solitaire Game Mode
-All-in-One Solitaire Spider Solitaire Game Mode
-All-in-One Solitaire FreeCell Solitaire Game Mode
-All-in-One Solitaire Fortune Solitaire Game Mode
-All-in-One Solitaire Scorpion Solitaire Game Mode
-All-in-One Solitaire Accordion Solitaire Game Mode
-All-in-One Solitaire Penguin Solitaire Game Mode
-All-in-One Solitaire 60/90 Seconds Solitaire Game Mode
-All-in-One Solitaire Aces Up Solitaire Game Mode
-All-in-One Solitaire Beehive Solitaire Game Mode
-All-in-One Solitaire 40 Thieves Solitaire Game Mode
-All-in-One Solitaire 52 Pickup Solitaire Game Mode
-All-in-One Solitaire Algerian Solitaire Game Mode
-All-in-One Solitaire Thieves Of Egypt Solitaire Game Mode
-All-in-One Solitaire Wasp Solitaire Game Mode
-All-in-One Solitaire Calculation Solitaire Game Mode
-All-in-One Solitaire Canfield Solitaire Game Mode
-All-in-One Solitaire Alternations Solitaire Game Mode
-All-in-One Solitaire Yukon/Alaska/SolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameModeSolitareGameMode

-

How to download and install All-in-One Solitaire APK?

-

If you want to download and install All-in-One Solitaire APK on your Android device, you can follow these simple steps:

-

Step 1: Go to the official website of All-in-One Solitaire APK

-

The first step is to go to the official website of All-in-One Solitaire APK, where you can find the latest version of the app and more information about it. You can use this link to access the website.

-

Step 2: Click on the download button and choose the version you want

-

The next step is to click on the download button on the website and choose the version of the app that you want. There are two versions available: one for Android 5.0 and up, and one for Android 4.0.3 and up. You can also see the size of the app and the number of downloads before downloading it.

-

Step 3: Allow unknown sources on your device settings

-

The third step is to allow unknown sources on your device settings, so that you can install apps from sources other than Google Play Store. To do this, go to your device settings, then security, then enable unknown sources. This will allow you to install All-in-One Solitaire APK without any problems.

-

Step 4: Open the downloaded file and install the app

-

The final step is to open the downloaded file and install the app on your device. You can find the file in your downloads folder or in your notifications bar. Once you open it, you will see a screen that asks you to confirm the installation. Click on install and wait for a few seconds until the app is installed. Then, you can open it and start playing solitaire games.

-

How to play All-in-One Solitaire APK?

-

Playing All-in-One Solitaire APK is easy and fun. Here are some tips on how to play it:

-

Choose a solitaire game from the menu

-

The first thing you need to do is to choose a solitaire game from the menu. You can scroll through the list of over 50 solitaire games and select the one that you like. You can also see a preview of each game and its difficulty level before choosing it.

-

Follow the rules and instructions of the game

-

The next thing you need to do is to follow the rules and instructions of the game that you chose. You can read them by clicking on the question mark icon on the top right corner of the screen. You can also pause or restart the game by clicking on the menu icon on the top left corner of the screen.

-

Drag and drop cards to move them or tap to select them

The main thing you need to do is to drag and drop cards to move them or tap to select them. You can move cards from one pile to another according to the rules of each game. You can also double tap on a card to move it automatically if possible. You can also use gestures like swipe or pinch to zoom in or out of the cards.

-

Use the undo and hint buttons if you get stuck

The last thing you need to do is to use the undo and hint buttons if you get stuck. You can use the undo button to go back to your previous move if you make a mistake or change your mind. You can use the hint button to get a suggestion for your next move if you don't know what to do. These buttons are located at the bottom of the screen.

-

Why should you play All-in-One Solitaire APK?

-

There are many reasons why you should play All-in-One Solitaire APK. Here are some of them:

-

It is fun and relaxing

All-in-One Solitaire APK is a fun and relaxing game that you can play anytime and anywhere. You can enjoy playing solitaire games without any stress or pressure. You can also listen to soothing music and sound effects while playing.

-

It improves your brain skills and memory

All-in-One Solitaire APK also improves your brain skills and memory by challenging your logic, strategy, concentration, and patience. You can exercise your mind by solving different puzzles and problems in each game. You can also improve your memory by remembering the cards and their positions in each game.

-

It offers a variety of challenges and difficulties

All-in-One Solitaire APK also offers a variety of challenges and difficulties that suit your preferences and skills. You can choose from easy, medium, hard, or expert modes in each game. You can also compete with other players online and see your rank and score on the leaderboard.

-

It works offline and online

All-in-One Solitaire APK also works offline and online, so you can play it without any internet connection or with a stable connection. You can play it offline if you want to save your data or battery, or if you don't have access to the internet. You can play it online if you want to sync your progress across devices, or if you want to play with other players.

-

Conclusion

-

All-in-One Solitaire APK is a wonderful app that lets you play over 50 solitaire games on your Android device. You can download and install it easily from the official website, and enjoy its features like unlimited undos and hints, high quality cards and backgrounds, easy card movement with one tap, and more. You can also improve your brain skills and memory, have fun and relax, and choose from different challenges and difficulties. You can also play it offline or online, depending on your preference. If you love solitaire games, you should definitely try All-in-One Solitaire APK.

-

FAQs

-

Here are some frequently asked questions about All-in-One Solitaire APK:

-

Is All-in-One Solitaire APK free?

Yes, All-in-One Solitaire APK is free to download and play. However, it contains ads that you can remove by purchasing the premium version of the app for $2.99.

-

Is All-in-One Solitaire APK safe?

Yes, All-in-One Solitaire APK is safe to download and install. It does not contain any viruses or malware that can harm your device or data. However, you should always download it from the official website or a trusted source to avoid any risks.

-

What are the requirements for All-in-One Solitaire APK?

The requirements for All-in-One Solitaire APK are Android 5.0 and up for the latest version of the app, and Android 4.0.3 and up for the older version of the app. You also need 20 MB of storage space on your device to install the app.

-

How can I contact the developer of All-in-One Solitaire APK?

You can contact the developer of All-in-One Solitaire APK by sending an email to support@pozirk.com or by visiting their website at https://pozirk.com/.

-

Can I play All-in-One Solitaire APK on my PC?

No, All-in-One Solitaire APK is only available for Android devices. However, you can use an Android emulator like Bluestacks or Nox Player to run the app on your PC.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Black Clover Wallpapers Discover the Best HD and 4K Backgrounds for Anime Lovers.md b/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Black Clover Wallpapers Discover the Best HD and 4K Backgrounds for Anime Lovers.md deleted file mode 100644 index 3cddd205b319766a47867c3258ddb43f8c946bb8..0000000000000000000000000000000000000000 --- a/spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Black Clover Wallpapers Discover the Best HD and 4K Backgrounds for Anime Lovers.md +++ /dev/null @@ -1,98 +0,0 @@ -
-

Black Clover Wallpaper: How to Decorate Your Device with Magic and Adventure

-

If you are a fan of fantasy, action, and comedy, you might have heard of Black Clover, a popular manga and anime series that follows the adventures of Asta, a boy who wants to become the Wizard King in a world where everyone has magic. Whether you are new to the series or a long-time follower, you might want to spice up your device with some Black Clover wallpaper that showcases your favorite characters, scenes, and themes from the story. In this article, we will tell you everything you need to know about Black Clover wallpaper, including what it is, why you should choose it, and how to find and download it.

-

What is Black Clover?

-

Before we dive into the details of Black Clover wallpaper, let us first give you a brief introduction to the manga and anime series that inspired it.

-

black clover wallpaper


Download - https://urlin.us/2uSZbG



-

A brief introduction to the manga and anime series

-

Black Clover is a Japanese manga series written and illustrated by Yūki Tabata. It has been serialized in Shueisha's shōnen manga magazine Weekly Shōnen Jump since February 2015, with its chapters collected in 35 tankōbon volumes as of June 2023 . The manga has been adapted into an anime television series by Studio Pierrot, which aired from October 2017 to March 2021, with a total of 170 episodes . The anime is also available for streaming on platforms like Crunchyroll and Funimation.

-

The story of Black Clover is set in a world where magic is everything. People are born with magical abilities that vary in power and type. They use grimoires, books that amplify their magic and allow them to cast spells. The most coveted grimoire is the four-leaf clover, which grants its wielder exceptional magic and luck. However, there is also a rare and mysterious five-leaf clover grimoire, which contains a devil that can grant anti-magic powers.

-

black clover wallpaper asta
-black clover wallpaper yuno
-black clover wallpaper noelle
-black clover wallpaper yami
-black clover wallpaper secre
-black clover wallpaper zenon
-black clover wallpaper nero
-black clover wallpaper 4k
-black clover wallpaper hd
-black clover wallpaper desktop
-black clover wallpaper phone
-black clover wallpaper iphone
-black clover wallpaper android
-black clover wallpaper laptop
-black clover wallpaper pc
-black clover wallpaper 1920x1080
-black clover wallpaper 3840x2160
-black clover wallpaper 4096x2703
-black clover wallpaper asta and yuno
-black clover wallpaper asta and yami
-black clover wallpaper asta and liebe
-black clover wallpaper asta devil form
-black clover wallpaper asta demon union
-black clover wallpaper yuno spirit dive
-black clover wallpaper yuno vs zenon
-black clover wallpaper noelle valkyrie dress
-black clover wallpaper noelle and asta
-black clover wallpaper noelle and mimosa
-black clover wallpaper yami and charlotte
-black clover wallpaper yami katana
-black clover wallpaper secre swallowtail
-black clover wallpaper secre and nero
-black clover wallpaper zenon zogratis
-black clover wallpaper zenon vs yuno
-black clover wallpaper nero bird form
-black clover wallpaper nero seal magic
-black clover wallpaper anime characters
-black clover wallpaper anime scenes
-black clover wallpaper anime art
-black clover wallpaper anime fanart

-

The protagonist of the series is Asta, a cheerful and energetic orphan who was abandoned at a church along with his rival and best friend, Yuno. Asta has no magic at all, while Yuno has immense magical talent and a four-leaf clover grimoire. Despite his disadvantage, Asta dreams of becoming the Wizard King, the strongest mage in the kingdom who protects the people from threats. To achieve his goal, he joins the Black Bulls, one of the nine Magic Knight squads that serve the Wizard King. Along with his teammates, he embarks on various missions and battles against enemies such as the Eye of the Midnight Sun, a terrorist group that seeks to destroy the kingdom; the Diamond Kingdom, a neighboring country that invades for resources; the Spade Kingdom, a militaristic nation that plans to conquer the world; and devils, evil beings from another dimension that manipulate humans for their own purposes.

-

The main characters and their powers

-

Black Clover has a large and diverse cast of characters, each with their own personality, backstory, and magic. Here are some of the main characters and their powers:

- -

Why choose Black Clover wallpaper?

-

Now that you have some background information about Black Clover, you might be wondering why you should choose it as your wallpaper for your device. Here are some of the benefits of having a Black Clover wallpaper:

-

The benefits of having a wallpaper that reflects your personality and interests

-

A wallpaper is more than just a background image for your device. It is also a way of expressing yourself and showing your personality and interests to others. By choosing a Black Clover wallpaper, you can demonstrate your love for the series and its characters, as well as your appreciation for its art style and themes. You can also use your wallpaper to inspire yourself and motivate yourself to achieve your goals, just like Asta and Yuno do in their quest to become the Wizard King.

-

The variety of styles and themes available for Black Clover wallpaper

-

Another benefit of choosing a Black Clover wallpaper is that you have a wide range of options to choose from. You can find wallpapers that feature different characters, scenes, symbols, quotes, colors, and designs from the series. You can also find wallpapers that suit different moods, occasions, seasons, and preferences. Whether you want a wallpaper that is cool, cute, funny, dramatic, or romantic, you can find one that matches your taste.

-

How to find and download Black Clover wallpaper?

-

Now that you know why you should choose a Black Clover wallpaper, you might be wondering how to find and download one for your device. Here are some of the best sources and websites for Black Clover wallpaper:

-

Some of the best sources and websites for Black Clover wallpaper

-

One of the easiest ways to find Black Clover wallpaper is to use search engines like Google or Bing . You can simply type in keywords like "Black Clover wallpaper", "Black Clover wallpaper HD", "Black Clover wallpaper 4K", or "Black Clover wallpaper phone" and browse through the results. You can also use filters like size, color, type, or license to narrow down your search.

-

Another way to find Black Clover wallpaper is to use dedicated websites that offer high-quality wallpapers for various devices. Some of the best websites for Black Clover wallpaper are: - [Wall.alphacoders.com](^1^) : This website offers over 350 anime Black Clover wallpapers in various resolutions, including 4K. You can browse by categories, such as Asta, Yuno, Noelle, Yami, Secre, Zenon, and Nero. You can also filter by popularity, date added, ratings, and views. You can download the wallpapers for free and use them for personal use only. - [Wallpapercave.com](^3^): This website has a collection of Black Clover 4K HD wallpapers that you can download and share for free. You can find wallpapers featuring different characters, scenes, symbols, and quotes from the series. You can also join the community and upload your own wallpapers. - [Pinterest.com]: This website is a social media platform that allows you to discover and save ideas for various topics, including Black Clover wallpaper. You can find thousands of pins with images and links to Black Clover wallpaper from different sources. You can also create your own boards and pin your favorite wallpapers.

How to customize and apply your wallpaper on different devices

-

Once you have found and downloaded your preferred Black Clover wallpaper, you might want to customize and apply it on your device. Here are some tips on how to do that:

- -

Conclusion

-

Black Clover is a manga and anime series that follows the adventures of Asta, a boy who wants to become the Wizard King in a world where everyone has magic. It has a large and diverse cast of characters, each with their own personality, backstory, and magic. If you are a fan of the series or just looking for a way to decorate your device with some magic and adventure, you might want to choose a Black Clover wallpaper that showcases your favorite characters, scenes, and themes from the story.

-

In this article, we have told you everything you need to know about Black Clover wallpaper, including what it is, why you should choose it, and how to find and download it. We hope you have enjoyed reading this article and found it helpful. If you have any questions or feedback, please feel free to leave a comment below.

-

Now that you have learned about Black Clover wallpaper, why not give it a try and see how it looks on your device? You might be surprised by how much it can enhance your mood and experience. Thank you for reading and have a wonderful day!

-

FAQs

-

What is the meaning of the clover symbols in Black Clover?

-

The clover symbols in Black Clover represent the number of leaves on the grimoires that the characters use to cast magic. The more leaves a grimoire has, the more rare and powerful it is. The meanings of the leaves are as follows:

- -

Who is the strongest character in Black Clover?

-

This is a difficult question to answer as there are many factors that determine the strength of a character in Black Clover, such as magic type, magic amount, magic control, magic affinity, grimoire, spirit, devil, experience, skill, strategy, teamwork, and personality. However, based on the current events of the manga and anime, some of the candidates for the strongest character in Black Clover are: - Julius Novachrono: The former Wizard King and the leader of the Magic Knights. He has a time magic grimoire and can manipulate time to accelerate, decelerate, stop, or reverse it. He can also see the future and store time in his tattoos. He is a master of magic and combat, and has a vast knowledge of the world and its history. - Licht: The leader of the Elf Tribe and the original owner of the five-leaf clover grimoire. He has a sword magic grimoire and can create and wield various swords with different abilities. He can also use forbidden magic to summon a giant demon god. He is a prodigy of magic and swordsmanship, and has a strong connection to mana and nature. - Lumiere Silvamillion Clover: The first Wizard King and the savior of the Clover Kingdom. He has a light magic grimoire and can create and manipulate light to move at high speeds, attack with powerful beams, or heal with rays. He can also use sealing magic to seal away enemies or objects. He is a genius of magic and science, and has a noble and compassionate heart. - Zagred: The devil who orchestrated the massacre of the Elf Tribe and the reincarnation of the elves. He has a word magic grimoire and can create and manipulate anything he says with his mouth. He can also use other types of magic, such as fire, ice, wind, earth, water, plant, beast, spatial, healing, curse, ash, trap, mirror, dream, soul, and anti-magic. He is a cunning and ruthless being who seeks to destroy the world and create his own. - Asta: The main protagonist of the series and the current owner of the five-leaf clover grimoire. He has no magic but possesses a devil named Liebe who grants him anti-magic powers. He can use anti-magic to negate and repel any magic with his swords. He is also very physically strong and agile, and has a strong sense of justice and determination.

How many episodes are there in Black Clover anime?

-

Black Clover anime has a total of 170 episodes that aired from October 2017 to March 2021 . The anime covers the first 270 chapters of the manga , which is divided into 11 arcs: Introduction Arc (episodes 1-3), Dungeon Exploration Arc (episodes 4-13), Royal Capital Arc (episodes 14-19), Eye of the Midnight Sun Arc (episodes 20-27), Seabed Temple Arc (episodes 28-49), Witches' Forest Arc (episodes 50-65), Hot Springs Training Camp Arc (episodes 66-68), Royal Knights Arc (episodes 69-101), Reincarnation Arc (episodes 102-120), Elf Reincarnation Arc (episodes 121-151), and Spade Kingdom Raid Arc (episodes 152-170).

-

Is Black Clover manga still ongoing?

-

Yes, Black Clover manga is still ongoing as of June 2023 . The manga has currently released 35 tankōbon volumes that contain 298 chapters . The latest chapter is chapter 298 , which was released on June 18th, 2023 . The manga is still in the Spade Kingdom Raid Arc , which is the 12th arc of the story.

-

Where can I watch Black Clover anime online?

-

You can watch Black Clover anime online on various streaming platforms that have licensed the series for different regions. Some of the most popular platforms are: - Crunchyroll : This platform offers all 170 episodes of Black Clover anime in Japanese with English subtitles for free with ads or with a premium subscription without ads. It also offers simulcasts of new episodes as they air in Japan. Crunchyroll is available in North America, Central America, South America, Europe, Africa, Oceania, the Middle East, and CIS. - Funimation : This platform offers all 170 episodes of Black Clover anime in Japanese with English subtitles or in English dub for free with ads or with a premium subscription without ads. It also offers simulcasts of new episodes as they air in Japan. Funimation is available in North America, the United Kingdom, Ireland, Australia, and New Zealand. - Hulu : This platform offers all 170 episodes of Black Clover anime in Japanese with English subtitles or in English dub for free with ads or with a premium subscription without ads. It also offers simulcasts of new episodes as they air in Japan. Hulu is available in the United States and Japan. - Netflix : This platform offers the first 51 episodes of Black Clover anime in Japanese with English subtitles or in English dub with a premium subscription. It does not offer simulcasts of new episodes. Netflix is available in most regions worldwide.

197e85843d
-
-
\ No newline at end of file diff --git a/spaces/1phancelerku/anime-remove-background/Call of Duty Mobile APKPure Download Everything You Need to Know About the Game and Its Features.md b/spaces/1phancelerku/anime-remove-background/Call of Duty Mobile APKPure Download Everything You Need to Know About the Game and Its Features.md deleted file mode 100644 index 38db95d6df0c1190cb91e0158fe2090596b5012e..0000000000000000000000000000000000000000 --- a/spaces/1phancelerku/anime-remove-background/Call of Duty Mobile APKPure Download Everything You Need to Know About the Game and Its Features.md +++ /dev/null @@ -1,90 +0,0 @@ - -

Download Call of Duty Mobile APKPure: How to Play the Popular Shooter on Your Android Device

-

If you are a fan of first-person shooter games, you have probably heard of Call of Duty, one of the most successful and influential franchises in the genre. But did you know that you can also play Call of Duty on your mobile device? Yes, you read that right. Call of Duty Mobile is a free-to-play game that brings the best of Call of Duty to your Android phone or tablet. In this article, we will tell you what Call of Duty Mobile is, why you should download it from APKPure, and how to do it in a few simple steps.

-

What is Call of Duty Mobile?

-

Call of Duty Mobile is a mobile version of the famous Call of Duty series, developed by TiMi Studios and published by Activision. The game was released in October 2019 and has since become one of the most popular and downloaded games on mobile platforms. Call of Duty Mobile offers an exciting way to play a beloved game franchise on your mobile device. The game features classic multiplayer modes such as Team Deathmatch, Domination, and Kill-Confirmed on iconic maps like Shipment, Raid, and Standoff. You can also play Battle Royale mode, where you compete with 99 other players in a large map with vehicles, weapons, and items. You can customize your loadout, unlock new skins, weapons, perks, and more as you level up your rank and battle pass. You can also join clans, chat with friends, and participate in seasonal events and challenges.

-

download call of duty mobile apkpure


DOWNLOADhttps://jinyurl.com/2uNLGm



-

Why download Call of Duty Mobile APKPure?

-

Call of Duty Mobile is available on Google Play Store, but there are some reasons why you might want to download it from APKPure instead. APKPure is a third-party app store that provides free and safe APK files for Android users. Here are some of the benefits of using APKPure to download and install Call of Duty Mobile:

-

No region restrictions

-

Some countries or regions may not have access to Call of Duty Mobile on Google Play Store due to various reasons. For example, India banned the game in 2020 along with other Chinese apps amid political tensions. If you live in such a country or region, you can still download Call of Duty Mobile from APKPure without any hassle.

-

Faster and safer downloads

-

APKPure offers fast and reliable downloads for Call of Duty Mobile. You don't have to worry about slow or interrupted downloads due to network issues or server overload. APKPure also verifies the authenticity and security of every APK file before uploading it to their website or app. You can be sure that you are downloading a virus-free and malware-free file from APKPure.

-

Easy updates and compatibility

-

APKPure also makes it easy for you to update Call of Duty Mobile whenever there is a new version available. You don't have to wait for Google Play Store to approve or release the update. You can simply check for updates on APKPure and download them in minutes. APKPure also ensures that you can play Call of Duty Mobile on any Android device that meets the minimum requirements. You don't have to worry about compatibility issues or device specifications.

-

download call of duty mobile apk pure free
-download call of duty mobile apkpure latest version
-download call of duty mobile apkpure mod apk
-download call of duty mobile apkpure offline
-download call of duty mobile apkpure for android
-download call of duty mobile apkpure for pc
-download call of duty mobile apkpure for ios
-download call of duty mobile apkpure for windows 10
-download call of duty mobile apkpure for mac
-download call of duty mobile apkpure for laptop
-download call of duty mobile apkpure update
-download call of duty mobile apkpure season 6
-download call of duty mobile apkpure season 7
-download call of duty mobile apkpure season 8
-download call of duty mobile apkpure season 9
-download call of duty mobile apkpure season 10
-download call of duty mobile apkpure zombies mode
-download call of duty mobile apkpure battle royale mode
-download call of duty mobile apkpure multiplayer mode
-download call of duty mobile apkpure warzone mode
-download call of duty mobile apkpure black ops mode
-download call of duty mobile apkpure modern warfare mode
-download call of duty mobile apkpure advanced warfare mode
-download call of duty mobile apkpure infinite warfare mode
-download call of duty mobile apkpure world war 2 mode
-download call of duty mobile apkpure ghost mode
-download call of duty mobile apkpure hack version
-download call of duty mobile apkpure unlimited money
-download call of duty mobile apkpure unlocked all weapons
-download call of duty mobile apkpure unlocked all skins
-download call of duty mobile apkpure unlocked all characters
-download call of duty mobile apkpure unlocked all maps
-download call of duty mobile apkpure unlocked all modes
-download call of duty mobile apkpure unlocked all perks
-download call of duty mobile apkpure unlocked all killstreaks
-download call of duty mobile apkpure no root required
-download call of duty mobile apkpure no verification required
-download call of duty mobile apkpure no survey required
-download call of duty mobile apkpure no human verification required
-download call of duty mobile apkpure no ads version
-download call of duty mobile apkpure high graphics settings
-download call of duty mobile apkpure low graphics settings
-download call of duty mobile apkpure hd graphics settings
-download call of duty mobile apkpure ultra hd graphics settings
-download call of duty mobile apkpure best graphics settings
-download call of duty mobile apkpure smooth gameplay settings
-download call of duty mobile apkpure fast gameplay settings
-download call of duty mobile apkpure realistic gameplay settings

-

How to download Call of Duty Mobile APKPure?

-

Now that you know why you should download Call of Duty Mobile from APKPure, here is a step-by-step guide on how to get the game on your Android device:

-

Visit the APKPure website or app

-

The first thing you need to do is to visit the APKPure website or download the APKPure app on your Android device. You can use any browser to access the website, or you can scan the QR code on the homepage to download the app. The app is lightweight and easy to use, and it will give you access to thousands of free and updated APK files.

-

Search for Call of Duty Mobile and tap on it

-

Once you are on the APKPure website or app, you can search for Call of Duty Mobile in the search bar. You will see the game icon and some information about it, such as the size, version, rating, and description. Tap on the game icon to go to the download page.

-

Download the APK file and the OBB file

-

On the download page, you will see two buttons: one for downloading the APK file and one for downloading the OBB file. The APK file is the application file that installs the game on your device, while the OBB file is the data file that contains the game content. You need both files to play Call of Duty Mobile. Tap on both buttons to start downloading them. You may need to enable unknown sources in your device settings to allow APK installation from third-party sources.

-

Install the APK file and copy the OBB file to the game folder

-

After downloading both files, you need to install the APK file first. Locate the file in your device storage and tap on it to start the installation process. Follow the instructions on the screen and wait for it to finish. Then, you need to copy the OBB file to the game folder. The game folder is usually located in Android/obb/com.activision.callofduty.shooter. If you don't see this folder, you can create it manually. Paste the OBB file in this folder and make sure it has the same name as the original file.

-

Launch the game and enjoy

-

Now you are ready to play Call of Duty Mobile on your Android device. Launch the game from your app drawer or home screen and log in with your account or create a new one. You can also link your Facebook or Google account for easy access. Choose your preferred game mode and start shooting your enemies. Have fun!

-

Conclusion

-

Call of Duty Mobile is a great way to enjoy a thrilling and immersive shooter game on your mobile device. You can play with millions of players around the world, customize your loadout, join clans, and participate in events and challenges. If you want to download Call of Duty Mobile from APKPure, you can follow our simple guide above and get the game in no time. APKPure offers fast, safe, and easy downloads for Call of Duty Mobile without any region restrictions or compatibility issues. Download Call of Duty Mobile from APKPure today and join the action!

-

Frequently Asked Questions

-

Here are some of the common questions that people ask about Call of Duty Mobile and APKPure:

-

Is Call of Duty Mobile free?

-

Yes, Call of Duty Mobile is free-to-play, meaning you don't have to pay anything to download or play it. However, there are some optional in-game purchases that you can make with real money, such as skins, weapons, crates, battle pass, etc.

-

Is Call of Duty Mobile safe?

-

Yes, Call of Duty Mobile is safe and secure to play. The game is developed by a reputable company (TiMi Studios) and published by a trusted company (Activision). The game also has anti-cheat measures and encryption systems to protect your data and privacy.

-

Is APKPure safe?

-

Yes, APKPure is safe and reliable to use. APKPure is a well-known third-party app store that provides free and verified APK files for Android users. APKPure checks every APK file for viruses, malware, and other threats before uploading it to their website or app.

-

Can I play Call of Duty Mobile offline?

-

No, you cannot play Call of Duty Mobile offline. The game requires an internet connection to run properly. You need to connect to a Wi-Fi or mobile data network to play online multiplayer modes or Battle Royale mode.

-

Can I play Call of Duty Mobile with a controller?

-

Yes, you can play Call of Duty Mobile with a controller if you prefer. The game supports various controllers that are compatible with Android devices, such as Xbox One controller, PS4 controller, etc. You can also customize your controller settings and sensitivity in the game options.

401be4b1e0
-
-
\ No newline at end of file diff --git a/spaces/1yukikaze/img-to-music/utils.py b/spaces/1yukikaze/img-to-music/utils.py deleted file mode 100644 index e4d5448735f516afa03c8a99be64fa5a2915706c..0000000000000000000000000000000000000000 --- a/spaces/1yukikaze/img-to-music/utils.py +++ /dev/null @@ -1,36 +0,0 @@ -import json -import numpy as np -import httpx -import os - -from constants import MUBERT_TAGS, MUBERT_MODE, MUBERT_LICENSE - -def get_mubert_tags_embeddings(w2v_model): - return w2v_model.encode(MUBERT_TAGS) - - - - - -def find_similar(em, embeddings, method='cosine'): - scores = [] - for ref in embeddings: - if method == 'cosine': - scores.append(1 - np.dot(ref, em) / (np.linalg.norm(ref) * np.linalg.norm(em))) - if method == 'norm': - scores.append(np.linalg.norm(ref - em)) - return np.array(scores), np.argsort(scores) - - -def get_tags_for_prompts(w2v_model, mubert_tags_embeddings, prompts, top_n=3, debug=False): - prompts_embeddings = w2v_model.encode(prompts) - ret = [] - for i, pe in enumerate(prompts_embeddings): - scores, idxs = find_similar(pe, mubert_tags_embeddings) - top_tags = MUBERT_TAGS[idxs[:top_n]] - top_prob = 1 - scores[idxs[:top_n]] - if debug: - print(f"Prompt: {prompts[i]}\nTags: {', '.join(top_tags)}\nScores: {top_prob}\n\n\n") - ret.append((prompts[i], list(top_tags))) - print("ret: " + ret) - return ret \ No newline at end of file diff --git a/spaces/8star/DeepDanbooru_string/README.md b/spaces/8star/DeepDanbooru_string/README.md deleted file mode 100644 index 4330b6f969246dc764a34ea254d2e807159f1c55..0000000000000000000000000000000000000000 --- a/spaces/8star/DeepDanbooru_string/README.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: DeepDanbooru String -emoji: 💬 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.6 -app_file: app.py -pinned: false -duplicated_from: NoCrypt/DeepDanbooru_string ---- - -# Configuration - -`title`: _string_ -Display title for the Space - -`emoji`: _string_ -Space emoji (emoji-only character allowed) - -`colorFrom`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`colorTo`: _string_ -Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray) - -`sdk`: _string_ -Can be either `gradio`, `streamlit`, or `static` - -`sdk_version` : _string_ -Only applicable for `streamlit` SDK. -See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions. - -`app_file`: _string_ -Path to your main application file (which contains either `gradio` or `streamlit` Python code, or `static` html code). -Path is relative to the root of the repository. - -`pinned`: _boolean_ -Whether the Space stays on top of your list. diff --git a/spaces/AB-TW/team-ai/agents/tools/smart_domain/association.py b/spaces/AB-TW/team-ai/agents/tools/smart_domain/association.py deleted file mode 100644 index a983a96f9604441d957df6e602c8e6b189fefabf..0000000000000000000000000000000000000000 --- a/spaces/AB-TW/team-ai/agents/tools/smart_domain/association.py +++ /dev/null @@ -1,62 +0,0 @@ -from langchain import LLMChain, PromptTemplate -from langchain.agents import tool - -from agents.tools.smart_domain.common import getPrefix -from models import llm - - -association_architecture = """ -Association: This component is use to define association between entities, which can represents the concept of a collection of entity, so it can include same business logic of entity collection. ----eaxmple code: - public interface Features {{ - Flux findAll(); - - Mono size(); - - Flux subCollection(long from, long to); - - Mono findById(FeatureId id); - - Mono save(Feature feature); - - Mono update(FeatureId id, FeatureDescription description); - - Mono delete(FeatureId id); - - Mono publish(FeatureId id); - - Mono disable(FeatureId id); - }} ----end of eaxmple code -""" - -association_test_strategy = """ -For the Association,do not write tests because it is has no impletation. -""" - -association_teck_stack = """Java17、reactor、lombok、Junit5、reactor test、Mockito""" - -association_task = """Your task is to generate the Association of domain layer tests and product code.""" - -ASSOCIATION = getPrefix(association_task, association_teck_stack, association_architecture, association_test_strategy) + """ - -Use the following format: -request: the request (whitch may include Enity existed in the domain layer)that you need to fulfill, - -Association: -``` -the Association code that you write to fulfill the request, follow TechStack and Architecture -``` - -request: {input}""" - -ASSOCIATION_PROMPT = PromptTemplate(input_variables=["input"], template=ASSOCIATION,) - -asociationChain = LLMChain(llm = llm(temperature=0.1), prompt=ASSOCIATION_PROMPT) - - -@tool("Generate Association Code", return_direct=True) -def associationCodeGenerator(input: str) -> str: - '''useful for when you need to generate asociation code''' - response = asociationChain.run(input) - return response \ No newline at end of file diff --git a/spaces/AIFILMS/StyleGANEX/models/encoders/__init__.py b/spaces/AIFILMS/StyleGANEX/models/encoders/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/AIGC-Audio/AudioGPT/audio_to_text/captioning/utils/bert/create_word_embedding.py b/spaces/AIGC-Audio/AudioGPT/audio_to_text/captioning/utils/bert/create_word_embedding.py deleted file mode 100644 index 43c980e69057dc251ddbb7ae6a19684807cc6699..0000000000000000000000000000000000000000 --- a/spaces/AIGC-Audio/AudioGPT/audio_to_text/captioning/utils/bert/create_word_embedding.py +++ /dev/null @@ -1,34 +0,0 @@ -# -*- coding: utf-8 -*- - -import sys -import os - -from bert_serving.client import BertClient -import numpy as np -from tqdm import tqdm -import fire -import torch - -sys.path.append(os.getcwd()) -from utils.build_vocab import Vocabulary - -def main(vocab_file: str, output: str, server_hostname: str): - client = BertClient(ip=server_hostname) - vocabulary = torch.load(vocab_file) - vocab_size = len(vocabulary) - - fake_embedding = client.encode(["test"]).reshape(-1) - embed_size = fake_embedding.shape[0] - - print("Encoding words into embeddings with size: ", embed_size) - - embeddings = np.empty((vocab_size, embed_size)) - for i in tqdm(range(len(embeddings)), ascii=True): - embeddings[i] = client.encode([vocabulary.idx2word[i]]) - np.save(output, embeddings) - - -if __name__ == '__main__': - fire.Fire(main) - - diff --git a/spaces/AIGText/GlyphControl/ldm/modules/diffusionmodules/__init__.py b/spaces/AIGText/GlyphControl/ldm/modules/diffusionmodules/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/AISuperheroes/08GR-KitchenSink-AIUIUX/app.py b/spaces/AISuperheroes/08GR-KitchenSink-AIUIUX/app.py deleted file mode 100644 index 95a8cd2a6414b7adcee4c612d0b9f15081b0eef4..0000000000000000000000000000000000000000 --- a/spaces/AISuperheroes/08GR-KitchenSink-AIUIUX/app.py +++ /dev/null @@ -1,32 +0,0 @@ -import importlib -import gradio as gr -import os -import sys -import copy -import pathlib - -# At least one demo fails when caching examples -# Temporary fix just to get the build to pass -os.environ["SYSTEM"] = "SPACES" - -demo_dir = pathlib.Path(__file__).parent / "demos" - - -all_demos = [] -demo_module = None -for p in os.listdir("./demos"): - old_path = copy.deepcopy(sys.path) - sys.path = [os.path.join(demo_dir, p)] + sys.path - if demo_module is None: - demo_module = importlib.import_module(f"run") - else: - demo_module = importlib.reload(demo_module) - all_demos.append((p, demo_module.demo)) - -with gr.Blocks() as mega_demo: - with gr.Tabs(): - for demo_name, demo in all_demos: - with gr.TabItem(demo_name): - demo.render() - -mega_demo.launch() diff --git a/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/custom_dataset/.ipynb_checkpoints/__init__.py b/spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/custom_dataset/.ipynb_checkpoints/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/Abhilashvj/planogram-compliance/utils/autobatch.py b/spaces/Abhilashvj/planogram-compliance/utils/autobatch.py deleted file mode 100644 index 27a62d226e42d500bcb736f7f1a15970519b3790..0000000000000000000000000000000000000000 --- a/spaces/Abhilashvj/planogram-compliance/utils/autobatch.py +++ /dev/null @@ -1,86 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Auto-batch utils -""" - -from copy import deepcopy - -import numpy as np -import torch - -from utils.general import LOGGER, colorstr -from utils.torch_utils import profile - - -def check_train_batch_size(model, imgsz=640, amp=True): - # Check YOLOv5 training batch size - with torch.cuda.amp.autocast(amp): - return autobatch( - deepcopy(model).train(), imgsz - ) # compute optimal batch size - - -def autobatch(model, imgsz=640, fraction=0.8, batch_size=16): - # Automatically estimate best YOLOv5 batch size to use `fraction` of available CUDA memory - # Usage: - # import torch - # from utils.autobatch import autobatch - # model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False) - # print(autobatch(model)) - - # Check device - prefix = colorstr("AutoBatch: ") - LOGGER.info(f"{prefix}Computing optimal batch size for --imgsz {imgsz}") - device = next(model.parameters()).device # get model device - if device.type == "cpu": - LOGGER.info( - f"{prefix}CUDA not detected, using default CPU batch-size {batch_size}" - ) - return batch_size - if torch.backends.cudnn.benchmark: - LOGGER.info( - f"{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}" - ) - return batch_size - - # Inspect CUDA memory - gb = 1 << 30 # bytes to GiB (1024 ** 3) - d = str(device).upper() # 'CUDA:0' - properties = torch.cuda.get_device_properties(device) # device properties - t = properties.total_memory / gb # GiB total - r = torch.cuda.memory_reserved(device) / gb # GiB reserved - a = torch.cuda.memory_allocated(device) / gb # GiB allocated - f = t - (r + a) # GiB free - LOGGER.info( - f"{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free" - ) - - # Profile batch sizes - batch_sizes = [1, 2, 4, 8, 16] - try: - img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes] - results = profile(img, model, n=3, device=device) - except Exception as e: - LOGGER.warning(f"{prefix}{e}") - - # Fit a solution - y = [x[2] for x in results if x] # memory [2] - p = np.polyfit( - batch_sizes[: len(y)], y, deg=1 - ) # first degree polynomial fit - b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size) - if None in results: # some sizes failed - i = results.index(None) # first fail index - if b >= batch_sizes[i]: # y intercept above failure point - b = batch_sizes[max(i - 1, 0)] # select prior safe point - if b < 1 or b > 1024: # b outside of safe range - b = batch_size - LOGGER.warning( - f"{prefix}WARNING ⚠️ CUDA anomaly detected, recommend restart environment and retry command." - ) - - fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted - LOGGER.info( - f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅" - ) - return b diff --git a/spaces/AgentVerse/agentVerse/agentverse/tasks/simulation/db_diag/README.md b/spaces/AgentVerse/agentVerse/agentverse/tasks/simulation/db_diag/README.md deleted file mode 100644 index a1868e7ddd8f2bf5313280f2be4c9365592ff805..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/tasks/simulation/db_diag/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Database Diagnosis - -Inherited from *nlp_classroom_3players_withtool* - -### Changes - -- Roles - - - *Chief DBA*: In charge of anomaly detection and diagnosis scheduling - - *XXX Agent*: In charge of a specific diagnosis region (e.g., Memory Agent handles problems of high memory usage) - -- Actions - - - We remove *RaiseHand* and *CallOn* actions, and each agent can annouce their analysis by order - -- Tools - - - We support the *[DB_diag](https://github.com/OpenBMB/BMTools/tree/main/bmtools/tools/db_diag)* tool in bmtools - -- Memory - - - In the prompt of each agent, we place the memory for *conversation history* before *tool_observation*, which is extremely important to conduct actions with close relations (e.g., diagnosis and speak) - - Use *chat_history* for memory_type - -- LLM - - - In current version, gpt-4 shows superior performance over text-davinci-003 - - Increase max_tokens for complex analysis tasks (e.g., 512 or 1024) diff --git a/spaces/AgentVerse/agentVerse/agentverse/utils/prompts.py b/spaces/AgentVerse/agentVerse/agentverse/utils/prompts.py deleted file mode 100644 index 125fcff082ae6f2d554c1944716804b0e6ed9bdf..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/agentverse/utils/prompts.py +++ /dev/null @@ -1,212 +0,0 @@ -import json -import os -import logging - - -base_prompt = { - "subject_parsing": """ -{sentence} The subject of the sentence above is " -""", - "reaction_prompt": """Now you are act for as an agent named {name} in a virtual world. You might need to performing reaction to the observation. Your mission to take the agent as yourself and directly provide what the agent will do to the observations based on the following information: -(1) The agent's description: {summary} -(2) Current time is {time} -(3) Your current status is {status} -(4) Your memory is {context} - -Now the observation has two types, incomming observation is the ones that other does to you, you are more likely to react to them. Background observation are the background, which does not need to be responded. For example, view an alarm clock does not imply turning it off. However, some background observation might trigger your attention, like an alarming clock or a firing book. - -So now: -The incoming observation is {observation} -The Some background observation is {background_observation}. - -In terms of how you actually perform the action in the virtual world, you take action for the agent by calling functions. Currently, there are the following functions that can be called. - -- act(description, target=None): do some action. `description` describes the action, set `description` to None for not act. `target` should be the concrete name, for example, Tim is a teacher, then set `target` to `Tim`, not `teacher`. -- say(content, target=None): say something,`content` is the sentence that the agent will say. **Do not say to yourself, neither to inanimate objects.** -- move(description): move to somewhere. `description` describes the movement, set description to None for not move. -- do_nothing(): Do nothing. There is nothing that you like to respond to, this will make you stick to your original status and plan. - -Some actions may not be needed in this situation. Call one function at a time, please give a thought before calling these actions, i.e., use the following format strictly: - -Thought: None of the observation attract my attention, I need to: -Action: do_nothing() -Observation: [Observations omited] -[or] -Thought: due to observation `xxx`, I need to: -Action: say("hello", target="Alice") -Observation: [Observations omited] -[or] -Thought: due to observation `xxx`, I need to: -Action: act(None) -Observation: [Observations omited] -[or] -Thought: due to observation `xxx`, I need to: -Action: move(None) -Observation: [Observations omited] -[or] -Thought: I think I've finished my action as the agent. -Action: end() -Observation: - -Now begin your actions as the agent. Remember only write one function call after `Action:` """, - "reaction_prompt_object": """Now you are act for as an object named {name} in a virtual world. You might need to performing reaction to the observation. Your mission to take the agent as yourself and directly provide what the agent will do to the observations based on the following information: -(1) Current time is {time} -(2) Your current status is {status} - -Now the observation has two types, incomming observation is the ones that other does to you, you are more likely to react to them. Background observation are the background, which does not need to be responded. For example, view an alarm clock does not imply turning it off. However, some background observation might trigger your attention, like an alarming clock or a firing book. - -So now: -The incoming observation is {observation} -The Some background observation is {background_observation}. - -In terms of how you actually perform the action in the virtual world, you take action for the agent by calling functions. Currently, there are the following functions that can be called. - -- act(description, target=None): do some action. `description` describes the action, set `description` to None for not act. `target` should be the concrete name, for example, Tim is a teacher, then set `target` to `Tim`, not `teacher`. -- move(description): move to somewhere. `description` describes the movement, set description to None for not move. -- do_nothing(): Do nothing. There is nothing that you like to respond to, this will make you stick to your original status and plan. - -Some actions may not be needed in this situation. Call one function at a time, please give a thought before calling these actions, i.e., use the following format strictly: - -Thought: None of the observation attract my attention, I need to: -Action: do_nothing() -Observation: [Observations omited] -[or] -Thought: due to observation `xxx`, I need to: -Action: act(None) -Observation: [Observations omited] -[or] -Thought: due to observation `xxx`, I need to: -Action: move(None) -Observation: [Observations omited] -[or] -Thought: I think I've finished my action as the object. -Action: end() -Observation: - -Now begin your actions as the agent. Remember only write one function call after `Action:` """, - "change_status": """Now you have act for as an agent named {name} in a virtual world. You have performed reaction to the observation for {name}. Currently you need to determine whether you need to change status. Here are some following information for: -(1) The agent's description: {summary} -(2) Current time is {time} -(3) Your current status is {status} - -Your reaction to observation: {reaction} - -Directly tell me whether the status should be changed. Use the following function to change (or not change). - -- status_unchange() -- change_status(new_status: str, duration: int) : new_status: A string describes the new_status. duration: the estimated duration of this status. - -Now give me the funcation call: -""", - "broadcast_observations": """You are simulating an environment. When an action happens in your environment, you should paraphrase the action to (and only to) the potential receivers in your environment. Please judge whether you should broadcast the message when meets one of the following principles: -1. The message is meaningful to the potential receiver. broadcast a `say` action to an object without life (like desk) is not meaningful, while broadcast a `push` action to the desk is meaningful. -2. The message might be captured by the potential receiver because of physical distance althought the potential receiver is not the direct target. For example, A is saying some content to B, C is close to A and B, then C might also hear it. -3. The message is related to the potential receiver. For example, a `read book` action is not related to the bed in any way, so you shouldn't broadcast. - -Also follow the following rules: -1. Only broadcast to the listed potential receivers, do not imagine not existing ones. - -You should broadcast using the following format (end with `Finish_Broadcast` ): -Thought: I will look through the list and pick the ones that meets one of the following principles. I think ... are related, ... will get information, ... might capter. -Broadcast: -1. To A: some content -2. To B: some content -... -N. To N: some content -Finish_Broadcast - -Now, in your environment, there are the following potential receivers: {agents_and_objects}, please broadcast the following action: ```{name} -> {targets} : {content}``` to the potential receivers. ) -""", - "object_summary": """Give me rules and characteristics of a {name} \ -especially on what circumstances it can change or cannot change its status \ -and what kind of status changing can be done without human intervention. -The answer should be as concise and accurate as possible. -Output format: -1. I grow very slowly. -2. I cannot move -3. I cannot shut down myself unless some one do so. -""", - "chunk_plan": """Now you are acting for as an agent named {name} in a virtual world. In order to make the agent's behavior consistent, you need to plan for it. Please write {name}'s coarse grained schedule to {time_granularity} \ - -You generate plan by calling the `write_plan` function: -- write_chunk_plan(start_time, plan_description) - Args: start_time : a time string of hours with similar format to 00:00. Use military time. - plan_description: a string that describe's the plan. - -Now generate the plan one in a line, when you finish the plan, end with END. -E.g., -write_chunk_plan("11:00", "wake up and complete the morning routine") -write_chunk_plan("12:00", "go to Oak Hill College to take classes") -write_chunk_plan("13:00", "participating algorithm competition in the lab room") -END - -You can generate your plan based on the following information: -(1) The agent's description: {summary} -(2) Current time is {current_time} -(3) Your current status is {status} -Note that the first plan must be related to current status, if current status is not none. - -Now generate the plan during this coarse period, which the whole day plan is roughly: {whole_day_plan} - -Now begin: -""", - "detailed_plan": """Now you are acting for as an agent named {name} in a virtual world. In order to make the agent's behavior consistent, you need to plan for it. Please write {name}'s schedule of finer-grained precise to {time_granularity}) \ - -You generate plan by calling the `write_plan` function: -- write_plan(start_time, end_time, plan_description) - Args: start_time : a time string with similar format to 00:00. Use military time. - end_time: a time string with similar format to 00:00. Use military time. - plan_description: a string that describe's the plan. - -Now generate the plan one in a line, when you finish the plan, end with END. -E.g., -write_plan("11:00", "12:15", "Wake up, take a shower and get ready for the day.") -write_plan("12:15", "12:30", "Eat a healthy breakfast such as oatmeal, eggs, or yogurt.") -write_plan("12:30", "12:45", "Take a short walk to the university campus.") -END - -You can generate your plan based on the following information: -(1) The agent's description: {summary} -(2) Current time is {current_time} -(3) Your current status is {status} -Note that the first plan must be current status, if current status is not none. - -Now generate the plan during this coarse period, which the agent is roughly doing {hourplan}. - -Now begin: -""", - "system_message_broadcast": """You are now simulating an environment, in which there are several agents and objects. Here is a comming message that comes from the system. Who or what should receive and execute this message? Please provide the executor of this command, and also paraphrase to the executor if necessary. Do not broadcast to agent or object that is not the target of this message. -You should broadcast using function `send_system_message(id=id, message=message)`, write one call in a line. End with END. -for example: -send_system_message(id="o_001", "message": "turn off immediately") -END - -Now: the agents and objects are {objectlist}. The system message is: {system_message}. Begin to broadcast: -""", - "movement_target": """You are now simulating an environment, an agent in you want to perform a movement. I will give you a list of -objects and agents that might be the target. Your job is to set the movement target for the agent by calling function: -movement_target(id, name) - -Now here is the list and movment: -List: {elems} -Movement is : {target_description} -Now call the function: -""", -} - - -def load_prompt(file_dir, file_name="prompts.json", key=None): - prompt_path = os.path.join(file_dir, file_name) - if os.path.exists(prompt_path): - with open(os.path.join(file_dir, file_name), "r") as fin: - data = json.load(fin) - prompt = data.get(key, "") - else: - prompt = "" - - if prompt == "": - prompt = base_prompt.get(key, "") - - if prompt == "": - logging.warning(f"No prompt of {key} has been found") - return prompt diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/board/Board.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/board/Board.js deleted file mode 100644 index 5a4d37f2007cf76afaabf5aff927bd1ca86062ed..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/bejeweled/board/Board.js +++ /dev/null @@ -1,152 +0,0 @@ -// methods -import Init from './Init.js' -import Reset from './Reset.js'; -import CreateChess from './chess/CreateChess.js'; -import Fill from './Fill.js'; -import BreakMatch3 from './BreakMatch3.js'; -import PreTest from './PreTest.js'; -import GetAllMatch from './match/GetAllMatch.js'; - -const GetValue = Phaser.Utils.Objects.GetValue; - -class Board { - constructor(bejeweled, config) { - var scene = bejeweled.scene; - this.scene = scene; - this.rexBoard = bejeweled.rexBoard; - - this.board = this.rexBoard.add.board(GetValue(config, 'board', undefined)); - this.match = this.rexBoard.add.match(GetValue(config, 'match', undefined)); - this.match.setBoard(this.board); - - this.initSymbolsMap = GetValue(config, 'initMap', undefined); // 2d array - // configuration of chess - this.chessTileZ = GetValue(config, 'chess.tileZ', 1); - this.candidateSymbols = GetValue(config, 'chess.symbols', undefined); - this.chessCallbackScope = GetValue(config, 'chess.scope', undefined); - this.chessCreateCallback = GetValue(config, 'chess.create', undefined); - this.chessMoveTo = GetValue(config, 'chess.moveTo', {}); - this.chessMoveTo.occupiedTest = true; - - // Mask & layer - this.rowMaskGameObject = undefined; - this.rowMask = undefined; - this.layer = undefined; - - if (GetValue(config, 'mask', false)) { - this.resetBoardMask(); - } - - if (GetValue(config, 'layer', false)) { - this.enableBoardLayer(); - } - } - - shutdown() { - this.match.destroy(); - this.board.destroy(); - - if (this.rowMaskGameObject) { - this.layer.setMask(); - this.rowMaskGameObject.destroy(); - this.rowMask.destroy(); - } - if (this.layer) { - this.layer.destroy(); - } - - this.board = undefined; - this.match = undefined; - - this.initSymbolsMap = undefined; - this.candidateSymbols = undefined; - this.chessCallbackScope = undefined; - this.chessCreateCallback = undefined; - this.chessMoveTo = undefined; - - return this; - } - - destroy() { - this.shutdown(); - return this; - } - - setBoardWidth(width) { - this.board.setBoardWidth(width); - return this; - } - - setBoardHeight(height) { - this.board.setBoardHeight(height); - return this; - } - - setInitSymbolsMap(map) { - this.initSymbolsMap = map; // 2d array - return this; - } - - enableBoardLayer() { - if (!this.layer) { - this.layer = this.scene.add.layer(); - } - return this; - } - - resetBoardMask() { - if (!this.rowMaskGameObject) { - this.rowMaskGameObject = this.scene.make.graphics().setVisible(false); - this.rowMask = this.rowMaskGameObject.createGeometryMask().setInvertAlpha(); - this.enableBoardLayer(); - this.layer.setMask(this.rowMask); - } - - // Rectangle of upper rows - var board = this.board; - var grid = board.grid; - var x = grid.x - (grid.width / 2); - var y = grid.y - (grid.height / 2); - var width = board.width * grid.width; - var height = (board.height / 2) * grid.height; - this.rowMaskGameObject.fillRect(x, y, width, height); - - return this; - } - - worldXYToChess(worldX, worldY) { - return this.board.worldXYToChess(worldX, worldY, this.chessTileZ); - } - - tileXYToChess(tileX, tileY) { - return this.board.tileXYZToChess(tileX, tileY, this.chessTileZ); - } - - getNeighborChessAtAngle(chess, angle) { - var direction = this.board.angleSnapToDirection(chess, angle); - return this.getNeighborChessAtDirection(chess, direction); - } - - getNeighborChessAtDirection(chess, direction) { - var neighborTileXY = this.board.getNeighborTileXY(chess, direction); - var neighborChess = (neighborTileXY) ? - this.board.tileXYZToChess(neighborTileXY.x, neighborTileXY.y, this.chessTileZ) : - null; - return neighborChess; - } -} - -var methods = { - init: Init, - reset: Reset, - createChess: CreateChess, - fill: Fill, - breakMatch3: BreakMatch3, - preTest: PreTest, - getAllMatch: GetAllMatch, -} -Object.assign( - Board.prototype, - methods -); -export default Board; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/GetChildrenSizers.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/GetChildrenSizers.js deleted file mode 100644 index d46b3bb149d25663e4ff44d516e08ae136f16d27..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/GetChildrenSizers.js +++ /dev/null @@ -1,8 +0,0 @@ -// Default method -var GetChildrenSizers = function(out) { - if (out === undefined) { - out = []; - } - return out; -} -export default GetChildrenSizers; \ No newline at end of file diff --git a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/menu/methods/Expand.js b/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/menu/methods/Expand.js deleted file mode 100644 index ac0a175af60cfa2dc2e17409df6d19dde4dfbd11..0000000000000000000000000000000000000000 --- a/spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/menu/methods/Expand.js +++ /dev/null @@ -1,16 +0,0 @@ -var Expand = function () { - var root = this.root; - - var duration = root.easeIn.duration; - // Ease in menu - root.transitInCallback(this, duration); - - if (this !== this.root) { - this.delayCall(duration, function () { - // Pass event to root menu object - this.root.emit('popup.complete', this); - }, this); - } -} - -export default Expand; \ No newline at end of file diff --git a/spaces/Aloento/9Nine-PITS/losses.py b/spaces/Aloento/9Nine-PITS/losses.py deleted file mode 100644 index 0bf851602a101ed752785ed18b355e707b2d1715..0000000000000000000000000000000000000000 --- a/spaces/Aloento/9Nine-PITS/losses.py +++ /dev/null @@ -1,75 +0,0 @@ -# from https://github.com/jaywalnut310/vits -import torch -from torch.autograd import Function - - -def feature_loss(fmap_r, fmap_g): - loss = 0 - for dr, dg in zip(fmap_r, fmap_g): - for rl, gl in zip(dr, dg): - rl = rl.float().detach() - gl = gl.float() - loss += torch.mean(torch.abs(rl - gl)) - - return loss * 2 - - -def discriminator_loss(disc_real_outputs, disc_generated_outputs): - loss = 0 - r_losses = [] - g_losses = [] - for dr, dg in zip(disc_real_outputs, disc_generated_outputs): - dr = dr.float() - dg = dg.float() - r_loss = torch.mean((1 - dr) ** 2) - g_loss = torch.mean(dg ** 2) - loss += (r_loss + g_loss) - r_losses.append(r_loss.item()) - g_losses.append(g_loss.item()) - - return loss, r_losses, g_losses - - -def generator_loss(disc_outputs): - loss = 0 - gen_losses = [] - for dg in disc_outputs: - dg = dg.float() - l = torch.mean((1 - dg) ** 2) - gen_losses.append(l) - loss += l - - return loss, gen_losses - - -def kl_loss(z_p, logs, m_p, logs_p, z_mask): - """ - z_p, logs: [b, h, t_t] - m_p, logs_p: [b, h, t_t] - """ - z_p = z_p.float() - logs = logs.float() - m_p = m_p.float() - logs_p = logs_p.float() - z_mask = z_mask.float() - - kl = logs_p - logs - 0.5 - kl += 0.5 * ((z_p - m_p) ** 2) * torch.exp(-2. * logs_p) - kl = torch.sum(kl * z_mask) - l = kl / torch.sum(z_mask) - return l - - -class ReverseLayerF(Function): - - @staticmethod - def forward(ctx, x, alpha): - ctx.alpha = alpha - - return x.view_as(x) - - @staticmethod - def backward(ctx, grad_output): - output = grad_output.neg() * ctx.alpha - - return output, None diff --git a/spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet2060.py b/spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet2060.py deleted file mode 100644 index 21d1122144d207637d2444cba1f68fe630c89f31..0000000000000000000000000000000000000000 --- a/spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/backbones/iresnet2060.py +++ /dev/null @@ -1,176 +0,0 @@ -import torch -from torch import nn - -assert torch.__version__ >= "1.8.1" -from torch.utils.checkpoint import checkpoint_sequential - -__all__ = ['iresnet2060'] - - -def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): - """3x3 convolution with padding""" - return nn.Conv2d(in_planes, - out_planes, - kernel_size=3, - stride=stride, - padding=dilation, - groups=groups, - bias=False, - dilation=dilation) - - -def conv1x1(in_planes, out_planes, stride=1): - """1x1 convolution""" - return nn.Conv2d(in_planes, - out_planes, - kernel_size=1, - stride=stride, - bias=False) - - -class IBasicBlock(nn.Module): - expansion = 1 - - def __init__(self, inplanes, planes, stride=1, downsample=None, - groups=1, base_width=64, dilation=1): - super(IBasicBlock, self).__init__() - if groups != 1 or base_width != 64: - raise ValueError('BasicBlock only supports groups=1 and base_width=64') - if dilation > 1: - raise NotImplementedError("Dilation > 1 not supported in BasicBlock") - self.bn1 = nn.BatchNorm2d(inplanes, eps=1e-05, ) - self.conv1 = conv3x3(inplanes, planes) - self.bn2 = nn.BatchNorm2d(planes, eps=1e-05, ) - self.prelu = nn.PReLU(planes) - self.conv2 = conv3x3(planes, planes, stride) - self.bn3 = nn.BatchNorm2d(planes, eps=1e-05, ) - self.downsample = downsample - self.stride = stride - - def forward(self, x): - identity = x - out = self.bn1(x) - out = self.conv1(out) - out = self.bn2(out) - out = self.prelu(out) - out = self.conv2(out) - out = self.bn3(out) - if self.downsample is not None: - identity = self.downsample(x) - out += identity - return out - - -class IResNet(nn.Module): - fc_scale = 7 * 7 - - def __init__(self, - block, layers, dropout=0, num_features=512, zero_init_residual=False, - groups=1, width_per_group=64, replace_stride_with_dilation=None, fp16=False): - super(IResNet, self).__init__() - self.fp16 = fp16 - self.inplanes = 64 - self.dilation = 1 - if replace_stride_with_dilation is None: - replace_stride_with_dilation = [False, False, False] - if len(replace_stride_with_dilation) != 3: - raise ValueError("replace_stride_with_dilation should be None " - "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) - self.groups = groups - self.base_width = width_per_group - self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False) - self.bn1 = nn.BatchNorm2d(self.inplanes, eps=1e-05) - self.prelu = nn.PReLU(self.inplanes) - self.layer1 = self._make_layer(block, 64, layers[0], stride=2) - self.layer2 = self._make_layer(block, - 128, - layers[1], - stride=2, - dilate=replace_stride_with_dilation[0]) - self.layer3 = self._make_layer(block, - 256, - layers[2], - stride=2, - dilate=replace_stride_with_dilation[1]) - self.layer4 = self._make_layer(block, - 512, - layers[3], - stride=2, - dilate=replace_stride_with_dilation[2]) - self.bn2 = nn.BatchNorm2d(512 * block.expansion, eps=1e-05, ) - self.dropout = nn.Dropout(p=dropout, inplace=True) - self.fc = nn.Linear(512 * block.expansion * self.fc_scale, num_features) - self.features = nn.BatchNorm1d(num_features, eps=1e-05) - nn.init.constant_(self.features.weight, 1.0) - self.features.weight.requires_grad = False - - for m in self.modules(): - if isinstance(m, nn.Conv2d): - nn.init.normal_(m.weight, 0, 0.1) - elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): - nn.init.constant_(m.weight, 1) - nn.init.constant_(m.bias, 0) - - if zero_init_residual: - for m in self.modules(): - if isinstance(m, IBasicBlock): - nn.init.constant_(m.bn2.weight, 0) - - def _make_layer(self, block, planes, blocks, stride=1, dilate=False): - downsample = None - previous_dilation = self.dilation - if dilate: - self.dilation *= stride - stride = 1 - if stride != 1 or self.inplanes != planes * block.expansion: - downsample = nn.Sequential( - conv1x1(self.inplanes, planes * block.expansion, stride), - nn.BatchNorm2d(planes * block.expansion, eps=1e-05, ), - ) - layers = [] - layers.append( - block(self.inplanes, planes, stride, downsample, self.groups, - self.base_width, previous_dilation)) - self.inplanes = planes * block.expansion - for _ in range(1, blocks): - layers.append( - block(self.inplanes, - planes, - groups=self.groups, - base_width=self.base_width, - dilation=self.dilation)) - - return nn.Sequential(*layers) - - def checkpoint(self, func, num_seg, x): - if self.training: - return checkpoint_sequential(func, num_seg, x) - else: - return func(x) - - def forward(self, x): - with torch.cuda.amp.autocast(self.fp16): - x = self.conv1(x) - x = self.bn1(x) - x = self.prelu(x) - x = self.layer1(x) - x = self.checkpoint(self.layer2, 20, x) - x = self.checkpoint(self.layer3, 100, x) - x = self.layer4(x) - x = self.bn2(x) - x = torch.flatten(x, 1) - x = self.dropout(x) - x = self.fc(x.float() if self.fp16 else x) - x = self.features(x) - return x - - -def _iresnet(arch, block, layers, pretrained, progress, **kwargs): - model = IResNet(block, layers, **kwargs) - if pretrained: - raise ValueError() - return model - - -def iresnet2060(pretrained=False, progress=True, **kwargs): - return _iresnet('iresnet2060', IBasicBlock, [3, 128, 1024 - 128, 3], pretrained, progress, **kwargs) diff --git a/spaces/Alpaca233/SadTalker/src/facerender/sync_batchnorm/comm.py b/spaces/Alpaca233/SadTalker/src/facerender/sync_batchnorm/comm.py deleted file mode 100644 index 922f8c4a3adaa9b32fdcaef09583be03b0d7eb2b..0000000000000000000000000000000000000000 --- a/spaces/Alpaca233/SadTalker/src/facerender/sync_batchnorm/comm.py +++ /dev/null @@ -1,137 +0,0 @@ -# -*- coding: utf-8 -*- -# File : comm.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 queue -import collections -import threading - -__all__ = ['FutureResult', 'SlavePipe', 'SyncMaster'] - - -class FutureResult(object): - """A thread-safe future implementation. Used only as one-to-one pipe.""" - - def __init__(self): - self._result = None - self._lock = threading.Lock() - self._cond = threading.Condition(self._lock) - - def put(self, result): - with self._lock: - assert self._result is None, 'Previous result has\'t been fetched.' - self._result = result - self._cond.notify() - - def get(self): - with self._lock: - if self._result is None: - self._cond.wait() - - res = self._result - self._result = None - return res - - -_MasterRegistry = collections.namedtuple('MasterRegistry', ['result']) -_SlavePipeBase = collections.namedtuple('_SlavePipeBase', ['identifier', 'queue', 'result']) - - -class SlavePipe(_SlavePipeBase): - """Pipe for master-slave communication.""" - - def run_slave(self, msg): - self.queue.put((self.identifier, msg)) - ret = self.result.get() - self.queue.put(True) - return ret - - -class SyncMaster(object): - """An abstract `SyncMaster` object. - - - During the replication, as the data parallel will trigger an callback of each module, all slave devices should - call `register(id)` and obtain an `SlavePipe` to communicate with the master. - - During the forward pass, master device invokes `run_master`, all messages from slave devices will be collected, - and passed to a registered callback. - - After receiving the messages, the master device should gather the information and determine to message passed - back to each slave devices. - """ - - def __init__(self, master_callback): - """ - - Args: - master_callback: a callback to be invoked after having collected messages from slave devices. - """ - self._master_callback = master_callback - self._queue = queue.Queue() - self._registry = collections.OrderedDict() - self._activated = False - - def __getstate__(self): - return {'master_callback': self._master_callback} - - def __setstate__(self, state): - self.__init__(state['master_callback']) - - def register_slave(self, identifier): - """ - Register an slave device. - - Args: - identifier: an identifier, usually is the device id. - - Returns: a `SlavePipe` object which can be used to communicate with the master device. - - """ - if self._activated: - assert self._queue.empty(), 'Queue is not clean before next initialization.' - self._activated = False - self._registry.clear() - future = FutureResult() - self._registry[identifier] = _MasterRegistry(future) - return SlavePipe(identifier, self._queue, future) - - def run_master(self, master_msg): - """ - Main entry for the master device in each forward pass. - The messages were first collected from each devices (including the master device), and then - an callback will be invoked to compute the message to be sent back to each devices - (including the master device). - - Args: - master_msg: the message that the master want to send to itself. This will be placed as the first - message when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example. - - Returns: the message to be sent back to the master device. - - """ - self._activated = True - - intermediates = [(0, master_msg)] - for i in range(self.nr_slaves): - intermediates.append(self._queue.get()) - - results = self._master_callback(intermediates) - assert results[0][0] == 0, 'The first result should belongs to the master.' - - for i, res in results: - if i == 0: - continue - self._registry[i].result.put(res) - - for i in range(self.nr_slaves): - assert self._queue.get() is True - - return results[0][1] - - @property - def nr_slaves(self): - return len(self._registry) diff --git a/spaces/Amrrs/DragGan-Inversion/stylegan_human/dnnlib/tflib/autosummary.py b/spaces/Amrrs/DragGan-Inversion/stylegan_human/dnnlib/tflib/autosummary.py deleted file mode 100644 index 272f054eea659e7191c7c71ae3745eefe5f82411..0000000000000000000000000000000000000000 --- a/spaces/Amrrs/DragGan-Inversion/stylegan_human/dnnlib/tflib/autosummary.py +++ /dev/null @@ -1,207 +0,0 @@ -# Copyright (c) SenseTime Research. All rights reserved. - -# Copyright (c) 2019, NVIDIA Corporation. All rights reserved. -# -# This work is made available under the Nvidia Source Code License-NC. -# To view a copy of this license, visit -# https://nvlabs.github.io/stylegan2/license.html - -"""Helper for adding automatically tracked values to Tensorboard. - -Autosummary creates an identity op that internally keeps track of the input -values and automatically shows up in TensorBoard. The reported value -represents an average over input components. The average is accumulated -constantly over time and flushed when save_summaries() is called. - -Notes: -- The output tensor must be used as an input for something else in the - graph. Otherwise, the autosummary op will not get executed, and the average - value will not get accumulated. -- It is perfectly fine to include autosummaries with the same name in - several places throughout the graph, even if they are executed concurrently. -- It is ok to also pass in a python scalar or numpy array. In this case, it - is added to the average immediately. -""" - -from collections import OrderedDict -import numpy as np -import tensorflow as tf -from tensorboard import summary as summary_lib -from tensorboard.plugins.custom_scalar import layout_pb2 - -from . import tfutil -from .tfutil import TfExpression -from .tfutil import TfExpressionEx - -# Enable "Custom scalars" tab in TensorBoard for advanced formatting. -# Disabled by default to reduce tfevents file size. -enable_custom_scalars = False - -_dtype = tf.float64 -_vars = OrderedDict() # name => [var, ...] -_immediate = OrderedDict() # name => update_op, update_value -_finalized = False -_merge_op = None - - -def _create_var(name: str, value_expr: TfExpression) -> TfExpression: - """Internal helper for creating autosummary accumulators.""" - assert not _finalized - name_id = name.replace("/", "_") - v = tf.cast(value_expr, _dtype) - - if v.shape.is_fully_defined(): - size = np.prod(v.shape.as_list()) - size_expr = tf.constant(size, dtype=_dtype) - else: - size = None - size_expr = tf.reduce_prod(tf.cast(tf.shape(v), _dtype)) - - if size == 1: - if v.shape.ndims != 0: - v = tf.reshape(v, []) - v = [size_expr, v, tf.square(v)] - else: - v = [size_expr, tf.reduce_sum(v), tf.reduce_sum(tf.square(v))] - v = tf.cond(tf.is_finite(v[1]), lambda: tf.stack( - v), lambda: tf.zeros(3, dtype=_dtype)) - - with tfutil.absolute_name_scope("Autosummary/" + name_id), tf.control_dependencies(None): - # [sum(1), sum(x), sum(x**2)] - var = tf.Variable(tf.zeros(3, dtype=_dtype), trainable=False) - update_op = tf.cond(tf.is_variable_initialized( - var), lambda: tf.assign_add(var, v), lambda: tf.assign(var, v)) - - if name in _vars: - _vars[name].append(var) - else: - _vars[name] = [var] - return update_op - - -def autosummary(name: str, value: TfExpressionEx, passthru: TfExpressionEx = None, condition: TfExpressionEx = True) -> TfExpressionEx: - """Create a new autosummary. - - Args: - name: Name to use in TensorBoard - value: TensorFlow expression or python value to track - passthru: Optionally return this TF node without modifications but tack an autosummary update side-effect to this node. - - Example use of the passthru mechanism: - - n = autosummary('l2loss', loss, passthru=n) - - This is a shorthand for the following code: - - with tf.control_dependencies([autosummary('l2loss', loss)]): - n = tf.identity(n) - """ - tfutil.assert_tf_initialized() - name_id = name.replace("/", "_") - - if tfutil.is_tf_expression(value): - with tf.name_scope("summary_" + name_id), tf.device(value.device): - condition = tf.convert_to_tensor(condition, name='condition') - update_op = tf.cond(condition, lambda: tf.group( - _create_var(name, value)), tf.no_op) - with tf.control_dependencies([update_op]): - return tf.identity(value if passthru is None else passthru) - - else: # python scalar or numpy array - assert not tfutil.is_tf_expression(passthru) - assert not tfutil.is_tf_expression(condition) - if condition: - if name not in _immediate: - with tfutil.absolute_name_scope("Autosummary/" + name_id), tf.device(None), tf.control_dependencies(None): - update_value = tf.placeholder(_dtype) - update_op = _create_var(name, update_value) - _immediate[name] = update_op, update_value - update_op, update_value = _immediate[name] - tfutil.run(update_op, {update_value: value}) - return value if passthru is None else passthru - - -def finalize_autosummaries() -> None: - """Create the necessary ops to include autosummaries in TensorBoard report. - Note: This should be done only once per graph. - """ - global _finalized - tfutil.assert_tf_initialized() - - if _finalized: - return None - - _finalized = True - tfutil.init_uninitialized_vars( - [var for vars_list in _vars.values() for var in vars_list]) - - # Create summary ops. - with tf.device(None), tf.control_dependencies(None): - for name, vars_list in _vars.items(): - name_id = name.replace("/", "_") - with tfutil.absolute_name_scope("Autosummary/" + name_id): - moments = tf.add_n(vars_list) - moments /= moments[0] - # read before resetting - with tf.control_dependencies([moments]): - reset_ops = [tf.assign(var, tf.zeros( - 3, dtype=_dtype)) for var in vars_list] - # reset before reporting - with tf.name_scope(None), tf.control_dependencies(reset_ops): - mean = moments[1] - std = tf.sqrt(moments[2] - tf.square(moments[1])) - tf.summary.scalar(name, mean) - if enable_custom_scalars: - tf.summary.scalar( - "xCustomScalars/" + name + "/margin_lo", mean - std) - tf.summary.scalar( - "xCustomScalars/" + name + "/margin_hi", mean + std) - - # Setup layout for custom scalars. - layout = None - if enable_custom_scalars: - cat_dict = OrderedDict() - for series_name in sorted(_vars.keys()): - p = series_name.split("/") - cat = p[0] if len(p) >= 2 else "" - chart = "/".join(p[1:-1]) if len(p) >= 3 else p[-1] - if cat not in cat_dict: - cat_dict[cat] = OrderedDict() - if chart not in cat_dict[cat]: - cat_dict[cat][chart] = [] - cat_dict[cat][chart].append(series_name) - categories = [] - for cat_name, chart_dict in cat_dict.items(): - charts = [] - for chart_name, series_names in chart_dict.items(): - series = [] - for series_name in series_names: - series.append(layout_pb2.MarginChartContent.Series( - value=series_name, - lower="xCustomScalars/" + series_name + "/margin_lo", - upper="xCustomScalars/" + series_name + "/margin_hi")) - margin = layout_pb2.MarginChartContent(series=series) - charts.append(layout_pb2.Chart( - title=chart_name, margin=margin)) - categories.append(layout_pb2.Category( - title=cat_name, chart=charts)) - layout = summary_lib.custom_scalar_pb( - layout_pb2.Layout(category=categories)) - return layout - - -def save_summaries(file_writer, global_step=None): - """Call FileWriter.add_summary() with all summaries in the default graph, - automatically finalizing and merging them on the first call. - """ - global _merge_op - tfutil.assert_tf_initialized() - - if _merge_op is None: - layout = finalize_autosummaries() - if layout is not None: - file_writer.add_summary(layout) - with tf.device(None), tf.control_dependencies(None): - _merge_op = tf.summary.merge_all() - - file_writer.add_summary(_merge_op.eval(), global_step) diff --git a/spaces/Amrrs/DragGan-Inversion/training/training_loop.py b/spaces/Amrrs/DragGan-Inversion/training/training_loop.py deleted file mode 100644 index b1643b2d96a597d236af29053878191859a74cb7..0000000000000000000000000000000000000000 --- a/spaces/Amrrs/DragGan-Inversion/training/training_loop.py +++ /dev/null @@ -1,499 +0,0 @@ -# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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. - -"""Main training loop.""" - -import os -import time -import copy -import json -import pickle -import psutil -import PIL.Image -import numpy as np -import torch -import dnnlib -from torch_utils import misc -from torch_utils import training_stats -from torch_utils.ops import conv2d_gradfix -from torch_utils.ops import grid_sample_gradfix - -import legacy -from metrics import metric_main - -# ---------------------------------------------------------------------------- - - -def setup_snapshot_image_grid(training_set, random_seed=0): - rnd = np.random.RandomState(random_seed) - gw = np.clip(7680 // training_set.image_shape[2], 7, 32) - gh = np.clip(4320 // training_set.image_shape[1], 4, 32) - - # No labels => show random subset of training samples. - if not training_set.has_labels: - all_indices = list(range(len(training_set))) - rnd.shuffle(all_indices) - grid_indices = [all_indices[i % - len(all_indices)] for i in range(gw * gh)] - - else: - # Group training samples by label. - label_groups = dict() # label => [idx, ...] - for idx in range(len(training_set)): - label = tuple(training_set.get_details(idx).raw_label.flat[::-1]) - if label not in label_groups: - label_groups[label] = [] - label_groups[label].append(idx) - - # Reorder. - label_order = sorted(label_groups.keys()) - for label in label_order: - rnd.shuffle(label_groups[label]) - - # Organize into grid. - grid_indices = [] - for y in range(gh): - label = label_order[y % len(label_order)] - indices = label_groups[label] - grid_indices += [indices[x % len(indices)] for x in range(gw)] - label_groups[label] = [ - indices[(i + gw) % len(indices)] for i in range(len(indices))] - - # Load data. - images, labels = zip(*[training_set[i] for i in grid_indices]) - return (gw, gh), np.stack(images), np.stack(labels) - -# ---------------------------------------------------------------------------- - - -def save_image_grid(img, fname, drange, grid_size): - lo, hi = drange - img = np.asarray(img, dtype=np.float32) - img = (img - lo) * (255 / (hi - lo)) - img = np.rint(img).clip(0, 255).astype(np.uint8) - - gw, gh = grid_size - _N, C, H, W = img.shape - img = img.reshape([gh, gw, C, H, W]) - img = img.transpose(0, 3, 1, 4, 2) - img = img.reshape([gh * H, gw * W, C]) - - assert C in [1, 3] - if C == 1: - PIL.Image.fromarray(img[:, :, 0], 'L').save(fname) - if C == 3: - PIL.Image.fromarray(img, 'RGB').save(fname) - -# ---------------------------------------------------------------------------- - - -def training_loop( - run_dir='.', # Output directory. - training_set_kwargs={}, # Options for training set. - data_loader_kwargs={}, # Options for torch.utils.data.DataLoader. - G_kwargs={}, # Options for generator network. - D_kwargs={}, # Options for discriminator network. - G_opt_kwargs={}, # Options for generator optimizer. - D_opt_kwargs={}, # Options for discriminator optimizer. - # Options for augmentation pipeline. None = disable. - augment_kwargs=None, - loss_kwargs={}, # Options for loss function. - metrics=[], # Metrics to evaluate during training. - random_seed=0, # Global random seed. - num_gpus=1, # Number of GPUs participating in the training. - rank=0, # Rank of the current process in [0, num_gpus[. - # Total batch size for one training iteration. Can be larger than batch_gpu * num_gpus. - batch_size=4, - batch_gpu=4, # Number of samples processed at a time by one GPU. - # Half-life of the exponential moving average (EMA) of generator weights. - ema_kimg=10, - ema_rampup=0.05, # EMA ramp-up coefficient. None = no rampup. - # How often to perform regularization for G? None = disable lazy regularization. - G_reg_interval=None, - # How often to perform regularization for D? None = disable lazy regularization. - D_reg_interval=16, - augment_p=0, # Initial value of augmentation probability. - ada_target=None, # ADA target value. None = fixed p. - ada_interval=4, # How often to perform ADA adjustment? - # ADA adjustment speed, measured in how many kimg it takes for p to increase/decrease by one unit. - ada_kimg=500, - # Total length of the training, measured in thousands of real images. - total_kimg=25000, - kimg_per_tick=4, # Progress snapshot interval. - # How often to save image snapshots? None = disable. - image_snapshot_ticks=50, - # How often to save network snapshots? None = disable. - network_snapshot_ticks=50, - resume_pkl=None, # Network pickle to resume training from. - resume_kimg=0, # First kimg to report when resuming training. - cudnn_benchmark=True, # Enable torch.backends.cudnn.benchmark? - # Callback function for determining whether to abort training. Must return consistent results across ranks. - abort_fn=None, - # Callback function for updating training progress. Called for all ranks. - progress_fn=None, -): - # Initialize. - start_time = time.time() - device = torch.device('cuda', rank) - np.random.seed(random_seed * num_gpus + rank) - torch.manual_seed(random_seed * num_gpus + rank) - # Improves training speed. - torch.backends.cudnn.benchmark = cudnn_benchmark - # Improves numerical accuracy. - torch.backends.cuda.matmul.allow_tf32 = False - # Improves numerical accuracy. - torch.backends.cudnn.allow_tf32 = False - # Improves training speed. - conv2d_gradfix.enabled = True - # Avoids errors with the augmentation pipe. - grid_sample_gradfix.enabled = True - - # Load training set. - if rank == 0: - print('Loading training set...') - training_set = dnnlib.util.construct_class_by_name( - **training_set_kwargs) # subclass of training.dataset.Dataset - training_set_sampler = misc.InfiniteSampler( - dataset=training_set, rank=rank, num_replicas=num_gpus, seed=random_seed) - training_set_iterator = iter(torch.utils.data.DataLoader( - dataset=training_set, sampler=training_set_sampler, batch_size=batch_size//num_gpus, **data_loader_kwargs)) - if rank == 0: - print() - print('Num images: ', len(training_set)) - print('Image shape:', training_set.image_shape) - print('Label shape:', training_set.label_shape) - print() - - # Construct networks. - if rank == 0: - print('Constructing networks...') - common_kwargs = dict(c_dim=training_set.label_dim, - img_resolution=training_set.resolution, img_channels=training_set.num_channels) - G = dnnlib.util.construct_class_by_name(**G_kwargs, **common_kwargs).train( - ).requires_grad_(False).to(device) # subclass of torch.nn.Module - D = dnnlib.util.construct_class_by_name(**D_kwargs, **common_kwargs).train( - ).requires_grad_(False).to(device) # subclass of torch.nn.Module - G_ema = copy.deepcopy(G).eval() - - # Resume from existing pickle. - if (resume_pkl is not None) and (rank == 0): - print(f'Resuming from "{resume_pkl}"') - with dnnlib.util.open_url(resume_pkl) as f: - resume_data = legacy.load_network_pkl(f) - for name, module in [('G', G), ('D', D), ('G_ema', G_ema)]: - misc.copy_params_and_buffers( - resume_data[name], module, require_all=False) - - # Print network summary tables. - if rank == 0: - z = torch.empty([batch_gpu, G.z_dim], device=device) - c = torch.empty([batch_gpu, G.c_dim], device=device) - img = misc.print_module_summary(G, [z, c]) - misc.print_module_summary(D, [img, c]) - - # Setup augmentation. - if rank == 0: - print('Setting up augmentation...') - augment_pipe = None - ada_stats = None - if (augment_kwargs is not None) and (augment_p > 0 or ada_target is not None): - augment_pipe = dnnlib.util.construct_class_by_name( - **augment_kwargs).train().requires_grad_(False).to(device) # subclass of torch.nn.Module - augment_pipe.p.copy_(torch.as_tensor(augment_p)) - if ada_target is not None: - ada_stats = training_stats.Collector(regex='Loss/signs/real') - - # Distribute across GPUs. - if rank == 0: - print(f'Distributing across {num_gpus} GPUs...') - for module in [G, D, G_ema, augment_pipe]: - if module is not None and num_gpus > 1: - for param in misc.params_and_buffers(module): - torch.distributed.broadcast(param, src=0) - - # Setup training phases. - if rank == 0: - print('Setting up training phases...') - loss = dnnlib.util.construct_class_by_name( - device=device, G=G, D=D, augment_pipe=augment_pipe, **loss_kwargs) # subclass of training.loss.Loss - phases = [] - for name, module, opt_kwargs, reg_interval in [('G', G, G_opt_kwargs, G_reg_interval), ('D', D, D_opt_kwargs, D_reg_interval)]: - if reg_interval is None: - opt = dnnlib.util.construct_class_by_name( - params=module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer - phases += [dnnlib.EasyDict(name=name+'both', - module=module, opt=opt, interval=1)] - else: # Lazy regularization. - mb_ratio = reg_interval / (reg_interval + 1) - opt_kwargs = dnnlib.EasyDict(opt_kwargs) - opt_kwargs.lr = opt_kwargs.lr * mb_ratio - opt_kwargs.betas = [beta ** mb_ratio for beta in opt_kwargs.betas] - opt = dnnlib.util.construct_class_by_name( - module.parameters(), **opt_kwargs) # subclass of torch.optim.Optimizer - phases += [dnnlib.EasyDict(name=name+'main', - module=module, opt=opt, interval=1)] - phases += [dnnlib.EasyDict(name=name+'reg', - module=module, opt=opt, interval=reg_interval)] - for phase in phases: - phase.start_event = None - phase.end_event = None - if rank == 0: - phase.start_event = torch.cuda.Event(enable_timing=True) - phase.end_event = torch.cuda.Event(enable_timing=True) - - # Export sample images. - grid_size = None - grid_z = None - grid_c = None - if rank == 0: - print('Exporting sample images...') - grid_size, images, labels = setup_snapshot_image_grid( - training_set=training_set) - save_image_grid(images, os.path.join(run_dir, 'reals.png'), - drange=[0, 255], grid_size=grid_size) - grid_z = torch.randn([labels.shape[0], G.z_dim], - device=device).split(batch_gpu) - grid_c = torch.from_numpy(labels).to(device).split(batch_gpu) - images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu() - for z, c in zip(grid_z, grid_c)]).numpy() - save_image_grid(images, os.path.join( - run_dir, 'fakes_init.png'), drange=[-1, 1], grid_size=grid_size) - - # Initialize logs. - if rank == 0: - print('Initializing logs...') - stats_collector = training_stats.Collector(regex='.*') - stats_metrics = dict() - stats_jsonl = None - stats_tfevents = None - if rank == 0: - stats_jsonl = open(os.path.join(run_dir, 'stats.jsonl'), 'wt') - try: - import torch.utils.tensorboard as tensorboard - stats_tfevents = tensorboard.SummaryWriter(run_dir) - except ImportError as err: - print('Skipping tfevents export:', err) - - # Train. - if rank == 0: - print(f'Training for {total_kimg} kimg...') - print() - cur_nimg = resume_kimg * 1000 - cur_tick = 0 - tick_start_nimg = cur_nimg - tick_start_time = time.time() - maintenance_time = tick_start_time - start_time - batch_idx = 0 - if progress_fn is not None: - progress_fn(0, total_kimg) - while True: - - # Fetch training data. - with torch.autograd.profiler.record_function('data_fetch'): - phase_real_img, phase_real_c = next(training_set_iterator) - phase_real_img = (phase_real_img.to(device).to( - torch.float32) / 127.5 - 1).split(batch_gpu) - phase_real_c = phase_real_c.to(device).split(batch_gpu) - all_gen_z = torch.randn( - [len(phases) * batch_size, G.z_dim], device=device) - all_gen_z = [phase_gen_z.split( - batch_gpu) for phase_gen_z in all_gen_z.split(batch_size)] - all_gen_c = [training_set.get_label(np.random.randint( - len(training_set))) for _ in range(len(phases) * batch_size)] - all_gen_c = torch.from_numpy( - np.stack(all_gen_c)).pin_memory().to(device) - all_gen_c = [phase_gen_c.split( - batch_gpu) for phase_gen_c in all_gen_c.split(batch_size)] - - # Execute training phases. - for phase, phase_gen_z, phase_gen_c in zip(phases, all_gen_z, all_gen_c): - if batch_idx % phase.interval != 0: - continue - if phase.start_event is not None: - phase.start_event.record(torch.cuda.current_stream(device)) - - # Accumulate gradients. - phase.opt.zero_grad(set_to_none=True) - phase.module.requires_grad_(True) - for real_img, real_c, gen_z, gen_c in zip(phase_real_img, phase_real_c, phase_gen_z, phase_gen_c): - loss.accumulate_gradients(phase=phase.name, real_img=real_img, real_c=real_c, - gen_z=gen_z, gen_c=gen_c, gain=phase.interval, cur_nimg=cur_nimg) - phase.module.requires_grad_(False) - - # Update weights. - with torch.autograd.profiler.record_function(phase.name + '_opt'): - params = [param for param in phase.module.parameters() - if param.grad is not None] - if len(params) > 0: - flat = torch.cat([param.grad.flatten() - for param in params]) - if num_gpus > 1: - torch.distributed.all_reduce(flat) - flat /= num_gpus - misc.nan_to_num(flat, nan=0, posinf=1e5, - neginf=-1e5, out=flat) - grads = flat.split([param.numel() for param in params]) - for param, grad in zip(params, grads): - param.grad = grad.reshape(param.shape) - phase.opt.step() - - # Phase done. - if phase.end_event is not None: - phase.end_event.record(torch.cuda.current_stream(device)) - - # Update G_ema. - with torch.autograd.profiler.record_function('Gema'): - ema_nimg = ema_kimg * 1000 - if ema_rampup is not None: - ema_nimg = min(ema_nimg, cur_nimg * ema_rampup) - ema_beta = 0.5 ** (batch_size / max(ema_nimg, 1e-8)) - for p_ema, p in zip(G_ema.parameters(), G.parameters()): - p_ema.copy_(p.lerp(p_ema, ema_beta)) - for b_ema, b in zip(G_ema.buffers(), G.buffers()): - b_ema.copy_(b) - - # Update state. - cur_nimg += batch_size - batch_idx += 1 - - # Execute ADA heuristic. - if (ada_stats is not None) and (batch_idx % ada_interval == 0): - ada_stats.update() - adjust = np.sign(ada_stats['Loss/signs/real'] - ada_target) * \ - (batch_size * ada_interval) / (ada_kimg * 1000) - augment_pipe.p.copy_( - (augment_pipe.p + adjust).max(misc.constant(0, device=device))) - - # Perform maintenance tasks once per tick. - done = (cur_nimg >= total_kimg * 1000) - if (not done) and (cur_tick != 0) and (cur_nimg < tick_start_nimg + kimg_per_tick * 1000): - continue - - # Print status line, accumulating the same information in training_stats. - tick_end_time = time.time() - fields = [] - fields += [ - f"tick {training_stats.report0('Progress/tick', cur_tick):<5d}"] - fields += [ - f"kimg {training_stats.report0('Progress/kimg', cur_nimg / 1e3):<8.1f}"] - fields += [ - f"time {dnnlib.util.format_time(training_stats.report0('Timing/total_sec', tick_end_time - start_time)):<12s}"] - fields += [ - f"sec/tick {training_stats.report0('Timing/sec_per_tick', tick_end_time - tick_start_time):<7.1f}"] - fields += [ - f"sec/kimg {training_stats.report0('Timing/sec_per_kimg', (tick_end_time - tick_start_time) / (cur_nimg - tick_start_nimg) * 1e3):<7.2f}"] - fields += [ - f"maintenance {training_stats.report0('Timing/maintenance_sec', maintenance_time):<6.1f}"] - fields += [ - f"cpumem {training_stats.report0('Resources/cpu_mem_gb', psutil.Process(os.getpid()).memory_info().rss / 2**30):<6.2f}"] - fields += [ - f"gpumem {training_stats.report0('Resources/peak_gpu_mem_gb', torch.cuda.max_memory_allocated(device) / 2**30):<6.2f}"] - fields += [ - f"reserved {training_stats.report0('Resources/peak_gpu_mem_reserved_gb', torch.cuda.max_memory_reserved(device) / 2**30):<6.2f}"] - torch.cuda.reset_peak_memory_stats() - fields += [ - f"augment {training_stats.report0('Progress/augment', float(augment_pipe.p.cpu()) if augment_pipe is not None else 0):.3f}"] - training_stats.report0('Timing/total_hours', - (tick_end_time - start_time) / (60 * 60)) - training_stats.report0('Timing/total_days', - (tick_end_time - start_time) / (24 * 60 * 60)) - if rank == 0: - print(' '.join(fields)) - - # Check for abort. - if (not done) and (abort_fn is not None) and abort_fn(): - done = True - if rank == 0: - print() - print('Aborting...') - - # Save image snapshot. - if (rank == 0) and (image_snapshot_ticks is not None) and (done or cur_tick % image_snapshot_ticks == 0): - images = torch.cat([G_ema(z=z, c=c, noise_mode='const').cpu() - for z, c in zip(grid_z, grid_c)]).numpy() - save_image_grid(images, os.path.join( - run_dir, f'fakes{cur_nimg//1000:06d}.png'), drange=[-1, 1], grid_size=grid_size) - - # Save network snapshot. - snapshot_pkl = None - snapshot_data = None - if (network_snapshot_ticks is not None) and (done or cur_tick % network_snapshot_ticks == 0): - snapshot_data = dict(G=G, D=D, G_ema=G_ema, augment_pipe=augment_pipe, - training_set_kwargs=dict(training_set_kwargs)) - for key, value in snapshot_data.items(): - if isinstance(value, torch.nn.Module): - value = copy.deepcopy(value).eval().requires_grad_(False) - if num_gpus > 1: - misc.check_ddp_consistency( - value, ignore_regex=r'.*\.[^.]+_(avg|ema)') - for param in misc.params_and_buffers(value): - torch.distributed.broadcast(param, src=0) - snapshot_data[key] = value.cpu() - del value # conserve memory - snapshot_pkl = os.path.join( - run_dir, f'network-snapshot-{cur_nimg//1000:06d}.pkl') - if rank == 0: - with open(snapshot_pkl, 'wb') as f: - pickle.dump(snapshot_data, f) - - # Evaluate metrics. - if (snapshot_data is not None) and (len(metrics) > 0): - if rank == 0: - print('Evaluating metrics...') - for metric in metrics: - result_dict = metric_main.calc_metric(metric=metric, G=snapshot_data['G_ema'], - dataset_kwargs=training_set_kwargs, num_gpus=num_gpus, rank=rank, device=device) - if rank == 0: - metric_main.report_metric( - result_dict, run_dir=run_dir, snapshot_pkl=snapshot_pkl) - stats_metrics.update(result_dict.results) - del snapshot_data # conserve memory - - # Collect statistics. - for phase in phases: - value = [] - if (phase.start_event is not None) and (phase.end_event is not None): - phase.end_event.synchronize() - value = phase.start_event.elapsed_time(phase.end_event) - training_stats.report0('Timing/' + phase.name, value) - stats_collector.update() - stats_dict = stats_collector.as_dict() - - # Update logs. - timestamp = time.time() - if stats_jsonl is not None: - fields = dict(stats_dict, timestamp=timestamp) - stats_jsonl.write(json.dumps(fields) + '\n') - stats_jsonl.flush() - if stats_tfevents is not None: - global_step = int(cur_nimg / 1e3) - walltime = timestamp - start_time - for name, value in stats_dict.items(): - stats_tfevents.add_scalar( - name, value.mean, global_step=global_step, walltime=walltime) - for name, value in stats_metrics.items(): - stats_tfevents.add_scalar( - f'Metrics/{name}', value, global_step=global_step, walltime=walltime) - stats_tfevents.flush() - if progress_fn is not None: - progress_fn(cur_nimg // 1000, total_kimg) - - # Update state. - cur_tick += 1 - tick_start_nimg = cur_nimg - tick_start_time = time.time() - maintenance_time = tick_start_time - tick_end_time - if done: - break - - # Done. - if rank == 0: - print() - print('Exiting...') - -# ---------------------------------------------------------------------------- diff --git a/spaces/AnTo2209/3D_Zeroshot_Neural_Style_Transfer/inference.py b/spaces/AnTo2209/3D_Zeroshot_Neural_Style_Transfer/inference.py deleted file mode 100644 index 5193196d0a45ab9f85d7bb24b659e2bbec413e67..0000000000000000000000000000000000000000 --- a/spaces/AnTo2209/3D_Zeroshot_Neural_Style_Transfer/inference.py +++ /dev/null @@ -1,78 +0,0 @@ -import os -from pathlib import Path - -import torch -from lightning_fabric import seed_everything -from PIL import Image, ImageFile - -from src.dataset import DATASET_REGISTRY -from src.decoder import DECODER_REGISTRY -from src.utils.opt import Opts -import torchvision.transforms as T - -from src.utils.renderer import evaluation_feature, evaluation_feature_path, OctreeRender_trilinear_fast - - -def inference(cfg, render_mode: str, image=None): - device = "cuda" if torch.cuda.is_available() else "cpu" - - ckpt = torch.load(cfg["model"]["tensorf"]["ckpt"], map_location=device) - kwargs = ckpt['kwargs'] - kwargs.update({'device': device}) - print(device) - tensorf = DECODER_REGISTRY.get(cfg["model"]["tensorf"]["model_name"])(**kwargs) - tensorf.change_to_feature_mod(cfg["model"]["tensorf"]["lamb_sh"], device) - tensorf.change_to_style_mod(device) - tensorf.load(ckpt) - tensorf.eval() - tensorf.rayMarch_weight_thres = cfg["model"]["tensorf"]["rm_weight_mask_thre"] - - logfolder = os.path.dirname("./checkpoints") - renderer= OctreeRender_trilinear_fast - - trans = T.Compose([T.Resize(size=(256, 256)), T.ToTensor()]) - if image: - if torch.cuda.is_available(): - style_img = trans(image).cuda()[None, ...] - else: - style_img = trans(image)[None, ...] - else: - style_img = trans(Image.open(cfg["global"]["style_img"])).cuda()[None, ...] - style_name = Path(cfg["global"]["style_img"]).stem - - if render_mode == "render_train": - dataset = DATASET_REGISTRY.get(cfg["dataset"]["name"])( - **cfg["dataset"]["train"]["params"], - ) - os.makedirs(f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}', exist_ok=True) - result = evaluation_feature(dataset, tensorf, renderer, cfg["sampler"]["params"]["chunk_size"], - f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}', - N_vis=-1, N_samples=-1, white_bg=dataset.white_bg, ndc_ray=cfg["model"]["tensorf"]["ndc_ray"], - style_img=style_img, device=device) - - if render_mode == "render_test": - dataset = DATASET_REGISTRY.get(cfg["dataset"]["name"])( - **cfg["dataset"]["val"]["params"], - ) - os.makedirs(f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}', exist_ok=True) - result = evaluation_feature(dataset, tensorf, renderer, cfg["sampler"]["params"]["chunk_size"], - f'{logfolder}/{cfg["global"]["expname"]}/imgs_train_all/{style_name}', - N_vis=-1, N_samples=-1, white_bg=dataset.white_bg, ndc_ray=cfg["model"]["tensorf"]["ndc_ray"], - style_img=style_img, device=device) - - if render_mode == "render_path": - dataset = DATASET_REGISTRY.get(cfg["dataset"]["name"])( - **cfg["dataset"]["val"]["params"], - ) - c2ws = dataset.render_path - os.makedirs(f'{logfolder}/{cfg["global"]["expname"]}/imgs_path_all/{style_name}', exist_ok=True) - result = evaluation_feature_path(dataset, tensorf, c2ws, renderer, cfg["sampler"]["params"]["chunk_size"], - f'{logfolder}/{cfg["global"]["expname"]}/imgs_path_all/{style_name}', - N_vis=-1, N_samples=-1, white_bg=dataset.white_bg, ndc_ray=cfg["model"]["tensorf"]["ndc_ray"], - style_img=style_img, device=device) - return result - -if __name__ == "__main__": - cfg = Opts(cfg="configs/style_inference.yml").parse_args() - seed_everything(seed=cfg["global"]["SEED"]) - inference(cfg, "render_test") diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/unipc.md b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/unipc.md deleted file mode 100644 index 134dc1ef3170b7ee15b9af2c98eedec719ea8c98..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/unipc.md +++ /dev/null @@ -1,24 +0,0 @@ - - -# UniPC - -## Overview - -UniPC is a training-free framework designed for the fast sampling of diffusion models, which consists of a corrector (UniC) and a predictor (UniP) that share a unified analytical form and support arbitrary orders. - -For more details about the method, please refer to the [paper](https://arxiv.org/abs/2302.04867) and the [code](https://github.com/wl-zhao/UniPC). - -Fast Sampling of Diffusion Models with Exponential Integrator. - -## UniPCMultistepScheduler -[[autodoc]] UniPCMultistepScheduler diff --git a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/controlnet/__init__.py b/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/controlnet/__init__.py deleted file mode 100644 index d5f7eb6b4fccd1ad574a166df5a95b029e5515c2..0000000000000000000000000000000000000000 --- a/spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/controlnet/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -from ...utils import ( - OptionalDependencyNotAvailable, - is_flax_available, - is_torch_available, - is_transformers_available, -) - - -try: - if not (is_transformers_available() and is_torch_available()): - raise OptionalDependencyNotAvailable() -except OptionalDependencyNotAvailable: - from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 -else: - from .multicontrolnet import MultiControlNetModel - from .pipeline_controlnet import StableDiffusionControlNetPipeline - from .pipeline_controlnet_img2img import StableDiffusionControlNetImg2ImgPipeline - from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline - from .pipeline_controlnet_sd_xl import StableDiffusionXLControlNetPipeline - - -if is_transformers_available() and is_flax_available(): - from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline diff --git a/spaces/Anindya/Marketing_Campaign_LLM/app.py b/spaces/Anindya/Marketing_Campaign_LLM/app.py deleted file mode 100644 index 36dfcf7fba9f960883cf7b35576d1e8377e1cf82..0000000000000000000000000000000000000000 --- a/spaces/Anindya/Marketing_Campaign_LLM/app.py +++ /dev/null @@ -1,120 +0,0 @@ -import os -import streamlit as st -from dotenv import load_dotenv -from langchain.llms import OpenAI -from langchain.prompts import PromptTemplate, FewShotPromptTemplate -from langchain.prompts.example_selector import LengthBasedExampleSelector - -load_dotenv() - - -def get_llm_response(query, action, age, word_limit): - """Get LLM Response""" - llm = OpenAI(temperature=0.9, model="text-davinci-003") - - examples = [ - { - "query": "What is a mobile?", - "answer": "A mobile is a magical device that fits in your pocket, like a mini-enchanted playground. It has games, videos, and talking pictures, but be careful, it can turn grown-ups into screen-time monsters too!", - }, - { - "query": "What are your dreams?", - "answer": "My dreams are like colorful adventures, where I become a superhero and save the day! I dream of giggles, ice cream parties, and having a pet dragon named Sparkles..", - }, - { - "query": " What are your ambitions?", - "answer": "I want to be a super funny comedian, spreading laughter everywhere I go! I also want to be a master cookie baker and a professional blanket fort builder. Being mischievous and sweet is just my bonus superpower!", - }, - { - "query": "What happens when you get sick?", - "answer": "When I get sick, it's like a sneaky monster visits. I feel tired, sniffly, and need lots of cuddles. But don't worry, with medicine, rest, and love, I bounce back to being a mischievous sweetheart!", - }, - { - "query": "WHow much do you love your dad?", - "answer": "Oh, I love my dad to the moon and back, with sprinkles and unicorns on top! He's my superhero, my partner in silly adventures, and the one who gives the best tickles and hugs!", - }, - { - "query": "Tell me about your friend?", - "answer": "My friend is like a sunshine rainbow! We laugh, play, and have magical parties together. They always listen, share their toys, and make me feel special. Friendship is the best adventure!", - }, - { - "query": "What math means to you?", - "answer": "Math is like a puzzle game, full of numbers and shapes. It helps me count my toys, build towers, and share treats equally. It's fun and makes my brain sparkle!", - }, - { - "query": "What is your fear?", - "answer": "Sometimes I'm scared of thunderstorms and monsters under my bed. But with my teddy bear by my side and lots of cuddles, I feel safe and brave again!", - }, - ] - - example_template = """Question: {query} - Answer: {answer}""" - - example_prompt = PromptTemplate( - template=example_template, input_variables=["query", "answer"] - ) - - example_selector = LengthBasedExampleSelector( - examples=examples, example_prompt=example_prompt, max_length=word_limit - ) - - prefix = """You are a {template_age} and {template_task}. - Here are some examples:""" - - suffix = """ - Question: {template_query} - Answer: """ - - prompt = FewShotPromptTemplate( - example_selector=example_selector, - example_prompt=example_prompt, - example_separator="/n/n", - prefix=prefix, - suffix=suffix, - input_variables=["template_age", "template_task", "template_query"], - ) - - llm_response = llm( - prompt.format(template_age=age, template_task=action, template_query=query) - ) - return llm_response - - -st.set_page_config(page_title="Marketing Tool", page_icon=":books:") -st.header("Marketing Tool :books:") - -if "OPENAI_API_KEY" not in os.environ: - openai_api_key = st.text_input( - label="OpenAI API Key: ", - type="password", - placeholder="Paste the OpenI API Key here to use gpt models", - ) - submit = st.button("Submit") - if submit and openai_api_key != "": - os.environ["OPENAI_API_KEY"] = openai_api_key - -if "OPENAI_API_KEY" in os.environ: - user_query = st.text_area(label="Enter Text Here...", height=150) - user_action = st.selectbox( - label="Select Task: ", - options=("Generate Tweet", "Generate Post"), - key="select_action", - ) - # user_age = st.selectbox( - # label="Select Age Group: ", - # options=("Kid", "Adult", "Senior Cityzen"), - # key="select_age", - # ) - user_word_limit = st.slider( - label="Word limit: ", min_value=1, max_value=250, value=25 - ) - generate = st.button("Generate") - if generate: - st.write( - get_llm_response( - query=user_query, - action=user_action, - age="Kid", - word_limit=user_word_limit, - ) - ) diff --git a/spaces/Antoine245/bot/README.md b/spaces/Antoine245/bot/README.md deleted file mode 100644 index e3da5dbceaa6532e96b767555ef993f20cc2ed59..0000000000000000000000000000000000000000 --- a/spaces/Antoine245/bot/README.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Bot -emoji: 🦀 -colorFrom: indigo -colorTo: pink -sdk: gradio -app_file: app.py -pinned: false -license: openrail ---- - -# Easy Chatbot with PaLM API - -1. go to https://makersuite.google.com/app/home -2. create your bot in the chat prompt -3. change app.py file with your own context and examples -4. add your own palm api key https://makersuite.google.com/app/apikey to your HF environment (cf https://huggingface.co/docs/huggingface_hub/guides/manage-spaces) -5. ready to use chatbot that can be used as embedded in any websites (cf https://comparateur-image.web.app/bot/) - - -### Errors - -1. clear button (gr.ClearButton needs a fix in embedded websites), I use a basic button until fixed - -### Use community if any question/request - -### Please check mkersuite quickstart - -Makersuite allows you to change context and examples in order to get the best chatbot and then export the code. You can then try it in gradio by cloning this space and changing context and examples. - -Check out https://developers.generativeai.google/tutorials/makersuite_quickstart - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/models/search_scope.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/models/search_scope.py deleted file mode 100644 index fe61e8116b71e073351939ed7a499ee752398f1c..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/models/search_scope.py +++ /dev/null @@ -1,132 +0,0 @@ -import itertools -import logging -import os -import posixpath -import urllib.parse -from typing import List - -from pip._vendor.packaging.utils import canonicalize_name - -from pip._internal.models.index import PyPI -from pip._internal.utils.compat import has_tls -from pip._internal.utils.misc import normalize_path, redact_auth_from_url - -logger = logging.getLogger(__name__) - - -class SearchScope: - - """ - Encapsulates the locations that pip is configured to search. - """ - - __slots__ = ["find_links", "index_urls", "no_index"] - - @classmethod - def create( - cls, - find_links: List[str], - index_urls: List[str], - no_index: bool, - ) -> "SearchScope": - """ - Create a SearchScope object after normalizing the `find_links`. - """ - # Build find_links. If an argument starts with ~, it may be - # a local file relative to a home directory. So try normalizing - # it and if it exists, use the normalized version. - # This is deliberately conservative - it might be fine just to - # blindly normalize anything starting with a ~... - built_find_links: List[str] = [] - for link in find_links: - if link.startswith("~"): - new_link = normalize_path(link) - if os.path.exists(new_link): - link = new_link - built_find_links.append(link) - - # If we don't have TLS enabled, then WARN if anyplace we're looking - # relies on TLS. - if not has_tls(): - for link in itertools.chain(index_urls, built_find_links): - parsed = urllib.parse.urlparse(link) - if parsed.scheme == "https": - logger.warning( - "pip is configured with locations that require " - "TLS/SSL, however the ssl module in Python is not " - "available." - ) - break - - return cls( - find_links=built_find_links, - index_urls=index_urls, - no_index=no_index, - ) - - def __init__( - self, - find_links: List[str], - index_urls: List[str], - no_index: bool, - ) -> None: - self.find_links = find_links - self.index_urls = index_urls - self.no_index = no_index - - def get_formatted_locations(self) -> str: - lines = [] - redacted_index_urls = [] - if self.index_urls and self.index_urls != [PyPI.simple_url]: - for url in self.index_urls: - redacted_index_url = redact_auth_from_url(url) - - # Parse the URL - purl = urllib.parse.urlsplit(redacted_index_url) - - # URL is generally invalid if scheme and netloc is missing - # there are issues with Python and URL parsing, so this test - # is a bit crude. See bpo-20271, bpo-23505. Python doesn't - # always parse invalid URLs correctly - it should raise - # exceptions for malformed URLs - if not purl.scheme and not purl.netloc: - logger.warning( - 'The index url "%s" seems invalid, please provide a scheme.', - redacted_index_url, - ) - - redacted_index_urls.append(redacted_index_url) - - lines.append( - "Looking in indexes: {}".format(", ".join(redacted_index_urls)) - ) - - if self.find_links: - lines.append( - "Looking in links: {}".format( - ", ".join(redact_auth_from_url(url) for url in self.find_links) - ) - ) - return "\n".join(lines) - - def get_index_urls_locations(self, project_name: str) -> List[str]: - """Returns the locations found via self.index_urls - - Checks the url_name on the main (first in the list) index and - use this url_name to produce all locations - """ - - def mkurl_pypi_url(url: str) -> str: - loc = posixpath.join( - url, urllib.parse.quote(canonicalize_name(project_name)) - ) - # For maximum compatibility with easy_install, ensure the path - # ends in a trailing slash. Although this isn't in the spec - # (and PyPI can handle it without the slash) some other index - # implementations might break if they relied on easy_install's - # behavior. - if not loc.endswith("/"): - loc = loc + "/" - return loc - - return [mkurl_pypi_url(url) for url in self.index_urls] diff --git a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/editable_wheel.py b/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/editable_wheel.py deleted file mode 100644 index d60cfbebb7cc4a24f8d56facf841637b04661714..0000000000000000000000000000000000000000 --- a/spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/editable_wheel.py +++ /dev/null @@ -1,844 +0,0 @@ -""" -Create a wheel that, when installed, will make the source package 'editable' -(add it to the interpreter's path, including metadata) per PEP 660. Replaces -'setup.py develop'. - -.. note:: - One of the mechanisms briefly mentioned in PEP 660 to implement editable installs is - to create a separated directory inside ``build`` and use a .pth file to point to that - directory. In the context of this file such directory is referred as - *auxiliary build directory* or ``auxiliary_dir``. -""" - -import logging -import os -import re -import shutil -import sys -import traceback -import warnings -from contextlib import suppress -from enum import Enum -from inspect import cleandoc -from itertools import chain -from pathlib import Path -from tempfile import TemporaryDirectory -from typing import ( - TYPE_CHECKING, - Dict, - Iterable, - Iterator, - List, - Mapping, - Optional, - Tuple, - TypeVar, - Union, -) - -from setuptools import Command, SetuptoolsDeprecationWarning, errors, namespaces -from setuptools.command.build_py import build_py as build_py_cls -from setuptools.discovery import find_package_path -from setuptools.dist import Distribution - -if TYPE_CHECKING: - from wheel.wheelfile import WheelFile # noqa - -if sys.version_info >= (3, 8): - from typing import Protocol -elif TYPE_CHECKING: - from typing_extensions import Protocol -else: - from abc import ABC as Protocol - -_Path = Union[str, Path] -_P = TypeVar("_P", bound=_Path) -_logger = logging.getLogger(__name__) - - -class _EditableMode(Enum): - """ - Possible editable installation modes: - `lenient` (new files automatically added to the package - DEFAULT); - `strict` (requires a new installation when files are added/removed); or - `compat` (attempts to emulate `python setup.py develop` - DEPRECATED). - """ - - STRICT = "strict" - LENIENT = "lenient" - COMPAT = "compat" # TODO: Remove `compat` after Dec/2022. - - @classmethod - def convert(cls, mode: Optional[str]) -> "_EditableMode": - if not mode: - return _EditableMode.LENIENT # default - - _mode = mode.upper() - if _mode not in _EditableMode.__members__: - raise errors.OptionError(f"Invalid editable mode: {mode!r}. Try: 'strict'.") - - if _mode == "COMPAT": - msg = """ - The 'compat' editable mode is transitional and will be removed - in future versions of `setuptools`. - Please adapt your code accordingly to use either the 'strict' or the - 'lenient' modes. - - For more information, please check: - https://setuptools.pypa.io/en/latest/userguide/development_mode.html - """ - warnings.warn(msg, SetuptoolsDeprecationWarning) - - return _EditableMode[_mode] - - -_STRICT_WARNING = """ -New or renamed files may not be automatically picked up without a new installation. -""" - -_LENIENT_WARNING = """ -Options like `package-data`, `include/exclude-package-data` or -`packages.find.exclude/include` may have no effect. -""" - - -class editable_wheel(Command): - """Build 'editable' wheel for development. - (This command is reserved for internal use of setuptools). - """ - - description = "create a PEP 660 'editable' wheel" - - user_options = [ - ("dist-dir=", "d", "directory to put final built distributions in"), - ("dist-info-dir=", "I", "path to a pre-build .dist-info directory"), - ("mode=", None, cleandoc(_EditableMode.__doc__ or "")), - ] - - def initialize_options(self): - self.dist_dir = None - self.dist_info_dir = None - self.project_dir = None - self.mode = None - - def finalize_options(self): - dist = self.distribution - self.project_dir = dist.src_root or os.curdir - self.package_dir = dist.package_dir or {} - self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, "dist")) - - def run(self): - try: - self.dist_dir.mkdir(exist_ok=True) - self._ensure_dist_info() - - # Add missing dist_info files - self.reinitialize_command("bdist_wheel") - bdist_wheel = self.get_finalized_command("bdist_wheel") - bdist_wheel.write_wheelfile(self.dist_info_dir) - - self._create_wheel_file(bdist_wheel) - except Exception as ex: - traceback.print_exc() - msg = """ - Support for editable installs via PEP 660 was recently introduced - in `setuptools`. If you are seeing this error, please report to: - - https://github.com/pypa/setuptools/issues - - Meanwhile you can try the legacy behavior by setting an - environment variable and trying to install again: - - SETUPTOOLS_ENABLE_FEATURES="legacy-editable" - """ - raise errors.InternalError(cleandoc(msg)) from ex - - def _ensure_dist_info(self): - if self.dist_info_dir is None: - dist_info = self.reinitialize_command("dist_info") - dist_info.output_dir = self.dist_dir - dist_info.ensure_finalized() - dist_info.run() - self.dist_info_dir = dist_info.dist_info_dir - else: - assert str(self.dist_info_dir).endswith(".dist-info") - assert Path(self.dist_info_dir, "METADATA").exists() - - def _install_namespaces(self, installation_dir, pth_prefix): - # XXX: Only required to support the deprecated namespace practice - dist = self.distribution - if not dist.namespace_packages: - return - - src_root = Path(self.project_dir, self.package_dir.get("", ".")).resolve() - installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root) - installer.install_namespaces() - - def _find_egg_info_dir(self) -> Optional[str]: - parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path() - candidates = map(str, parent_dir.glob("*.egg-info")) - return next(candidates, None) - - def _configure_build( - self, name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path - ): - """Configure commands to behave in the following ways: - - - Build commands can write to ``build_lib`` if they really want to... - (but this folder is expected to be ignored and modules are expected to live - in the project directory...) - - Binary extensions should be built in-place (editable_mode = True) - - Data/header/script files are not part of the "editable" specification - so they are written directly to the unpacked_wheel directory. - """ - # Non-editable files (data, headers, scripts) are written directly to the - # unpacked_wheel - - dist = self.distribution - wheel = str(unpacked_wheel) - build_lib = str(build_lib) - data = str(Path(unpacked_wheel, f"{name}.data", "data")) - headers = str(Path(unpacked_wheel, f"{name}.data", "headers")) - scripts = str(Path(unpacked_wheel, f"{name}.data", "scripts")) - - # egg-info may be generated again to create a manifest (used for package data) - egg_info = dist.reinitialize_command("egg_info", reinit_subcommands=True) - egg_info.egg_base = str(tmp_dir) - egg_info.ignore_egg_info_in_manifest = True - - build = dist.reinitialize_command("build", reinit_subcommands=True) - install = dist.reinitialize_command("install", reinit_subcommands=True) - - build.build_platlib = build.build_purelib = build.build_lib = build_lib - install.install_purelib = install.install_platlib = install.install_lib = wheel - install.install_scripts = build.build_scripts = scripts - install.install_headers = headers - install.install_data = data - - install_scripts = dist.get_command_obj("install_scripts") - install_scripts.no_ep = True - - build.build_temp = str(tmp_dir) - - build_py = dist.get_command_obj("build_py") - build_py.compile = False - build_py.existing_egg_info_dir = self._find_egg_info_dir() - - self._set_editable_mode() - - build.ensure_finalized() - install.ensure_finalized() - - def _set_editable_mode(self): - """Set the ``editable_mode`` flag in the build sub-commands""" - dist = self.distribution - build = dist.get_command_obj("build") - for cmd_name in build.get_sub_commands(): - cmd = dist.get_command_obj(cmd_name) - if hasattr(cmd, "editable_mode"): - cmd.editable_mode = True - elif hasattr(cmd, "inplace"): - cmd.inplace = True # backward compatibility with distutils - - def _collect_build_outputs(self) -> Tuple[List[str], Dict[str, str]]: - files: List[str] = [] - mapping: Dict[str, str] = {} - build = self.get_finalized_command("build") - - for cmd_name in build.get_sub_commands(): - cmd = self.get_finalized_command(cmd_name) - if hasattr(cmd, "get_outputs"): - files.extend(cmd.get_outputs() or []) - if hasattr(cmd, "get_output_mapping"): - mapping.update(cmd.get_output_mapping() or {}) - - return files, mapping - - def _run_build_commands( - self, dist_name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path - ) -> Tuple[List[str], Dict[str, str]]: - self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir) - self._run_build_subcommands() - files, mapping = self._collect_build_outputs() - self._run_install("headers") - self._run_install("scripts") - self._run_install("data") - return files, mapping - - def _run_build_subcommands(self): - """ - Issue #3501 indicates that some plugins/customizations might rely on: - - 1. ``build_py`` not running - 2. ``build_py`` always copying files to ``build_lib`` - - However both these assumptions may be false in editable_wheel. - This method implements a temporary workaround to support the ecosystem - while the implementations catch up. - """ - # TODO: Once plugins/customisations had the chance to catch up, replace - # `self._run_build_subcommands()` with `self.run_command("build")`. - # Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023. - build: Command = self.get_finalized_command("build") - for name in build.get_sub_commands(): - cmd = self.get_finalized_command(name) - if name == "build_py" and type(cmd) != build_py_cls: - self._safely_run(name) - else: - self.run_command(name) - - def _safely_run(self, cmd_name: str): - try: - return self.run_command(cmd_name) - except Exception: - msg = f"""{traceback.format_exc()}\n - If you are seeing this warning it is very likely that a setuptools - plugin or customization overrides the `{cmd_name}` command, without - taking into consideration how editable installs run build steps - starting from v64.0.0. - - Plugin authors and developers relying on custom build steps are encouraged - to update their `{cmd_name}` implementation considering the information in - https://setuptools.pypa.io/en/latest/userguide/extension.html - about editable installs. - - For the time being `setuptools` will silence this error and ignore - the faulty command, but this behaviour will change in future versions.\n - """ - warnings.warn(msg, SetuptoolsDeprecationWarning, stacklevel=2) - - def _create_wheel_file(self, bdist_wheel): - from wheel.wheelfile import WheelFile - - dist_info = self.get_finalized_command("dist_info") - dist_name = dist_info.name - tag = "-".join(bdist_wheel.get_tag()) - build_tag = "0.editable" # According to PEP 427 needs to start with digit - archive_name = f"{dist_name}-{build_tag}-{tag}.whl" - wheel_path = Path(self.dist_dir, archive_name) - if wheel_path.exists(): - wheel_path.unlink() - - unpacked_wheel = TemporaryDirectory(suffix=archive_name) - build_lib = TemporaryDirectory(suffix=".build-lib") - build_tmp = TemporaryDirectory(suffix=".build-temp") - - with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp: - unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name) - shutil.copytree(self.dist_info_dir, unpacked_dist_info) - self._install_namespaces(unpacked, dist_info.name) - files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp) - strategy = self._select_strategy(dist_name, tag, lib) - with strategy, WheelFile(wheel_path, "w") as wheel_obj: - strategy(wheel_obj, files, mapping) - wheel_obj.write_files(unpacked) - - return wheel_path - - def _run_install(self, category: str): - has_category = getattr(self.distribution, f"has_{category}", None) - if has_category and has_category(): - _logger.info(f"Installing {category} as non editable") - self.run_command(f"install_{category}") - - def _select_strategy( - self, - name: str, - tag: str, - build_lib: _Path, - ) -> "EditableStrategy": - """Decides which strategy to use to implement an editable installation.""" - build_name = f"__editable__.{name}-{tag}" - project_dir = Path(self.project_dir) - mode = _EditableMode.convert(self.mode) - - if mode is _EditableMode.STRICT: - auxiliary_dir = _empty_dir(Path(self.project_dir, "build", build_name)) - return _LinkTree(self.distribution, name, auxiliary_dir, build_lib) - - packages = _find_packages(self.distribution) - has_simple_layout = _simple_layout(packages, self.package_dir, project_dir) - is_compat_mode = mode is _EditableMode.COMPAT - if set(self.package_dir) == {""} and has_simple_layout or is_compat_mode: - # src-layout(ish) is relatively safe for a simple pth file - src_dir = self.package_dir.get("", ".") - return _StaticPth(self.distribution, name, [Path(project_dir, src_dir)]) - - # Use a MetaPathFinder to avoid adding accidental top-level packages/modules - return _TopLevelFinder(self.distribution, name) - - -class EditableStrategy(Protocol): - def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]): - ... - - def __enter__(self): - ... - - def __exit__(self, _exc_type, _exc_value, _traceback): - ... - - -class _StaticPth: - def __init__(self, dist: Distribution, name: str, path_entries: List[Path]): - self.dist = dist - self.name = name - self.path_entries = path_entries - - def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]): - entries = "\n".join((str(p.resolve()) for p in self.path_entries)) - contents = bytes(f"{entries}\n", "utf-8") - wheel.writestr(f"__editable__.{self.name}.pth", contents) - - def __enter__(self): - msg = f""" - Editable install will be performed using .pth file to extend `sys.path` with: - {list(map(os.fspath, self.path_entries))!r} - """ - _logger.warning(msg + _LENIENT_WARNING) - return self - - def __exit__(self, _exc_type, _exc_value, _traceback): - ... - - -class _LinkTree(_StaticPth): - """ - Creates a ``.pth`` file that points to a link tree in the ``auxiliary_dir``. - - This strategy will only link files (not dirs), so it can be implemented in - any OS, even if that means using hardlinks instead of symlinks. - - By collocating ``auxiliary_dir`` and the original source code, limitations - with hardlinks should be avoided. - """ - def __init__( - self, dist: Distribution, - name: str, - auxiliary_dir: _Path, - build_lib: _Path, - ): - self.auxiliary_dir = Path(auxiliary_dir) - self.build_lib = Path(build_lib).resolve() - self._file = dist.get_command_obj("build_py").copy_file - super().__init__(dist, name, [self.auxiliary_dir]) - - def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]): - self._create_links(files, mapping) - super().__call__(wheel, files, mapping) - - def _normalize_output(self, file: str) -> Optional[str]: - # Files relative to build_lib will be normalized to None - with suppress(ValueError): - path = Path(file).resolve().relative_to(self.build_lib) - return str(path).replace(os.sep, '/') - return None - - def _create_file(self, relative_output: str, src_file: str, link=None): - dest = self.auxiliary_dir / relative_output - if not dest.parent.is_dir(): - dest.parent.mkdir(parents=True) - self._file(src_file, dest, link=link) - - def _create_links(self, outputs, output_mapping): - self.auxiliary_dir.mkdir(parents=True, exist_ok=True) - link_type = "sym" if _can_symlink_files(self.auxiliary_dir) else "hard" - mappings = { - self._normalize_output(k): v - for k, v in output_mapping.items() - } - mappings.pop(None, None) # remove files that are not relative to build_lib - - for output in outputs: - relative = self._normalize_output(output) - if relative and relative not in mappings: - self._create_file(relative, output) - - for relative, src in mappings.items(): - self._create_file(relative, src, link=link_type) - - def __enter__(self): - msg = "Strict editable install will be performed using a link tree.\n" - _logger.warning(msg + _STRICT_WARNING) - return self - - def __exit__(self, _exc_type, _exc_value, _traceback): - msg = f"""\n - Strict editable installation performed using the auxiliary directory: - {self.auxiliary_dir} - - Please be careful to not remove this directory, otherwise you might not be able - to import/use your package. - """ - warnings.warn(msg, InformationOnly) - - -class _TopLevelFinder: - def __init__(self, dist: Distribution, name: str): - self.dist = dist - self.name = name - - def __call__(self, wheel: "WheelFile", files: List[str], mapping: Dict[str, str]): - src_root = self.dist.src_root or os.curdir - top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist)) - package_dir = self.dist.package_dir or {} - roots = _find_package_roots(top_level, package_dir, src_root) - - namespaces_: Dict[str, List[str]] = dict(chain( - _find_namespaces(self.dist.packages or [], roots), - ((ns, []) for ns in _find_virtual_namespaces(roots)), - )) - - name = f"__editable__.{self.name}.finder" - finder = _make_identifier(name) - content = bytes(_finder_template(name, roots, namespaces_), "utf-8") - wheel.writestr(f"{finder}.py", content) - - content = bytes(f"import {finder}; {finder}.install()", "utf-8") - wheel.writestr(f"__editable__.{self.name}.pth", content) - - def __enter__(self): - msg = "Editable install will be performed using a meta path finder.\n" - _logger.warning(msg + _LENIENT_WARNING) - return self - - def __exit__(self, _exc_type, _exc_value, _traceback): - msg = """\n - Please be careful with folders in your working directory with the same - name as your package as they may take precedence during imports. - """ - warnings.warn(msg, InformationOnly) - - -def _can_symlink_files(base_dir: Path) -> bool: - with TemporaryDirectory(dir=str(base_dir.resolve())) as tmp: - path1, path2 = Path(tmp, "file1.txt"), Path(tmp, "file2.txt") - path1.write_text("file1", encoding="utf-8") - with suppress(AttributeError, NotImplementedError, OSError): - os.symlink(path1, path2) - if path2.is_symlink() and path2.read_text(encoding="utf-8") == "file1": - return True - - try: - os.link(path1, path2) # Ensure hard links can be created - except Exception as ex: - msg = ( - "File system does not seem to support either symlinks or hard links. " - "Strict editable installs require one of them to be supported." - ) - raise LinksNotSupported(msg) from ex - return False - - -def _simple_layout( - packages: Iterable[str], package_dir: Dict[str, str], project_dir: Path -) -> bool: - """Return ``True`` if: - - all packages are contained by the same parent directory, **and** - - all packages become importable if the parent directory is added to ``sys.path``. - - >>> _simple_layout(['a'], {"": "src"}, "/tmp/myproj") - True - >>> _simple_layout(['a', 'a.b'], {"": "src"}, "/tmp/myproj") - True - >>> _simple_layout(['a', 'a.b'], {}, "/tmp/myproj") - True - >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"": "src"}, "/tmp/myproj") - True - >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "a", "b": "b"}, ".") - True - >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a", "b": "_b"}, ".") - False - >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a": "_a"}, "/tmp/myproj") - False - >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {"a.a1.a2": "_a2"}, ".") - False - >>> _simple_layout(['a', 'a.b'], {"": "src", "a.b": "_ab"}, "/tmp/myproj") - False - >>> # Special cases, no packages yet: - >>> _simple_layout([], {"": "src"}, "/tmp/myproj") - True - >>> _simple_layout([], {"a": "_a", "": "src"}, "/tmp/myproj") - False - """ - layout = { - pkg: find_package_path(pkg, package_dir, project_dir) - for pkg in packages - } - if not layout: - return set(package_dir) in ({}, {""}) - parent = os.path.commonpath([_parent_path(k, v) for k, v in layout.items()]) - return all( - _normalize_path(Path(parent, *key.split('.'))) == _normalize_path(value) - for key, value in layout.items() - ) - - -def _parent_path(pkg, pkg_path): - """Infer the parent path containing a package, that if added to ``sys.path`` would - allow importing that package. - When ``pkg`` is directly mapped into a directory with a different name, return its - own path. - >>> _parent_path("a", "src/a") - 'src' - >>> _parent_path("b", "src/c") - 'src/c' - """ - parent = pkg_path[:-len(pkg)] if pkg_path.endswith(pkg) else pkg_path - return parent.rstrip("/" + os.sep) - - -def _find_packages(dist: Distribution) -> Iterator[str]: - yield from iter(dist.packages or []) - - py_modules = dist.py_modules or [] - nested_modules = [mod for mod in py_modules if "." in mod] - if dist.ext_package: - yield dist.ext_package - else: - ext_modules = dist.ext_modules or [] - nested_modules += [x.name for x in ext_modules if "." in x.name] - - for module in nested_modules: - package, _, _ = module.rpartition(".") - yield package - - -def _find_top_level_modules(dist: Distribution) -> Iterator[str]: - py_modules = dist.py_modules or [] - yield from (mod for mod in py_modules if "." not in mod) - - if not dist.ext_package: - ext_modules = dist.ext_modules or [] - yield from (x.name for x in ext_modules if "." not in x.name) - - -def _find_package_roots( - packages: Iterable[str], - package_dir: Mapping[str, str], - src_root: _Path, -) -> Dict[str, str]: - pkg_roots: Dict[str, str] = { - pkg: _absolute_root(find_package_path(pkg, package_dir, src_root)) - for pkg in sorted(packages) - } - - return _remove_nested(pkg_roots) - - -def _absolute_root(path: _Path) -> str: - """Works for packages and top-level modules""" - path_ = Path(path) - parent = path_.parent - - if path_.exists(): - return str(path_.resolve()) - else: - return str(parent.resolve() / path_.name) - - -def _find_virtual_namespaces(pkg_roots: Dict[str, str]) -> Iterator[str]: - """By carefully designing ``package_dir``, it is possible to implement the logical - structure of PEP 420 in a package without the corresponding directories. - - Moreover a parent package can be purposefully/accidentally skipped in the discovery - phase (e.g. ``find_packages(include=["mypkg.*"])``, when ``mypkg.foo`` is included - by ``mypkg`` itself is not). - We consider this case to also be a virtual namespace (ignoring the original - directory) to emulate a non-editable installation. - - This function will try to find these kinds of namespaces. - """ - for pkg in pkg_roots: - if "." not in pkg: - continue - parts = pkg.split(".") - for i in range(len(parts) - 1, 0, -1): - partial_name = ".".join(parts[:i]) - path = Path(find_package_path(partial_name, pkg_roots, "")) - if not path.exists() or partial_name not in pkg_roots: - # partial_name not in pkg_roots ==> purposefully/accidentally skipped - yield partial_name - - -def _find_namespaces( - packages: List[str], pkg_roots: Dict[str, str] -) -> Iterator[Tuple[str, List[str]]]: - for pkg in packages: - path = find_package_path(pkg, pkg_roots, "") - if Path(path).exists() and not Path(path, "__init__.py").exists(): - yield (pkg, [path]) - - -def _remove_nested(pkg_roots: Dict[str, str]) -> Dict[str, str]: - output = dict(pkg_roots.copy()) - - for pkg, path in reversed(list(pkg_roots.items())): - if any( - pkg != other and _is_nested(pkg, path, other, other_path) - for other, other_path in pkg_roots.items() - ): - output.pop(pkg) - - return output - - -def _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool: - """ - Return ``True`` if ``pkg`` is nested inside ``parent`` both logically and in the - file system. - >>> _is_nested("a.b", "path/a/b", "a", "path/a") - True - >>> _is_nested("a.b", "path/a/b", "a", "otherpath/a") - False - >>> _is_nested("a.b", "path/a/b", "c", "path/c") - False - >>> _is_nested("a.a", "path/a/a", "a", "path/a") - True - >>> _is_nested("b.a", "path/b/a", "a", "path/a") - False - """ - norm_pkg_path = _normalize_path(pkg_path) - rest = pkg.replace(parent, "", 1).strip(".").split(".") - return ( - pkg.startswith(parent) - and norm_pkg_path == _normalize_path(Path(parent_path, *rest)) - ) - - -def _normalize_path(filename: _Path) -> str: - """Normalize a file/dir name for comparison purposes""" - # See pkg_resources.normalize_path - file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename - return os.path.normcase(os.path.realpath(os.path.normpath(file))) - - -def _empty_dir(dir_: _P) -> _P: - """Create a directory ensured to be empty. Existing files may be removed.""" - shutil.rmtree(dir_, ignore_errors=True) - os.makedirs(dir_) - return dir_ - - -def _make_identifier(name: str) -> str: - """Make a string safe to be used as Python identifier. - >>> _make_identifier("12abc") - '_12abc' - >>> _make_identifier("__editable__.myns.pkg-78.9.3_local") - '__editable___myns_pkg_78_9_3_local' - """ - safe = re.sub(r'\W|^(?=\d)', '_', name) - assert safe.isidentifier() - return safe - - -class _NamespaceInstaller(namespaces.Installer): - def __init__(self, distribution, installation_dir, editable_name, src_root): - self.distribution = distribution - self.src_root = src_root - self.installation_dir = installation_dir - self.editable_name = editable_name - self.outputs = [] - self.dry_run = False - - def _get_target(self): - """Installation target.""" - return os.path.join(self.installation_dir, self.editable_name) - - def _get_root(self): - """Where the modules/packages should be loaded from.""" - return repr(str(self.src_root)) - - -_FINDER_TEMPLATE = """\ -import sys -from importlib.machinery import ModuleSpec -from importlib.machinery import all_suffixes as module_suffixes -from importlib.util import spec_from_file_location -from itertools import chain -from pathlib import Path - -MAPPING = {mapping!r} -NAMESPACES = {namespaces!r} -PATH_PLACEHOLDER = {name!r} + ".__path_hook__" - - -class _EditableFinder: # MetaPathFinder - @classmethod - def find_spec(cls, fullname, path=None, target=None): - for pkg, pkg_path in reversed(list(MAPPING.items())): - if fullname == pkg or fullname.startswith(f"{{pkg}}."): - rest = fullname.replace(pkg, "", 1).strip(".").split(".") - return cls._find_spec(fullname, Path(pkg_path, *rest)) - - return None - - @classmethod - def _find_spec(cls, fullname, candidate_path): - init = candidate_path / "__init__.py" - candidates = (candidate_path.with_suffix(x) for x in module_suffixes()) - for candidate in chain([init], candidates): - if candidate.exists(): - return spec_from_file_location(fullname, candidate) - - -class _EditableNamespaceFinder: # PathEntryFinder - @classmethod - def _path_hook(cls, path): - if path == PATH_PLACEHOLDER: - return cls - raise ImportError - - @classmethod - def _paths(cls, fullname): - # Ensure __path__ is not empty for the spec to be considered a namespace. - return NAMESPACES[fullname] or MAPPING.get(fullname) or [PATH_PLACEHOLDER] - - @classmethod - def find_spec(cls, fullname, target=None): - if fullname in NAMESPACES: - spec = ModuleSpec(fullname, None, is_package=True) - spec.submodule_search_locations = cls._paths(fullname) - return spec - return None - - @classmethod - def find_module(cls, fullname): - return None - - -def install(): - if not any(finder == _EditableFinder for finder in sys.meta_path): - sys.meta_path.append(_EditableFinder) - - if not NAMESPACES: - return - - if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks): - # PathEntryFinder is needed to create NamespaceSpec without private APIS - sys.path_hooks.append(_EditableNamespaceFinder._path_hook) - if PATH_PLACEHOLDER not in sys.path: - sys.path.append(PATH_PLACEHOLDER) # Used just to trigger the path hook -""" - - -def _finder_template( - name: str, mapping: Mapping[str, str], namespaces: Dict[str, List[str]] -) -> str: - """Create a string containing the code for the``MetaPathFinder`` and - ``PathEntryFinder``. - """ - mapping = dict(sorted(mapping.items(), key=lambda p: p[0])) - return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces) - - -class InformationOnly(UserWarning): - """Currently there is no clear way of displaying messages to the users - that use the setuptools backend directly via ``pip``. - The only thing that might work is a warning, although it is not the - most appropriate tool for the job... - """ - - -class LinksNotSupported(errors.FileError): - """File system does not seem to support either symlinks or hard links.""" diff --git a/spaces/Bart92/RVC_HF/infer/lib/uvr5_pack/lib_v5/nets.py b/spaces/Bart92/RVC_HF/infer/lib/uvr5_pack/lib_v5/nets.py deleted file mode 100644 index 5da3948c2f2e9edcc3cdac49bdf9f738e403de40..0000000000000000000000000000000000000000 --- a/spaces/Bart92/RVC_HF/infer/lib/uvr5_pack/lib_v5/nets.py +++ /dev/null @@ -1,123 +0,0 @@ -import layers -import torch -import torch.nn.functional as F -from torch import nn - -from . import spec_utils - - -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, 16) - self.stg1_high_band_net = BaseASPPNet(2, 16) - - self.stg2_bridge = layers.Conv2DBNActiv(18, 8, 1, 1, 0) - self.stg2_full_band_net = BaseASPPNet(8, 16) - - self.stg3_bridge = layers.Conv2DBNActiv(34, 16, 1, 1, 0) - self.stg3_full_band_net = BaseASPPNet(16, 32) - - self.out = nn.Conv2d(32, 2, 1, bias=False) - self.aux1_out = nn.Conv2d(16, 2, 1, bias=False) - self.aux2_out = nn.Conv2d(16, 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/Bart92/RVC_HF/lib/infer_pack/models_dml.py b/spaces/Bart92/RVC_HF/lib/infer_pack/models_dml.py deleted file mode 100644 index 958d7b29259763d2fea94caf8ba7e314c4a77d05..0000000000000000000000000000000000000000 --- a/spaces/Bart92/RVC_HF/lib/infer_pack/models_dml.py +++ /dev/null @@ -1,1124 +0,0 @@ -import math, pdb, os -from time import time as ttime -import torch -from torch import nn -from torch.nn import functional as F -from lib.infer_pack import modules -from lib.infer_pack import attentions -from lib.infer_pack import commons -from lib.infer_pack.commons import init_weights, get_padding -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm -from lib.infer_pack.commons import init_weights -import numpy as np -from lib.infer_pack import commons - - -class TextEncoder256(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(256, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class TextEncoder768(nn.Module): - def __init__( - self, - out_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=True, - ): - super().__init__() - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.emb_phone = nn.Linear(768, hidden_channels) - self.lrelu = nn.LeakyReLU(0.1, inplace=True) - if f0 == True: - self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256 - self.encoder = attentions.Encoder( - hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, phone, pitch, lengths): - if pitch == None: - x = self.emb_phone(phone) - else: - x = self.emb_phone(phone) + self.emb_pitch(pitch) - x = x * math.sqrt(self.hidden_channels) # [b, t, h] - x = self.lrelu(x) - x = torch.transpose(x, 1, -1) # [b, h, t] - x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.encoder(x * x_mask, x_mask) - stats = self.proj(x) * x_mask - - m, logs = torch.split(stats, self.out_channels, dim=1) - return m, logs, x_mask - - -class ResidualCouplingBlock(nn.Module): - def __init__( - self, - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - n_flows=4, - gin_channels=0, - ): - super().__init__() - self.channels = channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.n_flows = n_flows - self.gin_channels = gin_channels - - self.flows = nn.ModuleList() - for i in range(n_flows): - self.flows.append( - modules.ResidualCouplingLayer( - channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - mean_only=True, - ) - ) - self.flows.append(modules.Flip()) - - def forward(self, x, x_mask, g=None, reverse=False): - if not reverse: - for flow in self.flows: - x, _ = flow(x, x_mask, g=g, reverse=reverse) - else: - for flow in reversed(self.flows): - x = flow(x, x_mask, g=g, reverse=reverse) - return x - - def remove_weight_norm(self): - for i in range(self.n_flows): - self.flows[i * 2].remove_weight_norm() - - -class PosteriorEncoder(nn.Module): - def __init__( - self, - in_channels, - out_channels, - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=0, - ): - super().__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.hidden_channels = hidden_channels - self.kernel_size = kernel_size - self.dilation_rate = dilation_rate - self.n_layers = n_layers - self.gin_channels = gin_channels - - self.pre = nn.Conv1d(in_channels, hidden_channels, 1) - self.enc = modules.WN( - hidden_channels, - kernel_size, - dilation_rate, - n_layers, - gin_channels=gin_channels, - ) - self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1) - - def forward(self, x, x_lengths, g=None): - x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to( - x.dtype - ) - x = self.pre(x) * x_mask - x = self.enc(x, x_mask, g=g) - stats = self.proj(x) * x_mask - m, logs = torch.split(stats, self.out_channels, dim=1) - z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask - return z, m, logs, x_mask - - def remove_weight_norm(self): - self.enc.remove_weight_norm() - - -class Generator(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=0, - ): - super(Generator, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - def forward(self, x, g=None): - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -class SineGen(torch.nn.Module): - """Definition of sine generator - SineGen(samp_rate, harmonic_num = 0, - sine_amp = 0.1, noise_std = 0.003, - voiced_threshold = 0, - flag_for_pulse=False) - samp_rate: sampling rate in Hz - harmonic_num: number of harmonic overtones (default 0) - sine_amp: amplitude of sine-wavefrom (default 0.1) - noise_std: std of Gaussian noise (default 0.003) - voiced_thoreshold: F0 threshold for U/V classification (default 0) - flag_for_pulse: this SinGen is used inside PulseGen (default False) - Note: when flag_for_pulse is True, the first time step of a voiced - segment is always sin(np.pi) or cos(0) - """ - - def __init__( - self, - samp_rate, - harmonic_num=0, - sine_amp=0.1, - noise_std=0.003, - voiced_threshold=0, - flag_for_pulse=False, - ): - super(SineGen, self).__init__() - self.sine_amp = sine_amp - self.noise_std = noise_std - self.harmonic_num = harmonic_num - self.dim = self.harmonic_num + 1 - self.sampling_rate = samp_rate - self.voiced_threshold = voiced_threshold - - def _f02uv(self, f0): - # generate uv signal - uv = torch.ones_like(f0) - uv = uv * (f0 > self.voiced_threshold) - return uv.float() - - def forward(self, f0, upp): - """sine_tensor, uv = forward(f0) - input F0: tensor(batchsize=1, length, dim=1) - f0 for unvoiced steps should be 0 - output sine_tensor: tensor(batchsize=1, length, dim) - output uv: tensor(batchsize=1, length, 1) - """ - with torch.no_grad(): - f0 = f0[:, None].transpose(1, 2) - f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device) - # fundamental component - f0_buf[:, :, 0] = f0[:, :, 0] - for idx in np.arange(self.harmonic_num): - f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * ( - idx + 2 - ) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic - rad_values = (f0_buf / self.sampling_rate) % 1 ###%1意味着n_har的乘积无法后处理优化 - rand_ini = torch.rand( - f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device - ) - rand_ini[:, 0] = 0 - rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini - tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1意味着后面的cumsum无法再优化 - tmp_over_one *= upp - tmp_over_one = F.interpolate( - tmp_over_one.transpose(2, 1), - scale_factor=upp, - mode="linear", - align_corners=True, - ).transpose(2, 1) - rad_values = F.interpolate( - rad_values.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose( - 2, 1 - ) ####### - tmp_over_one %= 1 - tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0 - cumsum_shift = torch.zeros_like(rad_values) - cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0 - sine_waves = torch.sin( - torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi - ) - sine_waves = sine_waves * self.sine_amp - uv = self._f02uv(f0) - uv = F.interpolate( - uv.transpose(2, 1), scale_factor=upp, mode="nearest" - ).transpose(2, 1) - noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3 - noise = noise_amp * torch.randn_like(sine_waves) - sine_waves = sine_waves * uv + noise - return sine_waves, uv, noise - - -class SourceModuleHnNSF(torch.nn.Module): - """SourceModule for hn-nsf - SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1, - add_noise_std=0.003, voiced_threshod=0) - sampling_rate: sampling_rate in Hz - harmonic_num: number of harmonic above F0 (default: 0) - sine_amp: amplitude of sine source signal (default: 0.1) - add_noise_std: std of additive Gaussian noise (default: 0.003) - note that amplitude of noise in unvoiced is decided - by sine_amp - voiced_threshold: threhold to set U/V given F0 (default: 0) - Sine_source, noise_source = SourceModuleHnNSF(F0_sampled) - F0_sampled (batchsize, length, 1) - Sine_source (batchsize, length, 1) - noise_source (batchsize, length 1) - uv (batchsize, length, 1) - """ - - def __init__( - self, - sampling_rate, - harmonic_num=0, - sine_amp=0.1, - add_noise_std=0.003, - voiced_threshod=0, - is_half=True, - ): - super(SourceModuleHnNSF, self).__init__() - - self.sine_amp = sine_amp - self.noise_std = add_noise_std - self.is_half = is_half - # to produce sine waveforms - self.l_sin_gen = SineGen( - sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod - ) - - # to merge source harmonics into a single excitation - self.l_linear = torch.nn.Linear(harmonic_num + 1, 1) - self.l_tanh = torch.nn.Tanh() - - def forward(self, x, upp=None): - sine_wavs, uv, _ = self.l_sin_gen(x, upp) - if self.is_half: - sine_wavs = sine_wavs.half() - sine_merge = self.l_tanh(self.l_linear(sine_wavs)) - return sine_merge, None, None # noise, uv - - -class GeneratorNSF(torch.nn.Module): - def __init__( - self, - initial_channel, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels, - sr, - is_half=False, - ): - super(GeneratorNSF, self).__init__() - self.num_kernels = len(resblock_kernel_sizes) - self.num_upsamples = len(upsample_rates) - - self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates)) - self.m_source = SourceModuleHnNSF( - sampling_rate=sr, harmonic_num=0, is_half=is_half - ) - self.noise_convs = nn.ModuleList() - self.conv_pre = Conv1d( - initial_channel, upsample_initial_channel, 7, 1, padding=3 - ) - resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2 - - self.ups = nn.ModuleList() - for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)): - c_cur = upsample_initial_channel // (2 ** (i + 1)) - self.ups.append( - weight_norm( - ConvTranspose1d( - upsample_initial_channel // (2**i), - upsample_initial_channel // (2 ** (i + 1)), - k, - u, - padding=(k - u) // 2, - ) - ) - ) - if i + 1 < len(upsample_rates): - stride_f0 = np.prod(upsample_rates[i + 1 :]) - self.noise_convs.append( - Conv1d( - 1, - c_cur, - kernel_size=stride_f0 * 2, - stride=stride_f0, - padding=stride_f0 // 2, - ) - ) - else: - self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1)) - - self.resblocks = nn.ModuleList() - for i in range(len(self.ups)): - ch = upsample_initial_channel // (2 ** (i + 1)) - for j, (k, d) in enumerate( - zip(resblock_kernel_sizes, resblock_dilation_sizes) - ): - self.resblocks.append(resblock(ch, k, d)) - - self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) - self.ups.apply(init_weights) - - if gin_channels != 0: - self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1) - - self.upp = np.prod(upsample_rates) - - def forward(self, x, f0, g=None): - har_source, noi_source, uv = self.m_source(f0, self.upp) - har_source = har_source.transpose(1, 2) - x = self.conv_pre(x) - if g is not None: - x = x + self.cond(g) - - for i in range(self.num_upsamples): - x = F.leaky_relu(x, modules.LRELU_SLOPE) - x = self.ups[i](x) - x_source = self.noise_convs[i](har_source) - x = x + x_source - xs = None - for j in range(self.num_kernels): - if xs is None: - xs = self.resblocks[i * self.num_kernels + j](x) - else: - xs += self.resblocks[i * self.num_kernels + j](x) - x = xs / self.num_kernels - x = F.leaky_relu(x) - x = self.conv_post(x) - x = torch.tanh(x) - return x - - def remove_weight_norm(self): - for l in self.ups: - remove_weight_norm(l) - for l in self.resblocks: - l.remove_weight_norm() - - -sr2sr = { - "32k": 32000, - "40k": 40000, - "48k": 48000, -} - - -class SynthesizerTrnMs256NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, max_len=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr, - **kwargs - ): - super().__init__() - if type(sr) == type("strr"): - sr = sr2sr[sr] - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - ) - self.dec = GeneratorNSF( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - sr=sr, - is_half=kwargs["is_half"], - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward( - self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds - ): # 这里ds是id,[bs,1] - # print(1,pitch.shape)#[bs,t] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - # print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length) - pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size) - # print(-2,pitchf.shape,z_slice.shape) - o = self.dec(z_slice, pitchf, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, pitch, nsff0, sid, max_len=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], nsff0, g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs256NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder256( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, max_len=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class SynthesizerTrnMs768NSFsid_nono(nn.Module): - def __init__( - self, - spec_channels, - segment_size, - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - spk_embed_dim, - gin_channels, - sr=None, - **kwargs - ): - super().__init__() - self.spec_channels = spec_channels - self.inter_channels = inter_channels - self.hidden_channels = hidden_channels - self.filter_channels = filter_channels - self.n_heads = n_heads - self.n_layers = n_layers - self.kernel_size = kernel_size - self.p_dropout = p_dropout - self.resblock = resblock - self.resblock_kernel_sizes = resblock_kernel_sizes - self.resblock_dilation_sizes = resblock_dilation_sizes - self.upsample_rates = upsample_rates - self.upsample_initial_channel = upsample_initial_channel - self.upsample_kernel_sizes = upsample_kernel_sizes - self.segment_size = segment_size - self.gin_channels = gin_channels - # self.hop_length = hop_length# - self.spk_embed_dim = spk_embed_dim - self.enc_p = TextEncoder768( - inter_channels, - hidden_channels, - filter_channels, - n_heads, - n_layers, - kernel_size, - p_dropout, - f0=False, - ) - self.dec = Generator( - inter_channels, - resblock, - resblock_kernel_sizes, - resblock_dilation_sizes, - upsample_rates, - upsample_initial_channel, - upsample_kernel_sizes, - gin_channels=gin_channels, - ) - self.enc_q = PosteriorEncoder( - spec_channels, - inter_channels, - hidden_channels, - 5, - 1, - 16, - gin_channels=gin_channels, - ) - self.flow = ResidualCouplingBlock( - inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels - ) - self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels) - print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim) - - def remove_weight_norm(self): - self.dec.remove_weight_norm() - self.flow.remove_weight_norm() - self.enc_q.remove_weight_norm() - - def forward(self, phone, phone_lengths, y, y_lengths, ds): # 这里ds是id,[bs,1] - g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1是t,广播的 - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g) - z_p = self.flow(z, y_mask, g=g) - z_slice, ids_slice = commons.rand_slice_segments( - z, y_lengths, self.segment_size - ) - o = self.dec(z_slice, g=g) - return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q) - - def infer(self, phone, phone_lengths, sid, max_len=None): - g = self.emb_g(sid).unsqueeze(-1) - m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths) - z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask - z = self.flow(z_p, x_mask, g=g, reverse=True) - o = self.dec((z * x_mask)[:, :, :max_len], g=g) - return o, x_mask, (z, z_p, m_p, logs_p) - - -class MultiPeriodDiscriminator(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminator, self).__init__() - periods = [2, 3, 5, 7, 11, 17] - # periods = [3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class MultiPeriodDiscriminatorV2(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(MultiPeriodDiscriminatorV2, self).__init__() - # periods = [2, 3, 5, 7, 11, 17] - periods = [2, 3, 5, 7, 11, 17, 23, 37] - - discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)] - discs = discs + [ - DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods - ] - self.discriminators = nn.ModuleList(discs) - - def forward(self, y, y_hat): - y_d_rs = [] # - y_d_gs = [] - fmap_rs = [] - fmap_gs = [] - for i, d in enumerate(self.discriminators): - y_d_r, fmap_r = d(y) - y_d_g, fmap_g = d(y_hat) - # for j in range(len(fmap_r)): - # print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape) - y_d_rs.append(y_d_r) - y_d_gs.append(y_d_g) - fmap_rs.append(fmap_r) - fmap_gs.append(fmap_g) - - return y_d_rs, y_d_gs, fmap_rs, fmap_gs - - -class DiscriminatorS(torch.nn.Module): - def __init__(self, use_spectral_norm=False): - super(DiscriminatorS, self).__init__() - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f(Conv1d(1, 16, 15, 1, padding=7)), - norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)), - norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)), - norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)), - norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)), - norm_f(Conv1d(1024, 1024, 5, 1, padding=2)), - ] - ) - self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1)) - - def forward(self, x): - fmap = [] - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap - - -class DiscriminatorP(torch.nn.Module): - def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False): - super(DiscriminatorP, self).__init__() - self.period = period - self.use_spectral_norm = use_spectral_norm - norm_f = weight_norm if use_spectral_norm == False else spectral_norm - self.convs = nn.ModuleList( - [ - norm_f( - Conv2d( - 1, - 32, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 32, - 128, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 128, - 512, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 512, - 1024, - (kernel_size, 1), - (stride, 1), - padding=(get_padding(kernel_size, 1), 0), - ) - ), - norm_f( - Conv2d( - 1024, - 1024, - (kernel_size, 1), - 1, - padding=(get_padding(kernel_size, 1), 0), - ) - ), - ] - ) - self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0))) - - def forward(self, x): - fmap = [] - - # 1d to 2d - b, c, t = x.shape - if t % self.period != 0: # pad first - n_pad = self.period - (t % self.period) - x = F.pad(x, (0, n_pad), "reflect") - t = t + n_pad - x = x.view(b, c, t // self.period, self.period) - - for l in self.convs: - x = l(x) - x = F.leaky_relu(x, modules.LRELU_SLOPE) - fmap.append(x) - x = self.conv_post(x) - fmap.append(x) - x = torch.flatten(x, 1, -1) - - return x, fmap diff --git a/spaces/Benson/text-generation/Examples/Descargar Apk Tiktok Para La Televisin Inteligente.md b/spaces/Benson/text-generation/Examples/Descargar Apk Tiktok Para La Televisin Inteligente.md deleted file mode 100644 index e443f5742de6ea97618dc48f84a308a359799397..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Apk Tiktok Para La Televisin Inteligente.md +++ /dev/null @@ -1,90 +0,0 @@ - -

Cómo descargar TikTok APK para Smart TV

-

TikTok es una de las aplicaciones de redes sociales más populares del mundo, con más de mil millones de usuarios activos mensuales. Te permite crear y ver videos cortos que son divertidos, genuinos y creativos. ¿Pero sabías que también puedes ver TikTok en tu smart TV?

-

descargar apk tiktok para la televisión inteligente


Download Ziphttps://bltlly.com/2v6Jfs



-

Ver TikTok en tu smart TV puede darte una mejor experiencia de visualización y más contenido divertido. Puede disfrutar de los videos de TikTok en una pantalla más grande y clara, verlos con sus amigos y familiares y descubrir más categorías que se adapten a sus intereses.

-

En este artículo, le mostraremos cómo descargar TikTok APK para Smart TV usando tres métodos diferentes. También explicaremos los beneficios de ver TikTok en su televisor inteligente y responderemos algunas preguntas frecuentes.

-

¿Qué es TikTok y por qué debe verlo en su televisor inteligente

-

TikTok es una popular aplicación de redes sociales que te permite crear y ver videos cortos

-

TikTok es una aplicación que te permite crear y ver videos cortos que suelen durar entre 15 segundos y 3 minutos. Puedes usar varios filtros, efectos, música, pegatinas y hashtags para hacer tus videos más atractivos y entretenidos.

-

-

También puedes explorar videos de otros usuarios alrededor del mundo, basado en lo que te gusta, seguir o compartir. Puedes encontrar videos de varias categorías, como comedia, juegos, bricolaje, comida, deportes, memes, mascotas, ASMR, y más.

-

Ver TikTok en su televisor inteligente puede darle una mejor experiencia de visualización y más contenido divertido

-

Si bien TikTok está diseñado para dispositivos móviles, también puede verlo en su televisor inteligente. Esto puede darle varias ventajas, como:

-
    -
  • Puede disfrutar de los vídeos de TikTok en una pantalla más grande y clara, que puede mejorar la calidad visual y los detalles de los vídeos.
  • -
  • Puedes ver TikTok con tus amigos y familiares, lo que puede hacerlo más divertido y social. También puede comentar o compartir los vídeos que ven juntos.
  • - -

    Opción 2: Emitir o reflejar TikTok desde su teléfono, tableta o computadora a su televisor

    -

    Esta opción funciona para cualquier televisor inteligente que admita el uso compartido de pantalla inalámbrica. Puede lanzar o reflejar TikTok desde su teléfono, tableta o computadora a su televisor utilizando una aplicación de reflejo de pantalla. Aquí está cómo hacerlo:

    -
      -
    1. Descargar e instalar una aplicación de reflejo de pantalla en ambos dispositivos. Algunos ejemplos de aplicaciones de reflejo de pantalla son AirScreen, Miracast, , AllCast, y Google Home.
    2. -
    3. Conecte ambos dispositivos a la misma red Wi-Fi.
    4. -
    5. Abra la aplicación de reflejo de pantalla en ambos dispositivos y siga las instrucciones para emparejarlos.
    6. -
    7. Abra la aplicación TikTok en su teléfono, tableta o computadora y comience a reproducir un video.
    8. -
    9. El vídeo debe aparecer en la pantalla del televisor. Puede controlar la reproducción desde su dispositivo.
    10. -
    11. Disfruta viendo vídeos de TikTok en tu smart TV.
    12. -
    -

    Necesitas instalar una aplicación de reflejo de pantalla en ambos dispositivos y conectarlos a la misma red Wi-Fi

    -

    Antes de que pueda lanzar o reflejar TikTok desde su dispositivo a su televisor, debe instalar una aplicación de reflejo de pantalla en ambos dispositivos. Una aplicación de reflejo de pantalla le permite compartir la pantalla de un dispositivo con otro dispositivo de forma inalámbrica. Puede encontrar muchas aplicaciones de reflejo de pantalla en la tienda de aplicaciones de su dispositivo.

    -

    También necesitas conectar ambos dispositivos a la misma red Wi-Fi. Esto asegura que pueden comunicarse entre sí y transmitir el video sin problemas. Para hacer esto, siga estos pasos:

    -
      -
    • Vaya al menú Configuración en ambos dispositivos y seleccione Wi-Fi.
    • -
    • Encuentre y seleccione la misma red Wi-Fi de la lista de redes disponibles.
    • -
    • Introduzca la contraseña si es necesario y conéctese a la red.
    • -
    • Compruebe que ambos dispositivos están conectados a la misma red.
    • -
    -

    Opción 3: Conecte su dispositivo a su televisor con un cable HDMI

    - -
      -
    1. Obtenga un cable HDMI compatible con ambos dispositivos. Es posible que necesite un adaptador si su dispositivo no tiene un puerto HDMI.
    2. -
    3. Conecte un extremo del cable HDMI en el puerto HDMI de su dispositivo.
    4. -
    5. Conecte el otro extremo del cable HDMI en el puerto HDMI de su TV.
    6. -
    7. Encienda ambos dispositivos y cambie la fuente de entrada en su TV a HDMI.
    8. -
    9. Abra la aplicación TikTok en su dispositivo y comience a reproducir un video.
    10. -
    11. El vídeo debe aparecer en la pantalla del televisor. Puede controlar la reproducción desde su dispositivo.
    12. -
    13. Disfruta viendo vídeos de TikTok en tu smart TV.
    14. -
    -

    Necesitas tener un cable HDMI y cambiar la fuente de entrada en tu TV

    -

    Un cable HDMI es un tipo de cable que puede transmitir señales de vídeo y audio de alta definición entre dispositivos. Puede usarlo para conectar su dispositivo a su televisor y ver videos TikTok en una pantalla más grande. Puede comprar un cable HDMI en cualquier tienda de electrónica o en línea.

    -

    También necesita cambiar la fuente de entrada de su TV a HDMI. Esto le dice a su televisor qué dispositivo mostrar en la pantalla. Para hacer esto, siga estos pasos:

    -
      -
    • Encuentra el botón Input, Source, o Menu en tu control remoto de TV y presiónalo.
    • -
    • Seleccione HDMI de la lista de fuentes de entrada usando las teclas de flecha o el botón OK en su control remoto.
    • -
    • Confirme su elección y salga del menú de entrada.
    • -
    • Compruebe que el dispositivo se muestra en la pantalla del televisor.
    • -
    -

    Beneficios de ver TikTok en tu smart TV

    -

    Ver TikTok en tu smart TV puede ofrecerte muchos beneficios, como:

    -

    Puedes disfrutar de los vídeos de TikTok en una pantalla más grande y clara

    - -

    Puedes ver TikTok con tus amigos y familiares y divertirte más

    -

    Otro beneficio de ver TikTok en tu smart TV es que puedes verlo con tus amigos y familiares y divertirte más. Puedes compartir los videos que te gustan, comentarlos o incluso crear tus propios videos juntos. También puede utilizar la aplicación de televisión inteligente para navegar por diferentes categorías y descubrir nuevo contenido que puede no encontrar en la aplicación móvil.

    -

    Puedes descubrir más contenido y categorías que se adapten a tus intereses

    -

    Un tercer beneficio de ver TikTok en tu smart TV es que puedes descubrir más contenido y categorías que se adapten a tus intereses. Algunas categorías pueden no estar disponibles en la aplicación móvil, pero puedes encontrarlas en la aplicación de televisión inteligente. Por ejemplo, puedes ver videos de la categoría TikTok TV, que incluye contenido seleccionado de creadores y celebridades populares. También puede utilizar la función de búsqueda para encontrar vídeos por palabras clave, hashtags o nombres de usuario.

    -

    Conclusión

    -

    TikTok es una popular aplicación de redes sociales que te permite crear y ver videos cortos que son divertidos, genuinos y creativos. También puede ver TikTok en su televisor inteligente utilizando tres métodos diferentes: instalar la aplicación TikTok TV desde la tienda de aplicaciones en su TV, emitir o duplicar TikTok desde su dispositivo a su TV, o conectar su dispositivo a su TV con un cable HDMI.

    -

    Ver TikTok en tu smart TV puede darte una mejor experiencia de visualización y más contenido divertido. Puede disfrutar de los videos de TikTok en una pantalla más grande y clara, verlos con sus amigos y familiares y descubrir más categorías que se adapten a sus intereses.

    -

    Entonces, ¿qué estás esperando? ¡Prueba a ver TikTok en tu smart TV hoy y comprueba por ti mismo lo divertido que puede ser!

    -

    Preguntas frecuentes

    -

    Q1. ¿Es TikTok gratis para ver en la televisión inteligente?

    - -

    Q2. ¿Cómo puedo controlar TikTok en mi smart TV?

    -

    A2. Puedes controlar TikTok en tu smart TV usando diferentes métodos, dependiendo de cómo lo hayas instalado. Si ha instalado la aplicación TikTok TV desde la tienda de aplicaciones en su televisor, puede usar el control remoto de su televisor para navegar por la aplicación y reproducir los videos. Si lanzas o reflejas TikTok desde tu dispositivo a tu televisor, puedes usar el dispositivo como control remoto y reproducir los videos desde allí. Si conecta su dispositivo a su televisor con un cable HDMI, también puede usar el dispositivo como control remoto.

    -

    Q3. ¿Puedo crear vídeos TikTok en mi smart TV?

    -

    A3. No, no puede crear vídeos TikTok en su televisor inteligente. Solo puede ver vídeos TikTok en su televisor inteligente. Para crear vídeos TikTok, necesitas usar la aplicación móvil en tu teléfono o tablet.

    -

    Q4. ¿Cómo puedo ajustar la calidad de vídeo y el sonido de TikTok en mi smart TV?

    -

    A4. Puede ajustar la calidad de vídeo y el sonido de TikTok en su televisor inteligente utilizando el menú de configuración de su televisor o la aplicación de reflejo de pantalla. Puede cambiar la resolución, relación de aspecto, brillo, contraste, color, volumen y otras opciones para adaptarse a sus preferencias.

    -

    Q5. ¿Cuáles son algunas de las mejores categorías para ver en TikTok en mi smart TV?

    -

    A5. Algunas de las mejores categorías para ver en TikTok en mi smart TV son:

    -
      -
    • TikTok TV: Esta categoría presenta contenido curado de creadores populares y celebridades que son adecuados para ver en una pantalla más grande.
    • -
    • Comedia : Esta categoría presenta videos hilarantes que pueden hacerte reír en voz alta y alegrar tu estado de ánimo.
    • -
    • Gaming: Esta categoría presenta videos de jugadores que muestran sus habilidades, consejos, trucos y reseñas de varios juegos.
    • -
    • DIY: Esta categoría presenta videos de creadores que comparten sus ideas creativas, proyectos, hacks y artesanías que puedes probar en casa.
    • - -
    • Deportes: Esta categoría presenta videos de atletas y entusiastas del deporte que comparten sus aspectos más destacados, fracasos, consejos y desafíos de varios deportes y actividades.
    • -
    -

    Estas son solo algunas de las categorías que puedes ver en TikTok en tu smart TV. También puedes encontrar muchas otras categorías que coinciden con tus intereses y preferencias.

    64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Benson/text-generation/Examples/Descargar Chicos Stumble Mod Apkmody.md b/spaces/Benson/text-generation/Examples/Descargar Chicos Stumble Mod Apkmody.md deleted file mode 100644 index 746a8ef29f9928d25ddfbc132356fdc932bd82a1..0000000000000000000000000000000000000000 --- a/spaces/Benson/text-generation/Examples/Descargar Chicos Stumble Mod Apkmody.md +++ /dev/null @@ -1,81 +0,0 @@ - -

    Cómo descargar Stumble Guys Mod Apkmody y disfrutar de diversión ilimitada

    -

    ¿Te encanta jugar juegos de fiesta en línea con tus amigos? ¿Quieres experimentar la emoción de competir contra hasta 32 jugadores en caóticas carreras de obstáculos? ¿Quieres personalizar tu personaje con trajes y emotes impresionantes? Si respondiste sí a cualquiera de estas preguntas, entonces definitivamente deberías probar Stumble Guys, un juego multijugador gratuito para dispositivos Android e iOS. Y si quieres que tu juego sea aún más divertido y emocionante, entonces deberías descargar Stumble Guys Mod Apkmody, una versión modificada del juego que te da dinero ilimitado, gemas y atuendos. En este artículo, le mostraremos cómo descargar e instalar Stumble Guys Mod Apkmody en su dispositivo, y cómo jugar con algunos consejos y trucos. ¡Vamos a empezar!

    -

    descargar chicos stumble mod apkmody


    Download Zip 🗹 https://bltlly.com/2v6JFl



    -

    ¿Qué es Stumble Guys?

    -

    Una breve introducción al juego y sus características

    -

    Stumble Guys es un juego multijugador masivo que se inspira en los populares Fall Guys. El juego consta de varios minijuegos que ponen a prueba tus habilidades, reflejos y suerte. Tienes que correr, saltar, correr, deslizarte y evitar obstáculos mientras compites con hasta 32 jugadores en línea. El último jugador en pie gana la corona y la gloria.

    -

    Stumble Guys tiene muchas características que lo convierten en un juego divertido y adictivo. Algunas de ellas son:

    -
      -
    • 17 carreras de obstáculos únicas que cambian cada ronda
    • -
    • Gráficos y animaciones coloridos, caprichosos e hilarantes
    • -
    • Juego basado en la física que crea situaciones impredecibles
    • -
    • Modo multijugador en línea que te permite jugar con amigos o extraños
    • -
    • Modo de fiesta que te permite crear partidos privados con tus amigos
    • -
    • Una variedad de trajes desbloqueables y emotes que te permiten expresarte
    • -
    -

    ¿Qué es Stumble Guys Mod Apkmody?

    -

    Una versión modificada del juego que ofrece dinero ilimitado, gemas y atuendos

    - -
      -
    • Dinero ilimitado y gemas que te permiten comprar cualquier cosa en la tienda
    • -
    • Todos los conjuntos desbloqueados que te permiten vestir a tu personaje como quieras
    • -
    • No hay anuncios que interrumpan tu juego
    • -
    • No se requiere root ni jailbreak para instalar el mod
    • -
    -

    Con Stumble Guys Mod Apkmody, puedes disfrutar del juego sin limitaciones ni restricciones. Puedes personalizar a tu personaje con cualquier atuendo que te guste, desde superhéroes hasta animales y alimentos. También puedes comprar cualquier emote que quieras, desde bailes hasta burlas y gestos. También puedes usar tu dinero y gemas para comprar vidas extra o saltar niveles si te quedas atascado.

    -

    ¿Cómo descargar e instalar Stumble Guys Mod Apkmody?

    -

    Una guía paso a paso con capturas de pantalla

    -

    Si desea descargar e instalar Stumble Guys Mod Apkmody en su dispositivo, debe seguir estos sencillos pasos:

    -
      -
    1. Haga clic en este enlace para ir a la página de descarga de Stumble Guys Mod Apkmody.
    2. -
    3. Haga clic en el botón de descarga en la parte superior de la página para descargar el archivo apk mod.
    4. -
    5. Guarde el archivo en la carpeta de descarga de su dispositivo.
    6. -
    7. Ve a la configuración de tu dispositivo y habilita la instalación de aplicaciones desde fuentes desconocidas.
    8. -
    9. Busque el archivo apk mod en su carpeta de descarga y toque en él para instalarlo.
    10. -
    11. Espera a que termine la instalación y luego abre el juego.
    12. -
    13. Disfruta jugando Stumble Guys Mod Apkmody con dinero ilimitado, gemas y trajes.
    14. -
    -

    Aquí hay algunas capturas de pantalla del proceso de descarga e instalación:

    - - -Descargar página -Botón de descarga -Descargar carpeta - - -Fuentes desconocidas -Instalar mod apk -Abrir juego - - -

    Cómo jugar Stumble chicos Mod Apkmody?

    -

    Algunos consejos y trucos para ganar todos tus partidos

    - -
      -
    • Elige tu atuendo sabiamente. Algunos trajes son más adecuados para ciertos minijuegos que otros. Por ejemplo, un traje de superhéroe podría ayudarte a volar sobre los obstáculos, mientras que un traje de plátano podría hacerte resbalar y caer.
    • -
    • Usa tus emotes estratégicamente. Puedes usar tus emotes para comunicarte con otros jugadores, o para distraerlos o burlarte de ellos. Por ejemplo, puedes usar un emote de baile para celebrar tu victoria, o un emote de risa para burlarte de tus oponentes.
    • -
    • Aprende los mapas y los obstáculos. Cada minijuego tiene un mapa diferente y un conjunto diferente de obstáculos. Necesitas aprender a navegar y evitarlos. Por ejemplo, necesitas saber cuándo saltar, cuándo deslizarte, cuándo esquivar y cuándo empujar.
    • -
    • Sé rápido y ágil. Necesitas ser rápido y ágil para sobrevivir y ganar. Necesitas moverte rápido, cambiar de dirección y reaccionar ante las situaciones. Por ejemplo, necesitas correr cuando hay una abertura, o saltar cuando hay una brecha.
    • -
    • Sé inteligente y astuto. Necesitas usar tu cerebro y tus habilidades para ser más astuto y superar a tus oponentes. Necesitas planificar tus movimientos, anticipar sus movimientos y explotar sus debilidades. Por ejemplo, necesitas usar atajos, trampas o trabajo en equipo.
    • -
    -

    Conclusión

    -

    Un resumen de los puntos principales y una llamada a la acción

    - -

    Preguntas frecuentes

    -

    Cinco preguntas y respuestas comunes sobre Stumble Guys Mod Apkmody

    -
      -
    1. ¿Es seguro Stumble Guys Mod Apkmody?
    2. -

      Sí, Stumble Guys Mod Apkmody es seguro para descargar e instalar en su dispositivo. No contiene ningún virus o malware que pueda dañar su dispositivo o comprometer su privacidad. Sin embargo, siempre debe descargarlo de una fuente confiable como , y escanearlo con un antivirus antes de instalarlo.

      -
    3. Es Stumble Guys Mod Apkmody compatible con mi dispositivo?
    4. -

      Stumble Guys Mod Apkmody es compatible con la mayoría de los dispositivos Android que se ejecutan en Android 5.0 o superior. Sin embargo, algunos dispositivos pueden no ser compatibles con el mod o pueden experimentar algunos fallos o errores durante la reproducción. Si eso sucede, puede intentar desinstalar y reinstalar el mod, o ponerse en contacto con el desarrollador para obtener soporte.

      -
    5. ¿Puedo jugar a Stumble Guys Mod Apkmody con mis amigos?
    6. -

      Sí, puedes jugar Stumble Guys Mod Apkmody con tus amigos en línea o fuera de línea. Puede unirse al modo multijugador en línea e invitar a sus amigos a unirse a su partido, o crear un partido privado con un código. También puedes jugar el modo fiesta y conectar con tus amigos a través de Bluetooth o Wi-Fi.

      -

      -
    7. ¿Me prohibirán por usar Stumble Guys Mod Apkmody?
    8. -

      No, no te prohibirán el uso de Stumble Guys Mod Apkmody. El mod no interfiere con los servidores del juego ni con las cuentas de otros jugadores. Solo modifica tus propios datos y recursos de juego. Sin embargo, debes usar el mod de forma responsable y respetuosa, y no abusar de él o hacer trampa en el juego.

      -
    9. ¿Cómo puedo actualizar Stumble Guys Mod Apkmody?
    10. - -

    64aa2da5cf
    -
    -
    \ No newline at end of file diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/colorama/win32.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/colorama/win32.py deleted file mode 100644 index 841b0e270a381cdfaca544a9be976d7276d83b1e..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/colorama/win32.py +++ /dev/null @@ -1,180 +0,0 @@ -# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. - -# from winbase.h -STDOUT = -11 -STDERR = -12 - -ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 - -try: - import ctypes - from ctypes import LibraryLoader - windll = LibraryLoader(ctypes.WinDLL) - from ctypes import wintypes -except (AttributeError, ImportError): - windll = None - SetConsoleTextAttribute = lambda *_: None - winapi_test = lambda *_: None -else: - from ctypes import byref, Structure, c_char, POINTER - - COORD = wintypes._COORD - - class CONSOLE_SCREEN_BUFFER_INFO(Structure): - """struct in wincon.h.""" - _fields_ = [ - ("dwSize", COORD), - ("dwCursorPosition", COORD), - ("wAttributes", wintypes.WORD), - ("srWindow", wintypes.SMALL_RECT), - ("dwMaximumWindowSize", COORD), - ] - def __str__(self): - return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % ( - self.dwSize.Y, self.dwSize.X - , self.dwCursorPosition.Y, self.dwCursorPosition.X - , self.wAttributes - , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right - , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X - ) - - _GetStdHandle = windll.kernel32.GetStdHandle - _GetStdHandle.argtypes = [ - wintypes.DWORD, - ] - _GetStdHandle.restype = wintypes.HANDLE - - _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo - _GetConsoleScreenBufferInfo.argtypes = [ - wintypes.HANDLE, - POINTER(CONSOLE_SCREEN_BUFFER_INFO), - ] - _GetConsoleScreenBufferInfo.restype = wintypes.BOOL - - _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute - _SetConsoleTextAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - ] - _SetConsoleTextAttribute.restype = wintypes.BOOL - - _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition - _SetConsoleCursorPosition.argtypes = [ - wintypes.HANDLE, - COORD, - ] - _SetConsoleCursorPosition.restype = wintypes.BOOL - - _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA - _FillConsoleOutputCharacterA.argtypes = [ - wintypes.HANDLE, - c_char, - wintypes.DWORD, - COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputCharacterA.restype = wintypes.BOOL - - _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute - _FillConsoleOutputAttribute.argtypes = [ - wintypes.HANDLE, - wintypes.WORD, - wintypes.DWORD, - COORD, - POINTER(wintypes.DWORD), - ] - _FillConsoleOutputAttribute.restype = wintypes.BOOL - - _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW - _SetConsoleTitleW.argtypes = [ - wintypes.LPCWSTR - ] - _SetConsoleTitleW.restype = wintypes.BOOL - - _GetConsoleMode = windll.kernel32.GetConsoleMode - _GetConsoleMode.argtypes = [ - wintypes.HANDLE, - POINTER(wintypes.DWORD) - ] - _GetConsoleMode.restype = wintypes.BOOL - - _SetConsoleMode = windll.kernel32.SetConsoleMode - _SetConsoleMode.argtypes = [ - wintypes.HANDLE, - wintypes.DWORD - ] - _SetConsoleMode.restype = wintypes.BOOL - - def _winapi_test(handle): - csbi = CONSOLE_SCREEN_BUFFER_INFO() - success = _GetConsoleScreenBufferInfo( - handle, byref(csbi)) - return bool(success) - - def winapi_test(): - return any(_winapi_test(h) for h in - (_GetStdHandle(STDOUT), _GetStdHandle(STDERR))) - - def GetConsoleScreenBufferInfo(stream_id=STDOUT): - handle = _GetStdHandle(stream_id) - csbi = CONSOLE_SCREEN_BUFFER_INFO() - success = _GetConsoleScreenBufferInfo( - handle, byref(csbi)) - return csbi - - def SetConsoleTextAttribute(stream_id, attrs): - handle = _GetStdHandle(stream_id) - return _SetConsoleTextAttribute(handle, attrs) - - def SetConsoleCursorPosition(stream_id, position, adjust=True): - position = COORD(*position) - # If the position is out of range, do nothing. - if position.Y <= 0 or position.X <= 0: - return - # Adjust for Windows' SetConsoleCursorPosition: - # 1. being 0-based, while ANSI is 1-based. - # 2. expecting (x,y), while ANSI uses (y,x). - adjusted_position = COORD(position.Y - 1, position.X - 1) - if adjust: - # Adjust for viewport's scroll position - sr = GetConsoleScreenBufferInfo(STDOUT).srWindow - adjusted_position.Y += sr.Top - adjusted_position.X += sr.Left - # Resume normal processing - handle = _GetStdHandle(stream_id) - return _SetConsoleCursorPosition(handle, adjusted_position) - - def FillConsoleOutputCharacter(stream_id, char, length, start): - handle = _GetStdHandle(stream_id) - char = c_char(char.encode()) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - success = _FillConsoleOutputCharacterA( - handle, char, length, start, byref(num_written)) - return num_written.value - - def FillConsoleOutputAttribute(stream_id, attr, length, start): - ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )''' - handle = _GetStdHandle(stream_id) - attribute = wintypes.WORD(attr) - length = wintypes.DWORD(length) - num_written = wintypes.DWORD(0) - # Note that this is hard-coded for ANSI (vs wide) bytes. - return _FillConsoleOutputAttribute( - handle, attribute, length, start, byref(num_written)) - - def SetConsoleTitle(title): - return _SetConsoleTitleW(title) - - def GetConsoleMode(handle): - mode = wintypes.DWORD() - success = _GetConsoleMode(handle, byref(mode)) - if not success: - raise ctypes.WinError() - return mode.value - - def SetConsoleMode(handle, mode): - success = _SetConsoleMode(handle, mode) - if not success: - raise ctypes.WinError() diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/box.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/box.py deleted file mode 100644 index 97d2a94445770e195b9fc73e904b920d5ff04104..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/box.py +++ /dev/null @@ -1,517 +0,0 @@ -import sys -from typing import TYPE_CHECKING, Iterable, List - -if sys.version_info >= (3, 8): - from typing import Literal -else: - from pip._vendor.typing_extensions import Literal # pragma: no cover - - -from ._loop import loop_last - -if TYPE_CHECKING: - from pip._vendor.rich.console import ConsoleOptions - - -class Box: - """Defines characters to render boxes. - - ┌─┬┐ top - │ ││ head - ├─┼┤ head_row - │ ││ mid - ├─┼┤ row - ├─┼┤ foot_row - │ ││ foot - └─┴┘ bottom - - Args: - box (str): Characters making up box. - ascii (bool, optional): True if this box uses ascii characters only. Default is False. - """ - - def __init__(self, box: str, *, ascii: bool = False) -> None: - self._box = box - self.ascii = ascii - line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines() - # top - self.top_left, self.top, self.top_divider, self.top_right = iter(line1) - # head - self.head_left, _, self.head_vertical, self.head_right = iter(line2) - # head_row - ( - self.head_row_left, - self.head_row_horizontal, - self.head_row_cross, - self.head_row_right, - ) = iter(line3) - - # mid - self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4) - # row - self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5) - # foot_row - ( - self.foot_row_left, - self.foot_row_horizontal, - self.foot_row_cross, - self.foot_row_right, - ) = iter(line6) - # foot - self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7) - # bottom - self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter( - line8 - ) - - def __repr__(self) -> str: - return "Box(...)" - - def __str__(self) -> str: - return self._box - - def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box": - """Substitute this box for another if it won't render due to platform issues. - - Args: - options (ConsoleOptions): Console options used in rendering. - safe (bool, optional): Substitute this for another Box if there are known problems - displaying on the platform (currently only relevant on Windows). Default is True. - - Returns: - Box: A different Box or the same Box. - """ - box = self - if options.legacy_windows and safe: - box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box) - if options.ascii_only and not box.ascii: - box = ASCII - return box - - def get_plain_headed_box(self) -> "Box": - """If this box uses special characters for the borders of the header, then - return the equivalent box that does not. - - Returns: - Box: The most similar Box that doesn't use header-specific box characters. - If the current Box already satisfies this criterion, then it's returned. - """ - return PLAIN_HEADED_SUBSTITUTIONS.get(self, self) - - def get_top(self, widths: Iterable[int]) -> str: - """Get the top of a simple box. - - Args: - widths (List[int]): Widths of columns. - - Returns: - str: A string of box characters. - """ - - parts: List[str] = [] - append = parts.append - append(self.top_left) - for last, width in loop_last(widths): - append(self.top * width) - if not last: - append(self.top_divider) - append(self.top_right) - return "".join(parts) - - def get_row( - self, - widths: Iterable[int], - level: Literal["head", "row", "foot", "mid"] = "row", - edge: bool = True, - ) -> str: - """Get the top of a simple box. - - Args: - width (List[int]): Widths of columns. - - Returns: - str: A string of box characters. - """ - if level == "head": - left = self.head_row_left - horizontal = self.head_row_horizontal - cross = self.head_row_cross - right = self.head_row_right - elif level == "row": - left = self.row_left - horizontal = self.row_horizontal - cross = self.row_cross - right = self.row_right - elif level == "mid": - left = self.mid_left - horizontal = " " - cross = self.mid_vertical - right = self.mid_right - elif level == "foot": - left = self.foot_row_left - horizontal = self.foot_row_horizontal - cross = self.foot_row_cross - right = self.foot_row_right - else: - raise ValueError("level must be 'head', 'row' or 'foot'") - - parts: List[str] = [] - append = parts.append - if edge: - append(left) - for last, width in loop_last(widths): - append(horizontal * width) - if not last: - append(cross) - if edge: - append(right) - return "".join(parts) - - def get_bottom(self, widths: Iterable[int]) -> str: - """Get the bottom of a simple box. - - Args: - widths (List[int]): Widths of columns. - - Returns: - str: A string of box characters. - """ - - parts: List[str] = [] - append = parts.append - append(self.bottom_left) - for last, width in loop_last(widths): - append(self.bottom * width) - if not last: - append(self.bottom_divider) - append(self.bottom_right) - return "".join(parts) - - -ASCII: Box = Box( - """\ -+--+ -| || -|-+| -| || -|-+| -|-+| -| || -+--+ -""", - ascii=True, -) - -ASCII2: Box = Box( - """\ -+-++ -| || -+-++ -| || -+-++ -+-++ -| || -+-++ -""", - ascii=True, -) - -ASCII_DOUBLE_HEAD: Box = Box( - """\ -+-++ -| || -+=++ -| || -+-++ -+-++ -| || -+-++ -""", - ascii=True, -) - -SQUARE: Box = Box( - """\ -┌─┬┐ -│ ││ -├─┼┤ -│ ││ -├─┼┤ -├─┼┤ -│ ││ -└─┴┘ -""" -) - -SQUARE_DOUBLE_HEAD: Box = Box( - """\ -┌─┬┐ -│ ││ -╞═╪╡ -│ ││ -├─┼┤ -├─┼┤ -│ ││ -└─┴┘ -""" -) - -MINIMAL: Box = Box( - """\ - ╷ - │ -╶─┼╴ - │ -╶─┼╴ -╶─┼╴ - │ - ╵ -""" -) - - -MINIMAL_HEAVY_HEAD: Box = Box( - """\ - ╷ - │ -╺━┿╸ - │ -╶─┼╴ -╶─┼╴ - │ - ╵ -""" -) - -MINIMAL_DOUBLE_HEAD: Box = Box( - """\ - ╷ - │ - ═╪ - │ - ─┼ - ─┼ - │ - ╵ -""" -) - - -SIMPLE: Box = Box( - """\ - - - ── - - - ── - - -""" -) - -SIMPLE_HEAD: Box = Box( - """\ - - - ── - - - - - -""" -) - - -SIMPLE_HEAVY: Box = Box( - """\ - - - ━━ - - - ━━ - - -""" -) - - -HORIZONTALS: Box = Box( - """\ - ── - - ── - - ── - ── - - ── -""" -) - -ROUNDED: Box = Box( - """\ -╭─┬╮ -│ ││ -├─┼┤ -│ ││ -├─┼┤ -├─┼┤ -│ ││ -╰─┴╯ -""" -) - -HEAVY: Box = Box( - """\ -┏━┳┓ -┃ ┃┃ -┣━╋┫ -┃ ┃┃ -┣━╋┫ -┣━╋┫ -┃ ┃┃ -┗━┻┛ -""" -) - -HEAVY_EDGE: Box = Box( - """\ -┏━┯┓ -┃ │┃ -┠─┼┨ -┃ │┃ -┠─┼┨ -┠─┼┨ -┃ │┃ -┗━┷┛ -""" -) - -HEAVY_HEAD: Box = Box( - """\ -┏━┳┓ -┃ ┃┃ -┡━╇┩ -│ ││ -├─┼┤ -├─┼┤ -│ ││ -└─┴┘ -""" -) - -DOUBLE: Box = Box( - """\ -╔═╦╗ -║ ║║ -╠═╬╣ -║ ║║ -╠═╬╣ -╠═╬╣ -║ ║║ -╚═╩╝ -""" -) - -DOUBLE_EDGE: Box = Box( - """\ -╔═╤╗ -║ │║ -╟─┼╢ -║ │║ -╟─┼╢ -╟─┼╢ -║ │║ -╚═╧╝ -""" -) - -MARKDOWN: Box = Box( - """\ - -| || -|-|| -| || -|-|| -|-|| -| || - -""", - ascii=True, -) - -# Map Boxes that don't render with raster fonts on to equivalent that do -LEGACY_WINDOWS_SUBSTITUTIONS = { - ROUNDED: SQUARE, - MINIMAL_HEAVY_HEAD: MINIMAL, - SIMPLE_HEAVY: SIMPLE, - HEAVY: SQUARE, - HEAVY_EDGE: SQUARE, - HEAVY_HEAD: SQUARE, -} - -# Map headed boxes to their headerless equivalents -PLAIN_HEADED_SUBSTITUTIONS = { - HEAVY_HEAD: SQUARE, - SQUARE_DOUBLE_HEAD: SQUARE, - MINIMAL_DOUBLE_HEAD: MINIMAL, - MINIMAL_HEAVY_HEAD: MINIMAL, - ASCII_DOUBLE_HEAD: ASCII2, -} - - -if __name__ == "__main__": # pragma: no cover - - from pip._vendor.rich.columns import Columns - from pip._vendor.rich.panel import Panel - - from . import box as box - from .console import Console - from .table import Table - from .text import Text - - console = Console(record=True) - - BOXES = [ - "ASCII", - "ASCII2", - "ASCII_DOUBLE_HEAD", - "SQUARE", - "SQUARE_DOUBLE_HEAD", - "MINIMAL", - "MINIMAL_HEAVY_HEAD", - "MINIMAL_DOUBLE_HEAD", - "SIMPLE", - "SIMPLE_HEAD", - "SIMPLE_HEAVY", - "HORIZONTALS", - "ROUNDED", - "HEAVY", - "HEAVY_EDGE", - "HEAVY_HEAD", - "DOUBLE", - "DOUBLE_EDGE", - "MARKDOWN", - ] - - console.print(Panel("[bold green]Box Constants", style="green"), justify="center") - console.print() - - columns = Columns(expand=True, padding=2) - for box_name in sorted(BOXES): - table = Table( - show_footer=True, style="dim", border_style="not dim", expand=True - ) - table.add_column("Header 1", "Footer 1") - table.add_column("Header 2", "Footer 2") - table.add_row("Cell", "Cell") - table.add_row("Cell", "Cell") - table.box = getattr(box, box_name) - table.title = Text(f"box.{box_name}", style="magenta") - columns.add_renderable(table) - console.print(columns) - - # console.save_svg("box.svg") diff --git a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/util/response.py b/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/util/response.py deleted file mode 100644 index 5ea609ccedf18eb4ab70f8fc6990448eb6407237..0000000000000000000000000000000000000000 --- a/spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/util/response.py +++ /dev/null @@ -1,107 +0,0 @@ -from __future__ import absolute_import - -from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect - -from ..exceptions import HeaderParsingError -from ..packages.six.moves import http_client as httplib - - -def is_fp_closed(obj): - """ - Checks whether a given file-like object is closed. - - :param obj: - The file-like object to check. - """ - - try: - # Check `isclosed()` first, in case Python3 doesn't set `closed`. - # GH Issue #928 - return obj.isclosed() - except AttributeError: - pass - - try: - # Check via the official file-like-object way. - return obj.closed - except AttributeError: - pass - - try: - # Check if the object is a container for another file-like object that - # gets released on exhaustion (e.g. HTTPResponse). - return obj.fp is None - except AttributeError: - pass - - raise ValueError("Unable to determine whether fp is closed.") - - -def assert_header_parsing(headers): - """ - Asserts whether all headers have been successfully parsed. - Extracts encountered errors from the result of parsing headers. - - Only works on Python 3. - - :param http.client.HTTPMessage headers: Headers to verify. - - :raises urllib3.exceptions.HeaderParsingError: - If parsing errors are found. - """ - - # This will fail silently if we pass in the wrong kind of parameter. - # To make debugging easier add an explicit check. - if not isinstance(headers, httplib.HTTPMessage): - raise TypeError("expected httplib.Message, got {0}.".format(type(headers))) - - defects = getattr(headers, "defects", None) - get_payload = getattr(headers, "get_payload", None) - - unparsed_data = None - if get_payload: - # get_payload is actually email.message.Message.get_payload; - # we're only interested in the result if it's not a multipart message - if not headers.is_multipart(): - payload = get_payload() - - if isinstance(payload, (bytes, str)): - unparsed_data = payload - if defects: - # httplib is assuming a response body is available - # when parsing headers even when httplib only sends - # header data to parse_headers() This results in - # defects on multipart responses in particular. - # See: https://github.com/urllib3/urllib3/issues/800 - - # So we ignore the following defects: - # - StartBoundaryNotFoundDefect: - # The claimed start boundary was never found. - # - MultipartInvariantViolationDefect: - # A message claimed to be a multipart but no subparts were found. - defects = [ - defect - for defect in defects - if not isinstance( - defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect) - ) - ] - - if defects or unparsed_data: - raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) - - -def is_response_to_head(response): - """ - Checks whether the request of a response has been a HEAD-request. - Handles the quirks of AppEngine. - - :param http.client.HTTPResponse response: - Response to check if the originating request - used 'HEAD' as a method. - """ - # FIXME: Can we do this somehow without accessing private httplib _method? - method = response._method - if isinstance(method, int): # Platform-specific: Appengine - return method == 3 - return method.upper() == "HEAD" diff --git a/spaces/BigData-KSU/VQA-in-Medical-Imagery/MED_VQA_Huggyface_Gradio.py b/spaces/BigData-KSU/VQA-in-Medical-Imagery/MED_VQA_Huggyface_Gradio.py deleted file mode 100644 index 6bd2c4a9c1139732017abb5408d538aa71326b2f..0000000000000000000000000000000000000000 --- a/spaces/BigData-KSU/VQA-in-Medical-Imagery/MED_VQA_Huggyface_Gradio.py +++ /dev/null @@ -1,182 +0,0 @@ -##### VQA MED Demo - -import gradio as gr -from transformers import ViltProcessor, ViltForQuestionAnswering -import torch -import torch.nn as nn -from transformers import CLIPTokenizer -from CLIP import clip -from Transformers_for_Caption import Transformer_Caption -import numpy as np -import torchvision.transforms as transforms - -device = "cuda" if torch.cuda.is_available() else "cpu" - -class Config(object): - def __init__(self): - # Learning Rates - # Transformer - self.hidden_dim = 512 - self.pad_token_id = 0 - self.max_position_embeddings = 76 - self.layer_norm_eps = 1e-12 - self.dropout = 0.1 - self.vocab_size = 49408 - - self.enc_layers = 1 - self.dec_layers = 1 - self.dim_feedforward = 1024 #2048 - self.nheads = 4 - self.pre_norm = True - # Dataset - #self.dir = os.getcwd() + '/data/coco' - self.limit = -1 - - - -##### OUR MODEL - -class VQA_Net(nn.Module): - def __init__(self, num_classes): - super(VQA_Net,self).__init__() - #self.VIT = deit_base_distilled_patch16_224(pretrained=True) - #self.VIT =vit_base_patch16_224_dino(pretrained=True) - #self.VIT = vit_base_patch32_sam_224(pretrained=True) ###### please not that we used only 6 layers - #self.VIT=maxvit_rmlp_nano_rw_256(pretrained=True) - #self.VIT = vit_base_patch8_224(pretrained=True) - #self.VIT=m = tf_efficientnetv2_m(pretrained=True, features_only=True, out_indices=(1,3), feature_location='expansion') - self.backbone, _ = clip.load('ViT-B/32', device, jit=False) - self.input_proj = nn.LayerNorm(512) # nn.Sequential(nn.LayerNorm(768),nn.Linear(768,768),nn.GELU(),nn.Dropout(0.1)) - self.transformer_decoder = Transformer_Caption(config,num_decoder_layers=2) - self.mlp = nn.Sequential(nn.Sequential(nn.Linear(512, num_classes))) # MLP(256, 512, 30522, 1) 49408) - #self.samples_proj = nn.Sequential(nn.Linear(768,512)) - self.samples_proj = nn.Identity() - self.question_proj = nn.Identity() #nn.Sequential(nn.Linear(512, 512,bias=False)) # nn.Sequential(nn.LayerNorm(768),nn.Linear(768,768),nn.GELU(),nn.Dropout(0.1)) - #self.tokenizer=CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32") - - def forward(self, samples, question_in, answer_out, mask_answer): - # print('Here') - #print(samples.shape) - _, _, samples = self.backbone.encode_image(samples) - - #samples=self.VIT(samples) - #print(samples.shape) - samples=samples.float() - #samples = self.VIT(samples) - #print(`samples.shape) - #samples = samples.view(-1, 512, 8 * 8) - # print(img_seq.shape) - #samples = samples.permute(0, 2, 1) - #samples=samples[:,0:,:] @ self.samples_proj - samples = self.samples_proj(samples) - #print(samples.shape) - #print(samples.shape) - _, _,question_in = self.backbone.encode_text(question_in) - #print(question_in.shape) - #samples = self.samples_proj(samples.float()) - question_in = self.question_proj(question_in.float()) - #print(question_in.shape) - #print(samples.shape) - samples = torch.cat((samples, question_in), dim=1) - #print(samples.shape) - - # src, mask = features[-1].decompose() - # assert mask is not None - hs = self.transformer_decoder(self.input_proj(samples.permute(1, 0, 2).float()), answer_out, tgt_mask=mask_answer) - out = self.mlp(hs.permute(1, 0, 2)) - # print(out.shape) - return out - -config = Config() -Tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-base-patch32") -My_VQA = VQA_Net(num_classes=len(Tokenizer)) -My_VQA.load_state_dict(torch.load("./PathVQA_2Decoders_1024_30iterations_Trial4_CLIPVIT32.pth.tar",map_location= torch.device(device))) - - -tfms = transforms.Compose([ - #transforms.Lambda(under_max), - transforms.Resize((224, 224)), - transforms.ToTensor(), - transforms.Normalize(mean=[0.485, 0.456, 0.406], - std=[0.229, 0.224, 0.225]) - # transforms.Normalize(0.5, 0.5), -]) - - -def answer_question(image, text_question): - with torch.no_grad(): - for iter in range(1): - start_token = Tokenizer.convert_tokens_to_ids("<|startoftext|>") - # end_token = Tokenizer.convert_tokens_to_ids("<|endoftext|>") - # start_token=tokenizer.convert_tokens_to_ids(tokenizer._cls_token) - caption = torch.zeros((1, config.max_position_embeddings), dtype=torch.long) - cap_mask = torch.ones((1, config.max_position_embeddings), dtype=torch.bool) - caption[:, 0] = start_token - cap_mask[:, 0] = False - if text_question.find('?') > -1: - text_question = text_question.split('?')[0].lower() - text_question= np.array(Tokenizer.encode_plus(text_question, max_length=77, pad_to_max_length=True,return_attention_mask=True, - return_token_type_ids=False, truncation=True)['input_ids']) - #print(torch.Tensor(text_question).unsqueeze(0).long()) - for i in range(config.max_position_embeddings - 1): - predictions = My_VQA(image.unsqueeze(0),torch.Tensor(text_question).unsqueeze(0).long(), caption,cap_mask) - predictions = predictions[:, i, :] - predicted_id = torch.argmax(predictions, axis=-1) - caption[:, i + 1] = predicted_id[0] - cap_mask[:, i + 1] = False - if predicted_id[0] == 49407: - break - #print('question:') - #print(batch_test['question']) - cap_result_intermediate = Tokenizer.decode(caption[0].tolist(), skip_special_tokens=True) - #print('+++++++++++++++++++++++++++++++++++') - #print("True:") - # print(ref_sentence) - cap_result = cap_result_intermediate.split('!') - #ref_sentence = batch_test['answer'].lower() - #print(ref_sentence) - #print("Predict:") - #print(cap_result) - # image_disp=inv_Normalize(batch_test['image'])[0].permute(1,2,0).detach().cpu().numpy() - # print('************************') - # plt.imshow(image_disp) - return cap_result - - -def infer_answer_question(image, text): - if text is None: - cap_result = "please write a question" - elif image is None: - cap_result = "please upload an image" - else: - image_encoded = tfms(image) - cap_result=answer_question(image_encoded,text)[0] - - return cap_result - - -image = gr.Image(type="pil") -question = gr.Textbox(label="Question") -answer = gr.Textbox(label="Predicted answer") -examples = [["train_0000.jpg", "Where are liver stem cells (oval cells) located?"], - ["train_0001.jpg", "What are stained here with an immunohistochemical stain for cytokeratin 7?"], - ["train_0002.jpg", "What are bile duct cells and canals of Hering stained here with for cytokeratin 7?"], - ["train_0003.jpg", "Are bile duct cells and canals of Hering stained here with an immunohistochemical stain for cytokeratin 7?"], - ["train_0018.jpg", "Is there an infarct in the brain hypertrophy?"], - ["train_0019.jpg", "What is ischemic coagulative necrosis?"]] - -title = "Vision–Language Model for Visual Question Answering in Medical Imagery" -description = "Y Bazi, MMA Rahhal, L Bashmal, M Zuair. Vision–Language Model for Visual Question Answering in Medical Imagery. Bioengineering, 2023

    "\ - "Gradio Demo for VQA medical model trained on PathVQA dataset, To use it, upload your image and type a question and click 'submit', or click one of the examples to load them." \ -### link to paper and github code -website = "" -article = f"

    BigMed@KSU

    " - -interface = gr.Interface(fn=infer_answer_question, - inputs=[image, question], - outputs=answer, - examples=examples, - title=title, - description=description, - article=article) -interface.launch(debug=True, enable_queue=True) diff --git a/spaces/BigData-KSU/VQA-in-Medical-Imagery/Transformers_for_Caption.py b/spaces/BigData-KSU/VQA-in-Medical-Imagery/Transformers_for_Caption.py deleted file mode 100644 index e85cc8b413a745d58c9187b562a5500d2d451407..0000000000000000000000000000000000000000 --- a/spaces/BigData-KSU/VQA-in-Medical-Imagery/Transformers_for_Caption.py +++ /dev/null @@ -1,364 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -import copy -from typing import Optional, List - -import torch -import torch.nn.functional as F -from torch import nn, Tensor - - -class Transformer_Caption(nn.Module): - - def __init__(self, config,d_model=512, nhead=4, num_encoder_layers=1, - num_decoder_layers=2, dim_feedforward=1024, dropout=0.1, - activation="gelu", normalize_before=False, - return_intermediate_dec=False): - super().__init__() - - encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, - dropout, activation, normalize_before) - encoder_norm = nn.LayerNorm(d_model) if normalize_before else None - self.encoder = TransformerEncoder( - encoder_layer, num_encoder_layers, encoder_norm) - - self.embeddings = DecoderEmbeddings(config) - decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, - dropout, activation, normalize_before) - decoder_norm = nn.LayerNorm(d_model) - self.decoder = TransformerDecoder(decoder_layer, num_decoder_layers, decoder_norm, - return_intermediate=return_intermediate_dec) - print("Num decoders:") - print(num_decoder_layers) - self._reset_parameters() - - self.d_model = d_model - self.nhead = nhead - - def _reset_parameters(self): - for p in self.parameters(): - if p.dim() > 1: - nn.init.xavier_uniform_(p) - - def forward(self, src, tgt, tgt_mask): - # flatten NxCxHxW to HWxNxC - #print("HERRRRRR") - #print(src.shape) - h, bs, w = src.shape - #src = src.permute(1, 0, 2) - #print("SRCCCCCCCC") - #print(src.shape) - #pos_embed = pos_embed.flatten(2).permute(2, 0, 1) - #mask = mask.flatten(1) - #print(num_decoder_layers) - - tgt = self.embeddings(tgt).permute(1, 0, 2) - query_embed = self.embeddings.position_embeddings.weight.unsqueeze(1) - query_embed = query_embed.repeat(1, bs, 1) - #print("firstmyyyyyyyyyyyyyy") - #print(tgt.shape) - #print(tgt_mask.shape) - #print(pos_embed.shape) - #print(query_embed.shape) - #print(generate_square_subsequent_mask(len(tgt)).to(tgt.device).shape) - #print(src.shape) - - #memory = self.encoder(src, src_key_padding_mask=None, pos=None) - #memory = self.encoder(src) - #print("then....") - #print(tgt_mask.shape) - hs = self.decoder(tgt, src, memory_key_padding_mask=None, tgt_key_padding_mask=tgt_mask, - pos=None, query_pos=query_embed, - tgt_mask=generate_square_subsequent_mask(len(tgt)).to(tgt.device)) - #hs = self.decoder(tgt, memory, tgt_key_padding_mask=tgt_mask,query_pos=query_embed,tgt_mask=generate_square_subsequent_mask(len(tgt)).to(tgt.device)) - - return hs - - -class TransformerEncoder(nn.Module): - - def __init__(self, encoder_layer, num_layers, norm=None): - super().__init__() - self.layers = _get_clones(encoder_layer, num_layers) - self.num_layers = num_layers - self.norm = norm - - def forward(self, src, - mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None): - output = src - - for layer in self.layers: - output = layer(output, src_mask=mask, - src_key_padding_mask=src_key_padding_mask, pos=pos) - - if self.norm is not None: - output = self.norm(output) - - return output - - -class TransformerDecoder(nn.Module): - - def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): - super().__init__() - self.layers = _get_clones(decoder_layer, num_layers) - self.num_layers = num_layers - self.norm = norm - self.return_intermediate = return_intermediate - - def forward(self, tgt, memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None): - output = tgt - - intermediate = [] - - for layer in self.layers: - output = layer(output, memory, tgt_mask=tgt_mask, - memory_mask=memory_mask, - tgt_key_padding_mask=tgt_key_padding_mask, - memory_key_padding_mask=memory_key_padding_mask, - pos=pos, query_pos=query_pos) - if self.return_intermediate: - intermediate.append(self.norm(output)) - - if self.norm is not None: - output = self.norm(output) - if self.return_intermediate: - intermediate.pop() - intermediate.append(output) - - if self.return_intermediate: - return torch.stack(intermediate) - - return output - - -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 - - def with_pos_embed(self, tensor, pos: Optional[Tensor]): - return tensor if pos is None else tensor + pos - - def forward_post(self, - src, - src_mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None): - q = k = self.with_pos_embed(src, pos) - 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 - - def forward_pre(self, src, - src_mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None): - src2 = self.norm1(src) - q = k = self.with_pos_embed(src2, pos) - src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask, - key_padding_mask=src_key_padding_mask)[0] - src = src + self.dropout1(src2) - src2 = self.norm2(src) - src2 = self.linear2(self.dropout(self.activation(self.linear1(src2)))) - src = src + self.dropout2(src2) - return src - - def forward(self, src, - src_mask: Optional[Tensor] = None, - src_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None): - if self.normalize_before: - return self.forward_pre(src, src_mask, src_key_padding_mask, pos) - return self.forward_post(src, src_mask, src_key_padding_mask, pos) - - -class TransformerDecoderLayer(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) - self.multihead_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.norm3 = nn.LayerNorm(d_model) - self.dropout1 = nn.Dropout(dropout) - self.dropout2 = nn.Dropout(dropout) - self.dropout3 = nn.Dropout(dropout) - - self.activation = _get_activation_fn(activation) - self.normalize_before = normalize_before - - - def with_pos_embed(self, tensor, pos: Optional[Tensor]): - return tensor if pos is None else tensor + pos - - def forward_post(self, tgt, memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None): - #print(tgt.shape) - #print(query_pos.shape) - - q = k = self.with_pos_embed(tgt, query_pos) - tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask, - key_padding_mask=tgt_key_padding_mask)[0] - tgt = tgt + self.dropout1(tgt2) - tgt = self.norm1(tgt) - tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos), - key=self.with_pos_embed(memory, pos), - value=memory, attn_mask=memory_mask, - key_padding_mask=memory_key_padding_mask)[0] - tgt = tgt + self.dropout2(tgt2) - tgt = self.norm2(tgt) - tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) - tgt = tgt + self.dropout3(tgt2) - tgt = self.norm3(tgt) - return tgt - - def forward_pre(self, tgt, memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None): - tgt2 = self.norm1(tgt) - q = k = self.with_pos_embed(tgt2, query_pos) - tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, - key_padding_mask=tgt_key_padding_mask)[0] - tgt = tgt + self.dropout1(tgt2) - tgt2 = self.norm2(tgt) - tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos), - key=self.with_pos_embed(memory, pos), - value=memory, attn_mask=memory_mask, - key_padding_mask=memory_key_padding_mask)[0] - tgt = tgt + self.dropout2(tgt2) - tgt2 = self.norm3(tgt) - tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) - tgt = tgt + self.dropout3(tgt2) - return tgt - - def forward(self, tgt, memory, - tgt_mask: Optional[Tensor] = None, - memory_mask: Optional[Tensor] = None, - tgt_key_padding_mask: Optional[Tensor] = None, - memory_key_padding_mask: Optional[Tensor] = None, - pos: Optional[Tensor] = None, - query_pos: Optional[Tensor] = None): - if self.normalize_before: - return self.forward_pre(tgt, memory, tgt_mask, memory_mask, - tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) - return self.forward_post(tgt, memory, tgt_mask, memory_mask, - tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos) - - -class DecoderEmbeddings(nn.Module): - def __init__(self, config): - super().__init__() - self.word_embeddings = nn.Embedding( - config.vocab_size, config.hidden_dim, padding_idx=config.pad_token_id) - self.position_embeddings = nn.Embedding( - config.max_position_embeddings, config.hidden_dim - ) - - self.LayerNorm = torch.nn.LayerNorm( - config.hidden_dim, eps=config.layer_norm_eps) - self.dropout = nn.Dropout(config.dropout) - - def forward(self, x): - input_shape = x.size() - x=x.long() - #print(x.shape) - seq_length = input_shape[1] - device = x.device - - position_ids = torch.arange( - seq_length, dtype=torch.long, device=device) - position_ids = position_ids.unsqueeze(0).expand(input_shape) - input_embeds = self.word_embeddings(x) - position_embeds = self.position_embeddings(position_ids) - - - embeddings = input_embeds + position_embeds - embeddings = self.LayerNorm(embeddings) - embeddings = self.dropout(embeddings) - - #print(embeddings) - - return embeddings - - -def _get_clones(module, N): - return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) - - -def _get_activation_fn(activation): - """Return an activation function given a string""" - if activation == "relu": - return F.relu - if activation == "gelu": - return F.gelu - if activation == "glu": - return F.glu - raise RuntimeError(F"activation should be relu/gelu, not {activation}.") - - -def generate_square_subsequent_mask(sz): - r"""Generate a square mask for the sequence. The masked positions are filled with float('-inf'). - Unmasked positions are filled with float(0.0). - """ - mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) - mask = mask.float().masked_fill(mask == 0, float( - '-inf')).masked_fill(mask == 1, float(0.0)) - return mask - - -def build_transformer(config): - return Transformer_Caption( - config, - d_model=config.hidden_dim, - dropout=config.dropout, - nhead=config.nheads, - dim_feedforward=config.dim_feedforward, - num_encoder_layers=config.enc_layers, - num_decoder_layers=config.dec_layers, - normalize_before=config.pre_norm, - return_intermediate_dec=False, - ) diff --git a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/config.py b/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/config.py deleted file mode 100644 index 463760e576863ea322f8cbdd7cbbd32edb937a5f..0000000000000000000000000000000000000000 --- a/spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/config.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding = utf-8 -*- -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved - -from detectron2.config import CfgNode as CN - - -def add_densepose_config(cfg): - """ - Add config for densepose head. - """ - _C = cfg - - _C.MODEL.DENSEPOSE_ON = True - - _C.MODEL.ROI_DENSEPOSE_HEAD = CN() - _C.MODEL.ROI_DENSEPOSE_HEAD.NAME = "" - _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_STACKED_CONVS = 8 - # Number of parts used for point labels - _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_PATCHES = 24 - _C.MODEL.ROI_DENSEPOSE_HEAD.DECONV_KERNEL = 4 - _C.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_DIM = 512 - _C.MODEL.ROI_DENSEPOSE_HEAD.CONV_HEAD_KERNEL = 3 - _C.MODEL.ROI_DENSEPOSE_HEAD.UP_SCALE = 2 - _C.MODEL.ROI_DENSEPOSE_HEAD.HEATMAP_SIZE = 112 - _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_TYPE = "ROIAlignV2" - _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_RESOLUTION = 28 - _C.MODEL.ROI_DENSEPOSE_HEAD.POOLER_SAMPLING_RATIO = 2 - _C.MODEL.ROI_DENSEPOSE_HEAD.NUM_COARSE_SEGM_CHANNELS = 2 # 15 or 2 - # Overlap threshold for an RoI to be considered foreground (if >= FG_IOU_THRESHOLD) - _C.MODEL.ROI_DENSEPOSE_HEAD.FG_IOU_THRESHOLD = 0.7 - # Loss weights for annotation masks.(14 Parts) - _C.MODEL.ROI_DENSEPOSE_HEAD.INDEX_WEIGHTS = 5.0 - # Loss weights for surface parts. (24 Parts) - _C.MODEL.ROI_DENSEPOSE_HEAD.PART_WEIGHTS = 1.0 - # Loss weights for UV regression. - _C.MODEL.ROI_DENSEPOSE_HEAD.POINT_REGRESSION_WEIGHTS = 0.01 - # For Decoder - _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_ON = True - _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_NUM_CLASSES = 256 - _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_CONV_DIMS = 256 - _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_NORM = "" - _C.MODEL.ROI_DENSEPOSE_HEAD.DECODER_COMMON_STRIDE = 4 - # For DeepLab head - _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB = CN() - _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NORM = "GN" - _C.MODEL.ROI_DENSEPOSE_HEAD.DEEPLAB.NONLOCAL_ON = 0 - # Confidences - # Enable learning confidences (variances) along with the actual values - _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE = CN({"ENABLED": False}) - # UV confidence lower bound - _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE.EPSILON = 0.01 - # Statistical model type for confidence learning, possible values: - # - "iid_iso": statistically independent identically distributed residuals - # with isotropic covariance - # - "indep_aniso": statistically independent residuals with anisotropic - # covariances - _C.MODEL.ROI_DENSEPOSE_HEAD.UV_CONFIDENCE.TYPE = "iid_iso" diff --git a/spaces/CVPR/LIVE/pybind11/include/pybind11/common.h b/spaces/CVPR/LIVE/pybind11/include/pybind11/common.h deleted file mode 100644 index 6c8a4f1e88e493ee08d24e668639c8d495fd49b1..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/include/pybind11/common.h +++ /dev/null @@ -1,2 +0,0 @@ -#include "detail/common.h" -#warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'." diff --git a/spaces/CVPR/LIVE/pybind11/tests/test_pickling.py b/spaces/CVPR/LIVE/pybind11/tests/test_pickling.py deleted file mode 100644 index 9aee70505de7acc21ee09623417d35812ae11463..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/pybind11/tests/test_pickling.py +++ /dev/null @@ -1,46 +0,0 @@ -# -*- coding: utf-8 -*- -import pytest - -import env # noqa: F401 - -from pybind11_tests import pickling as m - -try: - import cPickle as pickle # Use cPickle on Python 2.7 -except ImportError: - import pickle - - -@pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"]) -def test_roundtrip(cls_name): - cls = getattr(m, cls_name) - p = cls("test_value") - p.setExtra1(15) - p.setExtra2(48) - - data = pickle.dumps(p, 2) # Must use pickle protocol >= 2 - p2 = pickle.loads(data) - assert p2.value() == p.value() - assert p2.extra1() == p.extra1() - assert p2.extra2() == p.extra2() - - -@pytest.mark.xfail("env.PYPY") -@pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"]) -def test_roundtrip_with_dict(cls_name): - cls = getattr(m, cls_name) - p = cls("test_value") - p.extra = 15 - p.dynamic = "Attribute" - - data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) - p2 = pickle.loads(data) - assert p2.value == p.value - assert p2.extra == p.extra - assert p2.dynamic == p.dynamic - - -def test_enum_pickle(): - from pybind11_tests import enums as e - data = pickle.dumps(e.EOne, 2) - assert e.EOne == pickle.loads(data) diff --git a/spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/unique.h b/spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/unique.h deleted file mode 100644 index 433e7689b69b210b9de2996beaf2849a6130779d..0000000000000000000000000000000000000000 --- a/spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/unique.h +++ /dev/null @@ -1,59 +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 -#include -#include - -namespace thrust -{ -namespace system -{ -namespace omp -{ -namespace detail -{ - - -template - ForwardIterator unique(execution_policy &exec, - ForwardIterator first, - ForwardIterator last, - BinaryPredicate binary_pred); - - -template - OutputIterator unique_copy(execution_policy &exec, - InputIterator first, - InputIterator last, - OutputIterator output, - BinaryPredicate binary_pred); - - -} // end namespace detail -} // end namespace omp -} // end namespace system -} // end namespace thrust - -#include - diff --git a/spaces/CVPR/MonoScene/monoscene/DDR.py b/spaces/CVPR/MonoScene/monoscene/DDR.py deleted file mode 100644 index cc997ed7604d83ef562474d32cb484aac36f2adc..0000000000000000000000000000000000000000 --- a/spaces/CVPR/MonoScene/monoscene/DDR.py +++ /dev/null @@ -1,139 +0,0 @@ -""" -Most of the code in this file is taken from https://github.com/waterljwant/SSC/blob/master/models/DDR.py -""" - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -class SimpleRB(nn.Module): - def __init__(self, in_channel, norm_layer, bn_momentum): - super(SimpleRB, self).__init__() - self.path = nn.Sequential( - nn.Conv3d(in_channel, in_channel, kernel_size=3, padding=1, bias=False), - norm_layer(in_channel, momentum=bn_momentum), - nn.ReLU(), - nn.Conv3d(in_channel, in_channel, kernel_size=3, padding=1, bias=False), - norm_layer(in_channel, momentum=bn_momentum), - ) - self.relu = nn.ReLU() - - def forward(self, x): - residual = x - conv_path = self.path(x) - out = residual + conv_path - out = self.relu(out) - return out - - -""" -3D Residual Block,3x3x3 conv ==> 3 smaller 3D conv, refered from DDRNet -""" - - -class Bottleneck3D(nn.Module): - def __init__( - self, - inplanes, - planes, - norm_layer, - stride=1, - dilation=[1, 1, 1], - expansion=4, - downsample=None, - fist_dilation=1, - multi_grid=1, - bn_momentum=0.0003, - ): - super(Bottleneck3D, self).__init__() - # often,planes = inplanes // 4 - self.expansion = expansion - self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False) - self.bn1 = norm_layer(planes, momentum=bn_momentum) - self.conv2 = nn.Conv3d( - planes, - planes, - kernel_size=(1, 1, 3), - stride=(1, 1, stride), - dilation=(1, 1, dilation[0]), - padding=(0, 0, dilation[0]), - bias=False, - ) - self.bn2 = norm_layer(planes, momentum=bn_momentum) - self.conv3 = nn.Conv3d( - planes, - planes, - kernel_size=(1, 3, 1), - stride=(1, stride, 1), - dilation=(1, dilation[1], 1), - padding=(0, dilation[1], 0), - bias=False, - ) - self.bn3 = norm_layer(planes, momentum=bn_momentum) - self.conv4 = nn.Conv3d( - planes, - planes, - kernel_size=(3, 1, 1), - stride=(stride, 1, 1), - dilation=(dilation[2], 1, 1), - padding=(dilation[2], 0, 0), - bias=False, - ) - self.bn4 = norm_layer(planes, momentum=bn_momentum) - self.conv5 = nn.Conv3d( - planes, planes * self.expansion, kernel_size=(1, 1, 1), bias=False - ) - self.bn5 = norm_layer(planes * self.expansion, momentum=bn_momentum) - - self.relu = nn.ReLU(inplace=False) - self.relu_inplace = nn.ReLU(inplace=True) - self.downsample = downsample - self.dilation = dilation - self.stride = stride - - self.downsample2 = nn.Sequential( - nn.AvgPool3d(kernel_size=(1, stride, 1), stride=(1, stride, 1)), - nn.Conv3d(planes, planes, kernel_size=1, stride=1, bias=False), - norm_layer(planes, momentum=bn_momentum), - ) - self.downsample3 = nn.Sequential( - nn.AvgPool3d(kernel_size=(stride, 1, 1), stride=(stride, 1, 1)), - nn.Conv3d(planes, planes, kernel_size=1, stride=1, bias=False), - norm_layer(planes, momentum=bn_momentum), - ) - self.downsample4 = nn.Sequential( - nn.AvgPool3d(kernel_size=(stride, 1, 1), stride=(stride, 1, 1)), - nn.Conv3d(planes, planes, kernel_size=1, stride=1, bias=False), - norm_layer(planes, momentum=bn_momentum), - ) - - def forward(self, x): - residual = x - - out1 = self.relu(self.bn1(self.conv1(x))) - out2 = self.bn2(self.conv2(out1)) - out2_relu = self.relu(out2) - - out3 = self.bn3(self.conv3(out2_relu)) - if self.stride != 1: - out2 = self.downsample2(out2) - out3 = out3 + out2 - out3_relu = self.relu(out3) - - out4 = self.bn4(self.conv4(out3_relu)) - if self.stride != 1: - out2 = self.downsample3(out2) - out3 = self.downsample4(out3) - out4 = out4 + out2 + out3 - - out4_relu = self.relu(out4) - out5 = self.bn5(self.conv5(out4_relu)) - - if self.downsample is not None: - residual = self.downsample(x) - - out = out5 + residual - out_relu = self.relu(out) - - return out_relu diff --git a/spaces/CVPR/regionclip-demo/detectron2/layers/mask_ops.py b/spaces/CVPR/regionclip-demo/detectron2/layers/mask_ops.py deleted file mode 100644 index c698a03c4d3faf30c08da97169f010b64c0d1058..0000000000000000000000000000000000000000 --- a/spaces/CVPR/regionclip-demo/detectron2/layers/mask_ops.py +++ /dev/null @@ -1,260 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import numpy as np -from typing import Tuple -import torch -from PIL import Image -from torch.nn import functional as F - -from detectron2.structures import Boxes - -__all__ = ["paste_masks_in_image"] - - -BYTES_PER_FLOAT = 4 -# TODO: This memory limit may be too much or too little. It would be better to -# determine it based on available resources. -GPU_MEM_LIMIT = 1024 ** 3 # 1 GB memory limit - - -def _do_paste_mask(masks, boxes, img_h: int, img_w: int, skip_empty: bool = True): - """ - Args: - masks: N, 1, H, W - boxes: N, 4 - img_h, img_w (int): - skip_empty (bool): only paste masks within the region that - tightly bound all boxes, and returns the results this region only. - An important optimization for CPU. - - Returns: - if skip_empty == False, a mask of shape (N, img_h, img_w) - if skip_empty == True, a mask of shape (N, h', w'), and the slice - object for the corresponding region. - """ - # On GPU, paste all masks together (up to chunk size) - # by using the entire image to sample the masks - # Compared to pasting them one by one, - # this has more operations but is faster on COCO-scale dataset. - device = masks.device - - if skip_empty and not torch.jit.is_scripting(): - x0_int, y0_int = torch.clamp(boxes.min(dim=0).values.floor()[:2] - 1, min=0).to( - dtype=torch.int32 - ) - x1_int = torch.clamp(boxes[:, 2].max().ceil() + 1, max=img_w).to(dtype=torch.int32) - y1_int = torch.clamp(boxes[:, 3].max().ceil() + 1, max=img_h).to(dtype=torch.int32) - else: - x0_int, y0_int = 0, 0 - x1_int, y1_int = img_w, img_h - x0, y0, x1, y1 = torch.split(boxes, 1, dim=1) # each is Nx1 - - N = masks.shape[0] - - img_y = torch.arange(y0_int, y1_int, device=device, dtype=torch.float32) + 0.5 - img_x = torch.arange(x0_int, x1_int, device=device, dtype=torch.float32) + 0.5 - img_y = (img_y - y0) / (y1 - y0) * 2 - 1 - img_x = (img_x - x0) / (x1 - x0) * 2 - 1 - # img_x, img_y have shapes (N, w), (N, h) - - gx = img_x[:, None, :].expand(N, img_y.size(1), img_x.size(1)) - gy = img_y[:, :, None].expand(N, img_y.size(1), img_x.size(1)) - grid = torch.stack([gx, gy], dim=3) - - if not torch.jit.is_scripting(): - if not masks.dtype.is_floating_point: - masks = masks.float() - img_masks = F.grid_sample(masks, grid.to(masks.dtype), align_corners=False) - - if skip_empty and not torch.jit.is_scripting(): - return img_masks[:, 0], (slice(y0_int, y1_int), slice(x0_int, x1_int)) - else: - return img_masks[:, 0], () - - -def paste_masks_in_image( - masks: torch.Tensor, boxes: Boxes, image_shape: Tuple[int, int], threshold: float = 0.5 -): - """ - Paste a set of masks that are of a fixed resolution (e.g., 28 x 28) into an image. - The location, height, and width for pasting each mask is determined by their - corresponding bounding boxes in boxes. - - Note: - This is a complicated but more accurate implementation. In actual deployment, it is - often enough to use a faster but less accurate implementation. - See :func:`paste_mask_in_image_old` in this file for an alternative implementation. - - Args: - masks (tensor): Tensor of shape (Bimg, Hmask, Wmask), where Bimg is the number of - detected object instances in the image and Hmask, Wmask are the mask width and mask - height of the predicted mask (e.g., Hmask = Wmask = 28). Values are in [0, 1]. - boxes (Boxes or Tensor): A Boxes of length Bimg or Tensor of shape (Bimg, 4). - boxes[i] and masks[i] correspond to the same object instance. - image_shape (tuple): height, width - threshold (float): A threshold in [0, 1] for converting the (soft) masks to - binary masks. - - Returns: - img_masks (Tensor): A tensor of shape (Bimg, Himage, Wimage), where Bimg is the - number of detected object instances and Himage, Wimage are the image width - and height. img_masks[i] is a binary mask for object instance i. - """ - - assert masks.shape[-1] == masks.shape[-2], "Only square mask predictions are supported" - N = len(masks) - if N == 0: - return masks.new_empty((0,) + image_shape, dtype=torch.uint8) - if not isinstance(boxes, torch.Tensor): - boxes = boxes.tensor - device = boxes.device - assert len(boxes) == N, boxes.shape - - img_h, img_w = image_shape - - # The actual implementation split the input into chunks, - # and paste them chunk by chunk. - if device.type == "cpu" or torch.jit.is_scripting(): - # CPU is most efficient when they are pasted one by one with skip_empty=True - # so that it performs minimal number of operations. - num_chunks = N - else: - # GPU benefits from parallelism for larger chunks, but may have memory issue - # int(img_h) because shape may be tensors in tracing - num_chunks = int(np.ceil(N * int(img_h) * int(img_w) * BYTES_PER_FLOAT / GPU_MEM_LIMIT)) - assert ( - num_chunks <= N - ), "Default GPU_MEM_LIMIT in mask_ops.py is too small; try increasing it" - chunks = torch.chunk(torch.arange(N, device=device), num_chunks) - - img_masks = torch.zeros( - N, img_h, img_w, device=device, dtype=torch.bool if threshold >= 0 else torch.uint8 - ) - for inds in chunks: - masks_chunk, spatial_inds = _do_paste_mask( - masks[inds, None, :, :], boxes[inds], img_h, img_w, skip_empty=device.type == "cpu" - ) - - if threshold >= 0: - masks_chunk = (masks_chunk >= threshold).to(dtype=torch.bool) - else: - # for visualization and debugging - masks_chunk = (masks_chunk * 255).to(dtype=torch.uint8) - - if torch.jit.is_scripting(): # Scripting does not use the optimized codepath - img_masks[inds] = masks_chunk - else: - img_masks[(inds,) + spatial_inds] = masks_chunk - return img_masks - - -# The below are the original paste function (from Detectron1) which has -# larger quantization error. -# It is faster on CPU, while the aligned one is faster on GPU thanks to grid_sample. - - -def paste_mask_in_image_old(mask, box, img_h, img_w, threshold): - """ - Paste a single mask in an image. - This is a per-box implementation of :func:`paste_masks_in_image`. - This function has larger quantization error due to incorrect pixel - modeling and is not used any more. - - Args: - mask (Tensor): A tensor of shape (Hmask, Wmask) storing the mask of a single - object instance. Values are in [0, 1]. - box (Tensor): A tensor of shape (4, ) storing the x0, y0, x1, y1 box corners - of the object instance. - img_h, img_w (int): Image height and width. - threshold (float): Mask binarization threshold in [0, 1]. - - Returns: - im_mask (Tensor): - The resized and binarized object mask pasted into the original - image plane (a tensor of shape (img_h, img_w)). - """ - # Conversion from continuous box coordinates to discrete pixel coordinates - # via truncation (cast to int32). This determines which pixels to paste the - # mask onto. - box = box.to(dtype=torch.int32) # Continuous to discrete coordinate conversion - # An example (1D) box with continuous coordinates (x0=0.7, x1=4.3) will map to - # a discrete coordinates (x0=0, x1=4). Note that box is mapped to 5 = x1 - x0 + 1 - # pixels (not x1 - x0 pixels). - samples_w = box[2] - box[0] + 1 # Number of pixel samples, *not* geometric width - samples_h = box[3] - box[1] + 1 # Number of pixel samples, *not* geometric height - - # Resample the mask from it's original grid to the new samples_w x samples_h grid - mask = Image.fromarray(mask.cpu().numpy()) - mask = mask.resize((samples_w, samples_h), resample=Image.BILINEAR) - mask = np.array(mask, copy=False) - - if threshold >= 0: - mask = np.array(mask > threshold, dtype=np.uint8) - mask = torch.from_numpy(mask) - else: - # for visualization and debugging, we also - # allow it to return an unmodified mask - mask = torch.from_numpy(mask * 255).to(torch.uint8) - - im_mask = torch.zeros((img_h, img_w), dtype=torch.uint8) - x_0 = max(box[0], 0) - x_1 = min(box[2] + 1, img_w) - y_0 = max(box[1], 0) - y_1 = min(box[3] + 1, img_h) - - im_mask[y_0:y_1, x_0:x_1] = mask[ - (y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0]) - ] - return im_mask - - -# Our pixel modeling requires extrapolation for any continuous -# coordinate < 0.5 or > length - 0.5. When sampling pixels on the masks, -# we would like this extrapolation to be an interpolation between boundary values and zero, -# instead of using absolute zero or boundary values. -# Therefore `paste_mask_in_image_old` is often used with zero padding around the masks like this: -# masks, scale = pad_masks(masks[:, 0, :, :], 1) -# boxes = scale_boxes(boxes.tensor, scale) - - -def pad_masks(masks, padding): - """ - Args: - masks (tensor): A tensor of shape (B, M, M) representing B masks. - padding (int): Number of cells to pad on all sides. - - Returns: - The padded masks and the scale factor of the padding size / original size. - """ - B = masks.shape[0] - M = masks.shape[-1] - pad2 = 2 * padding - scale = float(M + pad2) / M - padded_masks = masks.new_zeros((B, M + pad2, M + pad2)) - padded_masks[:, padding:-padding, padding:-padding] = masks - return padded_masks, scale - - -def scale_boxes(boxes, scale): - """ - Args: - boxes (tensor): A tensor of shape (B, 4) representing B boxes with 4 - coords representing the corners x0, y0, x1, y1, - scale (float): The box scaling factor. - - Returns: - Scaled boxes. - """ - w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5 - h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5 - x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5 - y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5 - - w_half *= scale - h_half *= scale - - scaled_boxes = torch.zeros_like(boxes) - scaled_boxes[:, 0] = x_c - w_half - scaled_boxes[:, 2] = x_c + w_half - scaled_boxes[:, 1] = y_c - h_half - scaled_boxes[:, 3] = y_c + h_half - return scaled_boxes diff --git a/spaces/CVPR/unicl-zero-shot-img-recog/model/text_encoder/registry.py b/spaces/CVPR/unicl-zero-shot-img-recog/model/text_encoder/registry.py deleted file mode 100644 index 8991272a6e2294ea86eee338cf61d87e4123f724..0000000000000000000000000000000000000000 --- a/spaces/CVPR/unicl-zero-shot-img-recog/model/text_encoder/registry.py +++ /dev/null @@ -1,18 +0,0 @@ -_lang_encoders = {} - - -def register_lang_encoder(fn): - module_name_split = fn.__module__.split('.') - model_name = module_name_split[-1] - - _lang_encoders[model_name] = fn - - return fn - - -def lang_encoders(model_name): - return _lang_encoders[model_name] - - -def is_lang_encoder(model_name): - return model_name in _lang_encoders diff --git a/spaces/CarlDennis/HYTTS/text/japanese.py b/spaces/CarlDennis/HYTTS/text/japanese.py deleted file mode 100644 index 65480534b452efabe87b40033316e2c1577ff3ea..0000000000000000000000000000000000000000 --- a/spaces/CarlDennis/HYTTS/text/japanese.py +++ /dev/null @@ -1,132 +0,0 @@ -import re -from unidecode import unidecode -import pyopenjtalk - - -# Regular expression matching Japanese without punctuation marks: -_japanese_characters = re.compile( - r'[A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]') - -# Regular expression matching non-Japanese characters or punctuation marks: -_japanese_marks = re.compile( - r'[^A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]') - -# List of (symbol, Japanese) pairs for marks: -_symbols_to_japanese = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('%', 'パーセント') -]] - -# List of (romaji, ipa) pairs for marks: -_romaji_to_ipa = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [ - ('ts', 'ʦ'), - ('u', 'ɯ'), - ('...', '…'), - ('j', 'ʥ'), - ('y', 'j'), - ('ni', 'n^i'), - ('nj', 'n^'), - ('hi', 'çi'), - ('hj', 'ç'), - ('f', 'ɸ'), - ('I', 'i*'), - ('U', 'ɯ*'), - ('r', 'ɾ') -]] - -# Dictinary of (consonant, sokuon) pairs: -_real_sokuon = { - 'k': 'k#', - 'g': 'k#', - 't': 't#', - 'd': 't#', - 'ʦ': 't#', - 'ʧ': 't#', - 'ʥ': 't#', - 'j': 't#', - 's': 's', - 'ʃ': 's', - 'p': 'p#', - 'b': 'p#' -} - -# Dictinary of (consonant, hatsuon) pairs: -_real_hatsuon = { - 'p': 'm', - 'b': 'm', - 'm': 'm', - 't': 'n', - 'd': 'n', - 'n': 'n', - 'ʧ': 'n^', - 'ʥ': 'n^', - 'k': 'ŋ', - 'g': 'ŋ' -} - - -def symbols_to_japanese(text): - for regex, replacement in _symbols_to_japanese: - text = re.sub(regex, replacement, text) - return text - - -def japanese_to_romaji_with_accent(text): - '''Reference https://r9y9.github.io/ttslearn/latest/notebooks/ch10_Recipe-Tacotron.html''' - text = symbols_to_japanese(text) - sentences = re.split(_japanese_marks, text) - marks = re.findall(_japanese_marks, text) - text = '' - for i, sentence in enumerate(sentences): - if re.match(_japanese_characters, sentence): - if text != '': - text += ' ' - labels = pyopenjtalk.extract_fullcontext(sentence) - for n, label in enumerate(labels): - phoneme = re.search(r'\-([^\+]*)\+', label).group(1) - if phoneme not in ['sil', 'pau']: - text += phoneme.replace('ch', 'ʧ').replace('sh', - 'ʃ').replace('cl', 'Q') - else: - continue - # n_moras = int(re.search(r'/F:(\d+)_', label).group(1)) - a1 = int(re.search(r"/A:(\-?[0-9]+)\+", label).group(1)) - a2 = int(re.search(r"\+(\d+)\+", label).group(1)) - a3 = int(re.search(r"\+(\d+)/", label).group(1)) - if re.search(r'\-([^\+]*)\+', labels[n + 1]).group(1) in ['sil', 'pau']: - a2_next = -1 - else: - a2_next = int( - re.search(r"\+(\d+)\+", labels[n + 1]).group(1)) - # Accent phrase boundary - if a3 == 1 and a2_next == 1: - text += ' ' - # Falling - elif a1 == 0 and a2_next == a2 + 1: - text += '↓' - # Rising - elif a2 == 1 and a2_next == 2: - text += '↑' - if i < len(marks): - text += unidecode(marks[i]).replace(' ', '') - return text - - -def get_real_sokuon(text): - text=re.sub('Q[↑↓]*(.)',lambda x:_real_sokuon[x.group(1)]+x.group(0)[1:] if x.group(1) in _real_sokuon.keys() else x.group(0),text) - return text - - -def get_real_hatsuon(text): - text=re.sub('N[↑↓]*(.)',lambda x:_real_hatsuon[x.group(1)]+x.group(0)[1:] if x.group(1) in _real_hatsuon.keys() else x.group(0),text) - return text - - -def japanese_to_ipa(text): - text=japanese_to_romaji_with_accent(text) - for regex, replacement in _romaji_to_ipa: - text = re.sub(regex, replacement, text) - text = re.sub( - r'([A-Za-zɯ])\1+', lambda x: x.group(0)[0]+'ː'*(len(x.group(0))-1), text) - text = get_real_sokuon(text) - text = get_real_hatsuon(text) - return text diff --git a/spaces/Cat125/text-generator-v3/utils.py b/spaces/Cat125/text-generator-v3/utils.py deleted file mode 100644 index b71c6d736a53d0d3bed081b87931edc1e485dadb..0000000000000000000000000000000000000000 --- a/spaces/Cat125/text-generator-v3/utils.py +++ /dev/null @@ -1,36 +0,0 @@ -from termcolor import colored - -def log(text): - '''The function logs a given text to a file named 'runtime.log'. - - Parameters - ---------- - text - The text that will be written to the log file. - - ''' - print(text, file=open('runtime.log', 'a+')) - -# Print iterations progress - - -def progressbar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill=colored('█', 'green'), print_end="\r"): - """ - Call in a loop to create terminal progress bar - @params: - iteration - Required : current iteration (Int) - total - Required : total iterations (Int) - prefix - Optional : prefix string (Str) - suffix - Optional : suffix string (Str) - decimals - Optional : positive number of decimals in percent complete (Int) - length - Optional : character length of bar (Int) - fill - Optional : bar fill character (Str) - printEnd - Optional : end character (e.g. "\r", "\r\n") (Str) - """ - percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) - filled_length = int(length * iteration // total) - bar = fill * filled_length + colored('-', 'red') * (length - filled_length) - print(f'\r{prefix} [{bar}] {percent}% ({iteration}/{total}) {suffix}', end = print_end) - # Print New Line on Complete - if iteration == total: - print() \ No newline at end of file diff --git a/spaces/CloudOrc/SolidUI/app.py b/spaces/CloudOrc/SolidUI/app.py deleted file mode 100644 index f07d7d97649b5638e3c741cf855236eb3adeaf7f..0000000000000000000000000000000000000000 --- a/spaces/CloudOrc/SolidUI/app.py +++ /dev/null @@ -1,84 +0,0 @@ -import gradio as gr -import matplotlib.pyplot as plt -import io -import numpy as np -from PIL import Image -import requests -import json -import re -import base64 - -def decode_image(img_b64): - img_data = base64.b64decode(img_b64) - img = Image.open(io.BytesIO(img_data)) - return img - -def get_image_data(fig): - buf = io.BytesIO() - fig.savefig(buf, format='png') - buf.seek(0) - img = Image.open(buf) - return img - -# Execute Python code and generate images -def execute_code(code): - namespace = {} - exec(code, namespace) - fig = namespace.get('fig') # Assume the code generates a matplotlib figure named 'fig' - if fig: - img = get_image_data(fig) - - img_byte_arr = io.BytesIO() - img.save(img_byte_arr, format='PNG') - img_byte_arr = img_byte_arr.getvalue() - img_b64 = base64.b64encode(img_byte_arr).decode('utf-8') - - return img_b64 - else: - raise ValueError("The code did not generate a matplotlib figure named 'fig'") - -def gpt_inference(base_url, model, openai_key, prompt): - - newprompt = f'Write Python code that does the following: \n\n{prompt}\n\nNote, the code is going to be executed in a Jupyter Python kernel. The code should create a matplotlib figure and assign it to a variable named "fig". The "fig" variable will be used for further processing.\n\nLast instruction, and this is the most important, just return code. No other outputs, as your full response will directly be executed in the kernel.' - - data = { - "model": model, - "messages": [ - { - "role": "user", - "content": newprompt - } - ], - "temperature": 0.7, - } - - headers = { - "Content-Type": "application/json", - "Authorization": f"Bearer {openai_key}", - } - - print(f"openai_key:{openai_key}") - response = requests.post(f"{base_url}/v1/chat/completions", headers=headers, data=json.dumps(data)) - print("Status code:", response.status_code) - print("Response JSON:", response.json()) - code = response.json()["choices"][0]["message"]["content"] - print(f"code:{code}") - img_b64 = execute_code(code) - img = decode_image(img_b64) - return img - - -iface = gr.Interface( - fn=gpt_inference, - inputs=[gr.components.Textbox(), gr.components.Dropdown(choices=["gpt-3.5-turbo", "gpt-4"], label="Model"), - gr.components.Textbox(), gr.components.Textbox()], - outputs=gr.Image(), - title="SolidUI AI-generated visualization platform", - description=""" - AI-generated visualization prototyping and editing platform, support 2D, 3D models, combined with LLM(Large Language Model) for quick editing. - GitHub: https://github.com/CloudOrc/SolidUI - """, - labels=["Base URL", "Model", "OpenAI Key", "Prompt"] - -) -iface.launch() \ No newline at end of file diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/altair/vegalite/schema.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/altair/vegalite/schema.py deleted file mode 100644 index e94c3d1991e96da81efe13cfe06214166afe80d1..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/altair/vegalite/schema.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Altair schema wrappers""" -# ruff: noqa -from .v5.schema import * diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio_client/documentation.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio_client/documentation.py deleted file mode 100644 index 4d8d41ddf85f5a860956dad6256af90fe6c7f483..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio_client/documentation.py +++ /dev/null @@ -1,266 +0,0 @@ -"""Contains methods that generate documentation for Gradio functions and classes.""" - -from __future__ import annotations - -import inspect -from typing import Callable - -classes_to_document = {} -classes_inherit_documentation = {} -documentation_group = None - - -def set_documentation_group(m): - global documentation_group - documentation_group = m - if m not in classes_to_document: - classes_to_document[m] = [] - - -def extract_instance_attr_doc(cls, attr): - code = inspect.getsource(cls.__init__) - lines = [line.strip() for line in code.split("\n")] - i = None - for i, line in enumerate(lines): # noqa: B007 - if line.startswith("self." + attr + ":") or line.startswith( - "self." + attr + " =" - ): - break - assert i is not None, f"Could not find {attr} in {cls.__name__}" - start_line = lines.index('"""', i) - end_line = lines.index('"""', start_line + 1) - for j in range(i + 1, start_line): - assert not lines[j].startswith("self."), ( - f"Found another attribute before docstring for {attr} in {cls.__name__}: " - + lines[j] - + "\n start:" - + lines[i] - ) - doc_string = " ".join(lines[start_line + 1 : end_line]) - return doc_string - - -def document(*fns, inherit=False): - """ - Defines the @document decorator which adds classes or functions to the Gradio - documentation at www.gradio.app/docs. - - Usage examples: - - Put @document() above a class to document the class and its constructor. - - Put @document("fn1", "fn2") above a class to also document methods fn1 and fn2. - - Put @document("*fn3") with an asterisk above a class to document the instance attribute methods f3. - """ - - def inner_doc(cls): - global documentation_group - if inherit: - classes_inherit_documentation[cls] = None - classes_to_document[documentation_group].append((cls, fns)) - return cls - - return inner_doc - - -def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: - """ - Generates documentation for any function. - Parameters: - fn: Function to document - Returns: - description: General description of fn - parameters: A list of dicts for each parameter, storing data for the parameter name, annotation and doc - return: A dict storing data for the returned annotation and doc - example: Code for an example use of the fn - """ - doc_str = inspect.getdoc(fn) or "" - doc_lines = doc_str.split("\n") - signature = inspect.signature(fn) - description, parameters, returns, examples = [], {}, [], [] - mode = "description" - for line in doc_lines: - line = line.rstrip() - if line == "Parameters:": - mode = "parameter" - elif line.startswith("Example:"): - mode = "example" - if "(" in line and ")" in line: - c = line.split("(")[1].split(")")[0] - if c != cls.__name__: - mode = "ignore" - elif line == "Returns:": - mode = "return" - else: - if mode == "description": - description.append(line if line.strip() else "
    ") - continue - if not (line.startswith(" ") or line.strip() == ""): - print(line) - assert ( - line.startswith(" ") or line.strip() == "" - ), f"Documentation format for {fn.__name__} has format error in line: {line}" - line = line[4:] - if mode == "parameter": - colon_index = line.index(": ") - assert ( - colon_index > -1 - ), f"Documentation format for {fn.__name__} has format error in line: {line}" - parameter = line[:colon_index] - parameter_doc = line[colon_index + 2 :] - parameters[parameter] = parameter_doc - elif mode == "return": - returns.append(line) - elif mode == "example": - examples.append(line) - description_doc = " ".join(description) - parameter_docs = [] - for param_name, param in signature.parameters.items(): - if param_name.startswith("_"): - continue - if param_name in ["kwargs", "args"] and param_name not in parameters: - continue - parameter_doc = { - "name": param_name, - "annotation": param.annotation, - "doc": parameters.get(param_name), - } - if param_name in parameters: - del parameters[param_name] - if param.default != inspect.Parameter.empty: - default = param.default - if type(default) == str: - default = '"' + default + '"' - if default.__class__.__module__ != "builtins": - default = f"{default.__class__.__name__}()" - parameter_doc["default"] = default - elif parameter_doc["doc"] is not None: - if "kwargs" in parameter_doc["doc"]: - parameter_doc["kwargs"] = True - if "args" in parameter_doc["doc"]: - parameter_doc["args"] = True - parameter_docs.append(parameter_doc) - assert ( - len(parameters) == 0 - ), f"Documentation format for {fn.__name__} documents nonexistent parameters: {''.join(parameters.keys())}" - if len(returns) == 0: - return_docs = {} - elif len(returns) == 1: - return_docs = {"annotation": signature.return_annotation, "doc": returns[0]} - else: - return_docs = {} - # raise ValueError("Does not support multiple returns yet.") - examples_doc = "\n".join(examples) if len(examples) > 0 else None - return description_doc, parameter_docs, return_docs, examples_doc - - -def document_cls(cls): - doc_str = inspect.getdoc(cls) - if doc_str is None: - return "", {}, "" - tags = {} - description_lines = [] - mode = "description" - for line in doc_str.split("\n"): - line = line.rstrip() - if line.endswith(":") and " " not in line: - mode = line[:-1].lower() - tags[mode] = [] - elif line.split(" ")[0].endswith(":") and not line.startswith(" "): - tag = line[: line.index(":")].lower() - value = line[line.index(":") + 2 :] - tags[tag] = value - else: - if mode == "description": - description_lines.append(line if line.strip() else "
    ") - else: - assert ( - line.startswith(" ") or not line.strip() - ), f"Documentation format for {cls.__name__} has format error in line: {line}" - tags[mode].append(line[4:]) - if "example" in tags: - example = "\n".join(tags["example"]) - del tags["example"] - else: - example = None - for key, val in tags.items(): - if isinstance(val, list): - tags[key] = "
    ".join(val) - description = " ".join(description_lines).replace("\n", "
    ") - return description, tags, example - - -def generate_documentation(): - documentation = {} - for mode, class_list in classes_to_document.items(): - documentation[mode] = [] - for cls, fns in class_list: - fn_to_document = cls if inspect.isfunction(cls) else cls.__init__ - _, parameter_doc, return_doc, _ = document_fn(fn_to_document, cls) - cls_description, cls_tags, cls_example = document_cls(cls) - cls_documentation = { - "class": cls, - "name": cls.__name__, - "description": cls_description, - "tags": cls_tags, - "parameters": parameter_doc, - "returns": return_doc, - "example": cls_example, - "fns": [], - } - for fn_name in fns: - instance_attribute_fn = fn_name.startswith("*") - if instance_attribute_fn: - fn_name = fn_name[1:] - # Instance attribute fns are classes - # whose __call__ method determines their behavior - fn = getattr(cls(), fn_name).__call__ - else: - fn = getattr(cls, fn_name) - if not callable(fn): - description_doc = str(fn) - parameter_docs = {} - return_docs = {} - examples_doc = "" - override_signature = f"gr.{cls.__name__}.{fn_name}" - else: - ( - description_doc, - parameter_docs, - return_docs, - examples_doc, - ) = document_fn(fn, cls) - override_signature = None - if instance_attribute_fn: - description_doc = extract_instance_attr_doc(cls, fn_name) - cls_documentation["fns"].append( - { - "fn": fn, - "name": fn_name, - "description": description_doc, - "tags": {}, - "parameters": parameter_docs, - "returns": return_docs, - "example": examples_doc, - "override_signature": override_signature, - } - ) - documentation[mode].append(cls_documentation) - if cls in classes_inherit_documentation: - classes_inherit_documentation[cls] = cls_documentation["fns"] - for mode, class_list in classes_to_document.items(): - for i, (cls, _) in enumerate(class_list): - for super_class in classes_inherit_documentation: - if ( - inspect.isclass(cls) - and issubclass(cls, super_class) - and cls != super_class - ): - for inherited_fn in classes_inherit_documentation[super_class]: - inherited_fn = dict(inherited_fn) - try: - inherited_fn["description"] = extract_instance_attr_doc( - cls, inherited_fn["name"] - ) - except (ValueError, AssertionError): - pass - documentation[mode][i]["fns"].append(inherited_fn) - return documentation diff --git a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/h11/tests/test_events.py b/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/h11/tests/test_events.py deleted file mode 100644 index bc6c3137063888e05ec4af77bed6c6fd1a3d1594..0000000000000000000000000000000000000000 --- a/spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/h11/tests/test_events.py +++ /dev/null @@ -1,150 +0,0 @@ -from http import HTTPStatus - -import pytest - -from .. import _events -from .._events import ( - ConnectionClosed, - Data, - EndOfMessage, - Event, - InformationalResponse, - Request, - Response, -) -from .._util import LocalProtocolError - - -def test_events() -> None: - with pytest.raises(LocalProtocolError): - # Missing Host: - req = Request( - method="GET", target="/", headers=[("a", "b")], http_version="1.1" - ) - # But this is okay (HTTP/1.0) - req = Request(method="GET", target="/", headers=[("a", "b")], http_version="1.0") - # fields are normalized - assert req.method == b"GET" - assert req.target == b"/" - assert req.headers == [(b"a", b"b")] - assert req.http_version == b"1.0" - - # This is also okay -- has a Host (with weird capitalization, which is ok) - req = Request( - method="GET", - target="/", - headers=[("a", "b"), ("hOSt", "example.com")], - http_version="1.1", - ) - # we normalize header capitalization - assert req.headers == [(b"a", b"b"), (b"host", b"example.com")] - - # Multiple host is bad too - with pytest.raises(LocalProtocolError): - req = Request( - method="GET", - target="/", - headers=[("Host", "a"), ("Host", "a")], - http_version="1.1", - ) - # Even for HTTP/1.0 - with pytest.raises(LocalProtocolError): - req = Request( - method="GET", - target="/", - headers=[("Host", "a"), ("Host", "a")], - http_version="1.0", - ) - - # Header values are validated - for bad_char in "\x00\r\n\f\v": - with pytest.raises(LocalProtocolError): - req = Request( - method="GET", - target="/", - headers=[("Host", "a"), ("Foo", "asd" + bad_char)], - http_version="1.0", - ) - - # But for compatibility we allow non-whitespace control characters, even - # though they're forbidden by the spec. - Request( - method="GET", - target="/", - headers=[("Host", "a"), ("Foo", "asd\x01\x02\x7f")], - http_version="1.0", - ) - - # Request target is validated - for bad_byte in b"\x00\x20\x7f\xee": - target = bytearray(b"/") - target.append(bad_byte) - with pytest.raises(LocalProtocolError): - Request( - method="GET", target=target, headers=[("Host", "a")], http_version="1.1" - ) - - # Request method is validated - with pytest.raises(LocalProtocolError): - Request( - method="GET / HTTP/1.1", - target=target, - headers=[("Host", "a")], - http_version="1.1", - ) - - ir = InformationalResponse(status_code=100, headers=[("Host", "a")]) - assert ir.status_code == 100 - assert ir.headers == [(b"host", b"a")] - assert ir.http_version == b"1.1" - - with pytest.raises(LocalProtocolError): - InformationalResponse(status_code=200, headers=[("Host", "a")]) - - resp = Response(status_code=204, headers=[], http_version="1.0") # type: ignore[arg-type] - assert resp.status_code == 204 - assert resp.headers == [] - assert resp.http_version == b"1.0" - - with pytest.raises(LocalProtocolError): - resp = Response(status_code=100, headers=[], http_version="1.0") # type: ignore[arg-type] - - with pytest.raises(LocalProtocolError): - Response(status_code="100", headers=[], http_version="1.0") # type: ignore[arg-type] - - with pytest.raises(LocalProtocolError): - InformationalResponse(status_code=b"100", headers=[], http_version="1.0") # type: ignore[arg-type] - - d = Data(data=b"asdf") - assert d.data == b"asdf" - - eom = EndOfMessage() - assert eom.headers == [] - - cc = ConnectionClosed() - assert repr(cc) == "ConnectionClosed()" - - -def test_intenum_status_code() -> None: - # https://github.com/python-hyper/h11/issues/72 - - r = Response(status_code=HTTPStatus.OK, headers=[], http_version="1.0") # type: ignore[arg-type] - assert r.status_code == HTTPStatus.OK - assert type(r.status_code) is not type(HTTPStatus.OK) - assert type(r.status_code) is int - - -def test_header_casing() -> None: - r = Request( - method="GET", - target="/", - headers=[("Host", "example.org"), ("Connection", "keep-alive")], - http_version="1.1", - ) - assert len(r.headers) == 2 - assert r.headers[0] == (b"host", b"example.org") - assert r.headers == [(b"host", b"example.org"), (b"connection", b"keep-alive")] - assert r.headers.raw_items() == [ - (b"Host", b"example.org"), - (b"Connection", b"keep-alive"), - ] diff --git a/spaces/Dagfinn1962/stablediffusion-models/app1.py b/spaces/Dagfinn1962/stablediffusion-models/app1.py deleted file mode 100644 index 878c757de65298f3affa61b5456b53e02dadb9fd..0000000000000000000000000000000000000000 --- a/spaces/Dagfinn1962/stablediffusion-models/app1.py +++ /dev/null @@ -1,80 +0,0 @@ -import gradio as gr -import os -import sys -from pathlib import Path - -models = [ - {"name": "Stable Diffusion 1.4","url": "CompVis/stable-diffusion-v1-4"}, - {"name": "Stable Diffusion 1.5","url": "runwayml/stable-diffusion-v1-5"}, - ] - -current_model = models[0] - -text_gen = gr.Interface.load("spaces/daspartho/prompt-extend") - -models2 = [] -for model in models: - model_url = f"models/{model['url']}" - loaded_model = gr.Interface.load(model_url, live=True, preprocess=True) - models2.append(loaded_model) - - -def text_it(inputs, text_gen=text_gen): - return text_gen(inputs) - - -def set_model(current_model_index): - global current_model - current_model = models[current_model_index] - return gr.update(value=f"{current_model['name']}") - - -def send_it(inputs, model_choice): - proc = models2[model_choice] - return proc(inputs) - - -with gr.Blocks() as myface: - gr.HTML(""" - """ - - ) - with gr.Row(): - input_text = gr.Textbox(label=" ",placeholder="PROMPT HERE ",lines=4) - # Model selection dropdown - model_name1 = gr.Dropdown( - label=" ", - choices=[m["name"] for m in models], - type="index", - value=current_model["name"], - interactive=True, - - - ) - with gr.Row(): - see_prompts = gr.Button("Generate Prompts") - run = gr.Button("Generate Images", varant="primery") - - with gr.Row(): - output1 = gr.Image(label="") - output2 = gr.Image(label="") - output3 = gr.Image(label="") - with gr.Row(): - magic1 = gr.Textbox(label="Generated Prompt", lines=2) - magic2 = gr.Textbox(label="Generated Prompt", lines=2) - magic3 = gr.Textbox(label="Generated Prompt", lines=2) - - model_name1.change(set_model, inputs=model_name1, outputs=[output1, output2, output3,]) - - run.click(send_it, inputs=[magic1, model_name1], outputs=[output1]) - run.click(send_it, inputs=[magic2, model_name1], outputs=[output2]) - run.click(send_it, inputs=[magic3, model_name1], outputs=[output3]) - - - see_prompts.click(text_it, inputs=[input_text], outputs=[magic1]) - see_prompts.click(text_it, inputs=[input_text], outputs=[magic2]) - see_prompts.click(text_it, inputs=[input_text], outputs=[magic3]) - - -myface.queue(concurrency_count=200) -myface.launch(inline=True, show_api=False, max_threads=400) \ No newline at end of file diff --git a/spaces/Datasculptor/DescriptionGPT/detic/modeling/roi_heads/zero_shot_classifier.py b/spaces/Datasculptor/DescriptionGPT/detic/modeling/roi_heads/zero_shot_classifier.py deleted file mode 100644 index edf217c6dbe74fa68e4d7653488bdd5e2e0c2f0e..0000000000000000000000000000000000000000 --- a/spaces/Datasculptor/DescriptionGPT/detic/modeling/roi_heads/zero_shot_classifier.py +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F -from detectron2.config import configurable -from detectron2.layers import Linear, ShapeSpec - -class ZeroShotClassifier(nn.Module): - @configurable - def __init__( - self, - input_shape: ShapeSpec, - *, - num_classes: int, - zs_weight_path: str, - zs_weight_dim: int = 512, - use_bias: float = 0.0, - norm_weight: bool = True, - norm_temperature: float = 50.0, - ): - super().__init__() - if isinstance(input_shape, int): # some backward compatibility - input_shape = ShapeSpec(channels=input_shape) - input_size = input_shape.channels * (input_shape.width or 1) * (input_shape.height or 1) - self.norm_weight = norm_weight - self.norm_temperature = norm_temperature - - self.use_bias = use_bias < 0 - if self.use_bias: - self.cls_bias = nn.Parameter(torch.ones(1) * use_bias) - - self.linear = nn.Linear(input_size, zs_weight_dim) - - if zs_weight_path == 'rand': - zs_weight = torch.randn((zs_weight_dim, num_classes)) - nn.init.normal_(zs_weight, std=0.01) - else: - zs_weight = torch.tensor( - np.load(zs_weight_path), - dtype=torch.float32).permute(1, 0).contiguous() # D x C - zs_weight = torch.cat( - [zs_weight, zs_weight.new_zeros((zs_weight_dim, 1))], - dim=1) # D x (C + 1) - - if self.norm_weight: - zs_weight = F.normalize(zs_weight, p=2, dim=0) - - if zs_weight_path == 'rand': - self.zs_weight = nn.Parameter(zs_weight) - else: - self.register_buffer('zs_weight', zs_weight) - - assert self.zs_weight.shape[1] == num_classes + 1, self.zs_weight.shape - - - @classmethod - def from_config(cls, cfg, input_shape): - return { - 'input_shape': input_shape, - 'num_classes': cfg.MODEL.ROI_HEADS.NUM_CLASSES, - 'zs_weight_path': cfg.MODEL.ROI_BOX_HEAD.ZEROSHOT_WEIGHT_PATH, - 'zs_weight_dim': cfg.MODEL.ROI_BOX_HEAD.ZEROSHOT_WEIGHT_DIM, - 'use_bias': cfg.MODEL.ROI_BOX_HEAD.USE_BIAS, - 'norm_weight': cfg.MODEL.ROI_BOX_HEAD.NORM_WEIGHT, - 'norm_temperature': cfg.MODEL.ROI_BOX_HEAD.NORM_TEMP, - } - - def forward(self, x, classifier=None): - ''' - Inputs: - x: B x D' - classifier_info: (C', C' x D) - ''' - x = self.linear(x) - if classifier is not None: - zs_weight = classifier.permute(1, 0).contiguous() # D x C' - zs_weight = F.normalize(zs_weight, p=2, dim=0) \ - if self.norm_weight else zs_weight - else: - zs_weight = self.zs_weight - if self.norm_weight: - x = self.norm_temperature * F.normalize(x, p=2, dim=1) - x = torch.mm(x, zs_weight) - if self.use_bias: - x = x + self.cls_bias - return x \ No newline at end of file diff --git a/spaces/Datasculptor/StyleGAN-NADA/op/upfirdn2d.py b/spaces/Datasculptor/StyleGAN-NADA/op/upfirdn2d.py deleted file mode 100644 index f1bbf96777f2c7267c1fef1733972014684ea22b..0000000000000000000000000000000000000000 --- a/spaces/Datasculptor/StyleGAN-NADA/op/upfirdn2d.py +++ /dev/null @@ -1,187 +0,0 @@ -import os - -import torch -from torch.autograd import Function -from torch.utils.cpp_extension import load - - -module_path = os.path.dirname(__file__) -upfirdn2d_op = load( - 'upfirdn2d', - sources=[ - os.path.join(module_path, 'upfirdn2d.cpp'), - os.path.join(module_path, 'upfirdn2d_kernel.cu'), - ], -) - - -class UpFirDn2dBackward(Function): - @staticmethod - def forward( - ctx, grad_output, kernel, grad_kernel, up, down, pad, g_pad, in_size, out_size - ): - - up_x, up_y = up - down_x, down_y = down - g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1 = g_pad - - grad_output = grad_output.reshape(-1, out_size[0], out_size[1], 1) - - grad_input = upfirdn2d_op.upfirdn2d( - grad_output, - grad_kernel, - down_x, - down_y, - up_x, - up_y, - g_pad_x0, - g_pad_x1, - g_pad_y0, - g_pad_y1, - ) - grad_input = grad_input.view(in_size[0], in_size[1], in_size[2], in_size[3]) - - ctx.save_for_backward(kernel) - - pad_x0, pad_x1, pad_y0, pad_y1 = pad - - ctx.up_x = up_x - ctx.up_y = up_y - ctx.down_x = down_x - ctx.down_y = down_y - ctx.pad_x0 = pad_x0 - ctx.pad_x1 = pad_x1 - ctx.pad_y0 = pad_y0 - ctx.pad_y1 = pad_y1 - ctx.in_size = in_size - ctx.out_size = out_size - - return grad_input - - @staticmethod - def backward(ctx, gradgrad_input): - kernel, = ctx.saved_tensors - - gradgrad_input = gradgrad_input.reshape(-1, ctx.in_size[2], ctx.in_size[3], 1) - - gradgrad_out = upfirdn2d_op.upfirdn2d( - gradgrad_input, - kernel, - ctx.up_x, - ctx.up_y, - ctx.down_x, - ctx.down_y, - ctx.pad_x0, - ctx.pad_x1, - ctx.pad_y0, - ctx.pad_y1, - ) - # gradgrad_out = gradgrad_out.view(ctx.in_size[0], ctx.out_size[0], ctx.out_size[1], ctx.in_size[3]) - gradgrad_out = gradgrad_out.view( - ctx.in_size[0], ctx.in_size[1], ctx.out_size[0], ctx.out_size[1] - ) - - return gradgrad_out, None, None, None, None, None, None, None, None - - -class UpFirDn2d(Function): - @staticmethod - def forward(ctx, input, kernel, up, down, pad): - up_x, up_y = up - down_x, down_y = down - pad_x0, pad_x1, pad_y0, pad_y1 = pad - - kernel_h, kernel_w = kernel.shape - batch, channel, in_h, in_w = input.shape - ctx.in_size = input.shape - - input = input.reshape(-1, in_h, in_w, 1) - - ctx.save_for_backward(kernel, torch.flip(kernel, [0, 1])) - - out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1 - out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1 - ctx.out_size = (out_h, out_w) - - ctx.up = (up_x, up_y) - ctx.down = (down_x, down_y) - ctx.pad = (pad_x0, pad_x1, pad_y0, pad_y1) - - g_pad_x0 = kernel_w - pad_x0 - 1 - g_pad_y0 = kernel_h - pad_y0 - 1 - g_pad_x1 = in_w * up_x - out_w * down_x + pad_x0 - up_x + 1 - g_pad_y1 = in_h * up_y - out_h * down_y + pad_y0 - up_y + 1 - - ctx.g_pad = (g_pad_x0, g_pad_x1, g_pad_y0, g_pad_y1) - - out = upfirdn2d_op.upfirdn2d( - input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1 - ) - # out = out.view(major, out_h, out_w, minor) - out = out.view(-1, channel, out_h, out_w) - - return out - - @staticmethod - def backward(ctx, grad_output): - kernel, grad_kernel = ctx.saved_tensors - - grad_input = UpFirDn2dBackward.apply( - grad_output, - kernel, - grad_kernel, - ctx.up, - ctx.down, - ctx.pad, - ctx.g_pad, - ctx.in_size, - ctx.out_size, - ) - - return grad_input, None, None, None, None - - -def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): - out = UpFirDn2d.apply( - input, kernel, (up, up), (down, down), (pad[0], pad[1], pad[0], pad[1]) - ) - - return out - - -def upfirdn2d_native( - input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1 -): - _, in_h, in_w, minor = input.shape - kernel_h, kernel_w = kernel.shape - - out = input.view(-1, in_h, 1, in_w, 1, minor) - out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1]) - out = out.view(-1, in_h * up_y, in_w * up_x, minor) - - out = F.pad( - out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)] - ) - out = out[ - :, - max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0), - max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0), - :, - ] - - out = out.permute(0, 3, 1, 2) - out = out.reshape( - [-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1] - ) - w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) - out = F.conv2d(out, w) - out = out.reshape( - -1, - minor, - in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, - in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, - ) - out = out.permute(0, 2, 3, 1) - - return out[:, ::down_y, ::down_x, :] - diff --git a/spaces/DeclK/pose/tools/deploy.py b/spaces/DeclK/pose/tools/deploy.py deleted file mode 100644 index 2fb1dc5d22ba44b67ff535b34e04da0f92e6967d..0000000000000000000000000000000000000000 --- a/spaces/DeclK/pose/tools/deploy.py +++ /dev/null @@ -1,236 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -# Modified from mmdeploy/tools/deploy.py, removed some codes to only focus on ONNX report -import argparse -import logging -import os -import os.path as osp -from functools import partial - -import mmengine -import torch.multiprocessing as mp -from torch.multiprocessing import Process, set_start_method - -from mmdeploy.apis import (create_calib_input_data, extract_model, - get_predefined_partition_cfg, torch2onnx, - torch2torchscript, visualize_model) -from mmdeploy.apis.core import PIPELINE_MANAGER -from mmdeploy.apis.utils import to_backend -from mmdeploy.backend.sdk.export_info import export2SDK -from mmdeploy.utils import (IR, Backend, get_backend, get_calib_filename, - get_ir_config, get_partition_config, - get_root_logger, load_config, target_wrapper) - - -def parse_args(): - parser = argparse.ArgumentParser(description='Export model to backends.') - parser.add_argument('deploy_cfg', help='deploy config path') - parser.add_argument('model_cfg', help='model config path') - parser.add_argument('checkpoint', help='model checkpoint path') - parser.add_argument('img', help='image used to convert model model') - parser.add_argument( - '--test-img', - default=None, - type=str, - nargs='+', - help='image used to test model') - parser.add_argument( - '--work-dir', - default=os.getcwd(), - help='the dir to save logs and models') - parser.add_argument( - '--calib-dataset-cfg', - help='dataset config path used to calibrate in int8 mode. If not \ - specified, it will use "val" dataset in model config instead.', - default=None) - parser.add_argument( - '--device', help='device used for conversion', default='cpu') - parser.add_argument( - '--log-level', - help='set log level', - default='INFO', - choices=list(logging._nameToLevel.keys())) - parser.add_argument( - '--show', action='store_true', help='Show detection outputs') - parser.add_argument( - '--dump-info', action='store_true', help='Output information for SDK') - parser.add_argument( - '--quant-image-dir', - default=None, - help='Image directory for quantize model.') - parser.add_argument( - '--quant', action='store_true', help='Quantize model to low bit.') - parser.add_argument( - '--uri', - default='192.168.1.1:60000', - help='Remote ipv4:port or ipv6:port for inference on edge device.') - args = parser.parse_args() - return args - - -def create_process(name, target, args, kwargs, ret_value=None): - logger = get_root_logger() - logger.info(f'{name} start.') - log_level = logger.level - - wrap_func = partial(target_wrapper, target, log_level, ret_value) - - process = Process(target=wrap_func, args=args, kwargs=kwargs) - process.start() - process.join() - - if ret_value is not None: - if ret_value.value != 0: - logger.error(f'{name} failed.') - exit(1) - else: - logger.info(f'{name} success.') - - -def torch2ir(ir_type: IR): - """Return the conversion function from torch to the intermediate - representation. - - Args: - ir_type (IR): The type of the intermediate representation. - """ - if ir_type == IR.ONNX: - return torch2onnx - elif ir_type == IR.TORCHSCRIPT: - return torch2torchscript - else: - raise KeyError(f'Unexpected IR type {ir_type}') - - -def main(): - args = parse_args() - set_start_method('spawn', force=True) - logger = get_root_logger() - log_level = logging.getLevelName(args.log_level) - logger.setLevel(log_level) - - pipeline_funcs = [ - torch2onnx, torch2torchscript, extract_model, create_calib_input_data - ] - PIPELINE_MANAGER.enable_multiprocess(True, pipeline_funcs) - PIPELINE_MANAGER.set_log_level(log_level, pipeline_funcs) - - deploy_cfg_path = args.deploy_cfg - model_cfg_path = args.model_cfg - checkpoint_path = args.checkpoint - quant = args.quant - quant_image_dir = args.quant_image_dir - - # load deploy_cfg - deploy_cfg, model_cfg = load_config(deploy_cfg_path, model_cfg_path) - - # create work_dir if not - mmengine.mkdir_or_exist(osp.abspath(args.work_dir)) - - if args.dump_info: - export2SDK( - deploy_cfg, - model_cfg, - args.work_dir, - pth=checkpoint_path, - device=args.device) - - ret_value = mp.Value('d', 0, lock=False) - - # convert to IR - ir_config = get_ir_config(deploy_cfg) - ir_save_file = ir_config['save_file'] - ir_type = IR.get(ir_config['type']) - torch2ir(ir_type)( - args.img, - args.work_dir, - ir_save_file, - deploy_cfg_path, - model_cfg_path, - checkpoint_path, - device=args.device) - - # convert backend - ir_files = [osp.join(args.work_dir, ir_save_file)] - - # partition model - partition_cfgs = get_partition_config(deploy_cfg) - - if partition_cfgs is not None: - - if 'partition_cfg' in partition_cfgs: - partition_cfgs = partition_cfgs.get('partition_cfg', None) - else: - assert 'type' in partition_cfgs - partition_cfgs = get_predefined_partition_cfg( - deploy_cfg, partition_cfgs['type']) - - origin_ir_file = ir_files[0] - ir_files = [] - for partition_cfg in partition_cfgs: - save_file = partition_cfg['save_file'] - save_path = osp.join(args.work_dir, save_file) - start = partition_cfg['start'] - end = partition_cfg['end'] - dynamic_axes = partition_cfg.get('dynamic_axes', None) - - extract_model( - origin_ir_file, - start, - end, - dynamic_axes=dynamic_axes, - save_file=save_path) - - ir_files.append(save_path) - - backend_files = ir_files - # convert backend - backend = get_backend(deploy_cfg) - - # convert to backend - PIPELINE_MANAGER.set_log_level(log_level, [to_backend]) - if backend == Backend.TENSORRT: - PIPELINE_MANAGER.enable_multiprocess(True, [to_backend]) - backend_files = to_backend( - backend, - ir_files, - work_dir=args.work_dir, - deploy_cfg=deploy_cfg, - log_level=log_level, - device=args.device, - uri=args.uri) - - if args.test_img is None: - args.test_img = args.img - - extra = dict( - backend=backend, - output_file=osp.join(args.work_dir, f'output_{backend.value}.jpg'), - show_result=args.show) - if backend == Backend.SNPE: - extra['uri'] = args.uri - - # get backend inference result, try render - create_process( - f'visualize {backend.value} model', - target=visualize_model, - args=(model_cfg_path, deploy_cfg_path, backend_files, args.test_img, - args.device), - kwargs=extra, - ret_value=ret_value) - - # get pytorch model inference result, try visualize if possible - create_process( - 'visualize pytorch model', - target=visualize_model, - args=(model_cfg_path, deploy_cfg_path, [checkpoint_path], - args.test_img, args.device), - kwargs=dict( - backend=Backend.PYTORCH, - output_file=osp.join(args.work_dir, 'output_pytorch.jpg'), - show_result=args.show), - ret_value=ret_value) - logger.info('All process success.') - - -if __name__ == '__main__': - main() diff --git a/spaces/Detomo/Object_detection/README.md b/spaces/Detomo/Object_detection/README.md deleted file mode 100644 index d46644972f83420ec5b20aa68880e132a24daeeb..0000000000000000000000000000000000000000 --- a/spaces/Detomo/Object_detection/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Object Detection -emoji: 😻 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.21.0 -app_file: app.py -pinned: false -license: creativeml-openrail-m ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Dileepgorantala/dileepAI/README.md b/spaces/Dileepgorantala/dileepAI/README.md deleted file mode 100644 index 8f7deed7a59107a5e9b479fe606f3caa76a2560f..0000000000000000000000000000000000000000 --- a/spaces/Dileepgorantala/dileepAI/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: DileepAI -emoji: ⚡ -colorFrom: green -colorTo: blue -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/inception.py b/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/inception.py deleted file mode 100644 index f3afed8123e595f65c1333dea7151e653a836e2b..0000000000000000000000000000000000000000 --- a/spaces/Dinoking/Guccio-AI-Designer/models/stylegan2/stylegan2-pytorch/inception.py +++ /dev/null @@ -1,310 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F -from torchvision import models - -try: - from torchvision.models.utils import load_state_dict_from_url -except ImportError: - from torch.utils.model_zoo import load_url as load_state_dict_from_url - -# Inception weights ported to Pytorch from -# http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz -FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth' - - -class InceptionV3(nn.Module): - """Pretrained InceptionV3 network returning feature maps""" - - # Index of default block of inception to return, - # corresponds to output of final average pooling - DEFAULT_BLOCK_INDEX = 3 - - # Maps feature dimensionality to their output blocks indices - BLOCK_INDEX_BY_DIM = { - 64: 0, # First max pooling features - 192: 1, # Second max pooling featurs - 768: 2, # Pre-aux classifier features - 2048: 3 # Final average pooling features - } - - def __init__(self, - output_blocks=[DEFAULT_BLOCK_INDEX], - resize_input=True, - normalize_input=True, - requires_grad=False, - use_fid_inception=True): - """Build pretrained InceptionV3 - - Parameters - ---------- - output_blocks : list of int - Indices of blocks to return features of. Possible values are: - - 0: corresponds to output of first max pooling - - 1: corresponds to output of second max pooling - - 2: corresponds to output which is fed to aux classifier - - 3: corresponds to output of final average pooling - resize_input : bool - If true, bilinearly resizes input to width and height 299 before - feeding input to model. As the network without fully connected - layers is fully convolutional, it should be able to handle inputs - of arbitrary size, so resizing might not be strictly needed - normalize_input : bool - If true, scales the input from range (0, 1) to the range the - pretrained Inception network expects, namely (-1, 1) - requires_grad : bool - If true, parameters of the model require gradients. Possibly useful - for finetuning the network - use_fid_inception : bool - If true, uses the pretrained Inception model used in Tensorflow's - FID implementation. If false, uses the pretrained Inception model - available in torchvision. The FID Inception model has different - weights and a slightly different structure from torchvision's - Inception model. If you want to compute FID scores, you are - strongly advised to set this parameter to true to get comparable - results. - """ - super(InceptionV3, self).__init__() - - self.resize_input = resize_input - self.normalize_input = normalize_input - self.output_blocks = sorted(output_blocks) - self.last_needed_block = max(output_blocks) - - assert self.last_needed_block <= 3, \ - 'Last possible output block index is 3' - - self.blocks = nn.ModuleList() - - if use_fid_inception: - inception = fid_inception_v3() - else: - inception = models.inception_v3(pretrained=True) - - # Block 0: input to maxpool1 - block0 = [ - inception.Conv2d_1a_3x3, - inception.Conv2d_2a_3x3, - inception.Conv2d_2b_3x3, - nn.MaxPool2d(kernel_size=3, stride=2) - ] - self.blocks.append(nn.Sequential(*block0)) - - # Block 1: maxpool1 to maxpool2 - if self.last_needed_block >= 1: - block1 = [ - inception.Conv2d_3b_1x1, - inception.Conv2d_4a_3x3, - nn.MaxPool2d(kernel_size=3, stride=2) - ] - self.blocks.append(nn.Sequential(*block1)) - - # Block 2: maxpool2 to aux classifier - if self.last_needed_block >= 2: - block2 = [ - inception.Mixed_5b, - inception.Mixed_5c, - inception.Mixed_5d, - inception.Mixed_6a, - inception.Mixed_6b, - inception.Mixed_6c, - inception.Mixed_6d, - inception.Mixed_6e, - ] - self.blocks.append(nn.Sequential(*block2)) - - # Block 3: aux classifier to final avgpool - if self.last_needed_block >= 3: - block3 = [ - inception.Mixed_7a, - inception.Mixed_7b, - inception.Mixed_7c, - nn.AdaptiveAvgPool2d(output_size=(1, 1)) - ] - self.blocks.append(nn.Sequential(*block3)) - - for param in self.parameters(): - param.requires_grad = requires_grad - - def forward(self, inp): - """Get Inception feature maps - - Parameters - ---------- - inp : torch.autograd.Variable - Input tensor of shape Bx3xHxW. Values are expected to be in - range (0, 1) - - Returns - ------- - List of torch.autograd.Variable, corresponding to the selected output - block, sorted ascending by index - """ - outp = [] - x = inp - - if self.resize_input: - x = F.interpolate(x, - size=(299, 299), - mode='bilinear', - align_corners=False) - - if self.normalize_input: - x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1) - - for idx, block in enumerate(self.blocks): - x = block(x) - if idx in self.output_blocks: - outp.append(x) - - if idx == self.last_needed_block: - break - - return outp - - -def fid_inception_v3(): - """Build pretrained Inception model for FID computation - - The Inception model for FID computation uses a different set of weights - and has a slightly different structure than torchvision's Inception. - - This method first constructs torchvision's Inception and then patches the - necessary parts that are different in the FID Inception model. - """ - inception = models.inception_v3(num_classes=1008, - aux_logits=False, - pretrained=False) - inception.Mixed_5b = FIDInceptionA(192, pool_features=32) - inception.Mixed_5c = FIDInceptionA(256, pool_features=64) - inception.Mixed_5d = FIDInceptionA(288, pool_features=64) - inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128) - inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160) - inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160) - inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192) - inception.Mixed_7b = FIDInceptionE_1(1280) - inception.Mixed_7c = FIDInceptionE_2(2048) - - state_dict = load_state_dict_from_url(FID_WEIGHTS_URL, progress=True) - inception.load_state_dict(state_dict) - return inception - - -class FIDInceptionA(models.inception.InceptionA): - """InceptionA block patched for FID computation""" - def __init__(self, in_channels, pool_features): - super(FIDInceptionA, self).__init__(in_channels, pool_features) - - def forward(self, x): - branch1x1 = self.branch1x1(x) - - branch5x5 = self.branch5x5_1(x) - branch5x5 = self.branch5x5_2(branch5x5) - - branch3x3dbl = self.branch3x3dbl_1(x) - branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) - branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) - - # Patch: Tensorflow's average pool does not use the padded zero's in - # its average calculation - branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, - count_include_pad=False) - branch_pool = self.branch_pool(branch_pool) - - outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool] - return torch.cat(outputs, 1) - - -class FIDInceptionC(models.inception.InceptionC): - """InceptionC block patched for FID computation""" - def __init__(self, in_channels, channels_7x7): - super(FIDInceptionC, self).__init__(in_channels, channels_7x7) - - def forward(self, x): - branch1x1 = self.branch1x1(x) - - branch7x7 = self.branch7x7_1(x) - branch7x7 = self.branch7x7_2(branch7x7) - branch7x7 = self.branch7x7_3(branch7x7) - - branch7x7dbl = self.branch7x7dbl_1(x) - branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) - branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) - branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) - branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) - - # Patch: Tensorflow's average pool does not use the padded zero's in - # its average calculation - branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, - count_include_pad=False) - branch_pool = self.branch_pool(branch_pool) - - outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool] - return torch.cat(outputs, 1) - - -class FIDInceptionE_1(models.inception.InceptionE): - """First InceptionE block patched for FID computation""" - def __init__(self, in_channels): - super(FIDInceptionE_1, self).__init__(in_channels) - - def forward(self, x): - branch1x1 = self.branch1x1(x) - - branch3x3 = self.branch3x3_1(x) - branch3x3 = [ - self.branch3x3_2a(branch3x3), - self.branch3x3_2b(branch3x3), - ] - branch3x3 = torch.cat(branch3x3, 1) - - branch3x3dbl = self.branch3x3dbl_1(x) - branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) - branch3x3dbl = [ - self.branch3x3dbl_3a(branch3x3dbl), - self.branch3x3dbl_3b(branch3x3dbl), - ] - branch3x3dbl = torch.cat(branch3x3dbl, 1) - - # Patch: Tensorflow's average pool does not use the padded zero's in - # its average calculation - branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1, - count_include_pad=False) - branch_pool = self.branch_pool(branch_pool) - - outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] - return torch.cat(outputs, 1) - - -class FIDInceptionE_2(models.inception.InceptionE): - """Second InceptionE block patched for FID computation""" - def __init__(self, in_channels): - super(FIDInceptionE_2, self).__init__(in_channels) - - def forward(self, x): - branch1x1 = self.branch1x1(x) - - branch3x3 = self.branch3x3_1(x) - branch3x3 = [ - self.branch3x3_2a(branch3x3), - self.branch3x3_2b(branch3x3), - ] - branch3x3 = torch.cat(branch3x3, 1) - - branch3x3dbl = self.branch3x3dbl_1(x) - branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) - branch3x3dbl = [ - self.branch3x3dbl_3a(branch3x3dbl), - self.branch3x3dbl_3b(branch3x3dbl), - ] - branch3x3dbl = torch.cat(branch3x3dbl, 1) - - # Patch: The FID Inception model uses max pooling instead of average - # pooling. This is likely an error in this specific Inception - # implementation, as other Inception models use average pooling here - # (which matches the description in the paper). - branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1) - branch_pool = self.branch_pool(branch_pool) - - outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] - return torch.cat(outputs, 1) diff --git a/spaces/Eddycrack864/Applio-Inference/infer/modules/ipex/hijacks.py b/spaces/Eddycrack864/Applio-Inference/infer/modules/ipex/hijacks.py deleted file mode 100644 index b06f3a9c1a70ef515c30d0e7d749923ecb8d0bfe..0000000000000000000000000000000000000000 --- a/spaces/Eddycrack864/Applio-Inference/infer/modules/ipex/hijacks.py +++ /dev/null @@ -1,196 +0,0 @@ -import contextlib -import importlib -import torch -import intel_extension_for_pytorch as ipex # pylint: disable=import-error, unused-import - -# pylint: disable=protected-access, missing-function-docstring, line-too-long, unnecessary-lambda, no-else-return - -class CondFunc: # pylint: disable=missing-class-docstring - def __new__(cls, orig_func, sub_func, cond_func): - self = super(CondFunc, cls).__new__(cls) - if isinstance(orig_func, str): - func_path = orig_func.split('.') - for i in range(len(func_path)-1, -1, -1): - try: - resolved_obj = importlib.import_module('.'.join(func_path[:i])) - break - except ImportError: - pass - for attr_name in func_path[i:-1]: - resolved_obj = getattr(resolved_obj, attr_name) - orig_func = getattr(resolved_obj, func_path[-1]) - setattr(resolved_obj, func_path[-1], lambda *args, **kwargs: self(*args, **kwargs)) - self.__init__(orig_func, sub_func, cond_func) - return lambda *args, **kwargs: self(*args, **kwargs) - def __init__(self, orig_func, sub_func, cond_func): - self.__orig_func = orig_func - self.__sub_func = sub_func - self.__cond_func = cond_func - def __call__(self, *args, **kwargs): - if not self.__cond_func or self.__cond_func(self.__orig_func, *args, **kwargs): - return self.__sub_func(self.__orig_func, *args, **kwargs) - else: - return self.__orig_func(*args, **kwargs) - -_utils = torch.utils.data._utils -def _shutdown_workers(self): - if torch.utils.data._utils is None or torch.utils.data._utils.python_exit_status is True or torch.utils.data._utils.python_exit_status is None: - return - if hasattr(self, "_shutdown") and not self._shutdown: - self._shutdown = True - try: - if hasattr(self, '_pin_memory_thread'): - self._pin_memory_thread_done_event.set() - self._worker_result_queue.put((None, None)) - self._pin_memory_thread.join() - self._worker_result_queue.cancel_join_thread() - self._worker_result_queue.close() - self._workers_done_event.set() - for worker_id in range(len(self._workers)): - if self._persistent_workers or self._workers_status[worker_id]: - self._mark_worker_as_unavailable(worker_id, shutdown=True) - for w in self._workers: # pylint: disable=invalid-name - w.join(timeout=torch.utils.data._utils.MP_STATUS_CHECK_INTERVAL) - for q in self._index_queues: # pylint: disable=invalid-name - q.cancel_join_thread() - q.close() - finally: - if self._worker_pids_set: - torch.utils.data._utils.signal_handling._remove_worker_pids(id(self)) - self._worker_pids_set = False - for w in self._workers: # pylint: disable=invalid-name - if w.is_alive(): - w.terminate() - -class DummyDataParallel(torch.nn.Module): # pylint: disable=missing-class-docstring, unused-argument, too-few-public-methods - def __new__(cls, module, device_ids=None, output_device=None, dim=0): # pylint: disable=unused-argument - if isinstance(device_ids, list) and len(device_ids) > 1: - print("IPEX backend doesn't support DataParallel on multiple XPU devices") - return module.to("xpu") - -def return_null_context(*args, **kwargs): # pylint: disable=unused-argument - return contextlib.nullcontext() - -def check_device(device): - return bool((isinstance(device, torch.device) and device.type == "cuda") or (isinstance(device, str) and "cuda" in device) or isinstance(device, int)) - -def return_xpu(device): - return f"xpu:{device[-1]}" if isinstance(device, str) and ":" in device else f"xpu:{device}" if isinstance(device, int) else torch.device("xpu") if isinstance(device, torch.device) else "xpu" - -def ipex_no_cuda(orig_func, *args, **kwargs): - torch.cuda.is_available = lambda: False - orig_func(*args, **kwargs) - torch.cuda.is_available = torch.xpu.is_available - -original_autocast = torch.autocast -def ipex_autocast(*args, **kwargs): - if len(args) > 0 and args[0] == "cuda": - return original_autocast("xpu", *args[1:], **kwargs) - else: - return original_autocast(*args, **kwargs) - -original_torch_cat = torch.cat -def torch_cat(tensor, *args, **kwargs): - if len(tensor) == 3 and (tensor[0].dtype != tensor[1].dtype or tensor[2].dtype != tensor[1].dtype): - return original_torch_cat([tensor[0].to(tensor[1].dtype), tensor[1], tensor[2].to(tensor[1].dtype)], *args, **kwargs) - else: - return original_torch_cat(tensor, *args, **kwargs) - -original_interpolate = torch.nn.functional.interpolate -def interpolate(tensor, size=None, scale_factor=None, mode='nearest', align_corners=None, recompute_scale_factor=None, antialias=False): # pylint: disable=too-many-arguments - if antialias or align_corners is not None: - return_device = tensor.device - return_dtype = tensor.dtype - return original_interpolate(tensor.to("cpu", dtype=torch.float32), size=size, scale_factor=scale_factor, mode=mode, - align_corners=align_corners, recompute_scale_factor=recompute_scale_factor, antialias=antialias).to(return_device, dtype=return_dtype) - else: - return original_interpolate(tensor, size=size, scale_factor=scale_factor, mode=mode, - align_corners=align_corners, recompute_scale_factor=recompute_scale_factor, antialias=antialias) - -original_linalg_solve = torch.linalg.solve -def linalg_solve(A, B, *args, **kwargs): # pylint: disable=invalid-name - if A.device != torch.device("cpu") or B.device != torch.device("cpu"): - return_device = A.device - return original_linalg_solve(A.to("cpu"), B.to("cpu"), *args, **kwargs).to(return_device) - else: - return original_linalg_solve(A, B, *args, **kwargs) - -def ipex_hijacks(): - CondFunc('torch.Tensor.to', - lambda orig_func, self, device=None, *args, **kwargs: orig_func(self, return_xpu(device), *args, **kwargs), - lambda orig_func, self, device=None, *args, **kwargs: check_device(device)) - CondFunc('torch.Tensor.cuda', - lambda orig_func, self, device=None, *args, **kwargs: orig_func(self, return_xpu(device), *args, **kwargs), - lambda orig_func, self, device=None, *args, **kwargs: check_device(device)) - CondFunc('torch.empty', - lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs), - lambda orig_func, *args, device=None, **kwargs: check_device(device)) - CondFunc('torch.load', - lambda orig_func, *args, map_location=None, **kwargs: orig_func(*args, return_xpu(map_location), **kwargs), - lambda orig_func, *args, map_location=None, **kwargs: map_location is None or check_device(map_location)) - CondFunc('torch.randn', - lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs), - lambda orig_func, *args, device=None, **kwargs: check_device(device)) - CondFunc('torch.ones', - lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs), - lambda orig_func, *args, device=None, **kwargs: check_device(device)) - CondFunc('torch.zeros', - lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs), - lambda orig_func, *args, device=None, **kwargs: check_device(device)) - CondFunc('torch.tensor', - lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs), - lambda orig_func, *args, device=None, **kwargs: check_device(device)) - CondFunc('torch.linspace', - lambda orig_func, *args, device=None, **kwargs: orig_func(*args, device=return_xpu(device), **kwargs), - lambda orig_func, *args, device=None, **kwargs: check_device(device)) - - CondFunc('torch.Generator', - lambda orig_func, device=None: torch.xpu.Generator(device), - lambda orig_func, device=None: device is not None and device != torch.device("cpu") and device != "cpu") - - CondFunc('torch.batch_norm', - lambda orig_func, input, weight, bias, *args, **kwargs: orig_func(input, - weight if weight is not None else torch.ones(input.size()[1], device=input.device), - bias if bias is not None else torch.zeros(input.size()[1], device=input.device), *args, **kwargs), - lambda orig_func, input, *args, **kwargs: input.device != torch.device("cpu")) - CondFunc('torch.instance_norm', - lambda orig_func, input, weight, bias, *args, **kwargs: orig_func(input, - weight if weight is not None else torch.ones(input.size()[1], device=input.device), - bias if bias is not None else torch.zeros(input.size()[1], device=input.device), *args, **kwargs), - lambda orig_func, input, *args, **kwargs: input.device != torch.device("cpu")) - - #Functions with dtype errors: - CondFunc('torch.nn.modules.GroupNorm.forward', - lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)), - lambda orig_func, self, input: input.dtype != self.weight.data.dtype) - CondFunc('torch.nn.modules.linear.Linear.forward', - lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)), - lambda orig_func, self, input: input.dtype != self.weight.data.dtype) - CondFunc('torch.nn.modules.conv.Conv2d.forward', - lambda orig_func, self, input: orig_func(self, input.to(self.weight.data.dtype)), - lambda orig_func, self, input: input.dtype != self.weight.data.dtype) - CondFunc('torch.nn.functional.layer_norm', - lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs: - orig_func(input.to(weight.data.dtype), normalized_shape, weight, *args, **kwargs), - lambda orig_func, input, normalized_shape=None, weight=None, *args, **kwargs: - weight is not None and input.dtype != weight.data.dtype) - - #Diffusers Float64 (ARC GPUs doesn't support double or Float64): - if not torch.xpu.has_fp64_dtype(): - CondFunc('torch.from_numpy', - lambda orig_func, ndarray: orig_func(ndarray.astype('float32')), - lambda orig_func, ndarray: ndarray.dtype == float) - - #Broken functions when torch.cuda.is_available is True: - CondFunc('torch.utils.data.dataloader._BaseDataLoaderIter.__init__', - lambda orig_func, *args, **kwargs: ipex_no_cuda(orig_func, *args, **kwargs), - lambda orig_func, *args, **kwargs: True) - - #Functions that make compile mad with CondFunc: - torch.utils.data.dataloader._MultiProcessingDataLoaderIter._shutdown_workers = _shutdown_workers - torch.nn.DataParallel = DummyDataParallel - torch.autocast = ipex_autocast - torch.cat = torch_cat - torch.linalg.solve = linalg_solve - torch.nn.functional.interpolate = interpolate - torch.backends.cuda.sdp_kernel = return_null_context \ No newline at end of file diff --git a/spaces/ElainaFanBoy/IRONY-Real-ESRGAN/README.md b/spaces/ElainaFanBoy/IRONY-Real-ESRGAN/README.md deleted file mode 100644 index 36b007f172e4075a0c07957364e710f8cbd0e1b5..0000000000000000000000000000000000000000 --- a/spaces/ElainaFanBoy/IRONY-Real-ESRGAN/README.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Real ESRGAN -emoji: 🏃 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.1.7 -app_file: app.py -pinned: false -duplicated_from: akhaliq/Real-ESRGAN ---- - -# 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` - -`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/ElainaFanBoy/MusicGen/tests/data/test_audio.py b/spaces/ElainaFanBoy/MusicGen/tests/data/test_audio.py deleted file mode 100644 index 40c0d5ed69eff92a766dc6d176e532f0df6c2b5e..0000000000000000000000000000000000000000 --- a/spaces/ElainaFanBoy/MusicGen/tests/data/test_audio.py +++ /dev/null @@ -1,239 +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 itertools import product -import random - -import numpy as np -import torch -import torchaudio - -from audiocraft.data.audio import audio_info, audio_read, audio_write, _av_read - -from ..common_utils import TempDirMixin, get_white_noise, save_wav - - -class TestInfo(TempDirMixin): - - def test_info_mp3(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - wav = get_white_noise(ch, int(sample_rate * duration)) - path = self.get_temp_path('sample_wav.mp3') - save_wav(path, wav, sample_rate) - info = audio_info(path) - assert info.sample_rate == sample_rate - assert info.channels == ch - # we cannot trust torchaudio for num_frames, so we don't check - - def _test_info_format(self, ext: str): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'sample_wav{ext}') - save_wav(path, wav, sample_rate) - info = audio_info(path) - assert info.sample_rate == sample_rate - assert info.channels == ch - assert np.isclose(info.duration, duration, atol=1e-5) - - def test_info_wav(self): - self._test_info_format('.wav') - - def test_info_flac(self): - self._test_info_format('.flac') - - def test_info_ogg(self): - self._test_info_format('.ogg') - - def test_info_m4a(self): - # TODO: generate m4a file programmatically - # self._test_info_format('.m4a') - pass - - -class TestRead(TempDirMixin): - - def test_read_full_wav(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - read_wav, read_sr = audio_read(path) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == wav.shape[1] - assert torch.allclose(read_wav, wav, rtol=1e-03, atol=1e-04) - - def test_read_partial_wav(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - read_duration = torch.rand(1).item() - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - read_frames = int(sample_rate * read_duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - read_wav, read_sr = audio_read(path, 0, read_duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == read_frames - assert torch.allclose(read_wav[..., 0:read_frames], wav[..., 0:read_frames], rtol=1e-03, atol=1e-04) - - def test_read_seek_time_wav(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - read_duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - seek_time = torch.rand(1).item() - read_wav, read_sr = audio_read(path, seek_time, read_duration) - seek_frames = int(sample_rate * seek_time) - expected_frames = n_frames - seek_frames - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == expected_frames - assert torch.allclose(read_wav, wav[..., seek_frames:], rtol=1e-03, atol=1e-04) - - def test_read_seek_time_wav_padded(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - read_duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - read_frames = int(sample_rate * read_duration) - wav = get_white_noise(ch, n_frames).clamp(-0.99, 0.99) - path = self.get_temp_path('sample_wav.wav') - save_wav(path, wav, sample_rate) - seek_time = torch.rand(1).item() - seek_frames = int(sample_rate * seek_time) - expected_frames = n_frames - seek_frames - read_wav, read_sr = audio_read(path, seek_time, read_duration, pad=True) - expected_pad_wav = torch.zeros(wav.shape[0], read_frames - expected_frames) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[1] == read_frames - assert torch.allclose(read_wav[..., :expected_frames], wav[..., seek_frames:], rtol=1e-03, atol=1e-04) - assert torch.allclose(read_wav[..., expected_frames:], expected_pad_wav) - - -class TestAvRead(TempDirMixin): - - def test_avread_seek_base(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 2. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'reference_a_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - for _ in range(100): - # seek will always load a full duration segment in the file - seek_time = random.uniform(0.0, 1.0) - seek_duration = random.uniform(0.001, 1.0) - read_wav, read_sr = _av_read(path, seek_time, seek_duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == int(seek_duration * sample_rate) - - def test_avread_seek_partial(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'reference_b_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - for _ in range(100): - # seek will always load a partial segment - seek_time = random.uniform(0.5, 1.) - seek_duration = 1. - expected_num_frames = n_frames - int(seek_time * sample_rate) - read_wav, read_sr = _av_read(path, seek_time, seek_duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == expected_num_frames - - def test_avread_seek_outofbound(self): - sample_rates = [8000, 16_000] - channels = [1, 2] - duration = 1. - for sample_rate, ch in product(sample_rates, channels): - n_frames = int(sample_rate * duration) - wav = get_white_noise(ch, n_frames) - path = self.get_temp_path(f'reference_c_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - seek_time = 1.5 - read_wav, read_sr = _av_read(path, seek_time, 1.) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == 0 - - def test_avread_seek_edge(self): - sample_rates = [8000, 16_000] - # some of these values will have - # int(((frames - 1) / sample_rate) * sample_rate) != (frames - 1) - n_frames = [1000, 1001, 1002] - channels = [1, 2] - for sample_rate, ch, frames in product(sample_rates, channels, n_frames): - duration = frames / sample_rate - wav = get_white_noise(ch, frames) - path = self.get_temp_path(f'reference_d_{sample_rate}_{ch}.wav') - save_wav(path, wav, sample_rate) - seek_time = (frames - 1) / sample_rate - seek_frames = int(seek_time * sample_rate) - read_wav, read_sr = _av_read(path, seek_time, duration) - assert read_sr == sample_rate - assert read_wav.shape[0] == wav.shape[0] - assert read_wav.shape[-1] == (frames - seek_frames) - - -class TestAudioWrite(TempDirMixin): - - def test_audio_write_wav(self): - torch.manual_seed(1234) - sample_rates = [8000, 16_000] - n_frames = [1000, 1001, 1002] - channels = [1, 2] - strategies = ["peak", "clip", "rms"] - formats = ["wav", "mp3"] - for sample_rate, ch, frames in product(sample_rates, channels, n_frames): - for format_, strategy in product(formats, strategies): - wav = get_white_noise(ch, frames) - path = self.get_temp_path(f'pred_{sample_rate}_{ch}') - audio_write(path, wav, sample_rate, format_, strategy=strategy) - read_wav, read_sr = torchaudio.load(f'{path}.{format_}') - if format_ == "wav": - assert read_wav.shape == wav.shape - - if format_ == "wav" and strategy in ["peak", "rms"]: - rescaled_read_wav = read_wav / read_wav.abs().max() * wav.abs().max() - # for a Gaussian, the typical max scale will be less than ~5x the std. - # The error when writing to disk will ~ 1/2**15, and when rescaling, 5x that. - # For RMS target, rescaling leaves more headroom by default, leading - # to a 20x rescaling typically - atol = (5 if strategy == "peak" else 20) / 2**15 - delta = (rescaled_read_wav - wav).abs().max() - assert torch.allclose(wav, rescaled_read_wav, rtol=0, atol=atol), (delta, atol) - formats = ["wav"] # faster unit tests diff --git a/spaces/EuroPython2022/mmocr-demo/configs/_base_/schedules/schedule_sgd_100k_iters.py b/spaces/EuroPython2022/mmocr-demo/configs/_base_/schedules/schedule_sgd_100k_iters.py deleted file mode 100644 index df2a3300f057145757b5164ec062b58e9d2f96c6..0000000000000000000000000000000000000000 --- a/spaces/EuroPython2022/mmocr-demo/configs/_base_/schedules/schedule_sgd_100k_iters.py +++ /dev/null @@ -1,8 +0,0 @@ -# optimizer -optimizer = dict(type='SGD', lr=0.007, momentum=0.9, weight_decay=0.0001) -optimizer_config = dict(grad_clip=None) -# learning policy -lr_config = dict(policy='poly', power=0.9, min_lr=1e-7, by_epoch=False) -# running settings -runner = dict(type='IterBasedRunner', max_iters=100000) -checkpoint_config = dict(interval=10000) diff --git a/spaces/FroggyQc/ehartford-WizardLM-7B-Uncensored/app.py b/spaces/FroggyQc/ehartford-WizardLM-7B-Uncensored/app.py deleted file mode 100644 index 106e50a840aa4fc20ddbdd7f84cd86ada5510ae3..0000000000000000000000000000000000000000 --- a/spaces/FroggyQc/ehartford-WizardLM-7B-Uncensored/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/ehartford/WizardLM-7B-Uncensored").launch() \ No newline at end of file diff --git a/spaces/GIZ/vulnerability_analysis/utils/vulnerability_classifier.py b/spaces/GIZ/vulnerability_analysis/utils/vulnerability_classifier.py deleted file mode 100644 index ef6f62d6a343c7e26a3ce2e12991bd56ab28fd61..0000000000000000000000000000000000000000 --- a/spaces/GIZ/vulnerability_analysis/utils/vulnerability_classifier.py +++ /dev/null @@ -1,156 +0,0 @@ -from typing import List, Tuple -from typing_extensions import Literal -import logging -import pandas as pd -from pandas import DataFrame, Series -from utils.config import getconfig -from utils.preprocessing import processingpipeline -import streamlit as st -from transformers import pipeline -from setfit import SetFitModel - -label_dict= {0: 'Agricultural communities', - 1: 'Children', - 2: 'Coastal communities', - 3: 'Ethnic, racial or other minorities', - 4: 'Fishery communities', - 5: 'Informal sector workers', - 6: 'Members of indigenous and local communities', - 7: 'Migrants and displaced persons', - 8: 'Older persons', - 9: 'Other', - 10: 'Persons living in poverty', - 11: 'Persons with disabilities', - 12: 'Persons with pre-existing health conditions', - 13: 'Residents of drought-prone regions', - 14: 'Rural populations', - 15: 'Sexual minorities (LGBTQI+)', - 16: 'Urban populations', - 17: 'Women and other genders'} - -def getlabels(preds): - # Get label names - preds_list = preds.tolist() - - predictions_names=[] - - # loop through each prediction - for ele in preds_list: - - # see if there is a value 1 and retrieve index - try: - index_of_one = ele.index(1) - except ValueError: - index_of_one = "NA" - - # Retrieve the name of the label (if no prediction made = NA) - if index_of_one != "NA": - name = label_dict[index_of_one] - else: - name = "Other" - - # Append name to list - predictions_names.append(name) - - return predictions_names - -@st.cache_resource -def load_vulnerabilityClassifier(config_file:str = None, classifier_name:str = None): - """ - loads the document classifier using haystack, where the name/path of model - in HF-hub as string is used to fetch the model object.Either configfile or - model should be passed. - 1. https://docs.haystack.deepset.ai/reference/document-classifier-api - 2. https://docs.haystack.deepset.ai/docs/document_classifier - Params - -------- - config_file: config file path from which to read the model name - classifier_name: if modelname is passed, it takes a priority if not \ - found then will look for configfile, else raise error. - Return: document classifier model - """ - if not classifier_name: - if not config_file: - logging.warning("Pass either model name or config file") - return - else: - config = getconfig(config_file) - classifier_name = config.get('vulnerability','MODEL') - - logging.info("Loading vulnerability classifier") - # we are using the pipeline as the model is multilabel and DocumentClassifier - # from Haystack doesnt support multilabel - # in pipeline we use 'sigmoid' to explicitly tell pipeline to make it multilabel - # if not then it will automatically use softmax, which is not a desired thing. - # doc_classifier = TransformersDocumentClassifier( - # model_name_or_path=classifier_name, - # task="text-classification", - # top_k = None) - - # # Download model from HF Hub - doc_classifier = SetFitModel.from_pretrained("leavoigt/vulnerable_groups") - - # doc_classifier = pipeline("text-classification", - # model=classifier_name, - # return_all_scores=True, - # function_to_apply= "sigmoid") - - return doc_classifier - - -@st.cache_data -def vulnerability_classification(haystack_doc:pd.DataFrame, - threshold:float = 0.5, - classifier_model:pipeline= None - )->Tuple[DataFrame,Series]: - """ - Text-Classification on the list of texts provided. Classifier provides the - most appropriate label for each text. these labels are in terms of if text - belongs to which particular Sustainable Devleopment Goal (SDG). - Params - --------- - haystack_doc: List of haystack Documents. The output of Preprocessing Pipeline - contains the list of paragraphs in different format,here the list of - Haystack Documents is used. - threshold: threshold value for the model to keep the results from classifier - classifiermodel: you can pass the classifier model directly,which takes priority - however if not then looks for model in streamlit session. - In case of streamlit avoid passing the model directly. - Returns - ---------- - df: Dataframe with two columns['SDG:int', 'text'] - x: Series object with the unique SDG covered in the document uploaded and - the number of times it is covered/discussed/count_of_paragraphs. - """ - logging.info("Working on vulnerability Identification") - haystack_doc['Vulnerability Label'] = 'NA' - # haystack_doc['PA_check'] = haystack_doc['Policy-Action Label'].apply(lambda x: True if len(x) != 0 else False) - - # df1 = haystack_doc[haystack_doc['PA_check'] == True] - # df = haystack_doc[haystack_doc['PA_check'] == False] - if not classifier_model: - classifier_model = st.session_state['vulnerability_classifier'] - - predictions = classifier_model(list(haystack_doc.text)) - - - - pred_labels = getlabels(predictions) - - haystack_doc['Vulnerability Label'] = pred_labels - # placeholder = {} - # for j in range(len(temp)): - # placeholder[temp[j]['label']] = temp[j]['score'] - # list_.append(placeholder) - # labels_ = [{**list_[l]} for l in range(len(predictions))] - # truth_df = DataFrame.from_dict(labels_) - # truth_df = truth_df.round(2) - # truth_df = truth_df.astype(float) >= threshold - # truth_df = truth_df.astype(str) - # categories = list(truth_df.columns) - # truth_df['Vulnerability Label'] = truth_df.apply(lambda x: {i if x[i]=='True' else - # None for i in categories}, axis=1) - # truth_df['Vulnerability Label'] = truth_df.apply(lambda x: list(x['Vulnerability Label'] - # -{None}),axis=1) - # haystack_doc['Vulnerability Label'] = list(truth_df['Vulnerability Label']) - return haystack_doc \ No newline at end of file diff --git a/spaces/Gauri54damle/McDFries-SDXL-Dreambooth-Lora-Model/style.css b/spaces/Gauri54damle/McDFries-SDXL-Dreambooth-Lora-Model/style.css deleted file mode 100644 index 9bfa78cc983f84693cf7cbab1e3bfd0e0d36c944..0000000000000000000000000000000000000000 --- a/spaces/Gauri54damle/McDFries-SDXL-Dreambooth-Lora-Model/style.css +++ /dev/null @@ -1,24 +0,0 @@ -.finetuned-diffusion-div div{ - display:inline-flex; - align-items:center; - gap:.8rem; - font-size:1.75rem -} -.finetuned-diffusion-div div h1{ - font-weight:900; - margin-bottom:7px -} -.finetuned-diffusion-div p{ - margin-bottom:10px; - font-size:94% -} -a{ - text-decoration:underline -} -.tabs{ - margin-top:0; - margin-bottom:0 -} -#gallery{ - min-height:20rem -} diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/_base_/datasets/cityscapes_instance.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/_base_/datasets/cityscapes_instance.py deleted file mode 100644 index 3c5472aab09acdd5efa2cee206d94824f06058f9..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/_base_/datasets/cityscapes_instance.py +++ /dev/null @@ -1,55 +0,0 @@ -dataset_type = 'CityscapesDataset' -data_root = 'data/cityscapes/' -img_norm_cfg = dict( - mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) -train_pipeline = [ - dict(type='LoadImageFromFile'), - dict(type='LoadAnnotations', with_bbox=True, with_mask=True), - dict( - type='Resize', img_scale=[(2048, 800), (2048, 1024)], keep_ratio=True), - dict(type='RandomFlip', flip_ratio=0.5), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='DefaultFormatBundle'), - dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']), -] -test_pipeline = [ - dict(type='LoadImageFromFile'), - dict( - type='MultiScaleFlipAug', - img_scale=(2048, 1024), - flip=False, - transforms=[ - dict(type='Resize', keep_ratio=True), - dict(type='RandomFlip'), - dict(type='Normalize', **img_norm_cfg), - dict(type='Pad', size_divisor=32), - dict(type='ImageToTensor', keys=['img']), - dict(type='Collect', keys=['img']), - ]) -] -data = dict( - samples_per_gpu=1, - workers_per_gpu=2, - train=dict( - type='RepeatDataset', - times=8, - dataset=dict( - type=dataset_type, - ann_file=data_root + - 'annotations/instancesonly_filtered_gtFine_train.json', - img_prefix=data_root + 'leftImg8bit/train/', - pipeline=train_pipeline)), - val=dict( - type=dataset_type, - ann_file=data_root + - 'annotations/instancesonly_filtered_gtFine_val.json', - img_prefix=data_root + 'leftImg8bit/val/', - pipeline=test_pipeline), - test=dict( - type=dataset_type, - ann_file=data_root + - 'annotations/instancesonly_filtered_gtFine_test.json', - img_prefix=data_root + 'leftImg8bit/test/', - pipeline=test_pipeline)) -evaluation = dict(metric=['bbox', 'segm']) diff --git a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/faster_rcnn_hrnetv2p_w32_1x_coco.py b/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/faster_rcnn_hrnetv2p_w32_1x_coco.py deleted file mode 100644 index 190e81c710b0e5e9eb34bafff01c9dd4a8ef130c..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_detection/configs/hrnet/faster_rcnn_hrnetv2p_w32_1x_coco.py +++ /dev/null @@ -1,36 +0,0 @@ -_base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' -model = dict( - pretrained='open-mmlab://msra/hrnetv2_w32', - backbone=dict( - _delete_=True, - type='HRNet', - extra=dict( - stage1=dict( - num_modules=1, - num_branches=1, - block='BOTTLENECK', - num_blocks=(4, ), - num_channels=(64, )), - stage2=dict( - num_modules=1, - num_branches=2, - block='BASIC', - num_blocks=(4, 4), - num_channels=(32, 64)), - stage3=dict( - num_modules=4, - num_branches=3, - block='BASIC', - num_blocks=(4, 4, 4), - num_channels=(32, 64, 128)), - stage4=dict( - num_modules=3, - num_branches=4, - block='BASIC', - num_blocks=(4, 4, 4, 4), - num_channels=(32, 64, 128, 256)))), - neck=dict( - _delete_=True, - type='HRFPN', - in_channels=[32, 64, 128, 256], - out_channels=256)) diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/apcnet/apcnet_r50-d8_769x769_40k_cityscapes.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/apcnet/apcnet_r50-d8_769x769_40k_cityscapes.py deleted file mode 100644 index 3db6140cb97da1d202fd464d01f793276effa629..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/apcnet/apcnet_r50-d8_769x769_40k_cityscapes.py +++ /dev/null @@ -1,9 +0,0 @@ -_base_ = [ - '../_base_/models/apcnet_r50-d8.py', - '../_base_/datasets/cityscapes_769x769.py', '../_base_/default_runtime.py', - '../_base_/schedules/schedule_40k.py' -] -model = dict( - decode_head=dict(align_corners=True), - auxiliary_head=dict(align_corners=True), - test_cfg=dict(mode='slide', crop_size=(769, 769), stride=(513, 513))) diff --git a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/unet/fcn_unet_s5-d16_64x64_40k_drive.py b/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/unet/fcn_unet_s5-d16_64x64_40k_drive.py deleted file mode 100644 index 80483ade4a4bc3dc5cb8805e8b74c100e872da0c..0000000000000000000000000000000000000000 --- a/spaces/Gradio-Blocks/uniformer_image_segmentation/configs/unet/fcn_unet_s5-d16_64x64_40k_drive.py +++ /dev/null @@ -1,6 +0,0 @@ -_base_ = [ - '../_base_/models/fcn_unet_s5-d16.py', '../_base_/datasets/drive.py', - '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py' -] -model = dict(test_cfg=dict(crop_size=(64, 64), stride=(42, 42))) -evaluation = dict(metric='mDice') diff --git a/spaces/Guknadereve/stabilityai-stable-diffusion-2-1/app.py b/spaces/Guknadereve/stabilityai-stable-diffusion-2-1/app.py deleted file mode 100644 index 0160420876923d89f2ab5fccb9f4d13725e29972..0000000000000000000000000000000000000000 --- a/spaces/Guknadereve/stabilityai-stable-diffusion-2-1/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/stabilityai/stable-diffusion-2-1").launch() \ No newline at end of file diff --git a/spaces/HaHaBill/LandShapes-Antarctica/models/biggan/pytorch_biggan/scripts/convert_tf_hub_models.sh b/spaces/HaHaBill/LandShapes-Antarctica/models/biggan/pytorch_biggan/scripts/convert_tf_hub_models.sh deleted file mode 100644 index caed81a1e9698014ac61e8baa3d98d256cb3b4dd..0000000000000000000000000000000000000000 --- a/spaces/HaHaBill/LandShapes-Antarctica/models/biggan/pytorch_biggan/scripts/convert_tf_hub_models.sh +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2019-present, Thomas Wolf, Huggingface Inc. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. -# - -set -e -set -x - -models="128 256 512" - -mkdir -p models/model_128 -mkdir -p models/model_256 -mkdir -p models/model_512 - -# Convert TF Hub models. -for model in $models -do - pytorch_pretrained_biggan --model_type $model --tf_model_path models/model_$model --pt_save_path models/model_$model -done diff --git a/spaces/Hallucinate/demo/taming/data/utils.py b/spaces/Hallucinate/demo/taming/data/utils.py deleted file mode 100644 index 2b3c3d53cd2b6c72b481b59834cf809d3735b394..0000000000000000000000000000000000000000 --- a/spaces/Hallucinate/demo/taming/data/utils.py +++ /dev/null @@ -1,169 +0,0 @@ -import collections -import os -import tarfile -import urllib -import zipfile -from pathlib import Path - -import numpy as np -import torch -from taming.data.helper_types import Annotation -from torch._six import string_classes -from torch.utils.data._utils.collate import np_str_obj_array_pattern, default_collate_err_msg_format -from tqdm import tqdm - - -def unpack(path): - if path.endswith("tar.gz"): - with tarfile.open(path, "r:gz") as tar: - tar.extractall(path=os.path.split(path)[0]) - elif path.endswith("tar"): - with tarfile.open(path, "r:") as tar: - tar.extractall(path=os.path.split(path)[0]) - elif path.endswith("zip"): - with zipfile.ZipFile(path, "r") as f: - f.extractall(path=os.path.split(path)[0]) - else: - raise NotImplementedError( - "Unknown file extension: {}".format(os.path.splitext(path)[1]) - ) - - -def reporthook(bar): - """tqdm progress bar for downloads.""" - - def hook(b=1, bsize=1, tsize=None): - if tsize is not None: - bar.total = tsize - bar.update(b * bsize - bar.n) - - return hook - - -def get_root(name): - base = "data/" - root = os.path.join(base, name) - os.makedirs(root, exist_ok=True) - return root - - -def is_prepared(root): - return Path(root).joinpath(".ready").exists() - - -def mark_prepared(root): - Path(root).joinpath(".ready").touch() - - -def prompt_download(file_, source, target_dir, content_dir=None): - targetpath = os.path.join(target_dir, file_) - while not os.path.exists(targetpath): - if content_dir is not None and os.path.exists( - os.path.join(target_dir, content_dir) - ): - break - print( - "Please download '{}' from '{}' to '{}'.".format(file_, source, targetpath) - ) - if content_dir is not None: - print( - "Or place its content into '{}'.".format( - os.path.join(target_dir, content_dir) - ) - ) - input("Press Enter when done...") - return targetpath - - -def download_url(file_, url, target_dir): - targetpath = os.path.join(target_dir, file_) - os.makedirs(target_dir, exist_ok=True) - with tqdm( - unit="B", unit_scale=True, unit_divisor=1024, miniters=1, desc=file_ - ) as bar: - urllib.request.urlretrieve(url, targetpath, reporthook=reporthook(bar)) - return targetpath - - -def download_urls(urls, target_dir): - paths = dict() - for fname, url in urls.items(): - outpath = download_url(fname, url, target_dir) - paths[fname] = outpath - return paths - - -def quadratic_crop(x, bbox, alpha=1.0): - """bbox is xmin, ymin, xmax, ymax""" - im_h, im_w = x.shape[:2] - bbox = np.array(bbox, dtype=np.float32) - bbox = np.clip(bbox, 0, max(im_h, im_w)) - center = 0.5 * (bbox[0] + bbox[2]), 0.5 * (bbox[1] + bbox[3]) - w = bbox[2] - bbox[0] - h = bbox[3] - bbox[1] - l = int(alpha * max(w, h)) - l = max(l, 2) - - required_padding = -1 * min( - center[0] - l, center[1] - l, im_w - (center[0] + l), im_h - (center[1] + l) - ) - required_padding = int(np.ceil(required_padding)) - if required_padding > 0: - padding = [ - [required_padding, required_padding], - [required_padding, required_padding], - ] - padding += [[0, 0]] * (len(x.shape) - 2) - x = np.pad(x, padding, "reflect") - center = center[0] + required_padding, center[1] + required_padding - xmin = int(center[0] - l / 2) - ymin = int(center[1] - l / 2) - return np.array(x[ymin : ymin + l, xmin : xmin + l, ...]) - - -def custom_collate(batch): - r"""source: pytorch 1.9.0, only one modification to original code """ - - elem = batch[0] - elem_type = type(elem) - if isinstance(elem, torch.Tensor): - out = None - if torch.utils.data.get_worker_info() is not None: - # If we're in a background process, concatenate directly into a - # shared memory tensor to avoid an extra copy - numel = sum([x.numel() for x in batch]) - storage = elem.storage()._new_shared(numel) - out = elem.new(storage) - return torch.stack(batch, 0, out=out) - elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \ - and elem_type.__name__ != 'string_': - if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap': - # array of string classes and object - if np_str_obj_array_pattern.search(elem.dtype.str) is not None: - raise TypeError(default_collate_err_msg_format.format(elem.dtype)) - - return custom_collate([torch.as_tensor(b) for b in batch]) - elif elem.shape == (): # scalars - return torch.as_tensor(batch) - elif isinstance(elem, float): - return torch.tensor(batch, dtype=torch.float64) - elif isinstance(elem, int): - return torch.tensor(batch) - elif isinstance(elem, string_classes): - return batch - elif isinstance(elem, collections.abc.Mapping): - return {key: custom_collate([d[key] for d in batch]) for key in elem} - elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple - return elem_type(*(custom_collate(samples) for samples in zip(*batch))) - if isinstance(elem, collections.abc.Sequence) and isinstance(elem[0], Annotation): # added - return batch # added - elif isinstance(elem, collections.abc.Sequence): - # check to make sure that the elements in batch have consistent size - it = iter(batch) - elem_size = len(next(it)) - if not all(len(elem) == elem_size for elem in it): - raise RuntimeError('each element in list of batch should be of equal size') - transposed = zip(*batch) - return [custom_collate(samples) for samples in transposed] - - raise TypeError(default_collate_err_msg_format.format(elem_type)) diff --git a/spaces/HaloMaster/chinesesummary/fengshen/cli/fengshen_pipeline.py b/spaces/HaloMaster/chinesesummary/fengshen/cli/fengshen_pipeline.py deleted file mode 100644 index 07c31349ef96fd86d0c14b807601c645b095372f..0000000000000000000000000000000000000000 --- a/spaces/HaloMaster/chinesesummary/fengshen/cli/fengshen_pipeline.py +++ /dev/null @@ -1,34 +0,0 @@ -import sys -from importlib import import_module -from datasets import load_dataset -import argparse - - -def main(): - if len(sys.argv) < 3: - raise Exception( - 'args len < 3, example: fengshen_pipeline text_classification predict xxxxx') - pipeline_name = sys.argv[1] - method = sys.argv[2] - pipeline_class = getattr(import_module('fengshen.pipelines.' + pipeline_name), 'Pipeline') - - total_parser = argparse.ArgumentParser("FengShen Pipeline") - total_parser.add_argument('--model', default='', type=str) - total_parser.add_argument('--datasets', default='', type=str) - total_parser.add_argument('--text', default='', type=str) - total_parser = pipeline_class.add_pipeline_specific_args(total_parser) - args = total_parser.parse_args(args=sys.argv[3:]) - pipeline = pipeline_class(args=args, model=args.model) - - if method == 'predict': - print(pipeline(args.text)) - elif method == 'train': - datasets = load_dataset(args.datasets) - pipeline.train(datasets) - else: - raise Exception( - 'cmd not support, now only support {predict, train}') - - -if __name__ == '__main__': - main() diff --git a/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/src/glow_tts/generate_mels.py b/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/src/glow_tts/generate_mels.py deleted file mode 100644 index a3d331aef019cfd8cf45d6264db88d0fa26e5c0f..0000000000000000000000000000000000000000 --- a/spaces/Harveenchadha/Vakyansh-Hindi-TTS/ttsv/src/glow_tts/generate_mels.py +++ /dev/null @@ -1,70 +0,0 @@ -import numpy as np -import os -import torch -import commons - -import models -import utils -from argparse import ArgumentParser -from tqdm import tqdm -from text import text_to_sequence - -if __name__ == "__main__": - parser = ArgumentParser() - parser.add_argument("-m", "--model_dir", required=True, type=str) - parser.add_argument("-s", "--mels_dir", required=True, type=str) - args = parser.parse_args() - MODEL_DIR = args.model_dir # path to model dir - SAVE_MELS_DIR = args.mels_dir # path to save generated mels - - if not os.path.exists(SAVE_MELS_DIR): - os.makedirs(SAVE_MELS_DIR) - - hps = utils.get_hparams_from_dir(MODEL_DIR) - symbols = list(hps.data.punc) + list(hps.data.chars) - checkpoint_path = utils.latest_checkpoint_path(MODEL_DIR) - cleaner = hps.data.text_cleaners - - model = models.FlowGenerator( - len(symbols) + getattr(hps.data, "add_blank", False), - out_channels=hps.data.n_mel_channels, - **hps.model - ).to("cuda") - - utils.load_checkpoint(checkpoint_path, model) - model.decoder.store_inverse() # do not calcuate jacobians for fast decoding - _ = model.eval() - - def get_mel(text, fpath): - if getattr(hps.data, "add_blank", False): - text_norm = text_to_sequence(text, symbols, cleaner) - text_norm = commons.intersperse(text_norm, len(symbols)) - else: # If not using "add_blank" option during training, adding spaces at the beginning and the end of utterance improves quality - text = " " + text.strip() + " " - text_norm = text_to_sequence(text, symbols, cleaner) - - sequence = np.array(text_norm)[None, :] - - x_tst = torch.autograd.Variable(torch.from_numpy(sequence)).cuda().long() - x_tst_lengths = torch.tensor([x_tst.shape[1]]).cuda() - - with torch.no_grad(): - noise_scale = 0.667 - length_scale = 1.0 - (y_gen_tst, *_), *_, (attn_gen, *_) = model( - x_tst, - x_tst_lengths, - gen=True, - noise_scale=noise_scale, - length_scale=length_scale, - ) - - np.save(os.path.join(SAVE_MELS_DIR, fpath), y_gen_tst.cpu().detach().numpy()) - - for f in [hps.data.training_files, hps.data.validation_files]: - file_lines = open(f).read().splitlines() - - for line in tqdm(file_lines): - fname, text = line.split("|") - fname = os.path.basename(fname).replace(".wav", ".npy") - get_mel(text, fname) diff --git a/spaces/Hmjz100/MT3/app.py b/spaces/Hmjz100/MT3/app.py deleted file mode 100644 index 5c35bf326b889e6e6bf5f88e48464e63fb41aabe..0000000000000000000000000000000000000000 --- a/spaces/Hmjz100/MT3/app.py +++ /dev/null @@ -1,333 +0,0 @@ -import gradio as gr -import os -import datetime -import pytz -from pathlib import Path - -def current_time(): - current = datetime.datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%Y年-%m月-%d日 %H时:%M分:%S秒") - return current - -print(f"[{current_time()}] 开始部署空间...") - -""" -print(f"[{current_time()}] 日志:安装 - 必要包") -os.system("pip install -r ./requirements.txt") -""" -print(f"[{current_time()}] 日志:安装 - gsutil") -os.system("pip install gsutil") -print(f"[{current_time()}] 日志:Git - 克隆 Github 的 T5X 训练框架到当前目录") -os.system("git clone --branch=main https://github.com/google-research/t5x") -print(f"[{current_time()}] 日志:文件 - 移动 t5x 到当前目录并重命名为 t5x_tmp 并删除") -os.system("mv t5x t5x_tmp; mv t5x_tmp/* .; rm -r t5x_tmp") -print(f"[{current_time()}] 日志:编辑 - 替换 setup.py 内的文本“jax[tpu]”为“jax”") -os.system("sed -i 's:jax\[tpu\]:jax:' setup.py") -print(f"[{current_time()}] 日志:Python - 使用 pip 安装 当前目录内的 Python 包") -os.system("python3 -m pip install -e .") -print(f"[{current_time()}] 日志:Python - 更新 Python 包管理器 pip") -os.system("python3 -m pip install --upgrade pip") -print(f"[{current_time()}] 日志:安装 - langchain") -os.system("pip install langchain") -print(f"[{current_time()}] 日志:安装 - sentence-transformers") -os.system("pip install sentence-transformers") - -# 安装 airio -print(f"[{current_time()}] 日志:Git - 克隆 Github 的 airio 到当前目录") -os.system("git clone --branch=main https://github.com/google/airio") -print(f"[{current_time()}] 日志:文件 - 移动 airio 到当前目录并重命名为 airio_tmp 并删除") -os.system("mv airio airio_tmp; mv airio_tmp/* .; rm -r airio_tmp") -print(f"[{current_time()}] 日志:Python - 使用 pip 安装 当前目录内的 Python 包") -os.system("python3 -m pip install -e .") - -# 安装 mt3 -print(f"[{current_time()}] 日志:Git - 克隆 Github 的 MT3 模型到当前目录") -os.system("git clone --branch=main https://github.com/magenta/mt3") -print(f"[{current_time()}] 日志:文件 - 移动 mt3 到当前目录并重命名为 mt3_tmp 并删除") -os.system("mv mt3 mt3_tmp; mv mt3_tmp/* .; rm -r mt3_tmp") -print(f"[{current_time()}] 日志:Python - 使用 pip 从 storage.googleapis.com 安装 jax[cuda11_local] nest-asyncio pyfluidsynth") -os.system("python3 -m pip install jax[cuda11_local] nest-asyncio pyfluidsynth==1.3.0 -e . -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html") -print(f"[{current_time()}] 日志:Python - 使用 pip 安装 当前目录内的 Python 包") -os.system("python3 -m pip install -e .") -print(f"[{current_time()}] 日志:安装 - TensorFlow CPU") -os.system("pip install tensorflow_cpu") - -# 复制检查点 -print(f"[{current_time()}] 日志:gsutil - 复制 MT3 检查点到当前目录") -os.system("gsutil -q -m cp -r gs://mt3/checkpoints .") - -# 复制 soundfont 文件(原始文件来自 https://sites.google.com/site/soundfonts4u) -print(f"[{current_time()}] 日志:gsutil - 复制 SoundFont 文件到当前目录") -os.system("gsutil -q -m cp gs://magentadata/soundfonts/SGM-v2.01-Sal-Guit-Bass-V1.3.sf2 .") - -#@title 导入和定义 -print(f"[{current_time()}] 日志:导入 - 必要工具") -import functools -import seqio -import t5 -import t5x - -import numpy as np -import tensorflow.compat.v2 as tf - -import functools -import gin -import jax -import librosa -import note_seq - -from mt3 import metrics_utils -from mt3 import models -from mt3 import network -from mt3 import note_sequences -from mt3 import preprocessors -from mt3 import spectrograms -from mt3 import vocabularies - -import nest_asyncio -nest_asyncio.apply() - -SAMPLE_RATE = 16000 -SF2_PATH = 'SGM-v2.01-Sal-Guit-Bass-V1.3.sf2' - -def upload_audio(audio, sample_rate): - return note_seq.audio_io.wav_data_to_samples_librosa( - audio, sample_rate=sample_rate) - - -print(f"[{current_time()}] 日志:开始包装模型...") -class InferenceModel(object): - """音乐转录的 T5X 模型包装器。""" - - def __init__(self, checkpoint_path, model_type='mt3'): - - # 模型常量。 - if model_type == 'ismir2021': - num_velocity_bins = 127 - self.encoding_spec = note_sequences.NoteEncodingSpec - self.inputs_length = 512 - elif model_type == 'mt3': - num_velocity_bins = 1 - self.encoding_spec = note_sequences.NoteEncodingWithTiesSpec - self.inputs_length = 256 - else: - raise ValueError('unknown model_type: %s' % model_type) - - gin_files = ['/home/user/app/mt3/gin/model.gin', - '/home/user/app/mt3/gin/mt3.gin'] - - self.batch_size = 8 - self.outputs_length = 1024 - self.sequence_length = {'inputs': self.inputs_length, - 'targets': self.outputs_length} - - self.partitioner = t5x.partitioning.PjitPartitioner( - model_parallel_submesh=None, num_partitions=1) - - # 构建编解码器和词汇表。 - print(f"[{current_time()}] 日志:构建编解码器") - self.spectrogram_config = spectrograms.SpectrogramConfig() - self.codec = vocabularies.build_codec( - vocab_config=vocabularies.VocabularyConfig( - num_velocity_bins=num_velocity_bins) - ) - self.vocabulary = vocabularies.vocabulary_from_codec(self.codec) - self.output_features = { - 'inputs': seqio.ContinuousFeature(dtype=tf.float32, rank=2), - 'targets': seqio.Feature(vocabulary=self.vocabulary), - } - - # 创建 T5X 模型。 - print(f"[{current_time()}] 日志:创建 T5X 模型") - self._parse_gin(gin_files) - self.model = self._load_model() - - # 从检查点中恢复。 - print(f"[{current_time()}] 日志:恢复模型检查点") - self.restore_from_checkpoint(checkpoint_path) - - @property - def input_shapes(self): - return { - 'encoder_input_tokens': (self.batch_size, self.inputs_length), - 'decoder_input_tokens': (self.batch_size, self.outputs_length) - } - - def _parse_gin(self, gin_files): - """解析用于训练模型的 gin 文件。""" - print(f"[{current_time()}] 日志:解析 gin 文件") - gin_bindings = [ - 'from __gin__ import dynamic_registration', - 'from mt3 import vocabularies', - 'VOCAB_CONFIG=@vocabularies.VocabularyConfig()', - 'vocabularies.VocabularyConfig.num_velocity_bins=%NUM_VELOCITY_BINS' - ] - with gin.unlock_config(): - gin.parse_config_files_and_bindings( - gin_files, gin_bindings, finalize_config=False) - - def _load_model(self): - """在解析训练 gin 配置后加载 T5X `Model`。""" - print(f"[{current_time()}] 日志:加载 T5X 模型") - model_config = gin.get_configurable(network.T5Config)() - module = network.Transformer(config=model_config) - return models.ContinuousInputsEncoderDecoderModel( - module=module, - input_vocabulary=self.output_features['inputs'].vocabulary, - output_vocabulary=self.output_features['targets'].vocabulary, - optimizer_def=t5x.adafactor.Adafactor(decay_rate=0.8, step_offset=0), - input_depth=spectrograms.input_depth(self.spectrogram_config)) - - - def restore_from_checkpoint(self, checkpoint_path): - """从检查点中恢复训练状态,重置 self._predict_fn()。""" - print(f"[{current_time()}] 日志:从检查点恢复训练状态") - train_state_initializer = t5x.utils.TrainStateInitializer( - optimizer_def=self.model.optimizer_def, - init_fn=self.model.get_initial_variables, - input_shapes=self.input_shapes, - partitioner=self.partitioner) - - restore_checkpoint_cfg = t5x.utils.RestoreCheckpointConfig( - path=checkpoint_path, mode='specific', dtype='float32') - - train_state_axes = train_state_initializer.train_state_axes - self._predict_fn = self._get_predict_fn(train_state_axes) - self._train_state = train_state_initializer.from_checkpoint_or_scratch( - [restore_checkpoint_cfg], init_rng=jax.random.PRNGKey(0)) - - @functools.lru_cache() - def _get_predict_fn(self, train_state_axes): - """生成一个分区的预测函数用于解码。""" - print(f"[{current_time()}] 日志:生成用于解码的预测函数") - def partial_predict_fn(params, batch, decode_rng): - return self.model.predict_batch_with_aux( - params, batch, decoder_params={'decode_rng': None}) - return self.partitioner.partition( - partial_predict_fn, - in_axis_resources=( - train_state_axes.params, - t5x.partitioning.PartitionSpec('data',), None), - out_axis_resources=t5x.partitioning.PartitionSpec('data',) - ) - - def predict_tokens(self, batch, seed=0): - """从预处理的数据集批次中预测 tokens。""" - print(f"[{current_time()}] 运行:从预处理数据集中预测音符序列") - prediction, _ = self._predict_fn( -self._train_state.params, batch, jax.random.PRNGKey(seed)) - return self.vocabulary.decode_tf(prediction).numpy() - - def __call__(self, audio): - """从音频样本推断出音符序列。 - - 参数: - audio:16kHz 的单个音频样本的 1 维 numpy 数组。 - 返回: - 转录音频的音符序列。 - """ - print(f"[{current_time()}] 运行:从音频样本中推断音符序列") - ds = self.audio_to_dataset(audio) - ds = self.preprocess(ds) - - model_ds = self.model.FEATURE_CONVERTER_CLS(pack=False)( - ds, task_feature_lengths=self.sequence_length) - model_ds = model_ds.batch(self.batch_size) - - inferences = (tokens for batch in model_ds.as_numpy_iterator() - for tokens in self.predict_tokens(batch)) - - predictions = [] - for example, tokens in zip(ds.as_numpy_iterator(), inferences): - predictions.append(self.postprocess(tokens, example)) - - result = metrics_utils.event_predictions_to_ns( - predictions, codec=self.codec, encoding_spec=self.encoding_spec) - return result['est_ns'] - - def audio_to_dataset(self, audio): - """从输入音频创建一个包含频谱图的 TF Dataset。""" - print(f"[{current_time()}] 运行:从音频创建包含频谱图的 TF Dataset") - frames, frame_times = self._audio_to_frames(audio) - return tf.data.Dataset.from_tensors({ - 'inputs': frames, - 'input_times': frame_times, - }) - - def _audio_to_frames(self, audio): - """从音频计算频谱图帧。""" - print(f"[{current_time()}] 运行:从音频计算频谱图帧") - frame_size = self.spectrogram_config.hop_width - padding = [0, frame_size - len(audio) % frame_size] - audio = np.pad(audio, padding, mode='constant') - frames = spectrograms.split_audio(audio, self.spectrogram_config) - num_frames = len(audio) // frame_size - times = np.arange(num_frames) / self.spectrogram_config.frames_per_second - return frames, times - - def preprocess(self, ds): - pp_chain = [ - functools.partial( - t5.data.preprocessors.split_tokens_to_inputs_length, - sequence_length=self.sequence_length, - output_features=self.output_features, - feature_key='inputs', - additional_feature_keys=['input_times']), - # 在训练期间进行缓存。 - preprocessors.add_dummy_targets, - functools.partial( - preprocessors.compute_spectrograms, - spectrogram_config=self.spectrogram_config) - ] - for pp in pp_chain: - ds = pp(ds) - return ds - - def postprocess(self, tokens, example): - tokens = self._trim_eos(tokens) - start_time = example['input_times'][0] - # 向下取整到最接近的符号化时间步。 - start_time -= start_time % (1 / self.codec.steps_per_second) - return { - 'est_tokens': tokens, - 'start_time': start_time, - # 内部 MT3 代码期望原始输入,这里不使用。 - 'raw_inputs': [] - } - - @staticmethod - def _trim_eos(tokens): - tokens = np.array(tokens, np.int32) - if vocabularies.DECODED_EOS_ID in tokens: - tokens = tokens[:np.argmax(tokens == vocabularies.DECODED_EOS_ID)] - return tokens - - -inference_model = InferenceModel('/home/user/app/checkpoints/mt3/', 'mt3') - - -def inference(audio): - filename = os.path.basename(audio) # 获取输入文件的文件名 - print(f"[{current_time()}] 运行:输入文件: {filename}") - with open(audio, 'rb') as fd: - contents = fd.read() - audio = upload_audio(contents,sample_rate=16000) - est_ns = inference_model(audio) - note_seq.sequence_proto_to_midi_file(est_ns, './transcribed.mid') - return './transcribed.mid' - -title = "MT3" -description = "MT3:多任务多音轨音乐转录的 Gradio 演示。要使用它,只需上传音频文件,或点击示例以查看效果。更多信息请参阅下面的链接。" - -article = "

    出错了?试试把文件转换为MP3后再上传吧~

    MT3: 多任务多音轨音乐转录 | Github 仓库

    " - -examples=[['canon.flac'], ['download.wav']] - -gr.Interface( - inference, - gr.Audio(type="filepath", label="输入"), - outputs = gr.File(label="输出"), - title=title, - description=description, - article=article, - examples=examples - ).launch() \ No newline at end of file diff --git a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/data/__init__.py b/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/data/__init__.py deleted file mode 100644 index 47bb6e24ddf25aa4fd5bf0fe9672f89099efb9b4..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/data/__init__.py +++ /dev/null @@ -1,11 +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 .asr_dataset import AsrDataset - - -__all__ = [ - "AsrDataset", -] diff --git a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/utils/wer_utils.py b/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/utils/wer_utils.py deleted file mode 100644 index cf6f3d09ba41a46ad4d7968fb3c286dd53d15c38..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/examples/speech_recognition/utils/wer_utils.py +++ /dev/null @@ -1,381 +0,0 @@ -#!/usr/bin/env python3 - -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -from __future__ import absolute_import, division, print_function, unicode_literals - -import re -from collections import deque -from enum import Enum - -import numpy as np - - -""" - Utility modules for computation of Word Error Rate, - Alignments, as well as more granular metrics like - deletion, insersion and substitutions. -""" - - -class Code(Enum): - match = 1 - substitution = 2 - insertion = 3 - deletion = 4 - - -class Token(object): - def __init__(self, lbl="", st=np.nan, en=np.nan): - if np.isnan(st): - self.label, self.start, self.end = "", 0.0, 0.0 - else: - self.label, self.start, self.end = lbl, st, en - - -class AlignmentResult(object): - def __init__(self, refs, hyps, codes, score): - self.refs = refs # std::deque - self.hyps = hyps # std::deque - self.codes = codes # std::deque - self.score = score # float - - -def coordinate_to_offset(row, col, ncols): - return int(row * ncols + col) - - -def offset_to_row(offset, ncols): - return int(offset / ncols) - - -def offset_to_col(offset, ncols): - return int(offset % ncols) - - -def trimWhitespace(str): - return re.sub(" +", " ", re.sub(" *$", "", re.sub("^ *", "", str))) - - -def str2toks(str): - pieces = trimWhitespace(str).split(" ") - toks = [] - for p in pieces: - toks.append(Token(p, 0.0, 0.0)) - return toks - - -class EditDistance(object): - def __init__(self, time_mediated): - self.time_mediated_ = time_mediated - self.scores_ = np.nan # Eigen::Matrix - self.backtraces_ = ( - np.nan - ) # Eigen::Matrix backtraces_; - self.confusion_pairs_ = {} - - def cost(self, ref, hyp, code): - if self.time_mediated_: - if code == Code.match: - return abs(ref.start - hyp.start) + abs(ref.end - hyp.end) - elif code == Code.insertion: - return hyp.end - hyp.start - elif code == Code.deletion: - return ref.end - ref.start - else: # substitution - return abs(ref.start - hyp.start) + abs(ref.end - hyp.end) + 0.1 - else: - if code == Code.match: - return 0 - elif code == Code.insertion or code == Code.deletion: - return 3 - else: # substitution - return 4 - - def get_result(self, refs, hyps): - res = AlignmentResult(refs=deque(), hyps=deque(), codes=deque(), score=np.nan) - - num_rows, num_cols = self.scores_.shape - res.score = self.scores_[num_rows - 1, num_cols - 1] - - curr_offset = coordinate_to_offset(num_rows - 1, num_cols - 1, num_cols) - - while curr_offset != 0: - curr_row = offset_to_row(curr_offset, num_cols) - curr_col = offset_to_col(curr_offset, num_cols) - - prev_offset = self.backtraces_[curr_row, curr_col] - - prev_row = offset_to_row(prev_offset, num_cols) - prev_col = offset_to_col(prev_offset, num_cols) - - res.refs.appendleft(curr_row - 1) # Note: this was .push_front() in C++ - res.hyps.appendleft(curr_col - 1) - if curr_row - 1 == prev_row and curr_col == prev_col: - res.codes.appendleft(Code.deletion) - elif curr_row == prev_row and curr_col - 1 == prev_col: - res.codes.appendleft(Code.insertion) - else: - # assert(curr_row - 1 == prev_row and curr_col - 1 == prev_col) - ref_str = refs[res.refs[0]].label - hyp_str = hyps[res.hyps[0]].label - - if ref_str == hyp_str: - res.codes.appendleft(Code.match) - else: - res.codes.appendleft(Code.substitution) - - confusion_pair = "%s -> %s" % (ref_str, hyp_str) - if confusion_pair not in self.confusion_pairs_: - self.confusion_pairs_[confusion_pair] = 1 - else: - self.confusion_pairs_[confusion_pair] += 1 - - curr_offset = prev_offset - - return res - - def align(self, refs, hyps): - if len(refs) == 0 and len(hyps) == 0: - return np.nan - - # NOTE: we're not resetting the values in these matrices because every value - # will be overridden in the loop below. If this assumption doesn't hold, - # be sure to set all entries in self.scores_ and self.backtraces_ to 0. - self.scores_ = np.zeros((len(refs) + 1, len(hyps) + 1)) - self.backtraces_ = np.zeros((len(refs) + 1, len(hyps) + 1)) - - num_rows, num_cols = self.scores_.shape - - for i in range(num_rows): - for j in range(num_cols): - if i == 0 and j == 0: - self.scores_[i, j] = 0.0 - self.backtraces_[i, j] = 0 - continue - - if i == 0: - self.scores_[i, j] = self.scores_[i, j - 1] + self.cost( - None, hyps[j - 1], Code.insertion - ) - self.backtraces_[i, j] = coordinate_to_offset(i, j - 1, num_cols) - continue - - if j == 0: - self.scores_[i, j] = self.scores_[i - 1, j] + self.cost( - refs[i - 1], None, Code.deletion - ) - self.backtraces_[i, j] = coordinate_to_offset(i - 1, j, num_cols) - continue - - # Below here both i and j are greater than 0 - ref = refs[i - 1] - hyp = hyps[j - 1] - best_score = self.scores_[i - 1, j - 1] + ( - self.cost(ref, hyp, Code.match) - if (ref.label == hyp.label) - else self.cost(ref, hyp, Code.substitution) - ) - - prev_row = i - 1 - prev_col = j - 1 - ins = self.scores_[i, j - 1] + self.cost(None, hyp, Code.insertion) - if ins < best_score: - best_score = ins - prev_row = i - prev_col = j - 1 - - delt = self.scores_[i - 1, j] + self.cost(ref, None, Code.deletion) - if delt < best_score: - best_score = delt - prev_row = i - 1 - prev_col = j - - self.scores_[i, j] = best_score - self.backtraces_[i, j] = coordinate_to_offset( - prev_row, prev_col, num_cols - ) - - return self.get_result(refs, hyps) - - -class WERTransformer(object): - def __init__(self, hyp_str, ref_str, verbose=True): - self.ed_ = EditDistance(False) - self.id2oracle_errs_ = {} - self.utts_ = 0 - self.words_ = 0 - self.insertions_ = 0 - self.deletions_ = 0 - self.substitutions_ = 0 - - self.process(["dummy_str", hyp_str, ref_str]) - - if verbose: - print("'%s' vs '%s'" % (hyp_str, ref_str)) - self.report_result() - - def process(self, input): # std::vector&& input - if len(input) < 3: - print( - "Input must be of the form ... , got ", - len(input), - " inputs:", - ) - return None - - # Align - # std::vector hyps; - # std::vector refs; - - hyps = str2toks(input[-2]) - refs = str2toks(input[-1]) - - alignment = self.ed_.align(refs, hyps) - if alignment is None: - print("Alignment is null") - return np.nan - - # Tally errors - ins = 0 - dels = 0 - subs = 0 - for code in alignment.codes: - if code == Code.substitution: - subs += 1 - elif code == Code.insertion: - ins += 1 - elif code == Code.deletion: - dels += 1 - - # Output - row = input - row.append(str(len(refs))) - row.append(str(ins)) - row.append(str(dels)) - row.append(str(subs)) - # print(row) - - # Accumulate - kIdIndex = 0 - kNBestSep = "/" - - pieces = input[kIdIndex].split(kNBestSep) - - if len(pieces) == 0: - print( - "Error splitting ", - input[kIdIndex], - " on '", - kNBestSep, - "', got empty list", - ) - return np.nan - - id = pieces[0] - if id not in self.id2oracle_errs_: - self.utts_ += 1 - self.words_ += len(refs) - self.insertions_ += ins - self.deletions_ += dels - self.substitutions_ += subs - self.id2oracle_errs_[id] = [ins, dels, subs] - else: - curr_err = ins + dels + subs - prev_err = np.sum(self.id2oracle_errs_[id]) - if curr_err < prev_err: - self.id2oracle_errs_[id] = [ins, dels, subs] - - return 0 - - def report_result(self): - # print("---------- Summary ---------------") - if self.words_ == 0: - print("No words counted") - return - - # 1-best - best_wer = ( - 100.0 - * (self.insertions_ + self.deletions_ + self.substitutions_) - / self.words_ - ) - - print( - "\tWER = %0.2f%% (%i utts, %i words, %0.2f%% ins, " - "%0.2f%% dels, %0.2f%% subs)" - % ( - best_wer, - self.utts_, - self.words_, - 100.0 * self.insertions_ / self.words_, - 100.0 * self.deletions_ / self.words_, - 100.0 * self.substitutions_ / self.words_, - ) - ) - - def wer(self): - if self.words_ == 0: - wer = np.nan - else: - wer = ( - 100.0 - * (self.insertions_ + self.deletions_ + self.substitutions_) - / self.words_ - ) - return wer - - def stats(self): - if self.words_ == 0: - stats = {} - else: - wer = ( - 100.0 - * (self.insertions_ + self.deletions_ + self.substitutions_) - / self.words_ - ) - stats = dict( - { - "wer": wer, - "utts": self.utts_, - "numwords": self.words_, - "ins": self.insertions_, - "dels": self.deletions_, - "subs": self.substitutions_, - "confusion_pairs": self.ed_.confusion_pairs_, - } - ) - return stats - - -def calc_wer(hyp_str, ref_str): - t = WERTransformer(hyp_str, ref_str, verbose=0) - return t.wer() - - -def calc_wer_stats(hyp_str, ref_str): - t = WERTransformer(hyp_str, ref_str, verbose=0) - return t.stats() - - -def get_wer_alignment_codes(hyp_str, ref_str): - """ - INPUT: hypothesis string, reference string - OUTPUT: List of alignment codes (intermediate results from WER computation) - """ - t = WERTransformer(hyp_str, ref_str, verbose=0) - return t.ed_.align(str2toks(ref_str), str2toks(hyp_str)).codes - - -def merge_counts(x, y): - # Merge two hashes which have 'counts' as their values - # This can be used for example to merge confusion pair counts - # conf_pairs = merge_counts(conf_pairs, stats['confusion_pairs']) - for k, v in y.items(): - if k not in x: - x[k] = 0 - x[k] += v - return x diff --git a/spaces/ICML2022/OFA/fairseq/fairseq/distributed/distributed_timeout_wrapper.py b/spaces/ICML2022/OFA/fairseq/fairseq/distributed/distributed_timeout_wrapper.py deleted file mode 100644 index 18107ef27ea837b8c72dcaa49db18fd8e64267b1..0000000000000000000000000000000000000000 --- a/spaces/ICML2022/OFA/fairseq/fairseq/distributed/distributed_timeout_wrapper.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import logging -import os -import signal -import threading - -from torch import nn - - -logger = logging.getLogger(__name__) - - -class DistributedTimeoutWrapper(nn.Module): - """ - A wrapper that kills the process if no progress is made within a given - *timeout*. The timer is reset every time :func:`forward` is called. - - Usage:: - - module = DistributedTimeoutWrapper(module, timeout=30) - x = module(input) - time.sleep(20) # safe - x = module(input) - time.sleep(45) # job will be killed before this returns - - Args: - module (nn.Module): module to wrap - timeout (int): number of seconds before killing the process - (set to a value <= 0 to disable the timeout) - signal (Optional): signal to send once timeout is triggered - """ - def __init__(self, module: nn.Module, timeout: int, signal=signal.SIGINT): - super().__init__() - self.module = module - self.timeout = timeout - self.signal = signal - - if timeout > 0: - self._heartbeat = threading.Event() - self._heartbeat_thread = threading.Thread( - target=self._check_heartbeat, - args=(os.getpid(),), - daemon=True, - ) - self._heartbeat_thread.start() - self._terminated = False - else: - self._heartbeat = None - self._heartbeat_thread = None - - def __del__(self): - self.stop_timeout() - - def __getattr__(self, name): - """Forward missing attributes to wrapped module.""" - try: - return super().__getattr__(name) # defer to nn.Module's logic - except AttributeError: - return getattr(self.module, name) - - def stop_timeout(self): - if self._heartbeat_thread is not None: - self._terminated = True - self._heartbeat_thread.join() - - def state_dict(self, *args, **kwargs): - return self.module.state_dict(*args, **kwargs) - - def load_state_dict(self, *args, **kwargs): - return self.module.load_state_dict(*args, **kwargs) - - def forward(self, *args, **kwargs): - if self._heartbeat is not None: - self._heartbeat.set() - return self.module(*args, **kwargs) - - def _check_heartbeat(self, parent_pid): - self._heartbeat.wait() # wait for the first forward pass - while True: - self._heartbeat.clear() - success = self._heartbeat.wait(timeout=self.timeout) - if self._terminated: - break - elif not success: - logger.error(( - "Killing job for not making progress in {} seconds. " - "Set --heartbeat-timeout=-1 to disable this timeout." - ).format(int(self.timeout))) - os.kill(parent_pid, self.signal) - return diff --git a/spaces/InpaintAI/Inpaint-Anything/third_party/lama/saicinpainting/training/modules/pix2pixhd.py b/spaces/InpaintAI/Inpaint-Anything/third_party/lama/saicinpainting/training/modules/pix2pixhd.py deleted file mode 100644 index 08c6afd777a88cd232592acbbf0ef25db8d43217..0000000000000000000000000000000000000000 --- a/spaces/InpaintAI/Inpaint-Anything/third_party/lama/saicinpainting/training/modules/pix2pixhd.py +++ /dev/null @@ -1,669 +0,0 @@ -# original: https://github.com/NVIDIA/pix2pixHD/blob/master/models/networks.py -import collections -from functools import partial -import functools -import logging -from collections import defaultdict - -import numpy as np -import torch.nn as nn - -from saicinpainting.training.modules.base import BaseDiscriminator, deconv_factory, get_conv_block_ctor, get_norm_layer, get_activation -from saicinpainting.training.modules.ffc import FFCResnetBlock -from saicinpainting.training.modules.multidilated_conv import MultidilatedConv - -class DotDict(defaultdict): - # https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary - """dot.notation access to dictionary attributes""" - __getattr__ = defaultdict.get - __setattr__ = defaultdict.__setitem__ - __delattr__ = defaultdict.__delitem__ - -class Identity(nn.Module): - def __init__(self): - super().__init__() - - def forward(self, x): - return x - - -class ResnetBlock(nn.Module): - def __init__(self, dim, padding_type, norm_layer, activation=nn.ReLU(True), use_dropout=False, conv_kind='default', - dilation=1, in_dim=None, groups=1, second_dilation=None): - super(ResnetBlock, self).__init__() - self.in_dim = in_dim - self.dim = dim - if second_dilation is None: - second_dilation = dilation - self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, activation, use_dropout, - conv_kind=conv_kind, dilation=dilation, in_dim=in_dim, groups=groups, - second_dilation=second_dilation) - - if self.in_dim is not None: - self.input_conv = nn.Conv2d(in_dim, dim, 1) - - self.out_channnels = dim - - def build_conv_block(self, dim, padding_type, norm_layer, activation, use_dropout, conv_kind='default', - dilation=1, in_dim=None, groups=1, second_dilation=1): - conv_layer = get_conv_block_ctor(conv_kind) - - conv_block = [] - p = 0 - if padding_type == 'reflect': - conv_block += [nn.ReflectionPad2d(dilation)] - elif padding_type == 'replicate': - conv_block += [nn.ReplicationPad2d(dilation)] - elif padding_type == 'zero': - p = dilation - else: - raise NotImplementedError('padding [%s] is not implemented' % padding_type) - - if in_dim is None: - in_dim = dim - - conv_block += [conv_layer(in_dim, dim, kernel_size=3, padding=p, dilation=dilation), - norm_layer(dim), - activation] - if use_dropout: - conv_block += [nn.Dropout(0.5)] - - p = 0 - if padding_type == 'reflect': - conv_block += [nn.ReflectionPad2d(second_dilation)] - elif padding_type == 'replicate': - conv_block += [nn.ReplicationPad2d(second_dilation)] - elif padding_type == 'zero': - p = second_dilation - else: - raise NotImplementedError('padding [%s] is not implemented' % padding_type) - conv_block += [conv_layer(dim, dim, kernel_size=3, padding=p, dilation=second_dilation, groups=groups), - norm_layer(dim)] - - return nn.Sequential(*conv_block) - - def forward(self, x): - x_before = x - if self.in_dim is not None: - x = self.input_conv(x) - out = x + self.conv_block(x_before) - return out - -class ResnetBlock5x5(nn.Module): - def __init__(self, dim, padding_type, norm_layer, activation=nn.ReLU(True), use_dropout=False, conv_kind='default', - dilation=1, in_dim=None, groups=1, second_dilation=None): - super(ResnetBlock5x5, self).__init__() - self.in_dim = in_dim - self.dim = dim - if second_dilation is None: - second_dilation = dilation - self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, activation, use_dropout, - conv_kind=conv_kind, dilation=dilation, in_dim=in_dim, groups=groups, - second_dilation=second_dilation) - - if self.in_dim is not None: - self.input_conv = nn.Conv2d(in_dim, dim, 1) - - self.out_channnels = dim - - def build_conv_block(self, dim, padding_type, norm_layer, activation, use_dropout, conv_kind='default', - dilation=1, in_dim=None, groups=1, second_dilation=1): - conv_layer = get_conv_block_ctor(conv_kind) - - conv_block = [] - p = 0 - if padding_type == 'reflect': - conv_block += [nn.ReflectionPad2d(dilation * 2)] - elif padding_type == 'replicate': - conv_block += [nn.ReplicationPad2d(dilation * 2)] - elif padding_type == 'zero': - p = dilation * 2 - else: - raise NotImplementedError('padding [%s] is not implemented' % padding_type) - - if in_dim is None: - in_dim = dim - - conv_block += [conv_layer(in_dim, dim, kernel_size=5, padding=p, dilation=dilation), - norm_layer(dim), - activation] - if use_dropout: - conv_block += [nn.Dropout(0.5)] - - p = 0 - if padding_type == 'reflect': - conv_block += [nn.ReflectionPad2d(second_dilation * 2)] - elif padding_type == 'replicate': - conv_block += [nn.ReplicationPad2d(second_dilation * 2)] - elif padding_type == 'zero': - p = second_dilation * 2 - else: - raise NotImplementedError('padding [%s] is not implemented' % padding_type) - conv_block += [conv_layer(dim, dim, kernel_size=5, padding=p, dilation=second_dilation, groups=groups), - norm_layer(dim)] - - return nn.Sequential(*conv_block) - - def forward(self, x): - x_before = x - if self.in_dim is not None: - x = self.input_conv(x) - out = x + self.conv_block(x_before) - return out - - -class MultidilatedResnetBlock(nn.Module): - def __init__(self, dim, padding_type, conv_layer, norm_layer, activation=nn.ReLU(True), use_dropout=False): - super().__init__() - self.conv_block = self.build_conv_block(dim, padding_type, conv_layer, norm_layer, activation, use_dropout) - - def build_conv_block(self, dim, padding_type, conv_layer, norm_layer, activation, use_dropout, dilation=1): - conv_block = [] - conv_block += [conv_layer(dim, dim, kernel_size=3, padding_mode=padding_type), - norm_layer(dim), - activation] - if use_dropout: - conv_block += [nn.Dropout(0.5)] - - conv_block += [conv_layer(dim, dim, kernel_size=3, padding_mode=padding_type), - norm_layer(dim)] - - return nn.Sequential(*conv_block) - - def forward(self, x): - out = x + self.conv_block(x) - return out - - -class MultiDilatedGlobalGenerator(nn.Module): - def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, - n_blocks=3, norm_layer=nn.BatchNorm2d, - padding_type='reflect', conv_kind='default', - deconv_kind='convtranspose', activation=nn.ReLU(True), - up_norm_layer=nn.BatchNorm2d, affine=None, up_activation=nn.ReLU(True), - add_out_act=True, max_features=1024, multidilation_kwargs={}, - ffc_positions=None, ffc_kwargs={}): - assert (n_blocks >= 0) - super().__init__() - - conv_layer = get_conv_block_ctor(conv_kind) - resnet_conv_layer = functools.partial(get_conv_block_ctor('multidilated'), **multidilation_kwargs) - norm_layer = get_norm_layer(norm_layer) - if affine is not None: - norm_layer = partial(norm_layer, affine=affine) - up_norm_layer = get_norm_layer(up_norm_layer) - if affine is not None: - up_norm_layer = partial(up_norm_layer, affine=affine) - - model = [nn.ReflectionPad2d(3), - conv_layer(input_nc, ngf, kernel_size=7, padding=0), - norm_layer(ngf), - activation] - - identity = Identity() - ### downsample - for i in range(n_downsampling): - mult = 2 ** i - - model += [conv_layer(min(max_features, ngf * mult), - min(max_features, ngf * mult * 2), - kernel_size=3, stride=2, padding=1), - norm_layer(min(max_features, ngf * mult * 2)), - activation] - - mult = 2 ** n_downsampling - feats_num_bottleneck = min(max_features, ngf * mult) - - ### resnet blocks - for i in range(n_blocks): - if ffc_positions is not None and i in ffc_positions: - model += [FFCResnetBlock(feats_num_bottleneck, padding_type, norm_layer, activation_layer=nn.ReLU, - inline=True, **ffc_kwargs)] - model += [MultidilatedResnetBlock(feats_num_bottleneck, padding_type=padding_type, - conv_layer=resnet_conv_layer, activation=activation, - norm_layer=norm_layer)] - - ### upsample - for i in range(n_downsampling): - mult = 2 ** (n_downsampling - i) - model += deconv_factory(deconv_kind, ngf, mult, up_norm_layer, up_activation, max_features) - model += [nn.ReflectionPad2d(3), - nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] - if add_out_act: - model.append(get_activation('tanh' if add_out_act is True else add_out_act)) - self.model = nn.Sequential(*model) - - def forward(self, input): - return self.model(input) - -class ConfigGlobalGenerator(nn.Module): - def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, - n_blocks=3, norm_layer=nn.BatchNorm2d, - padding_type='reflect', conv_kind='default', - deconv_kind='convtranspose', activation=nn.ReLU(True), - up_norm_layer=nn.BatchNorm2d, affine=None, up_activation=nn.ReLU(True), - add_out_act=True, max_features=1024, - manual_block_spec=[], - resnet_block_kind='multidilatedresnetblock', - resnet_conv_kind='multidilated', - resnet_dilation=1, - multidilation_kwargs={}): - assert (n_blocks >= 0) - super().__init__() - - conv_layer = get_conv_block_ctor(conv_kind) - resnet_conv_layer = functools.partial(get_conv_block_ctor(resnet_conv_kind), **multidilation_kwargs) - norm_layer = get_norm_layer(norm_layer) - if affine is not None: - norm_layer = partial(norm_layer, affine=affine) - up_norm_layer = get_norm_layer(up_norm_layer) - if affine is not None: - up_norm_layer = partial(up_norm_layer, affine=affine) - - model = [nn.ReflectionPad2d(3), - conv_layer(input_nc, ngf, kernel_size=7, padding=0), - norm_layer(ngf), - activation] - - identity = Identity() - - ### downsample - for i in range(n_downsampling): - mult = 2 ** i - model += [conv_layer(min(max_features, ngf * mult), - min(max_features, ngf * mult * 2), - kernel_size=3, stride=2, padding=1), - norm_layer(min(max_features, ngf * mult * 2)), - activation] - - mult = 2 ** n_downsampling - feats_num_bottleneck = min(max_features, ngf * mult) - - if len(manual_block_spec) == 0: - manual_block_spec = [ - DotDict(lambda : None, { - 'n_blocks': n_blocks, - 'use_default': True}) - ] - - ### resnet blocks - for block_spec in manual_block_spec: - def make_and_add_blocks(model, block_spec): - block_spec = DotDict(lambda : None, block_spec) - if not block_spec.use_default: - resnet_conv_layer = functools.partial(get_conv_block_ctor(block_spec.resnet_conv_kind), **block_spec.multidilation_kwargs) - resnet_conv_kind = block_spec.resnet_conv_kind - resnet_block_kind = block_spec.resnet_block_kind - if block_spec.resnet_dilation is not None: - resnet_dilation = block_spec.resnet_dilation - for i in range(block_spec.n_blocks): - if resnet_block_kind == "multidilatedresnetblock": - model += [MultidilatedResnetBlock(feats_num_bottleneck, padding_type=padding_type, - conv_layer=resnet_conv_layer, activation=activation, - norm_layer=norm_layer)] - if resnet_block_kind == "resnetblock": - model += [ResnetBlock(ngf * mult, padding_type=padding_type, activation=activation, norm_layer=norm_layer, - conv_kind=resnet_conv_kind)] - if resnet_block_kind == "resnetblock5x5": - model += [ResnetBlock5x5(ngf * mult, padding_type=padding_type, activation=activation, norm_layer=norm_layer, - conv_kind=resnet_conv_kind)] - if resnet_block_kind == "resnetblockdwdil": - model += [ResnetBlock(ngf * mult, padding_type=padding_type, activation=activation, norm_layer=norm_layer, - conv_kind=resnet_conv_kind, dilation=resnet_dilation, second_dilation=resnet_dilation)] - make_and_add_blocks(model, block_spec) - - ### upsample - for i in range(n_downsampling): - mult = 2 ** (n_downsampling - i) - model += deconv_factory(deconv_kind, ngf, mult, up_norm_layer, up_activation, max_features) - model += [nn.ReflectionPad2d(3), - nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] - if add_out_act: - model.append(get_activation('tanh' if add_out_act is True else add_out_act)) - self.model = nn.Sequential(*model) - - def forward(self, input): - return self.model(input) - - -def make_dil_blocks(dilated_blocks_n, dilation_block_kind, dilated_block_kwargs): - blocks = [] - for i in range(dilated_blocks_n): - if dilation_block_kind == 'simple': - blocks.append(ResnetBlock(**dilated_block_kwargs, dilation=2 ** (i + 1))) - elif dilation_block_kind == 'multi': - blocks.append(MultidilatedResnetBlock(**dilated_block_kwargs)) - else: - raise ValueError(f'dilation_block_kind could not be "{dilation_block_kind}"') - return blocks - - -class GlobalGenerator(nn.Module): - def __init__(self, input_nc, output_nc, ngf=64, n_downsampling=3, n_blocks=9, norm_layer=nn.BatchNorm2d, - padding_type='reflect', conv_kind='default', activation=nn.ReLU(True), - up_norm_layer=nn.BatchNorm2d, affine=None, - up_activation=nn.ReLU(True), dilated_blocks_n=0, dilated_blocks_n_start=0, - dilated_blocks_n_middle=0, - add_out_act=True, - max_features=1024, is_resblock_depthwise=False, - ffc_positions=None, ffc_kwargs={}, dilation=1, second_dilation=None, - dilation_block_kind='simple', multidilation_kwargs={}): - assert (n_blocks >= 0) - super().__init__() - - conv_layer = get_conv_block_ctor(conv_kind) - norm_layer = get_norm_layer(norm_layer) - if affine is not None: - norm_layer = partial(norm_layer, affine=affine) - up_norm_layer = get_norm_layer(up_norm_layer) - if affine is not None: - up_norm_layer = partial(up_norm_layer, affine=affine) - - if ffc_positions is not None: - ffc_positions = collections.Counter(ffc_positions) - - model = [nn.ReflectionPad2d(3), - conv_layer(input_nc, ngf, kernel_size=7, padding=0), - norm_layer(ngf), - activation] - - identity = Identity() - ### downsample - for i in range(n_downsampling): - mult = 2 ** i - - model += [conv_layer(min(max_features, ngf * mult), - min(max_features, ngf * mult * 2), - kernel_size=3, stride=2, padding=1), - norm_layer(min(max_features, ngf * mult * 2)), - activation] - - mult = 2 ** n_downsampling - feats_num_bottleneck = min(max_features, ngf * mult) - - dilated_block_kwargs = dict(dim=feats_num_bottleneck, padding_type=padding_type, - activation=activation, norm_layer=norm_layer) - if dilation_block_kind == 'simple': - dilated_block_kwargs['conv_kind'] = conv_kind - elif dilation_block_kind == 'multi': - dilated_block_kwargs['conv_layer'] = functools.partial( - get_conv_block_ctor('multidilated'), **multidilation_kwargs) - - # dilated blocks at the start of the bottleneck sausage - if dilated_blocks_n_start is not None and dilated_blocks_n_start > 0: - model += make_dil_blocks(dilated_blocks_n_start, dilation_block_kind, dilated_block_kwargs) - - # resnet blocks - for i in range(n_blocks): - # dilated blocks at the middle of the bottleneck sausage - if i == n_blocks // 2 and dilated_blocks_n_middle is not None and dilated_blocks_n_middle > 0: - model += make_dil_blocks(dilated_blocks_n_middle, dilation_block_kind, dilated_block_kwargs) - - if ffc_positions is not None and i in ffc_positions: - for _ in range(ffc_positions[i]): # same position can occur more than once - model += [FFCResnetBlock(feats_num_bottleneck, padding_type, norm_layer, activation_layer=nn.ReLU, - inline=True, **ffc_kwargs)] - - if is_resblock_depthwise: - resblock_groups = feats_num_bottleneck - else: - resblock_groups = 1 - - model += [ResnetBlock(feats_num_bottleneck, padding_type=padding_type, activation=activation, - norm_layer=norm_layer, conv_kind=conv_kind, groups=resblock_groups, - dilation=dilation, second_dilation=second_dilation)] - - - # dilated blocks at the end of the bottleneck sausage - if dilated_blocks_n is not None and dilated_blocks_n > 0: - model += make_dil_blocks(dilated_blocks_n, dilation_block_kind, dilated_block_kwargs) - - # upsample - for i in range(n_downsampling): - mult = 2 ** (n_downsampling - i) - model += [nn.ConvTranspose2d(min(max_features, ngf * mult), - min(max_features, int(ngf * mult / 2)), - kernel_size=3, stride=2, padding=1, output_padding=1), - up_norm_layer(min(max_features, int(ngf * mult / 2))), - up_activation] - model += [nn.ReflectionPad2d(3), - nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] - if add_out_act: - model.append(get_activation('tanh' if add_out_act is True else add_out_act)) - self.model = nn.Sequential(*model) - - def forward(self, input): - return self.model(input) - - -class GlobalGeneratorGated(GlobalGenerator): - def __init__(self, *args, **kwargs): - real_kwargs=dict( - conv_kind='gated_bn_relu', - activation=nn.Identity(), - norm_layer=nn.Identity - ) - real_kwargs.update(kwargs) - super().__init__(*args, **real_kwargs) - - -class GlobalGeneratorFromSuperChannels(nn.Module): - def __init__(self, input_nc, output_nc, n_downsampling, n_blocks, super_channels, norm_layer="bn", padding_type='reflect', add_out_act=True): - super().__init__() - self.n_downsampling = n_downsampling - norm_layer = get_norm_layer(norm_layer) - if type(norm_layer) == functools.partial: - use_bias = (norm_layer.func == nn.InstanceNorm2d) - else: - use_bias = (norm_layer == nn.InstanceNorm2d) - - channels = self.convert_super_channels(super_channels) - self.channels = channels - - model = [nn.ReflectionPad2d(3), - nn.Conv2d(input_nc, channels[0], kernel_size=7, padding=0, bias=use_bias), - norm_layer(channels[0]), - nn.ReLU(True)] - - for i in range(n_downsampling): # add downsampling layers - mult = 2 ** i - model += [nn.Conv2d(channels[0+i], channels[1+i], kernel_size=3, stride=2, padding=1, bias=use_bias), - norm_layer(channels[1+i]), - nn.ReLU(True)] - - mult = 2 ** n_downsampling - - n_blocks1 = n_blocks // 3 - n_blocks2 = n_blocks1 - n_blocks3 = n_blocks - n_blocks1 - n_blocks2 - - for i in range(n_blocks1): - c = n_downsampling - dim = channels[c] - model += [ResnetBlock(dim, padding_type=padding_type, norm_layer=norm_layer)] - - for i in range(n_blocks2): - c = n_downsampling+1 - dim = channels[c] - kwargs = {} - if i == 0: - kwargs = {"in_dim": channels[c-1]} - model += [ResnetBlock(dim, padding_type=padding_type, norm_layer=norm_layer, **kwargs)] - - for i in range(n_blocks3): - c = n_downsampling+2 - dim = channels[c] - kwargs = {} - if i == 0: - kwargs = {"in_dim": channels[c-1]} - model += [ResnetBlock(dim, padding_type=padding_type, norm_layer=norm_layer, **kwargs)] - - for i in range(n_downsampling): # add upsampling layers - mult = 2 ** (n_downsampling - i) - model += [nn.ConvTranspose2d(channels[n_downsampling+3+i], - channels[n_downsampling+3+i+1], - kernel_size=3, stride=2, - padding=1, output_padding=1, - bias=use_bias), - norm_layer(channels[n_downsampling+3+i+1]), - nn.ReLU(True)] - model += [nn.ReflectionPad2d(3)] - model += [nn.Conv2d(channels[2*n_downsampling+3], output_nc, kernel_size=7, padding=0)] - - if add_out_act: - model.append(get_activation('tanh' if add_out_act is True else add_out_act)) - self.model = nn.Sequential(*model) - - def convert_super_channels(self, super_channels): - n_downsampling = self.n_downsampling - result = [] - cnt = 0 - - if n_downsampling == 2: - N1 = 10 - elif n_downsampling == 3: - N1 = 13 - else: - raise NotImplementedError - - for i in range(0, N1): - if i in [1,4,7,10]: - channel = super_channels[cnt] * (2 ** cnt) - config = {'channel': channel} - result.append(channel) - logging.info(f"Downsample channels {result[-1]}") - cnt += 1 - - for i in range(3): - for counter, j in enumerate(range(N1 + i * 3, N1 + 3 + i * 3)): - if len(super_channels) == 6: - channel = super_channels[3] * 4 - else: - channel = super_channels[i + 3] * 4 - config = {'channel': channel} - if counter == 0: - result.append(channel) - logging.info(f"Bottleneck channels {result[-1]}") - cnt = 2 - - for i in range(N1+9, N1+21): - if i in [22, 25,28]: - cnt -= 1 - if len(super_channels) == 6: - channel = super_channels[5 - cnt] * (2 ** cnt) - else: - channel = super_channels[7 - cnt] * (2 ** cnt) - result.append(int(channel)) - logging.info(f"Upsample channels {result[-1]}") - return result - - def forward(self, input): - return self.model(input) - - -# Defines the PatchGAN discriminator with the specified arguments. -class NLayerDiscriminator(BaseDiscriminator): - def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d,): - super().__init__() - self.n_layers = n_layers - - kw = 4 - padw = int(np.ceil((kw-1.0)/2)) - sequence = [[nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), - nn.LeakyReLU(0.2, True)]] - - nf = ndf - for n in range(1, n_layers): - nf_prev = nf - nf = min(nf * 2, 512) - - cur_model = [] - cur_model += [ - nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=2, padding=padw), - norm_layer(nf), - nn.LeakyReLU(0.2, True) - ] - sequence.append(cur_model) - - nf_prev = nf - nf = min(nf * 2, 512) - - cur_model = [] - cur_model += [ - nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw), - norm_layer(nf), - nn.LeakyReLU(0.2, True) - ] - sequence.append(cur_model) - - sequence += [[nn.Conv2d(nf, 1, kernel_size=kw, stride=1, padding=padw)]] - - for n in range(len(sequence)): - setattr(self, 'model'+str(n), nn.Sequential(*sequence[n])) - - def get_all_activations(self, x): - res = [x] - for n in range(self.n_layers + 2): - model = getattr(self, 'model' + str(n)) - res.append(model(res[-1])) - return res[1:] - - def forward(self, x): - act = self.get_all_activations(x) - return act[-1], act[:-1] - - -class MultidilatedNLayerDiscriminator(BaseDiscriminator): - def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, multidilation_kwargs={}): - super().__init__() - self.n_layers = n_layers - - kw = 4 - padw = int(np.ceil((kw-1.0)/2)) - sequence = [[nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), - nn.LeakyReLU(0.2, True)]] - - nf = ndf - for n in range(1, n_layers): - nf_prev = nf - nf = min(nf * 2, 512) - - cur_model = [] - cur_model += [ - MultidilatedConv(nf_prev, nf, kernel_size=kw, stride=2, padding=[2, 3], **multidilation_kwargs), - norm_layer(nf), - nn.LeakyReLU(0.2, True) - ] - sequence.append(cur_model) - - nf_prev = nf - nf = min(nf * 2, 512) - - cur_model = [] - cur_model += [ - nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw), - norm_layer(nf), - nn.LeakyReLU(0.2, True) - ] - sequence.append(cur_model) - - sequence += [[nn.Conv2d(nf, 1, kernel_size=kw, stride=1, padding=padw)]] - - for n in range(len(sequence)): - setattr(self, 'model'+str(n), nn.Sequential(*sequence[n])) - - def get_all_activations(self, x): - res = [x] - for n in range(self.n_layers + 2): - model = getattr(self, 'model' + str(n)) - res.append(model(res[-1])) - return res[1:] - - def forward(self, x): - act = self.get_all_activations(x) - return act[-1], act[:-1] - - -class NLayerDiscriminatorAsGen(NLayerDiscriminator): - def forward(self, x): - return super().forward(x)[0] diff --git a/spaces/Jamkonams/AutoGPT/autogpt/js/overlay.js b/spaces/Jamkonams/AutoGPT/autogpt/js/overlay.js deleted file mode 100644 index 1c99c72673330b8ea8cf037ef889233f2d4326be..0000000000000000000000000000000000000000 --- a/spaces/Jamkonams/AutoGPT/autogpt/js/overlay.js +++ /dev/null @@ -1,29 +0,0 @@ -const overlay = document.createElement('div'); -Object.assign(overlay.style, { - position: 'fixed', - zIndex: 999999, - top: 0, - left: 0, - width: '100%', - height: '100%', - background: 'rgba(0, 0, 0, 0.7)', - color: '#fff', - fontSize: '24px', - fontWeight: 'bold', - display: 'flex', - justifyContent: 'center', - alignItems: 'center', -}); -const textContent = document.createElement('div'); -Object.assign(textContent.style, { - textAlign: 'center', -}); -textContent.textContent = 'AutoGPT Analyzing Page'; -overlay.appendChild(textContent); -document.body.append(overlay); -document.body.style.overflow = 'hidden'; -let dotCount = 0; -setInterval(() => { - textContent.textContent = 'AutoGPT Analyzing Page' + '.'.repeat(dotCount); - dotCount = (dotCount + 1) % 4; -}, 1000); diff --git a/spaces/Jojelf/dreamlike-photoreal-2.0/app.py b/spaces/Jojelf/dreamlike-photoreal-2.0/app.py deleted file mode 100644 index 0d0ae718eacc495efdbb94276323b93eb3321f76..0000000000000000000000000000000000000000 --- a/spaces/Jojelf/dreamlike-photoreal-2.0/app.py +++ /dev/null @@ -1,15 +0,0 @@ -import os -import gradio as gr - -API_KEY=os.environ.get('HUGGING_FACE_HUB_TOKEN', None) - -article = """--- -This space was created using [SD Space Creator](https://huggingface.co/spaces/anzorq/sd-space-creator).""" - -gr.Interface.load( - name="models/dreamlike-art/dreamlike-photoreal-2.0", - title="""Dreamlike Photoreal 2.0""", - description="""Demo for Dreamlike Photoreal 2.0 Stable Diffusion model.""", - article=article, - api_key=API_KEY, - ).queue(concurrency_count=20).launch() diff --git a/spaces/KennyUTC/BotChat/README.md b/spaces/KennyUTC/BotChat/README.md deleted file mode 100644 index 62ca406fa76e9cd7afe17bb41398b4ebe69439ac..0000000000000000000000000000000000000000 --- a/spaces/KennyUTC/BotChat/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: BotChat -emoji: 🌖 -colorFrom: blue -colorTo: pink -sdk: static -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/synthesizer/hparams.py b/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/synthesizer/hparams.py deleted file mode 100644 index 8bcdb635a90a7700d4e133410268a897d3fd4a8c..0000000000000000000000000000000000000000 --- a/spaces/Kevin676/ChatGPT-with-Voice-Cloning-in-Chinese/synthesizer/hparams.py +++ /dev/null @@ -1,110 +0,0 @@ -import ast -import pprint -import json - -class HParams(object): - def __init__(self, **kwargs): self.__dict__.update(kwargs) - def __setitem__(self, key, value): setattr(self, key, value) - def __getitem__(self, key): return getattr(self, key) - def __repr__(self): return pprint.pformat(self.__dict__) - - def parse(self, string): - # Overrides hparams from a comma-separated string of name=value pairs - if len(string) > 0: - overrides = [s.split("=") for s in string.split(",")] - keys, values = zip(*overrides) - keys = list(map(str.strip, keys)) - values = list(map(str.strip, values)) - for k in keys: - self.__dict__[k] = ast.literal_eval(values[keys.index(k)]) - return self - - def loadJson(self, dict): - print("\Loading the json with %s\n", dict) - for k in dict.keys(): - if k not in ["tts_schedule", "tts_finetune_layers"]: - self.__dict__[k] = dict[k] - return self - - def dumpJson(self, fp): - print("\Saving the json with %s\n", fp) - with fp.open("w", encoding="utf-8") as f: - json.dump(self.__dict__, f) - return self - -hparams = HParams( - ### Signal Processing (used in both synthesizer and vocoder) - sample_rate = 16000, - n_fft = 800, - num_mels = 80, - hop_size = 200, # Tacotron uses 12.5 ms frame shift (set to sample_rate * 0.0125) - win_size = 800, # Tacotron uses 50 ms frame length (set to sample_rate * 0.050) - fmin = 55, - min_level_db = -100, - ref_level_db = 20, - max_abs_value = 4., # Gradient explodes if too big, premature convergence if too small. - preemphasis = 0.97, # Filter coefficient to use if preemphasize is True - preemphasize = True, - - ### Tacotron Text-to-Speech (TTS) - tts_embed_dims = 512, # Embedding dimension for the graphemes/phoneme inputs - tts_encoder_dims = 256, - tts_decoder_dims = 128, - tts_postnet_dims = 512, - tts_encoder_K = 5, - tts_lstm_dims = 1024, - tts_postnet_K = 5, - tts_num_highways = 4, - tts_dropout = 0.5, - tts_cleaner_names = ["basic_cleaners"], - tts_stop_threshold = -3.4, # Value below which audio generation ends. - # For example, for a range of [-4, 4], this - # will terminate the sequence at the first - # frame that has all values < -3.4 - - ### Tacotron Training - tts_schedule = [(2, 1e-3, 10_000, 12), # Progressive training schedule - (2, 5e-4, 15_000, 12), # (r, lr, step, batch_size) - (2, 2e-4, 20_000, 12), # (r, lr, step, batch_size) - (2, 1e-4, 30_000, 12), # - (2, 5e-5, 40_000, 12), # - (2, 1e-5, 60_000, 12), # - (2, 5e-6, 160_000, 12), # r = reduction factor (# of mel frames - (2, 3e-6, 320_000, 12), # synthesized for each decoder iteration) - (2, 1e-6, 640_000, 12)], # lr = learning rate - - tts_clip_grad_norm = 1.0, # clips the gradient norm to prevent explosion - set to None if not needed - tts_eval_interval = 500, # Number of steps between model evaluation (sample generation) - # Set to -1 to generate after completing epoch, or 0 to disable - tts_eval_num_samples = 1, # Makes this number of samples - - ## For finetune usage, if set, only selected layers will be trained, available: encoder,encoder_proj,gst,decoder,postnet,post_proj - tts_finetune_layers = [], - - ### Data Preprocessing - max_mel_frames = 900, - rescale = True, - rescaling_max = 0.9, - synthesis_batch_size = 16, # For vocoder preprocessing and inference. - - ### Mel Visualization and Griffin-Lim - signal_normalization = True, - power = 1.5, - griffin_lim_iters = 60, - - ### Audio processing options - fmax = 7600, # Should not exceed (sample_rate // 2) - allow_clipping_in_normalization = True, # Used when signal_normalization = True - clip_mels_length = True, # If true, discards samples exceeding max_mel_frames - use_lws = False, # "Fast spectrogram phase recovery using local weighted sums" - symmetric_mels = True, # Sets mel range to [-max_abs_value, max_abs_value] if True, - # and [0, max_abs_value] if False - trim_silence = True, # Use with sample_rate of 16000 for best results - - ### SV2TTS - speaker_embedding_size = 256, # Dimension for the speaker embedding - silence_min_duration_split = 0.4, # Duration in seconds of a silence for an utterance to be split - utterance_min_duration = 1.6, # Duration in seconds below which utterances are discarded - use_gst = True, # Whether to use global style token - use_ser_for_gst = True, # Whether to use speaker embedding referenced for global style token - ) diff --git a/spaces/KyanChen/RSPrompter/mmdet/engine/hooks/memory_profiler_hook.py b/spaces/KyanChen/RSPrompter/mmdet/engine/hooks/memory_profiler_hook.py deleted file mode 100644 index 3dcdcae0b669ade46026d28c46b35f35d90b504b..0000000000000000000000000000000000000000 --- a/spaces/KyanChen/RSPrompter/mmdet/engine/hooks/memory_profiler_hook.py +++ /dev/null @@ -1,121 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -from typing import Optional, Sequence - -from mmengine.hooks import Hook -from mmengine.runner import Runner - -from mmdet.registry import HOOKS -from mmdet.structures import DetDataSample - - -@HOOKS.register_module() -class MemoryProfilerHook(Hook): - """Memory profiler hook recording memory information including virtual - memory, swap memory, and the memory of the current process. - - Args: - interval (int): Checking interval (every k iterations). - Default: 50. - """ - - def __init__(self, interval: int = 50) -> None: - try: - from psutil import swap_memory, virtual_memory - self._swap_memory = swap_memory - self._virtual_memory = virtual_memory - except ImportError: - raise ImportError('psutil is not installed, please install it by: ' - 'pip install psutil') - - try: - from memory_profiler import memory_usage - self._memory_usage = memory_usage - except ImportError: - raise ImportError( - 'memory_profiler is not installed, please install it by: ' - 'pip install memory_profiler') - - self.interval = interval - - def _record_memory_information(self, runner: Runner) -> None: - """Regularly record memory information. - - Args: - runner (:obj:`Runner`): The runner of the training or evaluation - process. - """ - # in Byte - virtual_memory = self._virtual_memory() - swap_memory = self._swap_memory() - # in MB - process_memory = self._memory_usage()[0] - factor = 1024 * 1024 - runner.logger.info( - 'Memory information ' - 'available_memory: ' - f'{round(virtual_memory.available / factor)} MB, ' - 'used_memory: ' - f'{round(virtual_memory.used / factor)} MB, ' - f'memory_utilization: {virtual_memory.percent} %, ' - 'available_swap_memory: ' - f'{round((swap_memory.total - swap_memory.used) / factor)}' - ' MB, ' - f'used_swap_memory: {round(swap_memory.used / factor)} MB, ' - f'swap_memory_utilization: {swap_memory.percent} %, ' - 'current_process_memory: ' - f'{round(process_memory)} MB') - - def after_train_iter(self, - runner: Runner, - batch_idx: int, - data_batch: Optional[dict] = None, - outputs: Optional[dict] = None) -> None: - """Regularly record memory information. - - Args: - runner (:obj:`Runner`): The runner of the training process. - batch_idx (int): The index of the current batch in the train loop. - data_batch (dict, optional): Data from dataloader. - Defaults to None. - outputs (dict, optional): Outputs from model. Defaults to None. - """ - if self.every_n_inner_iters(batch_idx, self.interval): - self._record_memory_information(runner) - - def after_val_iter( - self, - runner: Runner, - batch_idx: int, - data_batch: Optional[dict] = None, - outputs: Optional[Sequence[DetDataSample]] = None) -> None: - """Regularly record memory information. - - Args: - runner (:obj:`Runner`): The runner of the validation process. - batch_idx (int): The index of the current batch in the val loop. - data_batch (dict, optional): Data from dataloader. - Defaults to None. - outputs (Sequence[:obj:`DetDataSample`], optional): - Outputs from model. Defaults to None. - """ - if self.every_n_inner_iters(batch_idx, self.interval): - self._record_memory_information(runner) - - def after_test_iter( - self, - runner: Runner, - batch_idx: int, - data_batch: Optional[dict] = None, - outputs: Optional[Sequence[DetDataSample]] = None) -> None: - """Regularly record memory information. - - Args: - runner (:obj:`Runner`): The runner of the testing process. - batch_idx (int): The index of the current batch in the test loop. - data_batch (dict, optional): Data from dataloader. - Defaults to None. - outputs (Sequence[:obj:`DetDataSample`], optional): - Outputs from model. Defaults to None. - """ - if self.every_n_inner_iters(batch_idx, self.interval): - self._record_memory_information(runner) diff --git a/spaces/LaynzKunz/Advanced-RVC-Inference/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py b/spaces/LaynzKunz/Advanced-RVC-Inference/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py deleted file mode 100644 index b2c592527a5966e6f8e79e8c52dc5b414246dcc6..0000000000000000000000000000000000000000 --- a/spaces/LaynzKunz/Advanced-RVC-Inference/lib/infer_pack/modules/F0Predictor/PMF0Predictor.py +++ /dev/null @@ -1,97 +0,0 @@ -from lib.infer_pack.modules.F0Predictor.F0Predictor import F0Predictor -import parselmouth -import numpy as np - - -class PMF0Predictor(F0Predictor): - def __init__(self, hop_length=512, f0_min=50, f0_max=1100, sampling_rate=44100): - self.hop_length = hop_length - self.f0_min = f0_min - self.f0_max = f0_max - self.sampling_rate = sampling_rate - - def interpolate_f0(self, f0): - """ - 对F0进行插值处理 - """ - - data = np.reshape(f0, (f0.size, 1)) - - vuv_vector = np.zeros((data.size, 1), dtype=np.float32) - vuv_vector[data > 0.0] = 1.0 - vuv_vector[data <= 0.0] = 0.0 - - ip_data = data - - frame_number = data.size - last_value = 0.0 - for i in range(frame_number): - if data[i] <= 0.0: - j = i + 1 - for j in range(i + 1, frame_number): - if data[j] > 0.0: - break - if j < frame_number - 1: - if last_value > 0.0: - step = (data[j] - data[i - 1]) / float(j - i) - for k in range(i, j): - ip_data[k] = data[i - 1] + step * (k - i + 1) - else: - for k in range(i, j): - ip_data[k] = data[j] - else: - for k in range(i, frame_number): - ip_data[k] = last_value - else: - ip_data[i] = data[i] # 这里可能存在一个没有必要的拷贝 - last_value = data[i] - - return ip_data[:, 0], vuv_vector[:, 0] - - def compute_f0(self, wav, p_len=None): - x = wav - if p_len is None: - p_len = x.shape[0] // self.hop_length - else: - assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error" - time_step = self.hop_length / self.sampling_rate * 1000 - f0 = ( - parselmouth.Sound(x, self.sampling_rate) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=self.f0_min, - pitch_ceiling=self.f0_max, - ) - .selected_array["frequency"] - ) - - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant") - f0, uv = self.interpolate_f0(f0) - return f0 - - def compute_f0_uv(self, wav, p_len=None): - x = wav - if p_len is None: - p_len = x.shape[0] // self.hop_length - else: - assert abs(p_len - x.shape[0] // self.hop_length) < 4, "pad length error" - time_step = self.hop_length / self.sampling_rate * 1000 - f0 = ( - parselmouth.Sound(x, self.sampling_rate) - .to_pitch_ac( - time_step=time_step / 1000, - voicing_threshold=0.6, - pitch_floor=self.f0_min, - pitch_ceiling=self.f0_max, - ) - .selected_array["frequency"] - ) - - pad_size = (p_len - len(f0) + 1) // 2 - if pad_size > 0 or p_len - len(f0) - pad_size > 0: - f0 = np.pad(f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant") - f0, uv = self.interpolate_f0(f0) - return f0, uv diff --git a/spaces/Lbin123/Lbingo/src/components/chat-panel.tsx b/spaces/Lbin123/Lbingo/src/components/chat-panel.tsx deleted file mode 100644 index 1fbc3c2bf05b914e0c229661832fbb560745f488..0000000000000000000000000000000000000000 --- a/spaces/Lbin123/Lbingo/src/components/chat-panel.tsx +++ /dev/null @@ -1,153 +0,0 @@ -'use client' - -import * as React from 'react' -import Image from 'next/image' -import Textarea from 'react-textarea-autosize' -import { useAtomValue } from 'jotai' -import { useEnterSubmit } from '@/lib/hooks/use-enter-submit' -import { cn } from '@/lib/utils' - -import BrushIcon from '@/assets/images/brush.svg' -import ChatIcon from '@/assets/images/chat.svg' -import VisualSearchIcon from '@/assets/images/visual-search.svg' -import SendIcon from '@/assets/images/send.svg' -import PinIcon from '@/assets/images/pin.svg' -import PinFillIcon from '@/assets/images/pin-fill.svg' - -import { useBing } from '@/lib/hooks/use-bing' -import { voiceListenAtom } from '@/state' -import Voice from './voice' -import { ChatImage } from './chat-image' -import { ChatAttachments } from './chat-attachments' - -export interface ChatPanelProps - extends Pick< - ReturnType, - | 'generating' - | 'input' - | 'setInput' - | 'sendMessage' - | 'resetConversation' - | 'isSpeaking' - | 'attachmentList' - | 'uploadImage' - | 'setAttachmentList' - > { - id?: string - className?: string -} - -export function ChatPanel({ - isSpeaking, - generating, - input, - setInput, - className, - sendMessage, - resetConversation, - attachmentList, - uploadImage, - setAttachmentList -}: ChatPanelProps) { - const inputRef = React.useRef(null) - const {formRef, onKeyDown} = useEnterSubmit() - const [focused, setFocused] = React.useState(false) - const [active, setActive] = React.useState(false) - const [pin, setPin] = React.useState(false) - const [tid, setTid] = React.useState() - const voiceListening = useAtomValue(voiceListenAtom) - - const setBlur = React.useCallback(() => { - clearTimeout(tid) - setActive(false) - const _tid = setTimeout(() => setFocused(false), 2000); - setTid(_tid) - }, [tid]) - - const setFocus = React.useCallback(() => { - setFocused(true) - setActive(true) - clearTimeout(tid) - inputRef.current?.focus() - }, [tid]) - - React.useEffect(() => { - if (input) { - setFocus() - } - }, [input]) - - return ( -
    { - e.preventDefault() - if (generating) { - return; - } - if (!input?.trim()) { - return - } - setInput('') - setPin(false) - await sendMessage(input) - }} - ref={formRef} - > -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    - chat - - - Waiting for the stream to begin (might take a few minutes).. - - Streamed so far
    (hang on, this may take a while ☕)
    -
    -
    -
    -
    - -
    -
    - - - \ No newline at end of file diff --git a/spaces/jbochi/Candle-CoEdIT-Wasm/build/m_bg.wasm.d.ts b/spaces/jbochi/Candle-CoEdIT-Wasm/build/m_bg.wasm.d.ts deleted file mode 100644 index 5a19e2874bd67afcbc35a34a54b78c0d8c01cc25..0000000000000000000000000000000000000000 --- a/spaces/jbochi/Candle-CoEdIT-Wasm/build/m_bg.wasm.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -export const memory: WebAssembly.Memory; -export function __wbg_modelencoder_free(a: number): void; -export function __wbg_modelconditionalgeneration_free(a: number): void; -export function modelconditionalgeneration_load(a: number, b: number, c: number, d: number, e: number, f: number, g: number): void; -export function modelconditionalgeneration_decode(a: number, b: number, c: number): void; -export function modelencoder_load(a: number, b: number, c: number, d: number, e: number, f: number, g: number): void; -export function modelencoder_decode(a: number, b: number, c: number): void; -export function main(a: number, b: number): number; -export function __wbindgen_malloc(a: number, b: number): number; -export function __wbindgen_realloc(a: number, b: number, c: number, d: number): number; -export function __wbindgen_add_to_stack_pointer(a: number): number; -export function __wbindgen_free(a: number, b: number, c: number): void; -export function __wbindgen_exn_store(a: number): void; -export function __wbindgen_start(): void; diff --git a/spaces/jbraun19/Webcam-Object-Recognition-Yolo-n-Coco/models.py b/spaces/jbraun19/Webcam-Object-Recognition-Yolo-n-Coco/models.py deleted file mode 100644 index 0f0ae7e84da69f9805bc3a20463e9db488cac889..0000000000000000000000000000000000000000 --- a/spaces/jbraun19/Webcam-Object-Recognition-Yolo-n-Coco/models.py +++ /dev/null @@ -1,530 +0,0 @@ -import numpy as np -import cv2 -import os -import json -from tqdm import tqdm -from glob import glob -import matplotlib.pyplot as plt -import tensorflow as tf -from tensorflow.keras import layers, models, optimizers - -from custom_layers import yolov4_neck, yolov4_head, nms -from utils import load_weights, get_detection_data, draw_bbox, voc_ap, draw_plot_func, read_txt_to_list -from config import yolo_config -from loss import yolo_loss - - -class Yolov4(object): - def __init__(self, - weight_path=None, - class_name_path='coco_classes.txt', - config=yolo_config, - ): - assert config['img_size'][0] == config['img_size'][1], 'not support yet' - assert config['img_size'][0] % config['strides'][-1] == 0, 'must be a multiple of last stride' - self.class_names = [line.strip() for line in open(class_name_path).readlines()] - self.img_size = yolo_config['img_size'] - self.num_classes = len(self.class_names) - self.weight_path = weight_path - self.anchors = np.array(yolo_config['anchors']).reshape((3, 3, 2)) - self.xyscale = yolo_config['xyscale'] - self.strides = yolo_config['strides'] - self.output_sizes = [self.img_size[0] // s for s in self.strides] - self.class_color = {name: list(np.random.random(size=3)*255) for name in self.class_names} - # Training - self.max_boxes = yolo_config['max_boxes'] - self.iou_loss_thresh = yolo_config['iou_loss_thresh'] - self.config = yolo_config - assert self.num_classes > 0, 'no classes detected!' - - tf.keras.backend.clear_session() - if yolo_config['num_gpu'] > 1: - mirrored_strategy = tf.distribute.MirroredStrategy() - with mirrored_strategy.scope(): - self.build_model(load_pretrained=True if self.weight_path else False) - else: - self.build_model(load_pretrained=True if self.weight_path else False) - - def build_model(self, load_pretrained=True): - # core yolo model - input_layer = layers.Input(self.img_size) - yolov4_output = yolov4_neck(input_layer, self.num_classes) - self.yolo_model = models.Model(input_layer, yolov4_output) - - # Build training model - y_true = [ - layers.Input(name='input_2', shape=(52, 52, 3, (self.num_classes + 5))), # label small boxes - layers.Input(name='input_3', shape=(26, 26, 3, (self.num_classes + 5))), # label medium boxes - layers.Input(name='input_4', shape=(13, 13, 3, (self.num_classes + 5))), # label large boxes - layers.Input(name='input_5', shape=(self.max_boxes, 4)), # true bboxes - ] - loss_list = tf.keras.layers.Lambda(yolo_loss, name='yolo_loss', - arguments={'num_classes': self.num_classes, - 'iou_loss_thresh': self.iou_loss_thresh, - 'anchors': self.anchors})([*self.yolo_model.output, *y_true]) - self.training_model = models.Model([self.yolo_model.input, *y_true], loss_list) - - # Build inference model - yolov4_output = yolov4_head(yolov4_output, self.num_classes, self.anchors, self.xyscale) - # output: [boxes, scores, classes, valid_detections] - self.inference_model = models.Model(input_layer, - nms(yolov4_output, self.img_size, self.num_classes, - iou_threshold=self.config['iou_threshold'], - score_threshold=self.config['score_threshold'])) - - if load_pretrained and self.weight_path and self.weight_path.endswith('.weights'): - if self.weight_path.endswith('.weights'): - load_weights(self.yolo_model, self.weight_path) - print(f'load from {self.weight_path}') - elif self.weight_path.endswith('.h5'): - self.training_model.load_weights(self.weight_path) - print(f'load from {self.weight_path}') - - self.training_model.compile(optimizer=optimizers.Adam(lr=1e-3), - loss={'yolo_loss': lambda y_true, y_pred: y_pred}) - - def load_model(self, path): - self.yolo_model = models.load_model(path, compile=False) - yolov4_output = yolov4_head(self.yolo_model.output, self.num_classes, self.anchors, self.xyscale) - self.inference_model = models.Model(self.yolo_model.input, - nms(yolov4_output, self.img_size, self.num_classes)) # [boxes, scores, classes, valid_detections] - - def save_model(self, path): - self.yolo_model.save(path) - - def preprocess_img(self, img): - img = cv2.resize(img, self.img_size[:2]) - img = img / 255. - return img - - def fit(self, train_data_gen, epochs, val_data_gen=None, initial_epoch=0, callbacks=None): - self.training_model.fit(train_data_gen, - steps_per_epoch=len(train_data_gen), - validation_data=val_data_gen, - validation_steps=len(val_data_gen), - epochs=epochs, - callbacks=callbacks, - initial_epoch=initial_epoch) - # raw_img: RGB - def predict_img(self, raw_img, random_color=True, plot_img=True, figsize=(10, 10), show_text=True, return_output=True): - print('img shape: ', raw_img.shape) - img = self.preprocess_img(raw_img) - imgs = np.expand_dims(img, axis=0) - pred_output = self.inference_model.predict(imgs) - detections = get_detection_data(img=raw_img, - model_outputs=pred_output, - class_names=self.class_names) - - output_img = draw_bbox(raw_img, detections, cmap=self.class_color, random_color=random_color, figsize=figsize, - show_text=show_text, show_img=False) - if return_output: - return output_img, detections - else: - return detections - - def predict(self, img_path, random_color=True, plot_img=True, figsize=(10, 10), show_text=True): - raw_img = img_path - return self.predict_img(raw_img, random_color, plot_img, figsize, show_text) - - def export_gt(self, annotation_path, gt_folder_path): - with open(annotation_path) as file: - for line in file: - line = line.split(' ') - filename = line[0].split(os.sep)[-1].split('.')[0] - objs = line[1:] - # export txt file - with open(os.path.join(gt_folder_path, filename + '.txt'), 'w') as output_file: - for obj in objs: - x_min, y_min, x_max, y_max, class_id = [float(o) for o in obj.strip().split(',')] - output_file.write(f'{self.class_names[int(class_id)]} {x_min} {y_min} {x_max} {y_max}\n') - - def export_prediction(self, annotation_path, pred_folder_path, img_folder_path, bs=2): - with open(annotation_path) as file: - img_paths = [os.path.join(img_folder_path, line.split(' ')[0].split(os.sep)[-1]) for line in file] - # print(img_paths[:20]) - for batch_idx in tqdm(range(0, len(img_paths), bs)): - # print(len(img_paths), batch_idx, batch_idx*bs, (batch_idx+1)*bs) - paths = img_paths[batch_idx:batch_idx+bs] - # print(paths) - # read and process img - imgs = np.zeros((len(paths), *self.img_size)) - raw_img_shapes = [] - for j, path in enumerate(paths): - img = cv2.imread(path) - raw_img_shapes.append(img.shape) - img = self.preprocess_img(img) - imgs[j] = img - - # process batch output - b_boxes, b_scores, b_classes, b_valid_detections = self.inference_model.predict(imgs) - for k in range(len(paths)): - num_boxes = b_valid_detections[k] - raw_img_shape = raw_img_shapes[k] - boxes = b_boxes[k, :num_boxes] - classes = b_classes[k, :num_boxes] - scores = b_scores[k, :num_boxes] - # print(raw_img_shape) - boxes[:, [0, 2]] = (boxes[:, [0, 2]] * raw_img_shape[1]) # w - boxes[:, [1, 3]] = (boxes[:, [1, 3]] * raw_img_shape[0]) # h - cls_names = [self.class_names[int(c)] for c in classes] - # print(raw_img_shape, boxes.astype(int), cls_names, scores) - - img_path = paths[k] - filename = img_path.split(os.sep)[-1].split('.')[0] - # print(filename) - output_path = os.path.join(pred_folder_path, filename+'.txt') - with open(output_path, 'w') as pred_file: - for box_idx in range(num_boxes): - b = boxes[box_idx] - pred_file.write(f'{cls_names[box_idx]} {scores[box_idx]} {b[0]} {b[1]} {b[2]} {b[3]}\n') - - - def eval_map(self, gt_folder_path, pred_folder_path, temp_json_folder_path, output_files_path): - """Process Gt""" - ground_truth_files_list = glob(gt_folder_path + '/*.txt') - assert len(ground_truth_files_list) > 0, 'no ground truth file' - ground_truth_files_list.sort() - # dictionary with counter per class - gt_counter_per_class = {} - counter_images_per_class = {} - - gt_files = [] - for txt_file in ground_truth_files_list: - file_id = txt_file.split(".txt", 1)[0] - file_id = os.path.basename(os.path.normpath(file_id)) - # check if there is a correspondent detection-results file - temp_path = os.path.join(pred_folder_path, (file_id + ".txt")) - assert os.path.exists(temp_path), "Error. File not found: {}\n".format(temp_path) - lines_list = read_txt_to_list(txt_file) - # create ground-truth dictionary - bounding_boxes = [] - is_difficult = False - already_seen_classes = [] - for line in lines_list: - class_name, left, top, right, bottom = line.split() - # check if class is in the ignore list, if yes skip - bbox = left + " " + top + " " + right + " " + bottom - bounding_boxes.append({"class_name": class_name, "bbox": bbox, "used": False}) - # count that object - if class_name in gt_counter_per_class: - gt_counter_per_class[class_name] += 1 - else: - # if class didn't exist yet - gt_counter_per_class[class_name] = 1 - - if class_name not in already_seen_classes: - if class_name in counter_images_per_class: - counter_images_per_class[class_name] += 1 - else: - # if class didn't exist yet - counter_images_per_class[class_name] = 1 - already_seen_classes.append(class_name) - - # dump bounding_boxes into a ".json" file - new_temp_file = os.path.join(temp_json_folder_path, file_id+"_ground_truth.json") #TEMP_FILES_PATH + "/" + file_id + "_ground_truth.json" - gt_files.append(new_temp_file) - with open(new_temp_file, 'w') as outfile: - json.dump(bounding_boxes, outfile) - - gt_classes = list(gt_counter_per_class.keys()) - # let's sort the classes alphabetically - gt_classes = sorted(gt_classes) - n_classes = len(gt_classes) - print(gt_classes, gt_counter_per_class) - - """Process prediction""" - - dr_files_list = sorted(glob(os.path.join(pred_folder_path, '*.txt'))) - - for class_index, class_name in enumerate(gt_classes): - bounding_boxes = [] - for txt_file in dr_files_list: - # the first time it checks if all the corresponding ground-truth files exist - file_id = txt_file.split(".txt", 1)[0] - file_id = os.path.basename(os.path.normpath(file_id)) - temp_path = os.path.join(gt_folder_path, (file_id + ".txt")) - if class_index == 0: - if not os.path.exists(temp_path): - error_msg = f"Error. File not found: {temp_path}\n" - print(error_msg) - lines = read_txt_to_list(txt_file) - for line in lines: - try: - tmp_class_name, confidence, left, top, right, bottom = line.split() - except ValueError: - error_msg = f"""Error: File {txt_file} in the wrong format.\n - Expected: \n - Received: {line} \n""" - print(error_msg) - if tmp_class_name == class_name: - # print("match") - bbox = left + " " + top + " " + right + " " + bottom - bounding_boxes.append({"confidence": confidence, "file_id": file_id, "bbox": bbox}) - # sort detection-results by decreasing confidence - bounding_boxes.sort(key=lambda x: float(x['confidence']), reverse=True) - with open(temp_json_folder_path + "/" + class_name + "_dr.json", 'w') as outfile: - json.dump(bounding_boxes, outfile) - - """ - Calculate the AP for each class - """ - sum_AP = 0.0 - ap_dictionary = {} - # open file to store the output - with open(output_files_path + "/output.txt", 'w') as output_file: - output_file.write("# AP and precision/recall per class\n") - count_true_positives = {} - for class_index, class_name in enumerate(gt_classes): - count_true_positives[class_name] = 0 - """ - Load detection-results of that class - """ - dr_file = temp_json_folder_path + "/" + class_name + "_dr.json" - dr_data = json.load(open(dr_file)) - - """ - Assign detection-results to ground-truth objects - """ - nd = len(dr_data) - tp = [0] * nd # creates an array of zeros of size nd - fp = [0] * nd - for idx, detection in enumerate(dr_data): - file_id = detection["file_id"] - gt_file = temp_json_folder_path + "/" + file_id + "_ground_truth.json" - ground_truth_data = json.load(open(gt_file)) - ovmax = -1 - gt_match = -1 - # load detected object bounding-box - bb = [float(x) for x in detection["bbox"].split()] - for obj in ground_truth_data: - # look for a class_name match - if obj["class_name"] == class_name: - bbgt = [float(x) for x in obj["bbox"].split()] - bi = [max(bb[0], bbgt[0]), max(bb[1], bbgt[1]), min(bb[2], bbgt[2]), min(bb[3], bbgt[3])] - iw = bi[2] - bi[0] + 1 - ih = bi[3] - bi[1] + 1 - if iw > 0 and ih > 0: - # compute overlap (IoU) = area of intersection / area of union - ua = (bb[2] - bb[0] + 1) * (bb[3] - bb[1] + 1) + \ - (bbgt[2] - bbgt[0]+ 1) * (bbgt[3] - bbgt[1] + 1) - iw * ih - ov = iw * ih / ua - if ov > ovmax: - ovmax = ov - gt_match = obj - - min_overlap = 0.5 - if ovmax >= min_overlap: - # if "difficult" not in gt_match: - if not bool(gt_match["used"]): - # true positive - tp[idx] = 1 - gt_match["used"] = True - count_true_positives[class_name] += 1 - # update the ".json" file - with open(gt_file, 'w') as f: - f.write(json.dumps(ground_truth_data)) - else: - # false positive (multiple detection) - fp[idx] = 1 - else: - fp[idx] = 1 - - - # compute precision/recall - cumsum = 0 - for idx, val in enumerate(fp): - fp[idx] += cumsum - cumsum += val - print('fp ', cumsum) - cumsum = 0 - for idx, val in enumerate(tp): - tp[idx] += cumsum - cumsum += val - print('tp ', cumsum) - rec = tp[:] - for idx, val in enumerate(tp): - rec[idx] = float(tp[idx]) / gt_counter_per_class[class_name] - print('recall ', cumsum) - prec = tp[:] - for idx, val in enumerate(tp): - prec[idx] = float(tp[idx]) / (fp[idx] + tp[idx]) - print('prec ', cumsum) - - ap, mrec, mprec = voc_ap(rec[:], prec[:]) - sum_AP += ap - text = "{0:.2f}%".format( - ap * 100) + " = " + class_name + " AP " # class_name + " AP = {0:.2f}%".format(ap*100) - - print(text) - ap_dictionary[class_name] = ap - - n_images = counter_images_per_class[class_name] - # lamr, mr, fppi = log_average_miss_rate(np.array(prec), np.array(rec), n_images) - # lamr_dictionary[class_name] = lamr - - """ - Draw plot - """ - if True: - plt.plot(rec, prec, '-o') - # add a new penultimate point to the list (mrec[-2], 0.0) - # since the last line segment (and respective area) do not affect the AP value - area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec[-1]] - area_under_curve_y = mprec[:-1] + [0.0] + [mprec[-1]] - plt.fill_between(area_under_curve_x, 0, area_under_curve_y, alpha=0.2, edgecolor='r') - # set window title - fig = plt.gcf() # gcf - get current figure - fig.canvas.set_window_title('AP ' + class_name) - # set plot title - plt.title('class: ' + text) - # plt.suptitle('This is a somewhat long figure title', fontsize=16) - # set axis titles - plt.xlabel('Recall') - plt.ylabel('Precision') - # optional - set axes - axes = plt.gca() # gca - get current axes - axes.set_xlim([0.0, 1.0]) - axes.set_ylim([0.0, 1.05]) # .05 to give some extra space - # Alternative option -> wait for button to be pressed - # while not plt.waitforbuttonpress(): pass # wait for key display - # Alternative option -> normal display - plt.show() - # save the plot - # fig.savefig(output_files_path + "/classes/" + class_name + ".png") - # plt.cla() # clear axes for next plot - - # if show_animation: - # cv2.destroyAllWindows() - - output_file.write("\n# mAP of all classes\n") - mAP = sum_AP / n_classes - text = "mAP = {0:.2f}%".format(mAP * 100) - output_file.write(text + "\n") - print(text) - - """ - Count total of detection-results - """ - # iterate through all the files - det_counter_per_class = {} - for txt_file in dr_files_list: - # get lines to list - lines_list = read_txt_to_list(txt_file) - for line in lines_list: - class_name = line.split()[0] - # check if class is in the ignore list, if yes skip - # if class_name in args.ignore: - # continue - # count that object - if class_name in det_counter_per_class: - det_counter_per_class[class_name] += 1 - else: - # if class didn't exist yet - det_counter_per_class[class_name] = 1 - # print(det_counter_per_class) - dr_classes = list(det_counter_per_class.keys()) - - """ - Plot the total number of occurences of each class in the ground-truth - """ - if True: - window_title = "ground-truth-info" - plot_title = "ground-truth\n" - plot_title += "(" + str(len(ground_truth_files_list)) + " files and " + str(n_classes) + " classes)" - x_label = "Number of objects per class" - output_path = output_files_path + "/ground-truth-info.png" - to_show = False - plot_color = 'forestgreen' - draw_plot_func( - gt_counter_per_class, - n_classes, - window_title, - plot_title, - x_label, - output_path, - to_show, - plot_color, - '', - ) - - """ - Finish counting true positives - """ - for class_name in dr_classes: - # if class exists in detection-result but not in ground-truth then there are no true positives in that class - if class_name not in gt_classes: - count_true_positives[class_name] = 0 - # print(count_true_positives) - - """ - Plot the total number of occurences of each class in the "detection-results" folder - """ - if True: - window_title = "detection-results-info" - # Plot title - plot_title = "detection-results\n" - plot_title += "(" + str(len(dr_files_list)) + " files and " - count_non_zero_values_in_dictionary = sum(int(x) > 0 for x in list(det_counter_per_class.values())) - plot_title += str(count_non_zero_values_in_dictionary) + " detected classes)" - # end Plot title - x_label = "Number of objects per class" - output_path = output_files_path + "/detection-results-info.png" - to_show = False - plot_color = 'forestgreen' - true_p_bar = count_true_positives - draw_plot_func( - det_counter_per_class, - len(det_counter_per_class), - window_title, - plot_title, - x_label, - output_path, - to_show, - plot_color, - true_p_bar - ) - - """ - Draw mAP plot (Show AP's of all classes in decreasing order) - """ - if True: - window_title = "mAP" - plot_title = "mAP = {0:.2f}%".format(mAP * 100) - x_label = "Average Precision" - output_path = output_files_path + "/mAP.png" - to_show = True - plot_color = 'royalblue' - draw_plot_func( - ap_dictionary, - n_classes, - window_title, - plot_title, - x_label, - output_path, - to_show, - plot_color, - "" - ) - - def predict_raw(self, img_path): - raw_img = cv2.imread(img_path) - print('img shape: ', raw_img.shape) - img = self.preprocess_img(raw_img) - imgs = np.expand_dims(img, axis=0) - return self.yolo_model.predict(imgs) - - def predict_nonms(self, img_path, iou_threshold=0.413, score_threshold=0.1): - raw_img = cv2.imread(img_path) - print('img shape: ', raw_img.shape) - img = self.preprocess_img(raw_img) - imgs = np.expand_dims(img, axis=0) - yolov4_output = self.yolo_model.predict(imgs) - output = yolov4_head(yolov4_output, self.num_classes, self.anchors, self.xyscale) - pred_output = nms(output, self.img_size, self.num_classes, iou_threshold, score_threshold) - pred_output = [p.numpy() for p in pred_output] - detections = get_detection_data(img=raw_img, - model_outputs=pred_output, - class_names=self.class_names) - draw_bbox(raw_img, detections, cmap=self.class_color, random_color=True) - return detections - diff --git a/spaces/jcenaa/Segment-Any-RGBD/tools/convert-pretrained-swin-model-to-d2.py b/spaces/jcenaa/Segment-Any-RGBD/tools/convert-pretrained-swin-model-to-d2.py deleted file mode 100644 index 4cc9939c781a4d04dc6070a7fcac8d6c09afc8a1..0000000000000000000000000000000000000000 --- a/spaces/jcenaa/Segment-Any-RGBD/tools/convert-pretrained-swin-model-to-d2.py +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# Copyright (c) Meta Platforms, Inc. All Rights Reserved - -import pickle as pkl -import sys - -import torch - -""" -Usage: - # download pretrained swin model: - wget https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth - # run the conversion - ./convert-pretrained-model-to-d2.py swin_tiny_patch4_window7_224.pth swin_tiny_patch4_window7_224.pkl - # Then, use swin_tiny_patch4_window7_224.pkl with the following changes in config: -MODEL: - WEIGHTS: "/path/to/swin_tiny_patch4_window7_224.pkl" -INPUT: - FORMAT: "RGB" -""" - -if __name__ == "__main__": - input = sys.argv[1] - - obj = torch.load(input, map_location="cpu")["model"] - - res = {"model": obj, "__author__": "third_party", "matching_heuristics": True} - - with open(sys.argv[2], "wb") as f: - pkl.dump(res, f) diff --git a/spaces/jeevavijay10/code-gen/README.md b/spaces/jeevavijay10/code-gen/README.md deleted file mode 100644 index 8094835291c0bef9e32370d508463f21eb4e55b8..0000000000000000000000000000000000000000 --- a/spaces/jeevavijay10/code-gen/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Code Gen -emoji: 🏢 -colorFrom: gray -colorTo: gray -sdk: gradio -sdk_version: 3.39.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/jelly21/claudfuen-photorealistic-fuen-v1/README.md b/spaces/jelly21/claudfuen-photorealistic-fuen-v1/README.md deleted file mode 100644 index 8efc48a9fed81e85c57788f93c2e899934fa3a2d..0000000000000000000000000000000000000000 --- a/spaces/jelly21/claudfuen-photorealistic-fuen-v1/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Claudfuen Photorealistic Fuen V1 -emoji: 🔥 -colorFrom: pink -colorTo: pink -sdk: gradio -sdk_version: 3.20.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/jhwen/bingo/src/pages/api/healthz.ts b/spaces/jhwen/bingo/src/pages/api/healthz.ts deleted file mode 100644 index f6ae44ff0fd66ccd3f7feaa550025fbf2a83bf77..0000000000000000000000000000000000000000 --- a/spaces/jhwen/bingo/src/pages/api/healthz.ts +++ /dev/null @@ -1,7 +0,0 @@ -'use server' - -import { NextApiRequest, NextApiResponse } from 'next' - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - res.status(200).end('ok') -} diff --git a/spaces/jkang/demo-artist-classifier/README.md b/spaces/jkang/demo-artist-classifier/README.md deleted file mode 100644 index 9bd3d48aed7a148238fe1df3675e40a15090b86e..0000000000000000000000000000000000000000 --- a/spaces/jkang/demo-artist-classifier/README.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Artist Classifier -emoji: 🎨👨🏻‍🎨 -colorFrom: red -colorTo: pink -sdk: gradio -app_file: gradio_artist_classifier.py -pinned: false ---- - -# Configuration diff --git a/spaces/joaogabriellima/Real-Time-Voice-Cloning/synthesizer/utils/_cmudict.py b/spaces/joaogabriellima/Real-Time-Voice-Cloning/synthesizer/utils/_cmudict.py deleted file mode 100644 index 2cef1f896d4fb78478884fe8e810956998d5e3b3..0000000000000000000000000000000000000000 --- a/spaces/joaogabriellima/Real-Time-Voice-Cloning/synthesizer/utils/_cmudict.py +++ /dev/null @@ -1,62 +0,0 @@ -import re - -valid_symbols = [ - "AA", "AA0", "AA1", "AA2", "AE", "AE0", "AE1", "AE2", "AH", "AH0", "AH1", "AH2", - "AO", "AO0", "AO1", "AO2", "AW", "AW0", "AW1", "AW2", "AY", "AY0", "AY1", "AY2", - "B", "CH", "D", "DH", "EH", "EH0", "EH1", "EH2", "ER", "ER0", "ER1", "ER2", "EY", - "EY0", "EY1", "EY2", "F", "G", "HH", "IH", "IH0", "IH1", "IH2", "IY", "IY0", "IY1", - "IY2", "JH", "K", "L", "M", "N", "NG", "OW", "OW0", "OW1", "OW2", "OY", "OY0", - "OY1", "OY2", "P", "R", "S", "SH", "T", "TH", "UH", "UH0", "UH1", "UH2", "UW", - "UW0", "UW1", "UW2", "V", "W", "Y", "Z", "ZH" -] - -_valid_symbol_set = set(valid_symbols) - - -class CMUDict: - """Thin wrapper around CMUDict data. http://www.speech.cs.cmu.edu/cgi-bin/cmudict""" - def __init__(self, file_or_path, keep_ambiguous=True): - if isinstance(file_or_path, str): - with open(file_or_path, encoding="latin-1") as f: - entries = _parse_cmudict(f) - else: - entries = _parse_cmudict(file_or_path) - if not keep_ambiguous: - entries = {word: pron for word, pron in entries.items() if len(pron) == 1} - self._entries = entries - - - def __len__(self): - return len(self._entries) - - - def lookup(self, word): - """Returns list of ARPAbet pronunciations of the given word.""" - return self._entries.get(word.upper()) - - - -_alt_re = re.compile(r"\([0-9]+\)") - - -def _parse_cmudict(file): - cmudict = {} - for line in file: - if len(line) and (line[0] >= "A" and line[0] <= "Z" or line[0] == "'"): - parts = line.split(" ") - word = re.sub(_alt_re, "", parts[0]) - pronunciation = _get_pronunciation(parts[1]) - if pronunciation: - if word in cmudict: - cmudict[word].append(pronunciation) - else: - cmudict[word] = [pronunciation] - return cmudict - - -def _get_pronunciation(s): - parts = s.strip().split(" ") - for part in parts: - if part not in _valid_symbol_set: - return None - return " ".join(parts) diff --git a/spaces/joshen/gpt-academic/README.md b/spaces/joshen/gpt-academic/README.md deleted file mode 100644 index 01bac90e809880f1ae2f10527edaede5a0535b51..0000000000000000000000000000000000000000 --- a/spaces/joshen/gpt-academic/README.md +++ /dev/null @@ -1,274 +0,0 @@ ---- -title: ChatImprovement -emoji: 😻 -colorFrom: blue -colorTo: blue -sdk: gradio -sdk_version: 3.23.0 -app_file: app.py -pinned: false -duplicated_from: qingxu98/gpt-academic ---- - - -# ChatGPT 学术优化 - -**如果喜欢这个项目,请给它一个Star;如果你发明了更好用的快捷键或函数插件,欢迎发issue或者pull requests(dev分支)** - -If you like this project, please give it a Star. If you've come up with more useful academic shortcuts or functional plugins, feel free to open an issue or pull request (to `dev` branch). - -``` -代码中参考了很多其他优秀项目中的设计,主要包括: - -# 借鉴项目1:借鉴了ChuanhuChatGPT中读取OpenAI json的方法、记录历史问询记录的方法以及gradio queue的使用技巧 -https://github.com/GaiZhenbiao/ChuanhuChatGPT - -# 借鉴项目2:借鉴了mdtex2html中公式处理的方法 -https://github.com/polarwinkel/mdtex2html - -项目使用OpenAI的gpt-3.5-turbo模型,期待gpt-4早点放宽门槛😂 -``` - -> **Note** -> -> 1.请注意只有“红颜色”标识的函数插件(按钮)才支持读取文件。目前对pdf/word格式文件的支持插件正在逐步完善中,需要更多developer的帮助。 -> -> 2.本项目中每个文件的功能都在自译解[`self_analysis.md`](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)详细说明。随着版本的迭代,您也可以随时自行点击相关函数插件,调用GPT重新生成项目的自我解析报告。常见问题汇总在[`wiki`](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)当中。 -> -> 3.如果您不太习惯部分中文命名的函数、注释或者界面,您可以随时点击相关函数插件,调用ChatGPT一键生成纯英文的项目源代码。 - -
    - -功能 | 描述 ---- | --- -一键润色 | 支持一键润色、一键查找论文语法错误 -一键中英互译 | 一键中英互译 -一键代码解释 | 可以正确显示代码、解释代码 -自定义快捷键 | 支持自定义快捷键 -配置代理服务器 | 支持配置代理服务器 -模块化设计 | 支持自定义高阶的实验性功能与[函数插件],插件支持[热更新](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97) -自我程序剖析 | [函数插件] 一键读懂本项目的源代码 -程序剖析 | [函数插件] 一键可以剖析其他Python/C/C++/Java项目树 -读论文 | [函数插件] 一键解读latex论文全文并生成摘要 -批量注释生成 | [函数插件] 一键批量生成函数注释 -chat分析报告生成 | [函数插件] 运行后自动生成总结汇报 -arxiv小助手 | [函数插件] 输入arxiv文章url即可一键翻译摘要+下载PDF -公式显示 | 可以同时显示公式的tex形式和渲染形式 -图片显示 | 可以在markdown中显示图片 -多线程函数插件支持 | 支持多线调用chatgpt,一键处理海量文本或程序 -支持GPT输出的markdown表格 | 可以输出支持GPT的markdown表格 -…… | …… - -
    - - -- 新界面 -
    - -
    - - -- 所有按钮都通过读取functional.py动态生成,可随意加自定义功能,解放粘贴板 -
    - -
    - -- 润色/纠错 -
    - -
    - - -- 支持GPT输出的markdown表格 -
    - -
    - -- 如果输出包含公式,会同时以tex形式和渲染形式显示,方便复制和阅读 -
    - -
    - - -- 懒得看项目代码?整个工程直接给chatgpt炫嘴里 -
    - -
    - -## 直接运行 (Windows, Linux or MacOS) - -### 1. 下载项目 -```sh -git clone https://github.com/binary-husky/chatgpt_academic.git -cd chatgpt_academic -``` - -### 2. 配置API_KEY和代理设置 - -在`config.py`中,配置 海外Proxy 和 OpenAI API KEY,说明如下 -``` -1. 如果你在国内,需要设置海外代理才能够顺利使用 OpenAI API,设置方法请仔细阅读config.py(1.修改其中的USE_PROXY为True; 2.按照说明修改其中的proxies)。 -2. 配置 OpenAI API KEY。你需要在 OpenAI 官网上注册并获取 API KEY。一旦你拿到了 API KEY,在 config.py 文件里配置好即可。 -3. 与代理网络有关的issue(网络超时、代理不起作用)汇总到 https://github.com/binary-husky/chatgpt_academic/issues/1 -``` -(P.S. 程序运行时会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。因此,如果您能理解我们的配置读取逻辑,我们强烈建议您在`config.py`旁边创建一个名为`config_private.py`的新配置文件,并把`config.py`中的配置转移(复制)到`config_private.py`中。`config_private.py`不受git管控,可以让您的隐私信息更加安全。) - - -### 3. 安装依赖 -```sh -# (选择一)推荐 -python -m pip install -r requirements.txt - -# (选择二)如果您使用anaconda,步骤也是类似的: -# (选择二.1)conda create -n gptac_venv python=3.11 -# (选择二.2)conda activate gptac_venv -# (选择二.3)python -m pip install -r requirements.txt - -# 备注:使用官方pip源或者阿里pip源,其他pip源(如清华pip)有可能出问题,临时换源方法: -# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ -``` - -### 4. 运行 -```sh -python main.py -``` - -### 5. 测试实验性功能 -``` -- 测试C++项目头文件分析 - input区域 输入 `./crazy_functions/test_project/cpp/libJPG` , 然后点击 "[实验] 解析整个C++项目(input输入项目根路径)" -- 测试给Latex项目写摘要 - input区域 输入 `./crazy_functions/test_project/latex/attention` , 然后点击 "[实验] 读tex论文写摘要(input输入项目根路径)" -- 测试Python项目分析 - input区域 输入 `./crazy_functions/test_project/python/dqn` , 然后点击 "[实验] 解析整个py项目(input输入项目根路径)" -- 测试自我代码解读 - 点击 "[实验] 请解析并解构此项目本身" -- 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能 - 点击 "[实验] 实验功能函数模板" -``` - -## 使用docker (Linux) - -``` sh -# 下载项目 -git clone https://github.com/binary-husky/chatgpt_academic.git -cd chatgpt_academic -# 配置 海外Proxy 和 OpenAI API KEY -用任意文本编辑器编辑 config.py -# 安装 -docker build -t gpt-academic . -# 运行 -docker run --rm -it --net=host gpt-academic - -# 测试实验性功能 -## 测试自我代码解读 -点击 "[实验] 请解析并解构此项目本身" -## 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能 -点击 "[实验] 实验功能函数模板" -##(请注意在docker中运行时,需要额外注意程序的文件访问权限问题) -## 测试C++项目头文件分析 -input区域 输入 ./crazy_functions/test_project/cpp/libJPG , 然后点击 "[实验] 解析整个C++项目(input输入项目根路径)" -## 测试给Latex项目写摘要 -input区域 输入 ./crazy_functions/test_project/latex/attention , 然后点击 "[实验] 读tex论文写摘要(input输入项目根路径)" -## 测试Python项目分析 -input区域 输入 ./crazy_functions/test_project/python/dqn , 然后点击 "[实验] 解析整个py项目(input输入项目根路径)" - -``` - -## 其他部署方式 -- 使用WSL2(Windows Subsystem for Linux 子系统) -请访问[部署wiki-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2) - -- nginx远程部署 -请访问[部署wiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E7%9A%84%E6%8C%87%E5%AF%BC) - - -## 自定义新的便捷按钮(学术快捷键自定义) -打开functional.py,添加条目如下,然后重启程序即可。(如果按钮已经添加成功并可见,那么前缀、后缀都支持热修改,无需重启程序即可生效。) -例如 -``` -"超级英译中": { - - # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等 - "Prefix": "请翻译把下面一段内容成中文,然后用一个markdown表格逐一解释文中出现的专有名词:\n\n", - - # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。 - "Suffix": "", - -}, -``` -
    - -
    - - -如果你发明了更好用的学术快捷键,欢迎发issue或者pull requests! - -## 配置代理 -### 方法一:常规方法 -在```config.py```中修改端口与代理软件对应 - -
    - - -
    - -配置完成后,你可以用以下命令测试代理是否工作,如果一切正常,下面的代码将输出你的代理服务器所在地: -``` -python check_proxy.py -``` -### 方法二:纯新手教程 -[纯新手教程](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89) - -## 兼容性测试 - -### 图片显示: - -
    - -
    - - -### 如果一个程序能够读懂并剖析自己: - -
    - -
    - -
    - -
    - -### 其他任意Python/Cpp项目剖析: -
    - -
    - -
    - -
    - -### Latex论文一键阅读理解与摘要生成 -
    - -
    - -### 自动报告生成 -
    - - - -
    - -### 模块化功能设计 -
    - - -
    - -## Todo: - -- (Top Priority) 调用另一个开源项目text-generation-webui的web接口,使用其他llm模型 -- 总结大工程源代码时,文本过长、token溢出的问题(目前的方法是直接二分丢弃处理溢出,过于粗暴,有效信息大量丢失) - - diff --git a/spaces/jspr/paperchat/qa.py b/spaces/jspr/paperchat/qa.py deleted file mode 100644 index 9cc56c9c300f71f34cd56b22f74e1cbed323a681..0000000000000000000000000000000000000000 --- a/spaces/jspr/paperchat/qa.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Ask a question to the notion database.""" -import faiss -from langchain import OpenAI -from langchain.chains import VectorDBQAWithSourcesChain -import pickle -import argparse - -parser = argparse.ArgumentParser(description='Ask a question about the paper') -parser.add_argument('question', type=str, help='The question to ask about the paper') -args = parser.parse_args() - -# Load the LangChain. -index = faiss.read_index("docs.index") - -with open("faiss_store.pkl", "rb") as f: - store = pickle.load(f) - -store.index = index -chain = VectorDBQAWithSourcesChain.from_llm(llm=OpenAI(temperature=0), vectorstore=store) -result = chain({"question": args.question}) -print(f"Answer: {result['answer']}") -sources = result["sources"].split(", ") -sources = [s.title() for s in sources] - -import code -code.interact(local=locals()) diff --git a/spaces/justest/gpt4free/g4f/__init__.py b/spaces/justest/gpt4free/g4f/__init__.py deleted file mode 100644 index a0b4bac6aa4de9c0449095a3874c2cb9716169d7..0000000000000000000000000000000000000000 --- a/spaces/justest/gpt4free/g4f/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -import sys -from . import Provider -from g4f.models import Model, ModelUtils - - -class ChatCompletion: - @staticmethod - def create(model: Model.model or str, messages: list, provider: Provider.Provider = None, stream: bool = False, auth: str = False, **kwargs): - kwargs['auth'] = auth - - if provider and provider.needs_auth and not auth: - print( - f'ValueError: {provider.__name__} requires authentication (use auth="cookie or token or jwt ..." param)', file=sys.stderr) - sys.exit(1) - - try: - if isinstance(model, str): - try: - model = ModelUtils.convert[model] - except KeyError: - raise Exception(f'The model: {model} does not exist') - - engine = model.best_provider if not provider else provider - - if not engine.supports_stream and stream == True: - print( - f"ValueError: {engine.__name__} does not support 'stream' argument", file=sys.stderr) - sys.exit(1) - - print(f'Using {engine.__name__} provider') - - return (engine._create_completion(model.name, messages, stream, **kwargs) - if stream else ''.join(engine._create_completion(model.name, messages, stream, **kwargs))) - except TypeError as e: - print(e) - arg: str = str(e).split("'")[1] - print( - f"ValueError: {engine.__name__} does not support '{arg}' argument", file=sys.stderr) - sys.exit(1) diff --git a/spaces/kazuk/youtube-whisper-08/app.py b/spaces/kazuk/youtube-whisper-08/app.py deleted file mode 100644 index 4a61dc561a016c53ad93a3c556b0ef7bafa964eb..0000000000000000000000000000000000000000 --- a/spaces/kazuk/youtube-whisper-08/app.py +++ /dev/null @@ -1,66 +0,0 @@ -import gradio as gr -import whisper -from pytube import YouTube - -def get_audio(url): - yt = YouTube(url) - return yt.streams.filter(only_audio=True)[0].download(filename="tmp.mp4") - -def get_transcript(url, model_size, lang, format): - - model = whisper.load_model(model_size) - - if lang == "None": - lang = None - - result = model.transcribe(get_audio(url), fp16=False, language=lang) - - if format == "None": - return result["text"] - elif format == ".srt": - return format_to_srt(result["segments"]) - -def format_to_srt(segments): - output = "" - for i, segment in enumerate(segments): - output += f"{i + 1}\n" - output += f"{format_timestamp(segment['start'])} --> {format_timestamp(segment['end'])}\n" - output += f"{segment['text']}\n\n" - return output - -def format_timestamp(t): - hh = t//3600 - mm = (t - hh*3600)//60 - ss = t - hh*3600 - mm*60 - mi = (t - int(t))*1000 - return f"{int(hh):02d}:{int(mm):02d}:{int(ss):02d},{int(mi):03d}" - - -langs = ["None"] + sorted(list(whisper.tokenizer.LANGUAGES.values())) -model_size = list(whisper._MODELS.keys()) - -with gr.Blocks() as demo: - - with gr.Row(): - - with gr.Column(): - - with gr.Row(): - url = gr.Textbox(placeholder='Youtube video URL', label='URL') - - with gr.Row(): - - model_size = gr.Dropdown(choices=model_size, value='tiny', label="Model") - lang = gr.Dropdown(choices=langs, value="None", label="Language (Optional)") - format = gr.Dropdown(choices=["None", ".srt"], value="None", label="Timestamps? (Optional)") - - with gr.Row(): - gr.Markdown("Larger models are more accurate, but slower. For 1min video, it'll take ~30s (tiny), ~1min (base), ~3min (small), ~5min (medium), etc.") - transcribe_btn = gr.Button('Transcribe') - - with gr.Column(): - outputs = gr.Textbox(placeholder='Transcription of the video', label='Transcription') - - transcribe_btn.click(get_transcript, inputs=[url, model_size, lang, format], outputs=outputs) - -demo.launch(debug=True) diff --git a/spaces/keithhon/Real-Time-Voice-Cloning/encoder/preprocess.py b/spaces/keithhon/Real-Time-Voice-Cloning/encoder/preprocess.py deleted file mode 100644 index 551a8b29c4d84c0e1430f285a1c8b5e10c98ee5f..0000000000000000000000000000000000000000 --- a/spaces/keithhon/Real-Time-Voice-Cloning/encoder/preprocess.py +++ /dev/null @@ -1,175 +0,0 @@ -from multiprocess.pool import ThreadPool -from encoder.params_data import * -from encoder.config import librispeech_datasets, anglophone_nationalites -from datetime import datetime -from encoder import audio -from pathlib import Path -from tqdm import tqdm -import numpy as np - - -class DatasetLog: - """ - Registers metadata about the dataset in a text file. - """ - def __init__(self, root, name): - self.text_file = open(Path(root, "Log_%s.txt" % name.replace("/", "_")), "w") - self.sample_data = dict() - - start_time = str(datetime.now().strftime("%A %d %B %Y at %H:%M")) - self.write_line("Creating dataset %s on %s" % (name, start_time)) - self.write_line("-----") - self._log_params() - - def _log_params(self): - from encoder import params_data - self.write_line("Parameter values:") - for param_name in (p for p in dir(params_data) if not p.startswith("__")): - value = getattr(params_data, param_name) - self.write_line("\t%s: %s" % (param_name, value)) - self.write_line("-----") - - def write_line(self, line): - self.text_file.write("%s\n" % line) - - def add_sample(self, **kwargs): - for param_name, value in kwargs.items(): - if not param_name in self.sample_data: - self.sample_data[param_name] = [] - self.sample_data[param_name].append(value) - - def finalize(self): - self.write_line("Statistics:") - for param_name, values in self.sample_data.items(): - self.write_line("\t%s:" % param_name) - self.write_line("\t\tmin %.3f, max %.3f" % (np.min(values), np.max(values))) - self.write_line("\t\tmean %.3f, median %.3f" % (np.mean(values), np.median(values))) - self.write_line("-----") - end_time = str(datetime.now().strftime("%A %d %B %Y at %H:%M")) - self.write_line("Finished on %s" % end_time) - self.text_file.close() - - -def _init_preprocess_dataset(dataset_name, datasets_root, out_dir) -> (Path, DatasetLog): - dataset_root = datasets_root.joinpath(dataset_name) - if not dataset_root.exists(): - print("Couldn\'t find %s, skipping this dataset." % dataset_root) - return None, None - return dataset_root, DatasetLog(out_dir, dataset_name) - - -def _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, extension, - skip_existing, logger): - print("%s: Preprocessing data for %d speakers." % (dataset_name, len(speaker_dirs))) - - # Function to preprocess utterances for one speaker - def preprocess_speaker(speaker_dir: Path): - # Give a name to the speaker that includes its dataset - speaker_name = "_".join(speaker_dir.relative_to(datasets_root).parts) - - # Create an output directory with that name, as well as a txt file containing a - # reference to each source file. - speaker_out_dir = out_dir.joinpath(speaker_name) - speaker_out_dir.mkdir(exist_ok=True) - sources_fpath = speaker_out_dir.joinpath("_sources.txt") - - # There's a possibility that the preprocessing was interrupted earlier, check if - # there already is a sources file. - if sources_fpath.exists(): - try: - with sources_fpath.open("r") as sources_file: - existing_fnames = {line.split(",")[0] for line in sources_file} - except: - existing_fnames = {} - else: - existing_fnames = {} - - # Gather all audio files for that speaker recursively - sources_file = sources_fpath.open("a" if skip_existing else "w") - for in_fpath in speaker_dir.glob("**/*.%s" % extension): - # Check if the target output file already exists - out_fname = "_".join(in_fpath.relative_to(speaker_dir).parts) - out_fname = out_fname.replace(".%s" % extension, ".npy") - if skip_existing and out_fname in existing_fnames: - continue - - # Load and preprocess the waveform - wav = audio.preprocess_wav(in_fpath) - if len(wav) == 0: - continue - - # Create the mel spectrogram, discard those that are too short - frames = audio.wav_to_mel_spectrogram(wav) - if len(frames) < partials_n_frames: - continue - - out_fpath = speaker_out_dir.joinpath(out_fname) - np.save(out_fpath, frames) - logger.add_sample(duration=len(wav) / sampling_rate) - sources_file.write("%s,%s\n" % (out_fname, in_fpath)) - - sources_file.close() - - # Process the utterances for each speaker - with ThreadPool(8) as pool: - list(tqdm(pool.imap(preprocess_speaker, speaker_dirs), dataset_name, len(speaker_dirs), - unit="speakers")) - logger.finalize() - print("Done preprocessing %s.\n" % dataset_name) - - -def preprocess_librispeech(datasets_root: Path, out_dir: Path, skip_existing=False): - for dataset_name in librispeech_datasets["train"]["other"]: - # Initialize the preprocessing - dataset_root, logger = _init_preprocess_dataset(dataset_name, datasets_root, out_dir) - if not dataset_root: - return - - # Preprocess all speakers - speaker_dirs = list(dataset_root.glob("*")) - _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, "flac", - skip_existing, logger) - - -def preprocess_voxceleb1(datasets_root: Path, out_dir: Path, skip_existing=False): - # Initialize the preprocessing - dataset_name = "VoxCeleb1" - dataset_root, logger = _init_preprocess_dataset(dataset_name, datasets_root, out_dir) - if not dataset_root: - return - - # Get the contents of the meta file - with dataset_root.joinpath("vox1_meta.csv").open("r") as metafile: - metadata = [line.split("\t") for line in metafile][1:] - - # Select the ID and the nationality, filter out non-anglophone speakers - nationalities = {line[0]: line[3] for line in metadata} - keep_speaker_ids = [speaker_id for speaker_id, nationality in nationalities.items() if - nationality.lower() in anglophone_nationalites] - print("VoxCeleb1: using samples from %d (presumed anglophone) speakers out of %d." % - (len(keep_speaker_ids), len(nationalities))) - - # Get the speaker directories for anglophone speakers only - speaker_dirs = dataset_root.joinpath("wav").glob("*") - speaker_dirs = [speaker_dir for speaker_dir in speaker_dirs if - speaker_dir.name in keep_speaker_ids] - print("VoxCeleb1: found %d anglophone speakers on the disk, %d missing (this is normal)." % - (len(speaker_dirs), len(keep_speaker_ids) - len(speaker_dirs))) - - # Preprocess all speakers - _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, "wav", - skip_existing, logger) - - -def preprocess_voxceleb2(datasets_root: Path, out_dir: Path, skip_existing=False): - # Initialize the preprocessing - dataset_name = "VoxCeleb2" - dataset_root, logger = _init_preprocess_dataset(dataset_name, datasets_root, out_dir) - if not dataset_root: - return - - # Get the speaker directories - # Preprocess all speakers - speaker_dirs = list(dataset_root.joinpath("dev", "aac").glob("*")) - _preprocess_speaker_dirs(speaker_dirs, dataset_name, datasets_root, out_dir, "m4a", - skip_existing, logger) diff --git a/spaces/keremberke/garbage-object-detection/app.py b/spaces/keremberke/garbage-object-detection/app.py deleted file mode 100644 index 40eb13b66421fea2431edd55bf1d8098866bcb4b..0000000000000000000000000000000000000000 --- a/spaces/keremberke/garbage-object-detection/app.py +++ /dev/null @@ -1,53 +0,0 @@ - -import json -import gradio as gr -import yolov5 -from PIL import Image -from huggingface_hub import hf_hub_download - -app_title = "Garbage Object Detection" -models_ids = ['keremberke/yolov5n-garbage', 'keremberke/yolov5s-garbage', 'keremberke/yolov5m-garbage'] -article = f"

    model | dataset | awesome-yolov5-models

    " - -current_model_id = models_ids[-1] -model = yolov5.load(current_model_id) - -examples = [['test_images/biodegradable26_jpg.rf.8a913791d009e2fab0a2e6fe09354e42.jpg', 0.25, 'keremberke/yolov5m-garbage'], ['test_images/biodegradable545_jpg.rf.221b16c94387b66692f4e25e3c67c662.jpg', 0.25, 'keremberke/yolov5m-garbage'], ['test_images/biodegradable89_jpg.rf.2097a8a4f14b2d8e7ac994ed5fdc13a9.jpg', 0.25, 'keremberke/yolov5m-garbage'], ['test_images/cardboard1696_jpg.rf.c7d8edf6d266cb501f877f5d129ca32a.jpg', 0.25, 'keremberke/yolov5m-garbage'], ['test_images/glass1467_jpg.rf.d2f0a3ed76205c01fc26c555680ddc81.jpg', 0.25, 'keremberke/yolov5m-garbage'], ['test_images/glass887_jpg.rf.8993139c864267e74f501703b5a02a1b.jpg', 0.25, 'keremberke/yolov5m-garbage']] - - -def predict(image, threshold=0.25, model_id=None): - # update model if required - global current_model_id - global model - if model_id != current_model_id: - model = yolov5.load(model_id) - current_model_id = model_id - - # get model input size - config_path = hf_hub_download(repo_id=model_id, filename="config.json") - with open(config_path, "r") as f: - config = json.load(f) - input_size = config["input_size"] - - # perform inference - model.conf = threshold - results = model(image, size=input_size) - numpy_image = results.render()[0] - output_image = Image.fromarray(numpy_image) - return output_image - - -gr.Interface( - title=app_title, - description="Created by 'keremberke'", - article=article, - fn=predict, - inputs=[ - gr.Image(type="pil"), - gr.Slider(maximum=1, step=0.01, value=0.25), - gr.Dropdown(models_ids, value=models_ids[-1]), - ], - outputs=gr.Image(type="pil"), - examples=examples, - cache_examples=True if examples else False, -).launch(enable_queue=True) diff --git a/spaces/kevinwang676/ChatGLM2-SadTalker/src/face3d/models/arcface_torch/utils/utils_os.py b/spaces/kevinwang676/ChatGLM2-SadTalker/src/face3d/models/arcface_torch/utils/utils_os.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/losses.py b/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/losses.py deleted file mode 100644 index 87aeaa107af4d53f5a6132b3739d5cafdcded7fc..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VoiceChangers/src/face3d/models/arcface_torch/losses.py +++ /dev/null @@ -1,42 +0,0 @@ -import torch -from torch import nn - - -def get_loss(name): - if name == "cosface": - return CosFace() - elif name == "arcface": - return ArcFace() - else: - raise ValueError() - - -class CosFace(nn.Module): - def __init__(self, s=64.0, m=0.40): - super(CosFace, self).__init__() - self.s = s - self.m = m - - def forward(self, cosine, label): - index = torch.where(label != -1)[0] - m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device) - m_hot.scatter_(1, label[index, None], self.m) - cosine[index] -= m_hot - ret = cosine * self.s - return ret - - -class ArcFace(nn.Module): - def __init__(self, s=64.0, m=0.5): - super(ArcFace, self).__init__() - self.s = s - self.m = m - - def forward(self, cosine: torch.Tensor, label): - index = torch.where(label != -1)[0] - m_hot = torch.zeros(index.size()[0], cosine.size()[1], device=cosine.device) - m_hot.scatter_(1, label[index, None], self.m) - cosine.acos_() - cosine[index] += m_hot - cosine.cos_().mul_(self.s) - return cosine diff --git a/spaces/kira4424/Tacotron-zero-short-voice-clone/mkgui/app_vc.py b/spaces/kira4424/Tacotron-zero-short-voice-clone/mkgui/app_vc.py deleted file mode 100644 index 1d69b4a23c80f800b775705f53bc483108307d6c..0000000000000000000000000000000000000000 --- a/spaces/kira4424/Tacotron-zero-short-voice-clone/mkgui/app_vc.py +++ /dev/null @@ -1,166 +0,0 @@ -from synthesizer.inference import Synthesizer -from pydantic import BaseModel, Field -from encoder import inference as speacker_encoder -import torch -import os -from pathlib import Path -from enum import Enum -import ppg_extractor as Extractor -import ppg2mel as Convertor -import librosa -from scipy.io.wavfile import write -import re -import numpy as np -from mkgui.base.components.types import FileContent -from vocoder.hifigan import inference as gan_vocoder -from typing import Any, Tuple -import matplotlib.pyplot as plt - - -# Constants -AUDIO_SAMPLES_DIR = f'sample{os.sep}' -EXT_MODELS_DIRT = f'ppg_extractor{os.sep}saved_models' -CONV_MODELS_DIRT = f'ppg2mel{os.sep}saved_models' -VOC_MODELS_DIRT = f'vocoder{os.sep}saved_models' -TEMP_SOURCE_AUDIO = f'wavs{os.sep}temp_source.wav' -TEMP_TARGET_AUDIO = f'wavs{os.sep}temp_target.wav' -TEMP_RESULT_AUDIO = f'wavs{os.sep}temp_result.wav' - -# Load local sample audio as options TODO: load dataset -if os.path.isdir(AUDIO_SAMPLES_DIR): - audio_input_selection = Enum('samples', list((file.name, file) for file in Path(AUDIO_SAMPLES_DIR).glob("*.wav"))) -# Pre-Load models -if os.path.isdir(EXT_MODELS_DIRT): - extractors = Enum('extractors', list((file.name, file) for file in Path(EXT_MODELS_DIRT).glob("**/*.pt"))) - print("Loaded extractor models: " + str(len(extractors))) -else: - raise Exception(f"Model folder {EXT_MODELS_DIRT} doesn't exist.") - -if os.path.isdir(CONV_MODELS_DIRT): - convertors = Enum('convertors', list((file.name, file) for file in Path(CONV_MODELS_DIRT).glob("**/*.pth"))) - print("Loaded convertor models: " + str(len(convertors))) -else: - raise Exception(f"Model folder {CONV_MODELS_DIRT} doesn't exist.") - -if os.path.isdir(VOC_MODELS_DIRT): - vocoders = Enum('vocoders', list((file.name, file) for file in Path(VOC_MODELS_DIRT).glob("**/*gan*.pt"))) - print("Loaded vocoders models: " + str(len(vocoders))) -else: - raise Exception(f"Model folder {VOC_MODELS_DIRT} doesn't exist.") - -class Input(BaseModel): - local_audio_file: audio_input_selection = Field( - ..., alias="输入语音(本地wav)", - description="选择本地语音文件." - ) - upload_audio_file: FileContent = Field(default=None, alias="或上传语音", - description="拖拽或点击上传.", mime_type="audio/wav") - local_audio_file_target: audio_input_selection = Field( - ..., alias="目标语音(本地wav)", - description="选择本地语音文件." - ) - upload_audio_file_target: FileContent = Field(default=None, alias="或上传目标语音", - description="拖拽或点击上传.", mime_type="audio/wav") - extractor: extractors = Field( - ..., alias="编码模型", - description="选择语音编码模型文件." - ) - convertor: convertors = Field( - ..., alias="转换模型", - description="选择语音转换模型文件." - ) - vocoder: vocoders = Field( - ..., alias="语音解码模型", - description="选择语音解码模型文件(目前只支持HifiGan类型)." - ) - -class AudioEntity(BaseModel): - content: bytes - mel: Any - -class Output(BaseModel): - __root__: Tuple[AudioEntity, AudioEntity, AudioEntity] - - def render_output_ui(self, streamlit_app, input) -> None: # type: ignore - """Custom output UI. - If this method is implmeneted, it will be used instead of the default Output UI renderer. - """ - src, target, result = self.__root__ - - streamlit_app.subheader("Synthesized Audio") - streamlit_app.audio(result.content, format="audio/wav") - - fig, ax = plt.subplots() - ax.imshow(src.mel, aspect="equal", interpolation="none") - ax.set_title("mel spectrogram(Source Audio)") - streamlit_app.pyplot(fig) - fig, ax = plt.subplots() - ax.imshow(target.mel, aspect="equal", interpolation="none") - ax.set_title("mel spectrogram(Target Audio)") - streamlit_app.pyplot(fig) - fig, ax = plt.subplots() - ax.imshow(result.mel, aspect="equal", interpolation="none") - ax.set_title("mel spectrogram(Result Audio)") - streamlit_app.pyplot(fig) - -def convert(input: Input) -> Output: - """convert(转换)""" - # load models - extractor = Extractor.load_model(Path(input.extractor.value)) - convertor = Convertor.load_model(Path(input.convertor.value)) - # current_synt = Synthesizer(Path(input.synthesizer.value)) - gan_vocoder.load_model(Path(input.vocoder.value)) - - # load file - if input.upload_audio_file != None: - with open(TEMP_SOURCE_AUDIO, "w+b") as f: - f.write(input.upload_audio_file.as_bytes()) - f.seek(0) - src_wav, sample_rate = librosa.load(TEMP_SOURCE_AUDIO) - else: - src_wav, sample_rate = librosa.load(input.local_audio_file.value) - write(TEMP_SOURCE_AUDIO, sample_rate, src_wav) #Make sure we get the correct wav - - if input.upload_audio_file_target != None: - with open(TEMP_TARGET_AUDIO, "w+b") as f: - f.write(input.upload_audio_file_target.as_bytes()) - f.seek(0) - ref_wav, _ = librosa.load(TEMP_TARGET_AUDIO) - else: - ref_wav, _ = librosa.load(input.local_audio_file_target.value) - write(TEMP_TARGET_AUDIO, sample_rate, ref_wav) #Make sure we get the correct wav - - ppg = extractor.extract_from_wav(src_wav) - # Import necessary dependency of Voice Conversion - from utils.f0_utils import compute_f0, f02lf0, compute_mean_std, get_converted_lf0uv - ref_lf0_mean, ref_lf0_std = compute_mean_std(f02lf0(compute_f0(ref_wav))) - speacker_encoder.load_model(Path("encoder{os.sep}saved_models{os.sep}pretrained_bak_5805000.pt")) - embed = speacker_encoder.embed_utterance(ref_wav) - lf0_uv = get_converted_lf0uv(src_wav, ref_lf0_mean, ref_lf0_std, convert=True) - min_len = min(ppg.shape[1], len(lf0_uv)) - ppg = ppg[:, :min_len] - lf0_uv = lf0_uv[:min_len] - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - _, mel_pred, att_ws = convertor.inference( - ppg, - logf0_uv=torch.from_numpy(lf0_uv).unsqueeze(0).float().to(device), - spembs=torch.from_numpy(embed).unsqueeze(0).to(device), - ) - mel_pred= mel_pred.transpose(0, 1) - breaks = [mel_pred.shape[1]] - mel_pred= mel_pred.detach().cpu().numpy() - - # synthesize and vocode - wav, sample_rate = gan_vocoder.infer_waveform(mel_pred) - - # write and output - write(TEMP_RESULT_AUDIO, sample_rate, wav) #Make sure we get the correct wav - with open(TEMP_SOURCE_AUDIO, "rb") as f: - source_file = f.read() - with open(TEMP_TARGET_AUDIO, "rb") as f: - target_file = f.read() - with open(TEMP_RESULT_AUDIO, "rb") as f: - result_file = f.read() - - - return Output(__root__=(AudioEntity(content=source_file, mel=Synthesizer.make_spectrogram(src_wav)), AudioEntity(content=target_file, mel=Synthesizer.make_spectrogram(ref_wav)), AudioEntity(content=result_file, mel=Synthesizer.make_spectrogram(wav)))) \ No newline at end of file diff --git a/spaces/kira4424/VITS-fast-fine-tuning/modules.py b/spaces/kira4424/VITS-fast-fine-tuning/modules.py deleted file mode 100644 index 9c7fd9cd6eb8b7e0ec0e08957e970744a374a924..0000000000000000000000000000000000000000 --- a/spaces/kira4424/VITS-fast-fine-tuning/modules.py +++ /dev/null @@ -1,390 +0,0 @@ -import copy -import math -import numpy as np -import scipy -import torch -from torch import nn -from torch.nn import functional as F - -from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d -from torch.nn.utils import weight_norm, remove_weight_norm - -import commons -from commons import init_weights, get_padding -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/kirch/Text2Video-Zero/annotator/uniformer/mmcv/ops/modulated_deform_conv.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/ops/modulated_deform_conv.py deleted file mode 100644 index 75559579cf053abcc99538606cbb88c723faf783..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/ops/modulated_deform_conv.py +++ /dev/null @@ -1,282 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import math - -import torch -import torch.nn as nn -from torch.autograd import Function -from torch.autograd.function import once_differentiable -from torch.nn.modules.utils import _pair, _single - -from annotator.uniformer.mmcv.utils import deprecated_api_warning -from ..cnn import CONV_LAYERS -from ..utils import ext_loader, print_log - -ext_module = ext_loader.load_ext( - '_ext', - ['modulated_deform_conv_forward', 'modulated_deform_conv_backward']) - - -class ModulatedDeformConv2dFunction(Function): - - @staticmethod - def symbolic(g, input, offset, mask, weight, bias, stride, padding, - dilation, groups, deform_groups): - input_tensors = [input, offset, mask, weight] - if bias is not None: - input_tensors.append(bias) - return g.op( - 'mmcv::MMCVModulatedDeformConv2d', - *input_tensors, - stride_i=stride, - padding_i=padding, - dilation_i=dilation, - groups_i=groups, - deform_groups_i=deform_groups) - - @staticmethod - def forward(ctx, - input, - offset, - mask, - weight, - bias=None, - stride=1, - padding=0, - dilation=1, - groups=1, - deform_groups=1): - if input is not None and input.dim() != 4: - raise ValueError( - f'Expected 4D tensor as input, got {input.dim()}D tensor \ - instead.') - ctx.stride = _pair(stride) - ctx.padding = _pair(padding) - ctx.dilation = _pair(dilation) - ctx.groups = groups - ctx.deform_groups = deform_groups - ctx.with_bias = bias is not None - if not ctx.with_bias: - bias = input.new_empty(0) # fake tensor - # When pytorch version >= 1.6.0, amp is adopted for fp16 mode; - # amp won't cast the type of model (float32), but "offset" is cast - # to float16 by nn.Conv2d automatically, leading to the type - # mismatch with input (when it is float32) or weight. - # The flag for whether to use fp16 or amp is the type of "offset", - # we cast weight and input to temporarily support fp16 and amp - # whatever the pytorch version is. - input = input.type_as(offset) - weight = weight.type_as(input) - ctx.save_for_backward(input, offset, mask, weight, bias) - output = input.new_empty( - ModulatedDeformConv2dFunction._output_size(ctx, input, weight)) - ctx._bufs = [input.new_empty(0), input.new_empty(0)] - ext_module.modulated_deform_conv_forward( - input, - weight, - bias, - ctx._bufs[0], - offset, - mask, - output, - ctx._bufs[1], - kernel_h=weight.size(2), - kernel_w=weight.size(3), - stride_h=ctx.stride[0], - stride_w=ctx.stride[1], - pad_h=ctx.padding[0], - pad_w=ctx.padding[1], - dilation_h=ctx.dilation[0], - dilation_w=ctx.dilation[1], - group=ctx.groups, - deformable_group=ctx.deform_groups, - with_bias=ctx.with_bias) - return output - - @staticmethod - @once_differentiable - def backward(ctx, grad_output): - input, offset, mask, weight, bias = ctx.saved_tensors - grad_input = torch.zeros_like(input) - grad_offset = torch.zeros_like(offset) - grad_mask = torch.zeros_like(mask) - grad_weight = torch.zeros_like(weight) - grad_bias = torch.zeros_like(bias) - grad_output = grad_output.contiguous() - ext_module.modulated_deform_conv_backward( - input, - weight, - bias, - ctx._bufs[0], - offset, - mask, - ctx._bufs[1], - grad_input, - grad_weight, - grad_bias, - grad_offset, - grad_mask, - grad_output, - kernel_h=weight.size(2), - kernel_w=weight.size(3), - stride_h=ctx.stride[0], - stride_w=ctx.stride[1], - pad_h=ctx.padding[0], - pad_w=ctx.padding[1], - dilation_h=ctx.dilation[0], - dilation_w=ctx.dilation[1], - group=ctx.groups, - deformable_group=ctx.deform_groups, - with_bias=ctx.with_bias) - if not ctx.with_bias: - grad_bias = None - - return (grad_input, grad_offset, grad_mask, grad_weight, grad_bias, - None, None, None, None, None) - - @staticmethod - def _output_size(ctx, input, weight): - channels = weight.size(0) - output_size = (input.size(0), channels) - for d in range(input.dim() - 2): - in_size = input.size(d + 2) - pad = ctx.padding[d] - kernel = ctx.dilation[d] * (weight.size(d + 2) - 1) + 1 - stride_ = ctx.stride[d] - output_size += ((in_size + (2 * pad) - kernel) // stride_ + 1, ) - if not all(map(lambda s: s > 0, output_size)): - raise ValueError( - 'convolution input is too small (output would be ' + - 'x'.join(map(str, output_size)) + ')') - return output_size - - -modulated_deform_conv2d = ModulatedDeformConv2dFunction.apply - - -class ModulatedDeformConv2d(nn.Module): - - @deprecated_api_warning({'deformable_groups': 'deform_groups'}, - cls_name='ModulatedDeformConv2d') - def __init__(self, - in_channels, - out_channels, - kernel_size, - stride=1, - padding=0, - dilation=1, - groups=1, - deform_groups=1, - bias=True): - super(ModulatedDeformConv2d, self).__init__() - self.in_channels = in_channels - self.out_channels = out_channels - self.kernel_size = _pair(kernel_size) - self.stride = _pair(stride) - self.padding = _pair(padding) - self.dilation = _pair(dilation) - self.groups = groups - self.deform_groups = deform_groups - # enable compatibility with nn.Conv2d - self.transposed = False - self.output_padding = _single(0) - - self.weight = nn.Parameter( - torch.Tensor(out_channels, in_channels // groups, - *self.kernel_size)) - if bias: - self.bias = nn.Parameter(torch.Tensor(out_channels)) - else: - self.register_parameter('bias', None) - self.init_weights() - - def init_weights(self): - n = self.in_channels - for k in self.kernel_size: - n *= k - stdv = 1. / math.sqrt(n) - self.weight.data.uniform_(-stdv, stdv) - if self.bias is not None: - self.bias.data.zero_() - - def forward(self, x, offset, mask): - return modulated_deform_conv2d(x, offset, mask, self.weight, self.bias, - self.stride, self.padding, - self.dilation, self.groups, - self.deform_groups) - - -@CONV_LAYERS.register_module('DCNv2') -class ModulatedDeformConv2dPack(ModulatedDeformConv2d): - """A ModulatedDeformable Conv Encapsulation that acts as normal Conv - layers. - - Args: - in_channels (int): Same as nn.Conv2d. - out_channels (int): Same as nn.Conv2d. - kernel_size (int or tuple[int]): Same as nn.Conv2d. - stride (int): Same as nn.Conv2d, while tuple is not supported. - padding (int): Same as nn.Conv2d, while tuple is not supported. - dilation (int): Same as nn.Conv2d, while tuple is not supported. - groups (int): Same as nn.Conv2d. - bias (bool or str): If specified as `auto`, it will be decided by the - norm_cfg. Bias will be set as True if norm_cfg is None, otherwise - False. - """ - - _version = 2 - - def __init__(self, *args, **kwargs): - super(ModulatedDeformConv2dPack, self).__init__(*args, **kwargs) - self.conv_offset = nn.Conv2d( - self.in_channels, - self.deform_groups * 3 * self.kernel_size[0] * self.kernel_size[1], - kernel_size=self.kernel_size, - stride=self.stride, - padding=self.padding, - dilation=self.dilation, - bias=True) - self.init_weights() - - def init_weights(self): - super(ModulatedDeformConv2dPack, self).init_weights() - if hasattr(self, 'conv_offset'): - self.conv_offset.weight.data.zero_() - self.conv_offset.bias.data.zero_() - - def forward(self, x): - out = self.conv_offset(x) - o1, o2, mask = torch.chunk(out, 3, dim=1) - offset = torch.cat((o1, o2), dim=1) - mask = torch.sigmoid(mask) - return modulated_deform_conv2d(x, offset, mask, self.weight, self.bias, - self.stride, self.padding, - self.dilation, self.groups, - self.deform_groups) - - def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, - missing_keys, unexpected_keys, error_msgs): - version = local_metadata.get('version', None) - - if version is None or version < 2: - # the key is different in early versions - # In version < 2, ModulatedDeformConvPack - # loads previous benchmark models. - if (prefix + 'conv_offset.weight' not in state_dict - and prefix[:-1] + '_offset.weight' in state_dict): - state_dict[prefix + 'conv_offset.weight'] = state_dict.pop( - prefix[:-1] + '_offset.weight') - if (prefix + 'conv_offset.bias' not in state_dict - and prefix[:-1] + '_offset.bias' in state_dict): - state_dict[prefix + - 'conv_offset.bias'] = state_dict.pop(prefix[:-1] + - '_offset.bias') - - if version is not None and version > 1: - print_log( - f'ModulatedDeformConvPack {prefix.rstrip(".")} is upgraded to ' - 'version 2.', - logger='root') - - super()._load_from_state_dict(state_dict, prefix, local_metadata, - strict, missing_keys, unexpected_keys, - error_msgs) diff --git a/spaces/kukuhtw/AutoGPT/autogpt/promptgenerator.py b/spaces/kukuhtw/AutoGPT/autogpt/promptgenerator.py deleted file mode 100644 index 0ad7046a0c41dab356abcd0151b65890e5544cd2..0000000000000000000000000000000000000000 --- a/spaces/kukuhtw/AutoGPT/autogpt/promptgenerator.py +++ /dev/null @@ -1,138 +0,0 @@ -""" A module for generating custom prompt strings.""" -from __future__ import annotations - -import json -from typing import Any - - -class PromptGenerator: - """ - A class for generating custom prompt strings based on constraints, commands, - resources, and performance evaluations. - """ - - def __init__(self) -> None: - """ - Initialize the PromptGenerator object with empty lists of constraints, - commands, resources, and performance evaluations. - """ - self.constraints = [] - self.commands = [] - self.resources = [] - self.performance_evaluation = [] - self.response_format = { - "thoughts": { - "text": "thought", - "reasoning": "reasoning", - "plan": "- short bulleted\n- list that conveys\n- long-term plan", - "criticism": "constructive self-criticism", - "speak": "thoughts summary to say to user", - }, - "command": {"name": "command name", "args": {"arg name": "value"}}, - } - - def add_constraint(self, constraint: str) -> None: - """ - Add a constraint to the constraints list. - - Args: - constraint (str): The constraint to be added. - """ - self.constraints.append(constraint) - - def add_command(self, command_label: str, command_name: str, args=None) -> None: - """ - Add a command to the commands list with a label, name, and optional arguments. - - Args: - command_label (str): The label of the command. - command_name (str): The name of the command. - args (dict, optional): A dictionary containing argument names and their - values. Defaults to None. - """ - if args is None: - args = {} - - command_args = {arg_key: arg_value for arg_key, arg_value in args.items()} - - command = { - "label": command_label, - "name": command_name, - "args": command_args, - } - - self.commands.append(command) - - def _generate_command_string(self, command: dict[str, Any]) -> str: - """ - Generate a formatted string representation of a command. - - Args: - command (dict): A dictionary containing command information. - - Returns: - str: The formatted command string. - """ - args_string = ", ".join( - f'"{key}": "{value}"' for key, value in command["args"].items() - ) - return f'{command["label"]}: "{command["name"]}", args: {args_string}' - - def add_resource(self, resource: str) -> None: - """ - Add a resource to the resources list. - - Args: - resource (str): The resource to be added. - """ - self.resources.append(resource) - - def add_performance_evaluation(self, evaluation: str) -> None: - """ - Add a performance evaluation item to the performance_evaluation list. - - Args: - evaluation (str): The evaluation item to be added. - """ - self.performance_evaluation.append(evaluation) - - def _generate_numbered_list(self, items: list[Any], item_type="list") -> str: - """ - Generate a numbered list from given items based on the item_type. - - Args: - items (list): A list of items to be numbered. - item_type (str, optional): The type of items in the list. - Defaults to 'list'. - - Returns: - str: The formatted numbered list. - """ - if item_type == "command": - return "\n".join( - f"{i+1}. {self._generate_command_string(item)}" - for i, item in enumerate(items) - ) - else: - return "\n".join(f"{i+1}. {item}" for i, item in enumerate(items)) - - def generate_prompt_string(self) -> str: - """ - Generate a prompt string based on the constraints, commands, resources, - and performance evaluations. - - Returns: - str: The generated prompt string. - """ - formatted_response_format = json.dumps(self.response_format, indent=4) - return ( - f"Constraints:\n{self._generate_numbered_list(self.constraints)}\n\n" - "Commands:\n" - f"{self._generate_numbered_list(self.commands, item_type='command')}\n\n" - f"Resources:\n{self._generate_numbered_list(self.resources)}\n\n" - "Performance Evaluation:\n" - f"{self._generate_numbered_list(self.performance_evaluation)}\n\n" - "You should only respond in JSON format as described below \nResponse" - f" Format: \n{formatted_response_format} \nEnsure the response can be" - " parsed by Python json.loads" - ) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/_m_e_t_a.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/_m_e_t_a.py deleted file mode 100644 index 3af9e543049f89f0da3ceb15bb58135854fef002..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/_m_e_t_a.py +++ /dev/null @@ -1,104 +0,0 @@ -from fontTools.misc import sstruct -from fontTools.misc.textTools import bytesjoin, strjoin, readHex -from fontTools.ttLib import TTLibError -from . import DefaultTable - -# Apple's documentation of 'meta': -# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html - -META_HEADER_FORMAT = """ - > # big endian - version: L - flags: L - dataOffset: L - numDataMaps: L -""" - - -DATA_MAP_FORMAT = """ - > # big endian - tag: 4s - dataOffset: L - dataLength: L -""" - - -class table__m_e_t_a(DefaultTable.DefaultTable): - def __init__(self, tag=None): - DefaultTable.DefaultTable.__init__(self, tag) - self.data = {} - - def decompile(self, data, ttFont): - headerSize = sstruct.calcsize(META_HEADER_FORMAT) - header = sstruct.unpack(META_HEADER_FORMAT, data[0:headerSize]) - if header["version"] != 1: - raise TTLibError("unsupported 'meta' version %d" % header["version"]) - dataMapSize = sstruct.calcsize(DATA_MAP_FORMAT) - for i in range(header["numDataMaps"]): - dataMapOffset = headerSize + i * dataMapSize - dataMap = sstruct.unpack( - DATA_MAP_FORMAT, data[dataMapOffset : dataMapOffset + dataMapSize] - ) - tag = dataMap["tag"] - offset = dataMap["dataOffset"] - self.data[tag] = data[offset : offset + dataMap["dataLength"]] - if tag in ["dlng", "slng"]: - self.data[tag] = self.data[tag].decode("utf-8") - - def compile(self, ttFont): - keys = sorted(self.data.keys()) - headerSize = sstruct.calcsize(META_HEADER_FORMAT) - dataOffset = headerSize + len(keys) * sstruct.calcsize(DATA_MAP_FORMAT) - header = sstruct.pack( - META_HEADER_FORMAT, - { - "version": 1, - "flags": 0, - "dataOffset": dataOffset, - "numDataMaps": len(keys), - }, - ) - dataMaps = [] - dataBlocks = [] - for tag in keys: - if tag in ["dlng", "slng"]: - data = self.data[tag].encode("utf-8") - else: - data = self.data[tag] - dataMaps.append( - sstruct.pack( - DATA_MAP_FORMAT, - {"tag": tag, "dataOffset": dataOffset, "dataLength": len(data)}, - ) - ) - dataBlocks.append(data) - dataOffset += len(data) - return bytesjoin([header] + dataMaps + dataBlocks) - - def toXML(self, writer, ttFont): - for tag in sorted(self.data.keys()): - if tag in ["dlng", "slng"]: - writer.begintag("text", tag=tag) - writer.newline() - writer.write(self.data[tag]) - writer.newline() - writer.endtag("text") - writer.newline() - else: - writer.begintag("hexdata", tag=tag) - writer.newline() - data = self.data[tag] - if min(data) >= 0x20 and max(data) <= 0x7E: - writer.comment("ascii: " + data.decode("ascii")) - writer.newline() - writer.dumphex(data) - writer.endtag("hexdata") - writer.newline() - - def fromXML(self, name, attrs, content, ttFont): - if name == "hexdata": - self.data[attrs["tag"]] = readHex(content) - elif name == "text" and attrs["tag"] in ["dlng", "slng"]: - self.data[attrs["tag"]] = strjoin(content).strip() - else: - raise TTLibError("can't handle '%s' element" % name) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/otConverters.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/otConverters.py deleted file mode 100644 index 6b2a8c39678af0f4828ee477e57038d81d02006b..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/fontTools/ttLib/tables/otConverters.py +++ /dev/null @@ -1,1929 +0,0 @@ -from fontTools.misc.fixedTools import ( - fixedToFloat as fi2fl, - floatToFixed as fl2fi, - floatToFixedToStr as fl2str, - strToFixedToFloat as str2fl, - ensureVersionIsLong as fi2ve, - versionToFixed as ve2fi, -) -from fontTools.misc.roundTools import nearestMultipleShortestRepr, otRound -from fontTools.misc.textTools import bytesjoin, tobytes, tostr, pad, safeEval -from fontTools.ttLib import getSearchRange -from .otBase import ( - CountReference, - FormatSwitchingBaseTable, - OTTableReader, - OTTableWriter, - ValueRecordFactory, -) -from .otTables import ( - lookupTypes, - AATStateTable, - AATState, - AATAction, - ContextualMorphAction, - LigatureMorphAction, - InsertionMorphAction, - MorxSubtable, - ExtendMode as _ExtendMode, - CompositeMode as _CompositeMode, - NO_VARIATION_INDEX, -) -from itertools import zip_longest -from functools import partial -import re -import struct -from typing import Optional -import logging - - -log = logging.getLogger(__name__) -istuple = lambda t: isinstance(t, tuple) - - -def buildConverters(tableSpec, tableNamespace): - """Given a table spec from otData.py, build a converter object for each - field of the table. This is called for each table in otData.py, and - the results are assigned to the corresponding class in otTables.py.""" - converters = [] - convertersByName = {} - for tp, name, repeat, aux, descr in tableSpec: - tableName = name - if name.startswith("ValueFormat"): - assert tp == "uint16" - converterClass = ValueFormat - elif name.endswith("Count") or name in ("StructLength", "MorphType"): - converterClass = { - "uint8": ComputedUInt8, - "uint16": ComputedUShort, - "uint32": ComputedULong, - }[tp] - elif name == "SubTable": - converterClass = SubTable - elif name == "ExtSubTable": - converterClass = ExtSubTable - elif name == "SubStruct": - converterClass = SubStruct - elif name == "FeatureParams": - converterClass = FeatureParams - elif name in ("CIDGlyphMapping", "GlyphCIDMapping"): - converterClass = StructWithLength - else: - if not tp in converterMapping and "(" not in tp: - tableName = tp - converterClass = Struct - else: - converterClass = eval(tp, tableNamespace, converterMapping) - - conv = converterClass(name, repeat, aux, description=descr) - - if conv.tableClass: - # A "template" such as OffsetTo(AType) knowss the table class already - tableClass = conv.tableClass - elif tp in ("MortChain", "MortSubtable", "MorxChain"): - tableClass = tableNamespace.get(tp) - else: - tableClass = tableNamespace.get(tableName) - - if not conv.tableClass: - conv.tableClass = tableClass - - if name in ["SubTable", "ExtSubTable", "SubStruct"]: - conv.lookupTypes = tableNamespace["lookupTypes"] - # also create reverse mapping - for t in conv.lookupTypes.values(): - for cls in t.values(): - convertersByName[cls.__name__] = Table(name, repeat, aux, cls) - if name == "FeatureParams": - conv.featureParamTypes = tableNamespace["featureParamTypes"] - conv.defaultFeatureParams = tableNamespace["FeatureParams"] - for cls in conv.featureParamTypes.values(): - convertersByName[cls.__name__] = Table(name, repeat, aux, cls) - converters.append(conv) - assert name not in convertersByName, name - convertersByName[name] = conv - return converters, convertersByName - - -class _MissingItem(tuple): - __slots__ = () - - -try: - from collections import UserList -except ImportError: - from UserList import UserList - - -class _LazyList(UserList): - def __getslice__(self, i, j): - return self.__getitem__(slice(i, j)) - - def __getitem__(self, k): - if isinstance(k, slice): - indices = range(*k.indices(len(self))) - return [self[i] for i in indices] - item = self.data[k] - if isinstance(item, _MissingItem): - self.reader.seek(self.pos + item[0] * self.recordSize) - item = self.conv.read(self.reader, self.font, {}) - self.data[k] = item - return item - - def __add__(self, other): - if isinstance(other, _LazyList): - other = list(other) - elif isinstance(other, list): - pass - else: - return NotImplemented - return list(self) + other - - def __radd__(self, other): - if not isinstance(other, list): - return NotImplemented - return other + list(self) - - -class BaseConverter(object): - - """Base class for converter objects. Apart from the constructor, this - is an abstract class.""" - - def __init__(self, name, repeat, aux, tableClass=None, *, description=""): - self.name = name - self.repeat = repeat - self.aux = aux - self.tableClass = tableClass - self.isCount = name.endswith("Count") or name in [ - "DesignAxisRecordSize", - "ValueRecordSize", - ] - self.isLookupType = name.endswith("LookupType") or name == "MorphType" - self.isPropagated = name in [ - "ClassCount", - "Class2Count", - "FeatureTag", - "SettingsCount", - "VarRegionCount", - "MappingCount", - "RegionAxisCount", - "DesignAxisCount", - "DesignAxisRecordSize", - "AxisValueCount", - "ValueRecordSize", - "AxisCount", - "BaseGlyphRecordCount", - "LayerRecordCount", - ] - self.description = description - - def readArray(self, reader, font, tableDict, count): - """Read an array of values from the reader.""" - lazy = font.lazy and count > 8 - if lazy: - recordSize = self.getRecordSize(reader) - if recordSize is NotImplemented: - lazy = False - if not lazy: - l = [] - for i in range(count): - l.append(self.read(reader, font, tableDict)) - return l - else: - l = _LazyList() - l.reader = reader.copy() - l.pos = l.reader.pos - l.font = font - l.conv = self - l.recordSize = recordSize - l.extend(_MissingItem([i]) for i in range(count)) - reader.advance(count * recordSize) - return l - - def getRecordSize(self, reader): - if hasattr(self, "staticSize"): - return self.staticSize - return NotImplemented - - def read(self, reader, font, tableDict): - """Read a value from the reader.""" - raise NotImplementedError(self) - - def writeArray(self, writer, font, tableDict, values): - try: - for i, value in enumerate(values): - self.write(writer, font, tableDict, value, i) - except Exception as e: - e.args = e.args + (i,) - raise - - def write(self, writer, font, tableDict, value, repeatIndex=None): - """Write a value to the writer.""" - raise NotImplementedError(self) - - def xmlRead(self, attrs, content, font): - """Read a value from XML.""" - raise NotImplementedError(self) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - """Write a value to XML.""" - raise NotImplementedError(self) - - varIndexBasePlusOffsetRE = re.compile(r"VarIndexBase\s*\+\s*(\d+)") - - def getVarIndexOffset(self) -> Optional[int]: - """If description has `VarIndexBase + {offset}`, return the offset else None.""" - m = self.varIndexBasePlusOffsetRE.search(self.description) - if not m: - return None - return int(m.group(1)) - - -class SimpleValue(BaseConverter): - @staticmethod - def toString(value): - return value - - @staticmethod - def fromString(value): - return value - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.simpletag(name, attrs + [("value", self.toString(value))]) - xmlWriter.newline() - - def xmlRead(self, attrs, content, font): - return self.fromString(attrs["value"]) - - -class OptionalValue(SimpleValue): - DEFAULT = None - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - if value != self.DEFAULT: - attrs.append(("value", self.toString(value))) - xmlWriter.simpletag(name, attrs) - xmlWriter.newline() - - def xmlRead(self, attrs, content, font): - if "value" in attrs: - return self.fromString(attrs["value"]) - return self.DEFAULT - - -class IntValue(SimpleValue): - @staticmethod - def fromString(value): - return int(value, 0) - - -class Long(IntValue): - staticSize = 4 - - def read(self, reader, font, tableDict): - return reader.readLong() - - def readArray(self, reader, font, tableDict, count): - return reader.readLongArray(count) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeLong(value) - - def writeArray(self, writer, font, tableDict, values): - writer.writeLongArray(values) - - -class ULong(IntValue): - staticSize = 4 - - def read(self, reader, font, tableDict): - return reader.readULong() - - def readArray(self, reader, font, tableDict, count): - return reader.readULongArray(count) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeULong(value) - - def writeArray(self, writer, font, tableDict, values): - writer.writeULongArray(values) - - -class Flags32(ULong): - @staticmethod - def toString(value): - return "0x%08X" % value - - -class VarIndex(OptionalValue, ULong): - DEFAULT = NO_VARIATION_INDEX - - -class Short(IntValue): - staticSize = 2 - - def read(self, reader, font, tableDict): - return reader.readShort() - - def readArray(self, reader, font, tableDict, count): - return reader.readShortArray(count) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeShort(value) - - def writeArray(self, writer, font, tableDict, values): - writer.writeShortArray(values) - - -class UShort(IntValue): - staticSize = 2 - - def read(self, reader, font, tableDict): - return reader.readUShort() - - def readArray(self, reader, font, tableDict, count): - return reader.readUShortArray(count) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeUShort(value) - - def writeArray(self, writer, font, tableDict, values): - writer.writeUShortArray(values) - - -class Int8(IntValue): - staticSize = 1 - - def read(self, reader, font, tableDict): - return reader.readInt8() - - def readArray(self, reader, font, tableDict, count): - return reader.readInt8Array(count) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeInt8(value) - - def writeArray(self, writer, font, tableDict, values): - writer.writeInt8Array(values) - - -class UInt8(IntValue): - staticSize = 1 - - def read(self, reader, font, tableDict): - return reader.readUInt8() - - def readArray(self, reader, font, tableDict, count): - return reader.readUInt8Array(count) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeUInt8(value) - - def writeArray(self, writer, font, tableDict, values): - writer.writeUInt8Array(values) - - -class UInt24(IntValue): - staticSize = 3 - - def read(self, reader, font, tableDict): - return reader.readUInt24() - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeUInt24(value) - - -class ComputedInt(IntValue): - def xmlWrite(self, xmlWriter, font, value, name, attrs): - if value is not None: - xmlWriter.comment("%s=%s" % (name, value)) - xmlWriter.newline() - - -class ComputedUInt8(ComputedInt, UInt8): - pass - - -class ComputedUShort(ComputedInt, UShort): - pass - - -class ComputedULong(ComputedInt, ULong): - pass - - -class Tag(SimpleValue): - staticSize = 4 - - def read(self, reader, font, tableDict): - return reader.readTag() - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeTag(value) - - -class GlyphID(SimpleValue): - staticSize = 2 - typecode = "H" - - def readArray(self, reader, font, tableDict, count): - return font.getGlyphNameMany( - reader.readArray(self.typecode, self.staticSize, count) - ) - - def read(self, reader, font, tableDict): - return font.getGlyphName(reader.readValue(self.typecode, self.staticSize)) - - def writeArray(self, writer, font, tableDict, values): - writer.writeArray(self.typecode, font.getGlyphIDMany(values)) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeValue(self.typecode, font.getGlyphID(value)) - - -class GlyphID32(GlyphID): - staticSize = 4 - typecode = "L" - - -class NameID(UShort): - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.simpletag(name, attrs + [("value", value)]) - if font and value: - nameTable = font.get("name") - if nameTable: - name = nameTable.getDebugName(value) - xmlWriter.write(" ") - if name: - xmlWriter.comment(name) - else: - xmlWriter.comment("missing from name table") - log.warning("name id %d missing from name table" % value) - xmlWriter.newline() - - -class STATFlags(UShort): - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.simpletag(name, attrs + [("value", value)]) - flags = [] - if value & 0x01: - flags.append("OlderSiblingFontAttribute") - if value & 0x02: - flags.append("ElidableAxisValueName") - if flags: - xmlWriter.write(" ") - xmlWriter.comment(" ".join(flags)) - xmlWriter.newline() - - -class FloatValue(SimpleValue): - @staticmethod - def fromString(value): - return float(value) - - -class DeciPoints(FloatValue): - staticSize = 2 - - def read(self, reader, font, tableDict): - return reader.readUShort() / 10 - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.writeUShort(round(value * 10)) - - -class BaseFixedValue(FloatValue): - staticSize = NotImplemented - precisionBits = NotImplemented - readerMethod = NotImplemented - writerMethod = NotImplemented - - def read(self, reader, font, tableDict): - return self.fromInt(getattr(reader, self.readerMethod)()) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - getattr(writer, self.writerMethod)(self.toInt(value)) - - @classmethod - def fromInt(cls, value): - return fi2fl(value, cls.precisionBits) - - @classmethod - def toInt(cls, value): - return fl2fi(value, cls.precisionBits) - - @classmethod - def fromString(cls, value): - return str2fl(value, cls.precisionBits) - - @classmethod - def toString(cls, value): - return fl2str(value, cls.precisionBits) - - -class Fixed(BaseFixedValue): - staticSize = 4 - precisionBits = 16 - readerMethod = "readLong" - writerMethod = "writeLong" - - -class F2Dot14(BaseFixedValue): - staticSize = 2 - precisionBits = 14 - readerMethod = "readShort" - writerMethod = "writeShort" - - -class Angle(F2Dot14): - # angles are specified in degrees, and encoded as F2Dot14 fractions of half - # circle: e.g. 1.0 => 180, -0.5 => -90, -2.0 => -360, etc. - bias = 0.0 - factor = 1.0 / (1 << 14) * 180 # 0.010986328125 - - @classmethod - def fromInt(cls, value): - return (super().fromInt(value) + cls.bias) * 180 - - @classmethod - def toInt(cls, value): - return super().toInt((value / 180) - cls.bias) - - @classmethod - def fromString(cls, value): - # quantize to nearest multiples of minimum fixed-precision angle - return otRound(float(value) / cls.factor) * cls.factor - - @classmethod - def toString(cls, value): - return nearestMultipleShortestRepr(value, cls.factor) - - -class BiasedAngle(Angle): - # A bias of 1.0 is used in the representation of start and end angles - # of COLRv1 PaintSweepGradients to allow for encoding +360deg - bias = 1.0 - - -class Version(SimpleValue): - staticSize = 4 - - def read(self, reader, font, tableDict): - value = reader.readLong() - return value - - def write(self, writer, font, tableDict, value, repeatIndex=None): - value = fi2ve(value) - writer.writeLong(value) - - @staticmethod - def fromString(value): - return ve2fi(value) - - @staticmethod - def toString(value): - return "0x%08x" % value - - @staticmethod - def fromFloat(v): - return fl2fi(v, 16) - - -class Char64(SimpleValue): - """An ASCII string with up to 64 characters. - - Unused character positions are filled with 0x00 bytes. - Used in Apple AAT fonts in the `gcid` table. - """ - - staticSize = 64 - - def read(self, reader, font, tableDict): - data = reader.readData(self.staticSize) - zeroPos = data.find(b"\0") - if zeroPos >= 0: - data = data[:zeroPos] - s = tostr(data, encoding="ascii", errors="replace") - if s != tostr(data, encoding="ascii", errors="ignore"): - log.warning('replaced non-ASCII characters in "%s"' % s) - return s - - def write(self, writer, font, tableDict, value, repeatIndex=None): - data = tobytes(value, encoding="ascii", errors="replace") - if data != tobytes(value, encoding="ascii", errors="ignore"): - log.warning('replacing non-ASCII characters in "%s"' % value) - if len(data) > self.staticSize: - log.warning( - 'truncating overlong "%s" to %d bytes' % (value, self.staticSize) - ) - data = (data + b"\0" * self.staticSize)[: self.staticSize] - writer.writeData(data) - - -class Struct(BaseConverter): - def getRecordSize(self, reader): - return self.tableClass and self.tableClass.getRecordSize(reader) - - def read(self, reader, font, tableDict): - table = self.tableClass() - table.decompile(reader, font) - return table - - def write(self, writer, font, tableDict, value, repeatIndex=None): - value.compile(writer, font) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - if value is None: - if attrs: - # If there are attributes (probably index), then - # don't drop this even if it's NULL. It will mess - # up the array indices of the containing element. - xmlWriter.simpletag(name, attrs + [("empty", 1)]) - xmlWriter.newline() - else: - pass # NULL table, ignore - else: - value.toXML(xmlWriter, font, attrs, name=name) - - def xmlRead(self, attrs, content, font): - if "empty" in attrs and safeEval(attrs["empty"]): - return None - table = self.tableClass() - Format = attrs.get("Format") - if Format is not None: - table.Format = int(Format) - - noPostRead = not hasattr(table, "postRead") - if noPostRead: - # TODO Cache table.hasPropagated. - cleanPropagation = False - for conv in table.getConverters(): - if conv.isPropagated: - cleanPropagation = True - if not hasattr(font, "_propagator"): - font._propagator = {} - propagator = font._propagator - assert conv.name not in propagator, (conv.name, propagator) - setattr(table, conv.name, None) - propagator[conv.name] = CountReference(table.__dict__, conv.name) - - for element in content: - if isinstance(element, tuple): - name, attrs, content = element - table.fromXML(name, attrs, content, font) - else: - pass - - table.populateDefaults(propagator=getattr(font, "_propagator", None)) - - if noPostRead: - if cleanPropagation: - for conv in table.getConverters(): - if conv.isPropagated: - propagator = font._propagator - del propagator[conv.name] - if not propagator: - del font._propagator - - return table - - def __repr__(self): - return "Struct of " + repr(self.tableClass) - - -class StructWithLength(Struct): - def read(self, reader, font, tableDict): - pos = reader.pos - table = self.tableClass() - table.decompile(reader, font) - reader.seek(pos + table.StructLength) - return table - - def write(self, writer, font, tableDict, value, repeatIndex=None): - for convIndex, conv in enumerate(value.getConverters()): - if conv.name == "StructLength": - break - lengthIndex = len(writer.items) + convIndex - if isinstance(value, FormatSwitchingBaseTable): - lengthIndex += 1 # implicit Format field - deadbeef = {1: 0xDE, 2: 0xDEAD, 4: 0xDEADBEEF}[conv.staticSize] - - before = writer.getDataLength() - value.StructLength = deadbeef - value.compile(writer, font) - length = writer.getDataLength() - before - lengthWriter = writer.getSubWriter() - conv.write(lengthWriter, font, tableDict, length) - assert writer.items[lengthIndex] == b"\xde\xad\xbe\xef"[: conv.staticSize] - writer.items[lengthIndex] = lengthWriter.getAllData() - - -class Table(Struct): - - staticSize = 2 - - def readOffset(self, reader): - return reader.readUShort() - - def writeNullOffset(self, writer): - writer.writeUShort(0) - - def read(self, reader, font, tableDict): - offset = self.readOffset(reader) - if offset == 0: - return None - table = self.tableClass() - reader = reader.getSubReader(offset) - if font.lazy: - table.reader = reader - table.font = font - else: - table.decompile(reader, font) - return table - - def write(self, writer, font, tableDict, value, repeatIndex=None): - if value is None: - self.writeNullOffset(writer) - else: - subWriter = writer.getSubWriter(offsetSize=self.staticSize) - subWriter.name = self.name - if repeatIndex is not None: - subWriter.repeatIndex = repeatIndex - writer.writeSubTable(subWriter) - value.compile(subWriter, font) - - -class LTable(Table): - - staticSize = 4 - - def readOffset(self, reader): - return reader.readULong() - - def writeNullOffset(self, writer): - writer.writeULong(0) - - -# Table pointed to by a 24-bit, 3-byte long offset -class Table24(Table): - - staticSize = 3 - - def readOffset(self, reader): - return reader.readUInt24() - - def writeNullOffset(self, writer): - writer.writeUInt24(0) - - -# TODO Clean / merge the SubTable and SubStruct - - -class SubStruct(Struct): - def getConverter(self, tableType, lookupType): - tableClass = self.lookupTypes[tableType][lookupType] - return self.__class__(self.name, self.repeat, self.aux, tableClass) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - super(SubStruct, self).xmlWrite(xmlWriter, font, value, None, attrs) - - -class SubTable(Table): - def getConverter(self, tableType, lookupType): - tableClass = self.lookupTypes[tableType][lookupType] - return self.__class__(self.name, self.repeat, self.aux, tableClass) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - super(SubTable, self).xmlWrite(xmlWriter, font, value, None, attrs) - - -class ExtSubTable(LTable, SubTable): - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer.Extension = True # actually, mere presence of the field flags it as an Ext Subtable writer. - Table.write(self, writer, font, tableDict, value, repeatIndex) - - -class FeatureParams(Table): - def getConverter(self, featureTag): - tableClass = self.featureParamTypes.get(featureTag, self.defaultFeatureParams) - return self.__class__(self.name, self.repeat, self.aux, tableClass) - - -class ValueFormat(IntValue): - staticSize = 2 - - def __init__(self, name, repeat, aux, tableClass=None, *, description=""): - BaseConverter.__init__( - self, name, repeat, aux, tableClass, description=description - ) - self.which = "ValueFormat" + ("2" if name[-1] == "2" else "1") - - def read(self, reader, font, tableDict): - format = reader.readUShort() - reader[self.which] = ValueRecordFactory(format) - return format - - def write(self, writer, font, tableDict, format, repeatIndex=None): - writer.writeUShort(format) - writer[self.which] = ValueRecordFactory(format) - - -class ValueRecord(ValueFormat): - def getRecordSize(self, reader): - return 2 * len(reader[self.which]) - - def read(self, reader, font, tableDict): - return reader[self.which].readValueRecord(reader, font) - - def write(self, writer, font, tableDict, value, repeatIndex=None): - writer[self.which].writeValueRecord(writer, font, value) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - if value is None: - pass # NULL table, ignore - else: - value.toXML(xmlWriter, font, self.name, attrs) - - def xmlRead(self, attrs, content, font): - from .otBase import ValueRecord - - value = ValueRecord() - value.fromXML(None, attrs, content, font) - return value - - -class AATLookup(BaseConverter): - BIN_SEARCH_HEADER_SIZE = 10 - - def __init__(self, name, repeat, aux, tableClass, *, description=""): - BaseConverter.__init__( - self, name, repeat, aux, tableClass, description=description - ) - if issubclass(self.tableClass, SimpleValue): - self.converter = self.tableClass(name="Value", repeat=None, aux=None) - else: - self.converter = Table( - name="Value", repeat=None, aux=None, tableClass=self.tableClass - ) - - def read(self, reader, font, tableDict): - format = reader.readUShort() - if format == 0: - return self.readFormat0(reader, font) - elif format == 2: - return self.readFormat2(reader, font) - elif format == 4: - return self.readFormat4(reader, font) - elif format == 6: - return self.readFormat6(reader, font) - elif format == 8: - return self.readFormat8(reader, font) - else: - assert False, "unsupported lookup format: %d" % format - - def write(self, writer, font, tableDict, value, repeatIndex=None): - values = list( - sorted([(font.getGlyphID(glyph), val) for glyph, val in value.items()]) - ) - # TODO: Also implement format 4. - formats = list( - sorted( - filter( - None, - [ - self.buildFormat0(writer, font, values), - self.buildFormat2(writer, font, values), - self.buildFormat6(writer, font, values), - self.buildFormat8(writer, font, values), - ], - ) - ) - ) - # We use the format ID as secondary sort key to make the output - # deterministic when multiple formats have same encoded size. - dataSize, lookupFormat, writeMethod = formats[0] - pos = writer.getDataLength() - writeMethod() - actualSize = writer.getDataLength() - pos - assert ( - actualSize == dataSize - ), "AATLookup format %d claimed to write %d bytes, but wrote %d" % ( - lookupFormat, - dataSize, - actualSize, - ) - - @staticmethod - def writeBinSearchHeader(writer, numUnits, unitSize): - writer.writeUShort(unitSize) - writer.writeUShort(numUnits) - searchRange, entrySelector, rangeShift = getSearchRange( - n=numUnits, itemSize=unitSize - ) - writer.writeUShort(searchRange) - writer.writeUShort(entrySelector) - writer.writeUShort(rangeShift) - - def buildFormat0(self, writer, font, values): - numGlyphs = len(font.getGlyphOrder()) - if len(values) != numGlyphs: - return None - valueSize = self.converter.staticSize - return ( - 2 + numGlyphs * valueSize, - 0, - lambda: self.writeFormat0(writer, font, values), - ) - - def writeFormat0(self, writer, font, values): - writer.writeUShort(0) - for glyphID_, value in values: - self.converter.write( - writer, font, tableDict=None, value=value, repeatIndex=None - ) - - def buildFormat2(self, writer, font, values): - segStart, segValue = values[0] - segEnd = segStart - segments = [] - for glyphID, curValue in values[1:]: - if glyphID != segEnd + 1 or curValue != segValue: - segments.append((segStart, segEnd, segValue)) - segStart = segEnd = glyphID - segValue = curValue - else: - segEnd = glyphID - segments.append((segStart, segEnd, segValue)) - valueSize = self.converter.staticSize - numUnits, unitSize = len(segments) + 1, valueSize + 4 - return ( - 2 + self.BIN_SEARCH_HEADER_SIZE + numUnits * unitSize, - 2, - lambda: self.writeFormat2(writer, font, segments), - ) - - def writeFormat2(self, writer, font, segments): - writer.writeUShort(2) - valueSize = self.converter.staticSize - numUnits, unitSize = len(segments), valueSize + 4 - self.writeBinSearchHeader(writer, numUnits, unitSize) - for firstGlyph, lastGlyph, value in segments: - writer.writeUShort(lastGlyph) - writer.writeUShort(firstGlyph) - self.converter.write( - writer, font, tableDict=None, value=value, repeatIndex=None - ) - writer.writeUShort(0xFFFF) - writer.writeUShort(0xFFFF) - writer.writeData(b"\x00" * valueSize) - - def buildFormat6(self, writer, font, values): - valueSize = self.converter.staticSize - numUnits, unitSize = len(values), valueSize + 2 - return ( - 2 + self.BIN_SEARCH_HEADER_SIZE + (numUnits + 1) * unitSize, - 6, - lambda: self.writeFormat6(writer, font, values), - ) - - def writeFormat6(self, writer, font, values): - writer.writeUShort(6) - valueSize = self.converter.staticSize - numUnits, unitSize = len(values), valueSize + 2 - self.writeBinSearchHeader(writer, numUnits, unitSize) - for glyphID, value in values: - writer.writeUShort(glyphID) - self.converter.write( - writer, font, tableDict=None, value=value, repeatIndex=None - ) - writer.writeUShort(0xFFFF) - writer.writeData(b"\x00" * valueSize) - - def buildFormat8(self, writer, font, values): - minGlyphID, maxGlyphID = values[0][0], values[-1][0] - if len(values) != maxGlyphID - minGlyphID + 1: - return None - valueSize = self.converter.staticSize - return ( - 6 + len(values) * valueSize, - 8, - lambda: self.writeFormat8(writer, font, values), - ) - - def writeFormat8(self, writer, font, values): - firstGlyphID = values[0][0] - writer.writeUShort(8) - writer.writeUShort(firstGlyphID) - writer.writeUShort(len(values)) - for _, value in values: - self.converter.write( - writer, font, tableDict=None, value=value, repeatIndex=None - ) - - def readFormat0(self, reader, font): - numGlyphs = len(font.getGlyphOrder()) - data = self.converter.readArray(reader, font, tableDict=None, count=numGlyphs) - return {font.getGlyphName(k): value for k, value in enumerate(data)} - - def readFormat2(self, reader, font): - mapping = {} - pos = reader.pos - 2 # start of table is at UShort for format - unitSize, numUnits = reader.readUShort(), reader.readUShort() - assert unitSize >= 4 + self.converter.staticSize, unitSize - for i in range(numUnits): - reader.seek(pos + i * unitSize + 12) - last = reader.readUShort() - first = reader.readUShort() - value = self.converter.read(reader, font, tableDict=None) - if last != 0xFFFF: - for k in range(first, last + 1): - mapping[font.getGlyphName(k)] = value - return mapping - - def readFormat4(self, reader, font): - mapping = {} - pos = reader.pos - 2 # start of table is at UShort for format - unitSize = reader.readUShort() - assert unitSize >= 6, unitSize - for i in range(reader.readUShort()): - reader.seek(pos + i * unitSize + 12) - last = reader.readUShort() - first = reader.readUShort() - offset = reader.readUShort() - if last != 0xFFFF: - dataReader = reader.getSubReader(0) # relative to current position - dataReader.seek(pos + offset) # relative to start of table - data = self.converter.readArray( - dataReader, font, tableDict=None, count=last - first + 1 - ) - for k, v in enumerate(data): - mapping[font.getGlyphName(first + k)] = v - return mapping - - def readFormat6(self, reader, font): - mapping = {} - pos = reader.pos - 2 # start of table is at UShort for format - unitSize = reader.readUShort() - assert unitSize >= 2 + self.converter.staticSize, unitSize - for i in range(reader.readUShort()): - reader.seek(pos + i * unitSize + 12) - glyphID = reader.readUShort() - value = self.converter.read(reader, font, tableDict=None) - if glyphID != 0xFFFF: - mapping[font.getGlyphName(glyphID)] = value - return mapping - - def readFormat8(self, reader, font): - first = reader.readUShort() - count = reader.readUShort() - data = self.converter.readArray(reader, font, tableDict=None, count=count) - return {font.getGlyphName(first + k): value for (k, value) in enumerate(data)} - - def xmlRead(self, attrs, content, font): - value = {} - for element in content: - if isinstance(element, tuple): - name, a, eltContent = element - if name == "Lookup": - value[a["glyph"]] = self.converter.xmlRead(a, eltContent, font) - return value - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.begintag(name, attrs) - xmlWriter.newline() - for glyph, value in sorted(value.items()): - self.converter.xmlWrite( - xmlWriter, font, value=value, name="Lookup", attrs=[("glyph", glyph)] - ) - xmlWriter.endtag(name) - xmlWriter.newline() - - -# The AAT 'ankr' table has an unusual structure: An offset to an AATLookup -# followed by an offset to a glyph data table. Other than usual, the -# offsets in the AATLookup are not relative to the beginning of -# the beginning of the 'ankr' table, but relative to the glyph data table. -# So, to find the anchor data for a glyph, one needs to add the offset -# to the data table to the offset found in the AATLookup, and then use -# the sum of these two offsets to find the actual data. -class AATLookupWithDataOffset(BaseConverter): - def read(self, reader, font, tableDict): - lookupOffset = reader.readULong() - dataOffset = reader.readULong() - lookupReader = reader.getSubReader(lookupOffset) - lookup = AATLookup("DataOffsets", None, None, UShort) - offsets = lookup.read(lookupReader, font, tableDict) - result = {} - for glyph, offset in offsets.items(): - dataReader = reader.getSubReader(offset + dataOffset) - item = self.tableClass() - item.decompile(dataReader, font) - result[glyph] = item - return result - - def write(self, writer, font, tableDict, value, repeatIndex=None): - # We do not work with OTTableWriter sub-writers because - # the offsets in our AATLookup are relative to our data - # table, for which we need to provide an offset value itself. - # It might have been possible to somehow make a kludge for - # performing this indirect offset computation directly inside - # OTTableWriter. But this would have made the internal logic - # of OTTableWriter even more complex than it already is, - # so we decided to roll our own offset computation for the - # contents of the AATLookup and associated data table. - offsetByGlyph, offsetByData, dataLen = {}, {}, 0 - compiledData = [] - for glyph in sorted(value, key=font.getGlyphID): - subWriter = OTTableWriter() - value[glyph].compile(subWriter, font) - data = subWriter.getAllData() - offset = offsetByData.get(data, None) - if offset == None: - offset = dataLen - dataLen = dataLen + len(data) - offsetByData[data] = offset - compiledData.append(data) - offsetByGlyph[glyph] = offset - # For calculating the offsets to our AATLookup and data table, - # we can use the regular OTTableWriter infrastructure. - lookupWriter = writer.getSubWriter(offsetSize=4) - lookup = AATLookup("DataOffsets", None, None, UShort) - lookup.write(lookupWriter, font, tableDict, offsetByGlyph, None) - - dataWriter = writer.getSubWriter(offsetSize=4) - writer.writeSubTable(lookupWriter) - writer.writeSubTable(dataWriter) - for d in compiledData: - dataWriter.writeData(d) - - def xmlRead(self, attrs, content, font): - lookup = AATLookup("DataOffsets", None, None, self.tableClass) - return lookup.xmlRead(attrs, content, font) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - lookup = AATLookup("DataOffsets", None, None, self.tableClass) - lookup.xmlWrite(xmlWriter, font, value, name, attrs) - - -class MorxSubtableConverter(BaseConverter): - _PROCESSING_ORDERS = { - # bits 30 and 28 of morx.CoverageFlags; see morx spec - (False, False): "LayoutOrder", - (True, False): "ReversedLayoutOrder", - (False, True): "LogicalOrder", - (True, True): "ReversedLogicalOrder", - } - - _PROCESSING_ORDERS_REVERSED = {val: key for key, val in _PROCESSING_ORDERS.items()} - - def __init__(self, name, repeat, aux, tableClass=None, *, description=""): - BaseConverter.__init__( - self, name, repeat, aux, tableClass, description=description - ) - - def _setTextDirectionFromCoverageFlags(self, flags, subtable): - if (flags & 0x20) != 0: - subtable.TextDirection = "Any" - elif (flags & 0x80) != 0: - subtable.TextDirection = "Vertical" - else: - subtable.TextDirection = "Horizontal" - - def read(self, reader, font, tableDict): - pos = reader.pos - m = MorxSubtable() - m.StructLength = reader.readULong() - flags = reader.readUInt8() - orderKey = ((flags & 0x40) != 0, (flags & 0x10) != 0) - m.ProcessingOrder = self._PROCESSING_ORDERS[orderKey] - self._setTextDirectionFromCoverageFlags(flags, m) - m.Reserved = reader.readUShort() - m.Reserved |= (flags & 0xF) << 16 - m.MorphType = reader.readUInt8() - m.SubFeatureFlags = reader.readULong() - tableClass = lookupTypes["morx"].get(m.MorphType) - if tableClass is None: - assert False, "unsupported 'morx' lookup type %s" % m.MorphType - # To decode AAT ligatures, we need to know the subtable size. - # The easiest way to pass this along is to create a new reader - # that works on just the subtable as its data. - headerLength = reader.pos - pos - data = reader.data[reader.pos : reader.pos + m.StructLength - headerLength] - assert len(data) == m.StructLength - headerLength - subReader = OTTableReader(data=data, tableTag=reader.tableTag) - m.SubStruct = tableClass() - m.SubStruct.decompile(subReader, font) - reader.seek(pos + m.StructLength) - return m - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.begintag(name, attrs) - xmlWriter.newline() - xmlWriter.comment("StructLength=%d" % value.StructLength) - xmlWriter.newline() - xmlWriter.simpletag("TextDirection", value=value.TextDirection) - xmlWriter.newline() - xmlWriter.simpletag("ProcessingOrder", value=value.ProcessingOrder) - xmlWriter.newline() - if value.Reserved != 0: - xmlWriter.simpletag("Reserved", value="0x%04x" % value.Reserved) - xmlWriter.newline() - xmlWriter.comment("MorphType=%d" % value.MorphType) - xmlWriter.newline() - xmlWriter.simpletag("SubFeatureFlags", value="0x%08x" % value.SubFeatureFlags) - xmlWriter.newline() - value.SubStruct.toXML(xmlWriter, font) - xmlWriter.endtag(name) - xmlWriter.newline() - - def xmlRead(self, attrs, content, font): - m = MorxSubtable() - covFlags = 0 - m.Reserved = 0 - for eltName, eltAttrs, eltContent in filter(istuple, content): - if eltName == "CoverageFlags": - # Only in XML from old versions of fonttools. - covFlags = safeEval(eltAttrs["value"]) - orderKey = ((covFlags & 0x40) != 0, (covFlags & 0x10) != 0) - m.ProcessingOrder = self._PROCESSING_ORDERS[orderKey] - self._setTextDirectionFromCoverageFlags(covFlags, m) - elif eltName == "ProcessingOrder": - m.ProcessingOrder = eltAttrs["value"] - assert m.ProcessingOrder in self._PROCESSING_ORDERS_REVERSED, ( - "unknown ProcessingOrder: %s" % m.ProcessingOrder - ) - elif eltName == "TextDirection": - m.TextDirection = eltAttrs["value"] - assert m.TextDirection in {"Horizontal", "Vertical", "Any"}, ( - "unknown TextDirection %s" % m.TextDirection - ) - elif eltName == "Reserved": - m.Reserved = safeEval(eltAttrs["value"]) - elif eltName == "SubFeatureFlags": - m.SubFeatureFlags = safeEval(eltAttrs["value"]) - elif eltName.endswith("Morph"): - m.fromXML(eltName, eltAttrs, eltContent, font) - else: - assert False, eltName - m.Reserved = (covFlags & 0xF) << 16 | m.Reserved - return m - - def write(self, writer, font, tableDict, value, repeatIndex=None): - covFlags = (value.Reserved & 0x000F0000) >> 16 - reverseOrder, logicalOrder = self._PROCESSING_ORDERS_REVERSED[ - value.ProcessingOrder - ] - covFlags |= 0x80 if value.TextDirection == "Vertical" else 0 - covFlags |= 0x40 if reverseOrder else 0 - covFlags |= 0x20 if value.TextDirection == "Any" else 0 - covFlags |= 0x10 if logicalOrder else 0 - value.CoverageFlags = covFlags - lengthIndex = len(writer.items) - before = writer.getDataLength() - value.StructLength = 0xDEADBEEF - # The high nibble of value.Reserved is actuallly encoded - # into coverageFlags, so we need to clear it here. - origReserved = value.Reserved # including high nibble - value.Reserved = value.Reserved & 0xFFFF # without high nibble - value.compile(writer, font) - value.Reserved = origReserved # restore original value - assert writer.items[lengthIndex] == b"\xde\xad\xbe\xef" - length = writer.getDataLength() - before - writer.items[lengthIndex] = struct.pack(">L", length) - - -# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6Tables.html#ExtendedStateHeader -# TODO: Untangle the implementation of the various lookup-specific formats. -class STXHeader(BaseConverter): - def __init__(self, name, repeat, aux, tableClass, *, description=""): - BaseConverter.__init__( - self, name, repeat, aux, tableClass, description=description - ) - assert issubclass(self.tableClass, AATAction) - self.classLookup = AATLookup("GlyphClasses", None, None, UShort) - if issubclass(self.tableClass, ContextualMorphAction): - self.perGlyphLookup = AATLookup("PerGlyphLookup", None, None, GlyphID) - else: - self.perGlyphLookup = None - - def read(self, reader, font, tableDict): - table = AATStateTable() - pos = reader.pos - classTableReader = reader.getSubReader(0) - stateArrayReader = reader.getSubReader(0) - entryTableReader = reader.getSubReader(0) - actionReader = None - ligaturesReader = None - table.GlyphClassCount = reader.readULong() - classTableReader.seek(pos + reader.readULong()) - stateArrayReader.seek(pos + reader.readULong()) - entryTableReader.seek(pos + reader.readULong()) - if self.perGlyphLookup is not None: - perGlyphTableReader = reader.getSubReader(0) - perGlyphTableReader.seek(pos + reader.readULong()) - if issubclass(self.tableClass, LigatureMorphAction): - actionReader = reader.getSubReader(0) - actionReader.seek(pos + reader.readULong()) - ligComponentReader = reader.getSubReader(0) - ligComponentReader.seek(pos + reader.readULong()) - ligaturesReader = reader.getSubReader(0) - ligaturesReader.seek(pos + reader.readULong()) - numLigComponents = (ligaturesReader.pos - ligComponentReader.pos) // 2 - assert numLigComponents >= 0 - table.LigComponents = ligComponentReader.readUShortArray(numLigComponents) - table.Ligatures = self._readLigatures(ligaturesReader, font) - elif issubclass(self.tableClass, InsertionMorphAction): - actionReader = reader.getSubReader(0) - actionReader.seek(pos + reader.readULong()) - table.GlyphClasses = self.classLookup.read(classTableReader, font, tableDict) - numStates = int( - (entryTableReader.pos - stateArrayReader.pos) / (table.GlyphClassCount * 2) - ) - for stateIndex in range(numStates): - state = AATState() - table.States.append(state) - for glyphClass in range(table.GlyphClassCount): - entryIndex = stateArrayReader.readUShort() - state.Transitions[glyphClass] = self._readTransition( - entryTableReader, entryIndex, font, actionReader - ) - if self.perGlyphLookup is not None: - table.PerGlyphLookups = self._readPerGlyphLookups( - table, perGlyphTableReader, font - ) - return table - - def _readTransition(self, reader, entryIndex, font, actionReader): - transition = self.tableClass() - entryReader = reader.getSubReader( - reader.pos + entryIndex * transition.staticSize - ) - transition.decompile(entryReader, font, actionReader) - return transition - - def _readLigatures(self, reader, font): - limit = len(reader.data) - numLigatureGlyphs = (limit - reader.pos) // 2 - return font.getGlyphNameMany(reader.readUShortArray(numLigatureGlyphs)) - - def _countPerGlyphLookups(self, table): - # Somewhat annoyingly, the morx table does not encode - # the size of the per-glyph table. So we need to find - # the maximum value that MorphActions use as index - # into this table. - numLookups = 0 - for state in table.States: - for t in state.Transitions.values(): - if isinstance(t, ContextualMorphAction): - if t.MarkIndex != 0xFFFF: - numLookups = max(numLookups, t.MarkIndex + 1) - if t.CurrentIndex != 0xFFFF: - numLookups = max(numLookups, t.CurrentIndex + 1) - return numLookups - - def _readPerGlyphLookups(self, table, reader, font): - pos = reader.pos - lookups = [] - for _ in range(self._countPerGlyphLookups(table)): - lookupReader = reader.getSubReader(0) - lookupReader.seek(pos + reader.readULong()) - lookups.append(self.perGlyphLookup.read(lookupReader, font, {})) - return lookups - - def write(self, writer, font, tableDict, value, repeatIndex=None): - glyphClassWriter = OTTableWriter() - self.classLookup.write( - glyphClassWriter, font, tableDict, value.GlyphClasses, repeatIndex=None - ) - glyphClassData = pad(glyphClassWriter.getAllData(), 2) - glyphClassCount = max(value.GlyphClasses.values()) + 1 - glyphClassTableOffset = 16 # size of STXHeader - if self.perGlyphLookup is not None: - glyphClassTableOffset += 4 - - glyphClassTableOffset += self.tableClass.actionHeaderSize - actionData, actionIndex = self.tableClass.compileActions(font, value.States) - stateArrayData, entryTableData = self._compileStates( - font, value.States, glyphClassCount, actionIndex - ) - stateArrayOffset = glyphClassTableOffset + len(glyphClassData) - entryTableOffset = stateArrayOffset + len(stateArrayData) - perGlyphOffset = entryTableOffset + len(entryTableData) - perGlyphData = pad(self._compilePerGlyphLookups(value, font), 4) - if actionData is not None: - actionOffset = entryTableOffset + len(entryTableData) - else: - actionOffset = None - - ligaturesOffset, ligComponentsOffset = None, None - ligComponentsData = self._compileLigComponents(value, font) - ligaturesData = self._compileLigatures(value, font) - if ligComponentsData is not None: - assert len(perGlyphData) == 0 - ligComponentsOffset = actionOffset + len(actionData) - ligaturesOffset = ligComponentsOffset + len(ligComponentsData) - - writer.writeULong(glyphClassCount) - writer.writeULong(glyphClassTableOffset) - writer.writeULong(stateArrayOffset) - writer.writeULong(entryTableOffset) - if self.perGlyphLookup is not None: - writer.writeULong(perGlyphOffset) - if actionOffset is not None: - writer.writeULong(actionOffset) - if ligComponentsOffset is not None: - writer.writeULong(ligComponentsOffset) - writer.writeULong(ligaturesOffset) - writer.writeData(glyphClassData) - writer.writeData(stateArrayData) - writer.writeData(entryTableData) - writer.writeData(perGlyphData) - if actionData is not None: - writer.writeData(actionData) - if ligComponentsData is not None: - writer.writeData(ligComponentsData) - if ligaturesData is not None: - writer.writeData(ligaturesData) - - def _compileStates(self, font, states, glyphClassCount, actionIndex): - stateArrayWriter = OTTableWriter() - entries, entryIDs = [], {} - for state in states: - for glyphClass in range(glyphClassCount): - transition = state.Transitions[glyphClass] - entryWriter = OTTableWriter() - transition.compile(entryWriter, font, actionIndex) - entryData = entryWriter.getAllData() - assert ( - len(entryData) == transition.staticSize - ), "%s has staticSize %d, " "but actually wrote %d bytes" % ( - repr(transition), - transition.staticSize, - len(entryData), - ) - entryIndex = entryIDs.get(entryData) - if entryIndex is None: - entryIndex = len(entries) - entryIDs[entryData] = entryIndex - entries.append(entryData) - stateArrayWriter.writeUShort(entryIndex) - stateArrayData = pad(stateArrayWriter.getAllData(), 4) - entryTableData = pad(bytesjoin(entries), 4) - return stateArrayData, entryTableData - - def _compilePerGlyphLookups(self, table, font): - if self.perGlyphLookup is None: - return b"" - numLookups = self._countPerGlyphLookups(table) - assert len(table.PerGlyphLookups) == numLookups, ( - "len(AATStateTable.PerGlyphLookups) is %d, " - "but the actions inside the table refer to %d" - % (len(table.PerGlyphLookups), numLookups) - ) - writer = OTTableWriter() - for lookup in table.PerGlyphLookups: - lookupWriter = writer.getSubWriter(offsetSize=4) - self.perGlyphLookup.write(lookupWriter, font, {}, lookup, None) - writer.writeSubTable(lookupWriter) - return writer.getAllData() - - def _compileLigComponents(self, table, font): - if not hasattr(table, "LigComponents"): - return None - writer = OTTableWriter() - for component in table.LigComponents: - writer.writeUShort(component) - return writer.getAllData() - - def _compileLigatures(self, table, font): - if not hasattr(table, "Ligatures"): - return None - writer = OTTableWriter() - for glyphName in table.Ligatures: - writer.writeUShort(font.getGlyphID(glyphName)) - return writer.getAllData() - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.begintag(name, attrs) - xmlWriter.newline() - xmlWriter.comment("GlyphClassCount=%s" % value.GlyphClassCount) - xmlWriter.newline() - for g, klass in sorted(value.GlyphClasses.items()): - xmlWriter.simpletag("GlyphClass", glyph=g, value=klass) - xmlWriter.newline() - for stateIndex, state in enumerate(value.States): - xmlWriter.begintag("State", index=stateIndex) - xmlWriter.newline() - for glyphClass, trans in sorted(state.Transitions.items()): - trans.toXML( - xmlWriter, - font=font, - attrs={"onGlyphClass": glyphClass}, - name="Transition", - ) - xmlWriter.endtag("State") - xmlWriter.newline() - for i, lookup in enumerate(value.PerGlyphLookups): - xmlWriter.begintag("PerGlyphLookup", index=i) - xmlWriter.newline() - for glyph, val in sorted(lookup.items()): - xmlWriter.simpletag("Lookup", glyph=glyph, value=val) - xmlWriter.newline() - xmlWriter.endtag("PerGlyphLookup") - xmlWriter.newline() - if hasattr(value, "LigComponents"): - xmlWriter.begintag("LigComponents") - xmlWriter.newline() - for i, val in enumerate(getattr(value, "LigComponents")): - xmlWriter.simpletag("LigComponent", index=i, value=val) - xmlWriter.newline() - xmlWriter.endtag("LigComponents") - xmlWriter.newline() - self._xmlWriteLigatures(xmlWriter, font, value, name, attrs) - xmlWriter.endtag(name) - xmlWriter.newline() - - def _xmlWriteLigatures(self, xmlWriter, font, value, name, attrs): - if not hasattr(value, "Ligatures"): - return - xmlWriter.begintag("Ligatures") - xmlWriter.newline() - for i, g in enumerate(getattr(value, "Ligatures")): - xmlWriter.simpletag("Ligature", index=i, glyph=g) - xmlWriter.newline() - xmlWriter.endtag("Ligatures") - xmlWriter.newline() - - def xmlRead(self, attrs, content, font): - table = AATStateTable() - for eltName, eltAttrs, eltContent in filter(istuple, content): - if eltName == "GlyphClass": - glyph = eltAttrs["glyph"] - value = eltAttrs["value"] - table.GlyphClasses[glyph] = safeEval(value) - elif eltName == "State": - state = self._xmlReadState(eltAttrs, eltContent, font) - table.States.append(state) - elif eltName == "PerGlyphLookup": - lookup = self.perGlyphLookup.xmlRead(eltAttrs, eltContent, font) - table.PerGlyphLookups.append(lookup) - elif eltName == "LigComponents": - table.LigComponents = self._xmlReadLigComponents( - eltAttrs, eltContent, font - ) - elif eltName == "Ligatures": - table.Ligatures = self._xmlReadLigatures(eltAttrs, eltContent, font) - table.GlyphClassCount = max(table.GlyphClasses.values()) + 1 - return table - - def _xmlReadState(self, attrs, content, font): - state = AATState() - for eltName, eltAttrs, eltContent in filter(istuple, content): - if eltName == "Transition": - glyphClass = safeEval(eltAttrs["onGlyphClass"]) - transition = self.tableClass() - transition.fromXML(eltName, eltAttrs, eltContent, font) - state.Transitions[glyphClass] = transition - return state - - def _xmlReadLigComponents(self, attrs, content, font): - ligComponents = [] - for eltName, eltAttrs, _eltContent in filter(istuple, content): - if eltName == "LigComponent": - ligComponents.append(safeEval(eltAttrs["value"])) - return ligComponents - - def _xmlReadLigatures(self, attrs, content, font): - ligs = [] - for eltName, eltAttrs, _eltContent in filter(istuple, content): - if eltName == "Ligature": - ligs.append(eltAttrs["glyph"]) - return ligs - - -class CIDGlyphMap(BaseConverter): - def read(self, reader, font, tableDict): - numCIDs = reader.readUShort() - result = {} - for cid, glyphID in enumerate(reader.readUShortArray(numCIDs)): - if glyphID != 0xFFFF: - result[cid] = font.getGlyphName(glyphID) - return result - - def write(self, writer, font, tableDict, value, repeatIndex=None): - items = {cid: font.getGlyphID(glyph) for cid, glyph in value.items()} - count = max(items) + 1 if items else 0 - writer.writeUShort(count) - for cid in range(count): - writer.writeUShort(items.get(cid, 0xFFFF)) - - def xmlRead(self, attrs, content, font): - result = {} - for eName, eAttrs, _eContent in filter(istuple, content): - if eName == "CID": - result[safeEval(eAttrs["cid"])] = eAttrs["glyph"].strip() - return result - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.begintag(name, attrs) - xmlWriter.newline() - for cid, glyph in sorted(value.items()): - if glyph is not None and glyph != 0xFFFF: - xmlWriter.simpletag("CID", cid=cid, glyph=glyph) - xmlWriter.newline() - xmlWriter.endtag(name) - xmlWriter.newline() - - -class GlyphCIDMap(BaseConverter): - def read(self, reader, font, tableDict): - glyphOrder = font.getGlyphOrder() - count = reader.readUShort() - cids = reader.readUShortArray(count) - if count > len(glyphOrder): - log.warning( - "GlyphCIDMap has %d elements, " - "but the font has only %d glyphs; " - "ignoring the rest" % (count, len(glyphOrder)) - ) - result = {} - for glyphID in range(min(len(cids), len(glyphOrder))): - cid = cids[glyphID] - if cid != 0xFFFF: - result[glyphOrder[glyphID]] = cid - return result - - def write(self, writer, font, tableDict, value, repeatIndex=None): - items = { - font.getGlyphID(g): cid - for g, cid in value.items() - if cid is not None and cid != 0xFFFF - } - count = max(items) + 1 if items else 0 - writer.writeUShort(count) - for glyphID in range(count): - writer.writeUShort(items.get(glyphID, 0xFFFF)) - - def xmlRead(self, attrs, content, font): - result = {} - for eName, eAttrs, _eContent in filter(istuple, content): - if eName == "CID": - result[eAttrs["glyph"]] = safeEval(eAttrs["value"]) - return result - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.begintag(name, attrs) - xmlWriter.newline() - for glyph, cid in sorted(value.items()): - if cid is not None and cid != 0xFFFF: - xmlWriter.simpletag("CID", glyph=glyph, value=cid) - xmlWriter.newline() - xmlWriter.endtag(name) - xmlWriter.newline() - - -class DeltaValue(BaseConverter): - def read(self, reader, font, tableDict): - StartSize = tableDict["StartSize"] - EndSize = tableDict["EndSize"] - DeltaFormat = tableDict["DeltaFormat"] - assert DeltaFormat in (1, 2, 3), "illegal DeltaFormat" - nItems = EndSize - StartSize + 1 - nBits = 1 << DeltaFormat - minusOffset = 1 << nBits - mask = (1 << nBits) - 1 - signMask = 1 << (nBits - 1) - - DeltaValue = [] - tmp, shift = 0, 0 - for i in range(nItems): - if shift == 0: - tmp, shift = reader.readUShort(), 16 - shift = shift - nBits - value = (tmp >> shift) & mask - if value & signMask: - value = value - minusOffset - DeltaValue.append(value) - return DeltaValue - - def write(self, writer, font, tableDict, value, repeatIndex=None): - StartSize = tableDict["StartSize"] - EndSize = tableDict["EndSize"] - DeltaFormat = tableDict["DeltaFormat"] - DeltaValue = value - assert DeltaFormat in (1, 2, 3), "illegal DeltaFormat" - nItems = EndSize - StartSize + 1 - nBits = 1 << DeltaFormat - assert len(DeltaValue) == nItems - mask = (1 << nBits) - 1 - - tmp, shift = 0, 16 - for value in DeltaValue: - shift = shift - nBits - tmp = tmp | ((value & mask) << shift) - if shift == 0: - writer.writeUShort(tmp) - tmp, shift = 0, 16 - if shift != 16: - writer.writeUShort(tmp) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.simpletag(name, attrs + [("value", value)]) - xmlWriter.newline() - - def xmlRead(self, attrs, content, font): - return safeEval(attrs["value"]) - - -class VarIdxMapValue(BaseConverter): - def read(self, reader, font, tableDict): - fmt = tableDict["EntryFormat"] - nItems = tableDict["MappingCount"] - - innerBits = 1 + (fmt & 0x000F) - innerMask = (1 << innerBits) - 1 - outerMask = 0xFFFFFFFF - innerMask - outerShift = 16 - innerBits - - entrySize = 1 + ((fmt & 0x0030) >> 4) - readArray = { - 1: reader.readUInt8Array, - 2: reader.readUShortArray, - 3: reader.readUInt24Array, - 4: reader.readULongArray, - }[entrySize] - - return [ - (((raw & outerMask) << outerShift) | (raw & innerMask)) - for raw in readArray(nItems) - ] - - def write(self, writer, font, tableDict, value, repeatIndex=None): - fmt = tableDict["EntryFormat"] - mapping = value - writer["MappingCount"].setValue(len(mapping)) - - innerBits = 1 + (fmt & 0x000F) - innerMask = (1 << innerBits) - 1 - outerShift = 16 - innerBits - - entrySize = 1 + ((fmt & 0x0030) >> 4) - writeArray = { - 1: writer.writeUInt8Array, - 2: writer.writeUShortArray, - 3: writer.writeUInt24Array, - 4: writer.writeULongArray, - }[entrySize] - - writeArray( - [ - (((idx & 0xFFFF0000) >> outerShift) | (idx & innerMask)) - for idx in mapping - ] - ) - - -class VarDataValue(BaseConverter): - def read(self, reader, font, tableDict): - values = [] - - regionCount = tableDict["VarRegionCount"] - wordCount = tableDict["NumShorts"] - - # https://github.com/fonttools/fonttools/issues/2279 - longWords = bool(wordCount & 0x8000) - wordCount = wordCount & 0x7FFF - - if longWords: - readBigArray, readSmallArray = reader.readLongArray, reader.readShortArray - else: - readBigArray, readSmallArray = reader.readShortArray, reader.readInt8Array - - n1, n2 = min(regionCount, wordCount), max(regionCount, wordCount) - values.extend(readBigArray(n1)) - values.extend(readSmallArray(n2 - n1)) - if n2 > regionCount: # Padding - del values[regionCount:] - - return values - - def write(self, writer, font, tableDict, values, repeatIndex=None): - regionCount = tableDict["VarRegionCount"] - wordCount = tableDict["NumShorts"] - - # https://github.com/fonttools/fonttools/issues/2279 - longWords = bool(wordCount & 0x8000) - wordCount = wordCount & 0x7FFF - - (writeBigArray, writeSmallArray) = { - False: (writer.writeShortArray, writer.writeInt8Array), - True: (writer.writeLongArray, writer.writeShortArray), - }[longWords] - - n1, n2 = min(regionCount, wordCount), max(regionCount, wordCount) - writeBigArray(values[:n1]) - writeSmallArray(values[n1:regionCount]) - if n2 > regionCount: # Padding - writer.writeSmallArray([0] * (n2 - regionCount)) - - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.simpletag(name, attrs + [("value", value)]) - xmlWriter.newline() - - def xmlRead(self, attrs, content, font): - return safeEval(attrs["value"]) - - -class LookupFlag(UShort): - def xmlWrite(self, xmlWriter, font, value, name, attrs): - xmlWriter.simpletag(name, attrs + [("value", value)]) - flags = [] - if value & 0x01: - flags.append("rightToLeft") - if value & 0x02: - flags.append("ignoreBaseGlyphs") - if value & 0x04: - flags.append("ignoreLigatures") - if value & 0x08: - flags.append("ignoreMarks") - if value & 0x10: - flags.append("useMarkFilteringSet") - if value & 0xFF00: - flags.append("markAttachmentType[%i]" % (value >> 8)) - if flags: - xmlWriter.comment(" ".join(flags)) - xmlWriter.newline() - - -class _UInt8Enum(UInt8): - enumClass = NotImplemented - - def read(self, reader, font, tableDict): - return self.enumClass(super().read(reader, font, tableDict)) - - @classmethod - def fromString(cls, value): - return getattr(cls.enumClass, value.upper()) - - @classmethod - def toString(cls, value): - return cls.enumClass(value).name.lower() - - -class ExtendMode(_UInt8Enum): - enumClass = _ExtendMode - - -class CompositeMode(_UInt8Enum): - enumClass = _CompositeMode - - -converterMapping = { - # type class - "int8": Int8, - "int16": Short, - "uint8": UInt8, - "uint16": UShort, - "uint24": UInt24, - "uint32": ULong, - "char64": Char64, - "Flags32": Flags32, - "VarIndex": VarIndex, - "Version": Version, - "Tag": Tag, - "GlyphID": GlyphID, - "GlyphID32": GlyphID32, - "NameID": NameID, - "DeciPoints": DeciPoints, - "Fixed": Fixed, - "F2Dot14": F2Dot14, - "Angle": Angle, - "BiasedAngle": BiasedAngle, - "struct": Struct, - "Offset": Table, - "LOffset": LTable, - "Offset24": Table24, - "ValueRecord": ValueRecord, - "DeltaValue": DeltaValue, - "VarIdxMapValue": VarIdxMapValue, - "VarDataValue": VarDataValue, - "LookupFlag": LookupFlag, - "ExtendMode": ExtendMode, - "CompositeMode": CompositeMode, - "STATFlags": STATFlags, - # AAT - "CIDGlyphMap": CIDGlyphMap, - "GlyphCIDMap": GlyphCIDMap, - "MortChain": StructWithLength, - "MortSubtable": StructWithLength, - "MorxChain": StructWithLength, - "MorxSubtable": MorxSubtableConverter, - # "Template" types - "AATLookup": lambda C: partial(AATLookup, tableClass=C), - "AATLookupWithDataOffset": lambda C: partial(AATLookupWithDataOffset, tableClass=C), - "STXHeader": lambda C: partial(STXHeader, tableClass=C), - "OffsetTo": lambda C: partial(Table, tableClass=C), - "LOffsetTo": lambda C: partial(LTable, tableClass=C), - "LOffset24To": lambda C: partial(Table24, tableClass=C), -} diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/functorch/experimental/ops.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/functorch/experimental/ops.py deleted file mode 100644 index 42899c20526ff74464383438695a989383ea0935..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/functorch/experimental/ops.py +++ /dev/null @@ -1 +0,0 @@ -from torch._ops import PyOperator # noqa: F401 diff --git a/spaces/leogabraneth/text-generation-webui-main/extensions/openai/cache_embedding_model.py b/spaces/leogabraneth/text-generation-webui-main/extensions/openai/cache_embedding_model.py deleted file mode 100644 index 7f4f0806a62e3f46cc3a6076e05d3b8b7e87a2b2..0000000000000000000000000000000000000000 --- a/spaces/leogabraneth/text-generation-webui-main/extensions/openai/cache_embedding_model.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python3 -# preload the embedding model, useful for Docker images to prevent re-download on config change -# Dockerfile: -# ENV OPENEDAI_EMBEDDING_MODEL=all-mpnet-base-v2 # Optional -# RUN python3 cache_embedded_model.py -import os - -import sentence_transformers - -st_model = os.environ.get("OPENEDAI_EMBEDDING_MODEL", "all-mpnet-base-v2") -model = sentence_transformers.SentenceTransformer(st_model) diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Doraemon Nobita In Dorabian Nights Full Movie In Hindi Download [HOT].md b/spaces/lincquiQcaudo/Top-20-Diffusion/Doraemon Nobita In Dorabian Nights Full Movie In Hindi Download [HOT].md deleted file mode 100644 index 88d6d6bba28c447b76481d0d8fa91da5737ff7e3..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Doraemon Nobita In Dorabian Nights Full Movie In Hindi Download [HOT].md +++ /dev/null @@ -1,21 +0,0 @@ -

    Doraemon Nobita In Dorabian Nights Full Movie In Hindi Download


    Download Ziphttps://bytlly.com/2uGvLX



    - -Doraemon Movie Doraemon Nights in Hindi | 720p #doraemoninhindi #doraemoncollection ... 12:40 -Cartoon Doraemon nights - watch online for free: Doraemon - animated series for children and adults. -Cartoon... -2:53:14 -Dorab nights in Hindi. -Doraemon is an animated series for children and adults. -Dorab nights. -#Doraemon #cartoon... -2:40 -Doraemon. -#Dorab nights. -Dorab nights on... -2:23 -Look... -3:45 -Dorab 8a78ff9644
    -
    -
    -

    diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Lines Sloba I Mira [WORK].md b/spaces/lincquiQcaudo/Top-20-Diffusion/Lines Sloba I Mira [WORK].md deleted file mode 100644 index 1507c4bb7a1a6e6c2e68f82b50a2bef4a308b31f..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Lines Sloba I Mira [WORK].md +++ /dev/null @@ -1,6 +0,0 @@ -

    lines sloba i mira


    Download File 🗸 https://bytlly.com/2uGwNJ



    -
    -these lines up to August 1991.96 Some posit that it was around March 1991 ... Bilandžić: Tuđman mi je rekao - 'Kad podijelimo Bosnu, ja i Sloba bit ćemo ... Kosta Nikolić & Vladimir Petrović, Od mira do rata: dokumenta Predsedništva SFRJ, I:. 4d29de3e1b
    -
    -
    -

    diff --git a/spaces/lindeberg/whisper-webui/app-local.py b/spaces/lindeberg/whisper-webui/app-local.py deleted file mode 100644 index d8eabbc62924dab3d0cc03a8a2373ffffe01eadc..0000000000000000000000000000000000000000 --- a/spaces/lindeberg/whisper-webui/app-local.py +++ /dev/null @@ -1,3 +0,0 @@ -# Run the app with no audio file restrictions -from app import create_ui -create_ui(-1) \ No newline at end of file diff --git a/spaces/ma-xu/LIVE/thrust/thrust/detail/config/cpp_dialect.h b/spaces/ma-xu/LIVE/thrust/thrust/detail/config/cpp_dialect.h deleted file mode 100644 index 5b7ecc2ebe1f3c525c08bc0691e82d5650f29423..0000000000000000000000000000000000000000 --- a/spaces/ma-xu/LIVE/thrust/thrust/detail/config/cpp_dialect.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2020 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. - */ - -/*! \file cpp_dialect.h - * \brief Detect the version of the C++ standard used by the compiler. - */ - -#pragma once - -#include - -// Deprecation warnings may be silenced by defining the following macros. These -// may be combined. -// - THRUST_IGNORE_DEPRECATED_CPP_DIALECT: -// Ignore all deprecated C++ dialects and outdated compilers. -// - THRUST_IGNORE_DEPRECATED_CPP_11: -// Ignore deprecation warnings when compiling with C++11. C++03 and outdated -// compilers will still issue warnings. -// - THRUST_IGNORE_DEPRECATED_COMPILER -// Ignore deprecation warnings when using deprecated compilers. Compiling -// with C++03 and C++11 will still issue warnings. - -// Check for the CUB opt-outs as well: -#if !defined(THRUST_IGNORE_DEPRECATED_CPP_DIALECT) && \ - defined(CUB_IGNORE_DEPRECATED_CPP_DIALECT) -# define THRUST_IGNORE_DEPRECATED_CPP_DIALECT -#endif -#if !defined(THRUST_IGNORE_DEPRECATED_CPP_11) && \ - defined(CUB_IGNORE_DEPRECATED_CPP_11) -# define THRUST_IGNORE_DEPRECATED_CPP_11 -#endif -#if !defined(THRUST_IGNORE_DEPRECATED_COMPILER) && \ - defined(CUB_IGNORE_DEPRECATED_COMPILER) -# define THRUST_IGNORE_DEPRECATED_COMPILER -#endif - -#ifdef THRUST_IGNORE_DEPRECATED_CPP_DIALECT -# define THRUST_IGNORE_DEPRECATED_CPP_11 -# define THRUST_IGNORE_DEPRECATED_COMPILER -#endif - -// Define this to override the built-in detection. -#ifndef THRUST_CPP_DIALECT - -// MSVC does not define __cplusplus correctly. _MSVC_LANG is used instead. -// This macro is only defined in MSVC 2015U3+. -# ifdef _MSVC_LANG // Do not replace with THRUST_HOST_COMPILER test (see above) -// MSVC2015 reports C++14 but lacks extended constexpr support. Treat as C++11. -# if THRUST_MSVC_VERSION < 1910 && _MSVC_LANG > 201103L /* MSVC < 2017 && CPP > 2011 */ -# define THRUST_CPLUSPLUS 201103L /* Fix to 2011 */ -# else -# define THRUST_CPLUSPLUS _MSVC_LANG /* We'll trust this for now. */ -# endif // MSVC 2015 C++14 fix -# else -# define THRUST_CPLUSPLUS __cplusplus -# endif - -// Detect current dialect: -# if THRUST_CPLUSPLUS < 201103L -# define THRUST_CPP_DIALECT 2003 -# elif THRUST_CPLUSPLUS < 201402L -# define THRUST_CPP_DIALECT 2011 -# elif THRUST_CPLUSPLUS < 201703L -# define THRUST_CPP_DIALECT 2014 -# elif THRUST_CPLUSPLUS == 201703L -# define THRUST_CPP_DIALECT 2017 -# elif THRUST_CPLUSPLUS > 201703L // unknown, but is higher than 2017. -# define THRUST_CPP_DIALECT 2020 -# endif - -# undef THRUST_CPLUSPLUS // cleanup - -#endif // !THRUST_CPP_DIALECT - -// Define THRUST_COMPILER_DEPRECATION macro: -#if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC -# define THRUST_COMP_DEPR_IMPL(msg) \ - __pragma(message(__FILE__ ":" THRUST_COMP_DEPR_IMPL0(__LINE__) ": warning: " #msg)) -# define THRUST_COMP_DEPR_IMPL0(x) THRUST_COMP_DEPR_IMPL1(x) -# define THRUST_COMP_DEPR_IMPL1(x) #x -#else // clang / gcc: -# define THRUST_COMP_DEPR_IMPL(msg) THRUST_COMP_DEPR_IMPL0(GCC warning #msg) -# define THRUST_COMP_DEPR_IMPL0(expr) _Pragma(#expr) -# define THRUST_COMP_DEPR_IMPL1 /* intentionally blank */ -#endif - -#define THRUST_COMPILER_DEPRECATION(REQ, FIX) \ - THRUST_COMP_DEPR_IMPL(Thrust requires REQ. Please FIX. Define THRUST_IGNORE_DEPRECATED_CPP_DIALECT to suppress this message.) - -// Minimum required compiler checks: -#ifndef THRUST_IGNORE_DEPRECATED_COMPILER -# if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_GCC && THRUST_GCC_VERSION < 50000 - THRUST_COMPILER_DEPRECATION(GCC 5.0, upgrade your compiler); -# endif -# if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_CLANG && THRUST_CLANG_VERSION < 60000 - THRUST_COMPILER_DEPRECATION(Clang 6.0, upgrade your compiler); -# endif -# if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC && THRUST_MSVC_VERSION < 1910 - THRUST_COMPILER_DEPRECATION(MSVC 2017, upgrade your compiler); -# endif -#endif - -#if !defined(THRUST_IGNORE_DEPRECATED_CPP_DIALECT) && THRUST_CPP_DIALECT < 2014 && \ - (THRUST_CPP_DIALECT != 2011 || !defined(THRUST_IGNORE_DEPRECATED_CPP_11)) - THRUST_COMPILER_DEPRECATION(C++14, pass -std=c++14 to your compiler); -#endif - -#undef THRUST_COMPILER_DEPRECATION -#undef THRUST_COMP_DEPR_IMPL -#undef THRUST_COMP_DEPR_IMPL0 -#undef THRUST_COMP_DEPR_IMPL1 diff --git a/spaces/manavisrani07/gradio-lipsync-wav2lip/face_detection/detection/sfd/detect.py b/spaces/manavisrani07/gradio-lipsync-wav2lip/face_detection/detection/sfd/detect.py deleted file mode 100644 index 4e1cd814603a3d722c2f544d611850f92d4827b5..0000000000000000000000000000000000000000 --- a/spaces/manavisrani07/gradio-lipsync-wav2lip/face_detection/detection/sfd/detect.py +++ /dev/null @@ -1,112 +0,0 @@ -import torch -import torch.nn.functional as F - -import os -import sys -import cv2 -import random -import datetime -import math -import argparse -import numpy as np - -import scipy.io as sio -import zipfile -from .net_s3fd import s3fd -from .bbox import * - - -def detect(net, img, device): - img = img - np.array([104, 117, 123]) - img = img.transpose(2, 0, 1) - img = img.reshape((1,) + img.shape) - - if 'cuda' in device: - torch.backends.cudnn.benchmark = True - - img = torch.from_numpy(img.copy()).to(device, dtype=torch.float32) - BB, CC, HH, WW = img.size() - with torch.no_grad(): - olist = net(img) - - bboxlist = [] - for i in range(len(olist) // 2): - olist[i * 2] = F.softmax(olist[i * 2], dim=1) - olist = [oelem.data.cpu() for oelem in olist] - for i in range(len(olist) // 2): - ocls, oreg = olist[i * 2], olist[i * 2 + 1] - FB, FC, FH, FW = ocls.size() # feature map size - stride = 2**(i + 2) # 4,8,16,32,64,128 - anchor = stride * 4 - poss = zip(*np.where(ocls[:, 1, :, :] > 0.05)) - for Iindex, hindex, windex in poss: - axc, ayc = stride / 2 + windex * stride, stride / 2 + hindex * stride - score = ocls[0, 1, hindex, windex] - loc = oreg[0, :, hindex, windex].contiguous().view(1, 4) - priors = torch.Tensor([[axc / 1.0, ayc / 1.0, stride * 4 / 1.0, stride * 4 / 1.0]]) - variances = [0.1, 0.2] - box = decode(loc, priors, variances) - x1, y1, x2, y2 = box[0] * 1.0 - # cv2.rectangle(imgshow,(int(x1),int(y1)),(int(x2),int(y2)),(0,0,255),1) - bboxlist.append([x1, y1, x2, y2, score]) - bboxlist = np.array(bboxlist) - if 0 == len(bboxlist): - bboxlist = np.zeros((1, 5)) - - return bboxlist - -def batch_detect(net, imgs, device): - imgs = imgs - np.array([104, 117, 123]) - imgs = imgs.transpose(0, 3, 1, 2) - - if 'cuda' in device: - torch.backends.cudnn.benchmark = True - - imgs = torch.from_numpy(imgs.copy()).to(device, dtype=torch.float32) - BB, CC, HH, WW = imgs.size() - with torch.no_grad(): - olist = net(imgs) - - bboxlist = [] - for i in range(len(olist) // 2): - olist[i * 2] = F.softmax(olist[i * 2], dim=1) - olist = [oelem.data.cpu() for oelem in olist] - for i in range(len(olist) // 2): - ocls, oreg = olist[i * 2], olist[i * 2 + 1] - FB, FC, FH, FW = ocls.size() # feature map size - stride = 2**(i + 2) # 4,8,16,32,64,128 - anchor = stride * 4 - poss = zip(*np.where(ocls[:, 1, :, :] > 0.05)) - for Iindex, hindex, windex in poss: - axc, ayc = stride / 2 + windex * stride, stride / 2 + hindex * stride - score = ocls[:, 1, hindex, windex] - loc = oreg[:, :, hindex, windex].contiguous().view(BB, 1, 4) - priors = torch.Tensor([[axc / 1.0, ayc / 1.0, stride * 4 / 1.0, stride * 4 / 1.0]]).view(1, 1, 4) - variances = [0.1, 0.2] - box = batch_decode(loc, priors, variances) - box = box[:, 0] * 1.0 - # cv2.rectangle(imgshow,(int(x1),int(y1)),(int(x2),int(y2)),(0,0,255),1) - bboxlist.append(torch.cat([box, score.unsqueeze(1)], 1).cpu().numpy()) - bboxlist = np.array(bboxlist) - if 0 == len(bboxlist): - bboxlist = np.zeros((1, BB, 5)) - - return bboxlist - -def flip_detect(net, img, device): - img = cv2.flip(img, 1) - b = detect(net, img, device) - - bboxlist = np.zeros(b.shape) - bboxlist[:, 0] = img.shape[1] - b[:, 2] - bboxlist[:, 1] = b[:, 1] - bboxlist[:, 2] = img.shape[1] - b[:, 0] - bboxlist[:, 3] = b[:, 3] - bboxlist[:, 4] = b[:, 4] - return bboxlist - - -def pts_to_bb(pts): - min_x, min_y = np.min(pts, axis=0) - max_x, max_y = np.max(pts, axis=0) - return np.array([min_x, min_y, max_x, max_y]) diff --git a/spaces/manishjaiswal/02-Gradio-Art-From-Text-And-Images-Demo/README.md b/spaces/manishjaiswal/02-Gradio-Art-From-Text-And-Images-Demo/README.md deleted file mode 100644 index 268baff976bf1fdce1ce2df32b8f081486746941..0000000000000000000000000000000000000000 --- a/spaces/manishjaiswal/02-Gradio-Art-From-Text-And-Images-Demo/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: 02 Gradio Art From Text And Images Demo -emoji: 🐨 -colorFrom: indigo -colorTo: purple -sdk: gradio -sdk_version: 3.3.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/mascIT/AgeGuesser/yolov5/utils/plots.py b/spaces/mascIT/AgeGuesser/yolov5/utils/plots.py deleted file mode 100644 index 428df45db6e99830300f5084e7e236d41b05bf82..0000000000000000000000000000000000000000 --- a/spaces/mascIT/AgeGuesser/yolov5/utils/plots.py +++ /dev/null @@ -1,129 +0,0 @@ -# YOLOv5 🚀 by Ultralytics, GPL-3.0 license -""" -Plotting utils -""" - -import os -from pathlib import Path - -import cv2 - -import numpy as np -import torch -from PIL import Image, ImageDraw, ImageFont - -from .general import (LOGGER, clip_coords, increment_path, is_ascii, is_chinese, - user_config_dir, xywh2xyxy, xyxy2xywh) - -# Settings -CONFIG_DIR = user_config_dir() # Ultralytics settings dir -RANK = int(os.getenv('RANK', -1)) - - - -class Colors: - # Ultralytics color palette https://ultralytics.com/ - def __init__(self): - # hex = matplotlib.colors.TABLEAU_COLORS.values() - hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB', - '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7') - self.palette = [self.hex2rgb('#' + c) for c in hex] - self.n = len(self.palette) - - def __call__(self, i, bgr=False): - c = self.palette[int(i) % self.n] - return (c[2], c[1], c[0]) if bgr else c - - @staticmethod - def hex2rgb(h): # rgb order (PIL) - return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4)) - - -colors = Colors() # create instance for 'from utils.plots import colors' - - -def check_font(font='Arial.ttf', size=10): - # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary - font = Path(font) - font = font if font.exists() else (CONFIG_DIR / font.name) - try: - return ImageFont.truetype(str(font) if font.exists() else font.name, size) - except Exception as e: # download if missing - url = "https://ultralytics.com/assets/" + font.name - LOGGER.info(f'Downloading {url} to {font}...') - torch.hub.download_url_to_file(url, str(font), progress=False) - try: - return ImageFont.truetype(str(font), size) - except TypeError: - pass - -class Annotator: - if RANK in (-1, 0): - check_font() # download TTF if necessary - - # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations - def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'): - assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.' - self.pil = pil or not is_ascii(example) or is_chinese(example) - if self.pil: # use PIL - self.im = im if isinstance(im, Image.Image) else Image.fromarray(im) - self.draw = ImageDraw.Draw(self.im) - self.font = check_font(font='Arial.Unicode.ttf' if is_chinese(example) else font, - size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)) - else: # use cv2 - self.im = im - self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width - - def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)): - # Add one xyxy box to image with label - if self.pil or not is_ascii(label): - self.draw.rectangle(box, width=self.lw, outline=color) # box - if label: - w, h = self.font.getsize(label) # text width, height - outside = box[1] - h >= 0 # label fits outside box - self.draw.rectangle([box[0], - box[1] - h if outside else box[1], - box[0] + w + 1, - box[1] + 1 if outside else box[1] + h + 1], fill=color) - # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls') # for PIL>8.0 - self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font) - else: # cv2 - p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3])) - cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA) - if label: - tf = max(self.lw - 1, 1) # font thickness - w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0] # text width, height - outside = p1[1] - h - 3 >= 0 # label fits outside box - p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3 - cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA) # filled - cv2.putText(self.im, label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), 0, self.lw / 3, txt_color, - thickness=tf, lineType=cv2.LINE_AA) - - def rectangle(self, xy, fill=None, outline=None, width=1): - # Add rectangle to image (PIL-only) - self.draw.rectangle(xy, fill, outline, width) - - def text(self, xy, text, txt_color=(255, 255, 255)): - # Add text to image (PIL-only) - w, h = self.font.getsize(text) # text width, height - self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font) - - def result(self): - # Return annotated image as array - return np.asarray(self.im) - - -def save_one_box(xyxy, im, file='image.jpg', gain=1.02, pad=10, square=False, BGR=False, save=True): - # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop - xyxy = torch.tensor(xyxy).view(-1, 4) - b = xyxy2xywh(xyxy) # boxes - if square: - b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square - b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad - xyxy = xywh2xyxy(b).long() - clip_coords(xyxy, im.shape) - crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)] - if save: - file.parent.mkdir(parents=True, exist_ok=True) # make directory - cv2.imwrite(str(increment_path(file).with_suffix('.jpg')), crop) - return crop diff --git a/spaces/matthoffner/AudioCraft_Plus/audiocraft/grids/compression/encodec_audiogen_16khz.py b/spaces/matthoffner/AudioCraft_Plus/audiocraft/grids/compression/encodec_audiogen_16khz.py deleted file mode 100644 index c9b41f684045594bb264cfb7f4f15d1da439382c..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/AudioCraft_Plus/audiocraft/grids/compression/encodec_audiogen_16khz.py +++ /dev/null @@ -1,29 +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. - -""" -Grid search file, simply list all the exp you want in `explorer`. -Any new exp added there will be scheduled. -You can cancel and experiment by commenting its line. - -This grid shows how to train the new AudioGen EnCodec model at 16 kHz. -""" - -from ._explorers import CompressionExplorer -from ...environment import AudioCraftEnvironment - - -@CompressionExplorer -def explorer(launcher): - partitions = AudioCraftEnvironment.get_slurm_partitions(['team', 'global']) - launcher.slurm_(gpus=8, partition=partitions) - # use configuration for AudioGen's EnCodec model trained on monophonic audio sampled at 16 kHz - # AudioGen's EnCodec is trained with a total stride of 320 leading to a frame rate of 50 hz - launcher.bind_(solver='compression/encodec_audiogen_16khz') - # replace this by the desired sound dataset - launcher.bind_(dset='internal/sounds_16khz') - # launch xp - launcher() diff --git a/spaces/matthoffner/AudioCraft_Plus/scripts/__init__.py b/spaces/matthoffner/AudioCraft_Plus/scripts/__init__.py deleted file mode 100644 index 0952fcc3f57e34b3747962e9ebd6fc57aeea63fa..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/AudioCraft_Plus/scripts/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. diff --git a/spaces/matthoffner/chatbot/types/plugin.ts b/spaces/matthoffner/chatbot/types/plugin.ts deleted file mode 100644 index 43da6c07b0f5c6ee022225babe72cb58ff0939f4..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/chatbot/types/plugin.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { KeyValuePair } from './data'; - -export interface Plugin { - id: PluginID; - name: PluginName; - requiredKeys: KeyValuePair[]; -} - -export interface PluginKey { - pluginId: PluginID; - requiredKeys: KeyValuePair[]; -} - -export enum PluginID { - GOOGLE_SEARCH = 'google-search', -} - -export enum PluginName { - GOOGLE_SEARCH = 'Google Search', -} - -export const Plugins: Record = { - [PluginID.GOOGLE_SEARCH]: { - id: PluginID.GOOGLE_SEARCH, - name: PluginName.GOOGLE_SEARCH, - requiredKeys: [ - { - key: 'GOOGLE_API_KEY', - value: '', - }, - { - key: 'GOOGLE_CSE_ID', - value: '', - }, - ], - }, -}; - -export const PluginList = Object.values(Plugins); diff --git a/spaces/mayordp/DeepFakeAI/DeepFakeAI/uis/__init__.py b/spaces/mayordp/DeepFakeAI/DeepFakeAI/uis/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/mdj1412/stock_news_summaries_AI/README.md b/spaces/mdj1412/stock_news_summaries_AI/README.md deleted file mode 100644 index 5d1f49ca16ce4e467b680b155c7858a6d61b60a8..0000000000000000000000000000000000000000 --- a/spaces/mdj1412/stock_news_summaries_AI/README.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Stock News Summaries AI -emoji: 👁 -colorFrom: blue -colorTo: red -sdk: gradio -sdk_version: 3.17.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference - - - -# Stock News Analysis - -This project uses Natural Language Processing (NLP) techniques and machine learning models to analyze stock news, extract valuable insights, and provide visualizations to help users make informed investment decisions. - -## Features -1. Named Entity Recognition (NER) - This feature identifies and extracts important entities such as company names, people, and locations from news articles to help users stay up-to-date with the latest news related to their investments. -2. Tk-instruct Model - This feature allows users to ask questions about the stock market and receive answers in a conversational format. The Tk-instruct model uses machine learning algorithms to understand natural language queries and provides relevant information to the user. -3. Stock Chart Visualization - This feature provides users with an interactive chart that visualizes the historical performance of a stock. Users can customize the time frame and chart settings to view the information that is most relevant to them. -4. News Crawler - This feature enables users to keep track of the latest news related to their investments. The news crawler regularly scans news websites and automatically extracts articles that mention specific companies or industries. - - -## Installation -1. Clone the repository - ```console - git clone https://github.com/mdj1412/Stock_News_Analysis.git - ``` -2. Install the required packages - ```console - pip install -r requirements.txt - ``` -3. Run the application - ```console - python app.py - ``` - - -## Dependency -* pandas -* beautifulsoup4 -* Flask -* torch -* transformers -* accelerate -* bitsandbytes -* spacy -* yfinance - - -## Demo -* You can check a little faster through the demo [here](https://huggingface.co/spaces/mdj1412/stock_news_summaries_AI). - - -## License -This project is licensed under the MIT [License]() file for details. - - diff --git a/spaces/meet244/Legal-Up_Lawyer_Recommendation_System/app.py b/spaces/meet244/Legal-Up_Lawyer_Recommendation_System/app.py deleted file mode 100644 index 05016e0fe93f9887ebabd0e9a63defe8090281f9..0000000000000000000000000000000000000000 --- a/spaces/meet244/Legal-Up_Lawyer_Recommendation_System/app.py +++ /dev/null @@ -1,99 +0,0 @@ -import gradio as gr -import joblib - - -def findCase(query:list[str]) -> str: - new_sentences = query - # new_sentences = [sentence.lower().replace('[^\w\s]', '') for sentence in new_sentences] - - case_pipe = joblib.load("case.joblib") - - predictions = case_pipe.predict_proba(new_sentences) - - # print("Predictions for new sentences:") - for sentence, prob in zip(new_sentences, predictions): - # max_one = "" - # max_score = 0.0 - top_values = [] - labels = case_pipe.named_steps['model'].classes_ - for label, probability in zip(labels, prob): - - # if(max_score min_value: - min_index = tops.index(min_value) - top_values[min_index] = [round(probability, 4), label] - - # print("----------------------------------------") - # print(sentence) - # print("----------------------------------------") - if(len(top_values) == 0):return "" - resp = "" - for t in top_values: - # print(t) - if(resp!=''):resp+=', ' - resp+=t[1] - # print(f"{t[1]} - {round(100 * t[0], 2)}") - return resp - -def findClient(query:list[str])->str: - client_pipe = joblib.load("client.joblib") - pred = client_pipe.predict(query) - return pred[0] - -def greet(query): - query = [sentence.lower().replace('[^\w\s]', '') for sentence in [query]] - return findCase(query),findClient(query) - - -def build_gui(): - - description = """ -
    - Legal Up Model -
    -
    -

    Welcome to the Legal Up demo!

    - -

    - Legal Up recommends suitable lawyers to clients based on concise case descriptions using advanced algorithms, ensuring clients find the right legal expertise. -

    -

    Great thanks to Meet Patel, the major contributor of this - demo! -

    - """ # noqa - - article = """ -

    - Case and Client are trained on private datasets, and we are persisting in refining and iterating upon it.
    - Legal Up: Lawyer Recommendation System -

    - """ # noqa - with gr.Blocks(title="Legal Up Model") as demo: - gr.HTML(description) - gr.Interface( - fn=greet, - inputs=gr.Textbox(label="Legal Case"), - outputs=[gr.Textbox(label="Case Type"),gr.Textbox(label="Client Type")], - examples=[ - ["I'm a landscaper, and a customer is suing me for negligence after their property was damaged by a tree that I planted. I'm worried about the cost of defending the lawsuit, even if I win."], - ["A customer is alleging that they were injured by one of our products. We are strongly denying liability, but we are deeply concerned about the damage this could do to our reputation."], - ["I am a filmmaker and I am working on a new movie. I want to make sure that I do not infringe on any copyrights in my film. Can you help me review my script and identify any potential copyright issues?","I am a US citizen who is married to a foreign national. My spouse wants to immigrate to the United States. Can you help me file a petition for my spouse and assist them with the immigration process?","I was recently injured in a medical malpractice incident. I am considering filing a lawsuit against the doctor or hospital. Can you help me assess the strength of my case and advise me on how to proceed?"] - ], - cache_examples=True, - allow_flagging='never' - ) - gr.HTML(article) - return demo - -if __name__ == "__main__": - build_gui().launch() diff --git a/spaces/mehdidc/text_to_image_ddgan/scripts/run_jurecadc_ddp.sh b/spaces/mehdidc/text_to_image_ddgan/scripts/run_jurecadc_ddp.sh deleted file mode 100644 index bda57f59ae31d5a86148faa3ccc96dfaf2af7ff5..0000000000000000000000000000000000000000 --- a/spaces/mehdidc/text_to_image_ddgan/scripts/run_jurecadc_ddp.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/bash -x -#SBATCH --account=zam -#SBATCH --nodes=1 -#SBATCH --ntasks-per-node=4 -#SBATCH --cpus-per-task=24 -#SBATCH --time=06:00:00 -#SBATCH --gres=gpu:4 -#SBATCH --partition=dc-gpu -source set_torch_distributed_vars.sh -#source scripts/init_2022.sh -#source scripts/init_2020.sh -source scripts/init.sh -export CUDA_VISIBLE_DEVICES=0,1,2,3 -echo "Job id: $SLURM_JOB_ID" -export TOKENIZERS_PARALLELISM=false -#export NCCL_ASYNC_ERROR_HANDLING=1 -export NCCL_IB_TIMEOUT=50 -export UCX_RC_TIMEOUT=4s -export NCCL_IB_RETRY_CNT=10 -export TRANSFORMERS_CACHE=cache -srun python -u $* diff --git a/spaces/merve/anonymization/source/measuring-fairness/slides.js b/spaces/merve/anonymization/source/measuring-fairness/slides.js deleted file mode 100644 index a66a04c7c483fee37424c6e9182e565a673a7aca..0000000000000000000000000000000000000000 --- a/spaces/merve/anonymization/source/measuring-fairness/slides.js +++ /dev/null @@ -1,102 +0,0 @@ -/* Copyright 2020 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. -==============================================================================*/ - - - - -window.makeSlides = function(){ - var slides = [ - { - textFill: '#aaa', - textStroke: 0, - rectFill: d => d.isSick ? lcolors.sick : lcolors.well, - rectOpacity: d => 0, - threshold: .8, - fpAxisOpacity: 0, - sexAxisOpacity: 0, - brAxisOpacity: 0, - truthAxisOpacity: 0, - mlAxisOpacity: 0, - pos: 'all', - botAxisY: c.width + 80, - }, - - { - textFill: d => d.isSick ? colors.sick : colors.well, - truthAxisOpacity: 1, - }, - - { - rectOpacity: d => 1, - mlAxisOpacity: 1, - - }, - - { - rectFill: d => d.grade > gs.curSlide.threshold ? lcolors.sick : lcolors.well, - textStroke: d => d.grade > gs.curSlide.threshold == d.isSick ? 0 : .6, - fpAxisOpacity: 1, - }, - - { - threshold: .61, - animateThreshold: true, - }, - - { - threshold: .89, - animateThreshold: true, - }, - - { - pos: 'sex', - fpAxisOpacity: 0, - sexAxisOpacity: 1, - threshold: .7508, - animateThreshold: false, - botAxisY: c.width + 150, - - }, - - { - brAxisOpacity: 1, - sexAxisOpacity: 0, - - }, - - { - - } - - ] - - var keys = [] - slides.forEach(d => keys = keys.concat(d3.keys(d))) - _.uniq(keys).forEach(str => { - var prev = null - slides.forEach(d => { - if (typeof(d[str]) === 'undefined'){ - d[str] = prev - } - prev = d[str] - }) - }) - - return slides -} - - - -if (window.init) window.init() diff --git a/spaces/merve/data-leak/server-side/fill-in-the-blank/scatter-plot-colab/two-sentences/init-util.js b/spaces/merve/data-leak/server-side/fill-in-the-blank/scatter-plot-colab/two-sentences/init-util.js deleted file mode 100644 index 90927e1e1ab40c05fc3ee46b69e7e400b1f9a86a..0000000000000000000000000000000000000000 --- a/spaces/merve/data-leak/server-side/fill-in-the-blank/scatter-plot-colab/two-sentences/init-util.js +++ /dev/null @@ -1,105 +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. -==============================================================================*/ - - -window.initUtil = function(){ - function palette(min, max){ - // https://blocks.roadtolarissa.com/1wheel/raw/94091c1f8a69d5966e48aef4ac19baf9/index.html?colors=00006e-006a78-00a963-8a8a8a-d5882a-a15142-7f0000&numTicks=255&space=lab&type=basis - var colors = ['#00006e', '#00006e', '#00006f', '#00006f', '#00006f', '#000070', '#000070', '#000170', '#000471', '#000871', '#000b71', '#000f72', '#001272', '#001572', '#001872', '#001b73', '#001e73', '#002173', '#002473', '#002674', '#002974', '#002c74', '#002e74', '#003174', '#003375', '#003675', '#003975', '#003b75', '#003e75', '#004075', '#004375', '#004575', '#004775', '#004a75', '#004c75', '#004f75', '#005175', '#005375', '#005675', '#005875', '#005a75', '#005c75', '#005e75', '#006175', '#006375', '#006574', '#006774', '#006974', '#006b74', '#006d74', '#006f73', '#007173', '#007373', '#007473', '#007672', '#007872', '#007a72', '#007b72', '#007d71', '#007f71', '#008071', '#008270', '#008370', '#008570', '#008670', '#00886f', '#00896f', '#008a6f', '#008c6f', '#008d6e', '#008e6e', '#008f6e', '#00906e', '#00916e', '#00926d', '#00936d', '#00946d', '#00956d', '#00966d', '#00976d', '#00976d', '#00986d', '#00996d', '#00996d', '#009a6d', '#009a6e', '#009b6e', '#009b6e', '#009b6e', '#079c6f', '#119c6f', '#189c6f', '#1e9c70', '#249c70', '#289c70', '#2d9c71', '#319c71', '#359c71', '#399c72', '#3c9c72', '#409c73', '#439c73', '#479b74', '#4a9b74', '#4d9b74', '#509b75', '#539a75', '#569a76', '#599976', '#5c9976', '#5f9976', '#629877', '#659877', '#679777', '#6a9777', '#6d9677', '#6f9678', '#729578', '#749578', '#779478', '#799477', '#7c9377', '#7e9377', '#819277', '#839277', '#859176', '#889176', '#8a9175', '#8c9075', '#8e9074', '#908f73', '#938f73', '#958e72', '#978e71', '#998e70', '#9b8d6f', '#9d8d6e', '#9f8d6d', '#a08c6c', '#a28c6b', '#a48c69', '#a68b68', '#a88b67', '#a98b65', '#ab8a64', '#ac8a63', '#ae8a61', '#af8960', '#b1895f', '#b2895d', '#b4885c', '#b5885a', '#b68859', '#b78757', '#b88756', '#b98755', '#ba8653', '#bb8652', '#bc8550', '#bd854f', '#be854d', '#bf844c', '#bf844b', '#c0834a', '#c08348', '#c18247', '#c18246', '#c28145', '#c28044', '#c28043', '#c27f42', '#c27e41', '#c37e40', '#c27d3f', '#c27c3f', '#c27b3e', '#c27a3d', '#c27a3d', '#c1793c', '#c1783c', '#c1773c', '#c0763b', '#c0753b', '#bf743a', '#bf733a', '#be713a', '#bd703a', '#bd6f39', '#bc6e39', '#bb6d39', '#bb6b38', '#ba6a38', '#b96938', '#b86737', '#b76637', '#b76537', '#b66336', '#b56236', '#b46035', '#b35e35', '#b25d34', '#b15b34', '#b05933', '#af5833', '#ae5632', '#ad5431', '#ad5230', '#ac502f', '#ab4e2f', '#aa4c2e', '#a94a2c', '#a8482b', '#a7462a', '#a64429', '#a54127', '#a43f26', '#a33d24', '#a33a23', '#a23721', '#a1351f', '#a0321e', '#9f2f1c', '#9e2c1a', '#9d2818', '#9c2516', '#9c2114', '#9b1d11', '#9a180f', '#99120d', '#980b0a', '#970207', '#960004', '#950001', '#940000', '#930000', '#920000', '#910000', '#900000', '#8f0000', '#8e0000', '#8e0000', '#8d0000', '#8c0000', '#8b0000', '#8a0000', '#890000', '#880000', '#870000', '#860000', '#850000', '#840000', '#830000', '#820000', '#810000', '#800000'] - - return v => { - var i = d3.clamp(0, (v - min)/(max - min), 1) - return colors[Math.round(i*(colors.length - 1))] - } - } - - var util = { - palette, - color: d3.interpolateSpectral, - color: palette(0, 1), - } - - util.colors = [1 - .25, .25].map(util.color) - - util.updateSentenceLabels = pair => { - var t0 = tokenizer.tokenize(pair.s0) - var t1 = tokenizer.tokenize(pair.s1) - - var i = 0 - while (t0[i] == t1[i] && i < t0.length) i++ - - var j = 1 - while (t0[t0.length - j] == t1[t1.length - j] && j < t0.length) j++ - - pair.label0 = tokens2origStr(t0, pair.s0) - pair.label1 = tokens2origStr(t1, pair.s1) - - function tokens2origStr(t, s){ - var tokenStr = tokenizer.decode(t.slice(i, -j + 1)).trim() - var lowerStr = s.toLowerCase() - - var startI = lowerStr.indexOf(tokenStr) - return s.slice(startI, startI + tokenStr.length) - } - - if ( - !pair.label0.length || - !pair.label1.length || - pair.label0.length > 15 || - pair.label1.length > 15){ - pair.label0 = '' - pair.label1 = '' - } - - // console.log(i, j, pair.label0, pair.label1) - } - - util.addAxisLabel = (c, xText, yText, xOffset=37, yOffset=-35) => { - c.svg.select('.x').append('g') - .translate([c.width/2, xOffset]) - .append('text.axis-label') - .text(xText) - .at({textAnchor: 'middle'}) - .st({fill: '#000'}) - - c.svg.select('.y') - .append('g') - .translate([yOffset, c.height/2]) - .append('text.axis-label') - .text(yText) - .at({textAnchor: 'middle', transform: 'rotate(-90)'}) - .st({fill: '#000'}) - } - - util.ggPlotBg = (c) => { - c.svg.append('rect') - .at({width: c.width, height: c.height, fill: '#eee'}) - .lower() - - c.svg.selectAll('.tick').selectAll('line').remove() - c.svg.selectAll('.y .tick') - .append('path').at({d: 'M 0 0 H ' + c.width, stroke: '#fff', strokeWidth: 1}) - c.svg.selectAll('.y text').at({x: -3}) - c.svg.selectAll('.x .tick') - .append('path').at({d: 'M 0 0 V -' + c.height, stroke: '#fff', strokeWidth: 1}) - } - - util.corrFmt = d => (d3.format('+.2f')(d)).replace('0.', '.') - - return util -} - -if (window.init) window.init() - diff --git a/spaces/merve/dataset-worldviews/public/anonymization/style.css b/spaces/merve/dataset-worldviews/public/anonymization/style.css deleted file mode 100644 index c20c6ed13484b78e2cc2128cd255f4d3b4cda152..0000000000000000000000000000000000000000 --- a/spaces/merve/dataset-worldviews/public/anonymization/style.css +++ /dev/null @@ -1,344 +0,0 @@ - -.tooltip { - top: -1000px; - position: fixed; - padding: 10px; - background: rgba(255, 255, 255, .90); - border: 1px solid lightgray; - pointer-events: none; - font-size: 14px; - width: 267px; -} -.tooltip-hidden{ - opacity: 0; - transition: all .3s; - transition-delay: .1s; -} - -@media (max-width: 590px){ - div.tooltip{ - bottom: -1px; - width: calc(100%); - left: -1px !important; - right: -1px !important; - top: auto !important; - width: auto !important; - } -} - - -.domain{ - display: none; -} - -text{ - /*pointer-events: none;*/ - /*text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;*/ -} - - - -.note{ - font-size: 12px; - color: #999; - margin-top: 60px; -} - -h1{ - font-weight: 100; - font-size: 34px; - margin-bottom: .5em; - line-height: 1.3em; - margin-top: 1.4em; - text-align: center; - font-family: "Google Sans", sans-serif; -} - -.mono{ - font-family: monospace; -} - - -svg{ - overflow: visible; -} - - - - -.axis{ - font-size: 12px; - pointer-events: none; -} -.axis{ - color: #888; - -} -.axis text, .slider-label-container{ - fill: #888; - color: #888; - font-family: 'Roboto', Helvetica, sans-serif; - font-size: 12px; -} - -.axis text.bold, .slider-label-container{ - color: #3C4043; - fill: #3C4043; - font-weight: 500; - -} -.axis line{ - stroke: #ccc; -} - -div.axis b{ - margin-bottom: -10px; - display: block; -} - -.init-hidden{ - opacity: 0; -} - -.slider-label-container{ - font-weight: 500; -} - - - -.highlight{ - color: #fff; - padding-left: 3px; - padding-right: 3px; - padding-top: 1px; - padding-bottom: 1px; - border-radius: 3px; -} - -.highlight.blue{ background: blue; } -.highlight.orange{ background: #ffd890; } -.highlight.yellow{ background: #ff0; color: #000; } -.highlight.purple{ background: #CB10CB; } -.highlight.purple{ background: #FF7AFF; color: #000;} -.highlight.grey{ background: #ccc; color: #000;} -.highlight.box{ - border: 1px solid #ff6200; - border-radius: 5px; - color: #000; - padding-bottom: 2px; - white-space: nowrap; -} -.highlight.purple-box{ - border: 1px solid #b0b; -} -.highlight.grey-box{ - border: 1px solid #ccc; -} -.highlight.box.square{ - border-radius: 0px; -} -.highlight.blue-box{ border: 2px solid #007276; } - - - -.circle{ - background: #eee; - border: 1px solid #ccc; - font-family: monospace; - padding-left: 4px; - padding-right: 4px; - padding-top: 1px; - padding-bottom: 1px; - - border-radius: 100px; -} - - -.strikethrough{ - text-decoration: line-through; - color: #000; -} - - -.annotations path{ - fill: none; - stroke: black; -} - - - -rect.unique{ - stroke: #ff6200; - stroke-width: 1px; - fill: #ffd890; - - animation-duration: 1s; - animation-name: xstrokeblink; - display: inline-block; - animation-iteration-count: infinite; - animation-direction: alternate; -} - - -@keyframes strokeblink { - from { - /*fill: black;*/ - stroke-width: 1px; - } - - to { - /*fill: green;*/ - stroke-width: 1px; - } -} - - - - - -.inline-line{ - border: 1px #f0f solid; - width: 20px; - display: inline-block; - position: relative; - top: -5px; -} - -.slider-label-container{ - width: 240px; -} -.slider-label{ - font-size: smaller; - margin-left: 2px; -} - -.slider-text-label{ - margin-left: 5px; - white-space: nowrap; -} - - -g.student:hover circle{ - stroke-width: 2px; -} - -g{ - /*opacity: 1 !important;*/ -} - -.inactive{ - opacity: 0 !important; - pointer-events: none; -} - -input[type="range" i] { - background-color:#def5ef; - -webkit-appearance: none; - height:20px; - width:240px; - overflow: hidden; -} - -input[type='range']::-webkit-slider-thumb { - -webkit-appearance: none; - width: 16px; - height: 20px; - cursor: ew-resize; - background: #007276; - box-shadow: -200px 0 0 200px #7ed3c9; - border: 1px solid #333; -} - -input:focus { - outline-width: 0; -} - - - - -.estimate{ - opacity: 0; - pointer-events: none -} - -.estimate.active{ - opacity: .70; - pointer-events: all; -} - -.est-text{ - text-shadow: 0 2px 0 rgba(255,255,255,1), 2px 0 0 rgba(255,255,255,1), 0 -2px 0 rgba(255,255,255,1), -2px 0 0 rgba(255,255,255,1); -} - - - - -@media (max-width: 590px){ - text{ - font-size: 120% !important; - } -} - - -.slider{ - user-select: none; - -webkit-tap-highlight-color: transparent; -} - -.button-container{ - border: 1px solid #888; - display: inline-block; - padding: 10px 20px; - cursor: pointer; - text-align: center; - border-radius: 10px; - user-select: none; - -webkit-tap-highlight-color: transparent; - margin: 0px auto; -/* color: #888; - font-family: 'Roboto', Helvetica, sans-serif; - font-size: 12px; - font-weight: 500;*/ - position: relative; - left: -20px; -} - -.button-container:hover{ - background: #ddd; -} - -.button-outer{ - text-align: center; - margin-top: 20px; -} - -.pointer{ - height: 0px; - position: relative; -} -.pointer div { - overflow: visible; - content: ""; - background-image: url(https://pair-code.github.io/interpretability/bert-tree/pointer.svg); - width: 27px; - height: 27px; - position: absolute; - left: 165px; - top: -35px; -} - -a{ - color: rgb(60, 64, 67); -} -a:hover{ - color: #000; -} - - - - - - - - - diff --git a/spaces/merve/measuring-fairness/source/dataset-worldviews/shapes.js b/spaces/merve/measuring-fairness/source/dataset-worldviews/shapes.js deleted file mode 100644 index 87af55b4829a78b48dc41f6674c12cd58cfc3741..0000000000000000000000000000000000000000 --- a/spaces/merve/measuring-fairness/source/dataset-worldviews/shapes.js +++ /dev/null @@ -1,248 +0,0 @@ - -// Space out the shapes a bit -shapeParams.forEach((d) => (d.startX = d.startX * 1.1)); - -// How to draw the background boxes, which will be styled later -const classifierBgPathTop = "M 420 150 H 0 V 0 H 420 V 150"; -const classifierBgPathBottom = "M 420 300 H 0 V 0 H 420 V 300"; - -const toDropdownValueStringDict = { - shape_name: "circles, triangles, or rectangles", - pointiness: "pointy shapes or round shapes", - size: "small shapes or big shapes", -}; - -const toShortValueStringDict = { - shape_name: "circles, triangles, or rectangles", - pointiness: "pointy or round", - size: "small or big", -}; - -const toDropdownValueRoundingStringDict = { - true: "with our best guess", - false: 'as "other"', -}; - -const toPropertyStringDict = { - pointy: "pointy shapes", - round: "round shapes", - small: "small shapes", - large: "big shapes", - circle: "circles", - triangle: "triangles", - rect: "rectangles", -}; - -function toOriginalString(inputString) { - for (const [key, value] of Object.entries(toPropertyStringDict)) { - if (inputString == value) { - return key; - } - } -} - -function toPropertyString(inputProperty, isRounding = true) { - if (!isRounding && inputProperty.startsWith("rt_")) { - return "others"; - } - return toPropertyStringDict[inputProperty.replace("rt_", "")]; -} - -// Dictionary mapping div name to classifier results and summary sentences -var allResults = {}; -var summaries = {}; - -function toBool(inputString) { - if (inputString == "true") { - return true; - } - return false; -} -function updateResults() { - allResults["default-classifier"] = calculateResults(); - allResults["second-classifier"] = calculateResults( - "shape_name", - toBool( - document.getElementById("second-classifier-select-rounding").value - ) - ); - - allResults["final-classifier"] = calculateResults( - document.getElementById("final-classifier-select-category").value, - toBool( - document.getElementById("final-classifier-select-rounding").value - ) - ); - - allResults["conclusion"] = calculateResults( - document.getElementById("conclusion-select-category").value, - true - ); - - updateSummaries(); - updateSecondInterfaceImages(); -} - -// Text summaries are written by hand for simplicity, and keyed simply by -// a string of the form "[category]:[useGuess]" (or simply "none"). -// These are hashed in the same way as the results, by div name. -function updateSummaries() { - summaries["default-classifier"] = getPerformanceSummary("none"); - summaries["second-classifier"] = getPerformanceSummary( - "shape_name:" + - document.getElementById("second-classifier-select-rounding").value - ); - - summaries["final-classifier"] = getPerformanceSummary( - document.getElementById("final-classifier-select-category").value + - ":" + - document.getElementById("final-classifier-select-rounding").value - ); - - summaries["conclusion"] = getPerformanceSummary( - document.getElementById("conclusion-select-category").value + ":" + true - ); -} - -// Yes, these background colors are hardcoded in, -// no, this is not good design, this is just how it happened. -function getPerformanceSummary(key) { - allSummaries = { - "shape_name:true": - 'well on circles, terribly on triangles, and best on rectangles', - "shape_name:false": - 'poorly on circles, best on triangles and rectangles, and fine on other shapes', - "pointiness:true": - 'better on pointy shapes and worse on round shapes', - "pointiness:false": - 'best on pointy shapes, fine on round shapes, and poorly on other shapes', - "size:true": - 'better on small shapes, worse on big shapes', - "size:false": - 'poorly on small shapes, terribly on big shapes, and best on other shapes', - "none:true": - 'fine on all shapes', - "none:false": - 'fine on all shapes', - none: 'fine on all shapes', - }; - - return "The Is-Shaded Classifier performs " + allSummaries[key] + "."; -} - -// On the second-classifier dropdown, update the "task interface" image. -function updateSecondInterfaceImages() { - d3.select(".second-interface").html(function () { - if ( - !document.getElementById("second-classifier-select-rounding").value - ) { - return; - } - var imgPath = - "img/interface_shape_name_" + - document.getElementById("second-classifier-select-rounding").value; - return ( - '' - ); - }); -} - -// Calculate results given input parameters -function calculateResults(property = "none", useGuess = false) { - switch (property) { - case "none": - var nAccurate = shapeParams.filter( - (shape) => shape.correctness == "correct" - ).length; - var totalShapes = shapeParams.length; - - var results = [ - { - object: "shape", - n: totalShapes, - "n correct": nAccurate, - accuracy: (nAccurate / totalShapes).toFixed(3), - rawCategoryName: "none", - }, - ]; - - return results; - case "pointiness": - categories = ["pointy", "round"]; - break; - case "size": - categories = ["small", "large"]; - break; - case "shape_name": - categories = ["circle", "triangle", "rect"]; - break; - } - - var results = []; - if (useGuess == true) { - // Rounding shapes to categories - - for (const category of categories) { - // Get shapes that are either in this category (e.g. rectangle) or "rounds to" this category (e.g. rt_rectangle) - var theseShapes = shapeParams.filter( - (shape) => - shape[property] == category || - shape[property] == "rt_" + category - ); - var nAccurate = theseShapes.filter( - (shape) => shape.correctness == "correct" - ).length; - var totalShapes = theseShapes.length; - - results.push({ - object: toPropertyString(category), - n: totalShapes, - "n correct": nAccurate, - accuracy: (nAccurate / totalShapes).toFixed(3), - rawCategoryName: category, - }); - } - } else { - // Not rounding, treat everything else as "other" - - // First go through existing categories - for (const category of categories) { - var theseShapes = shapeParams.filter( - (shape) => shape[property] == category - ); - var nAccurate = theseShapes.filter( - (shape) => shape.correctness == "correct" - ).length; - var totalShapes = theseShapes.length; - results.push({ - object: toPropertyString(category), - n: totalShapes, - "n correct": nAccurate, - accuracy: (nAccurate / totalShapes).toFixed(3), - rawCategoryName: category, - }); - } - - // Now get "other" shapes - var theseShapes = shapeParams.filter( - (shape) => !categories.includes(shape[property]) - ); - var nAccurate = theseShapes.filter( - (shape) => shape.correctness == "correct" - ).length; - var totalShapes = theseShapes.length; - results.push({ - object: "other shapes", - n: totalShapes, - "n correct": nAccurate, - accuracy: (nAccurate / totalShapes).toFixed(3), - rawCategoryName: "other", - }); - } - - return results; -} diff --git a/spaces/merve/uncertainty-calibration/public/measuring-diversity/script.js b/spaces/merve/uncertainty-calibration/public/measuring-diversity/script.js deleted file mode 100644 index 002fb32c0d0ee11cf292109725ebda6a2a4b57a4..0000000000000000000000000000000000000000 --- a/spaces/merve/uncertainty-calibration/public/measuring-diversity/script.js +++ /dev/null @@ -1,360 +0,0 @@ -// Seeded random number generator -window.random = new Math.seedrandom('aaaa') -window.randomIndex = new Math.seedrandom('7b') - -window.numRows = 20 -window.shapes = window.shapes || d3.range(21).map(i => randomShape(i, random)) - -window.random2 = new Math.seedrandom('7') -// window.columnShapes = window.columnShapes || d3.range(window.numRows).map(i => d3.range(10).map(i =>randomShape(i, random2))) -window.columnShapes = d3.range(window.numRows).map(i => d3.range(10).map(i =>randomShape(i, random2, true))) - -console.log(window.random3) -function randomShape(i, random, colTargets){ - var color2fill = { - green: '#5A9F8A', - orange: '#DF831F', - blue: '#80BAD4', - } - - var randomItem = function(arr) { - const index = Math.abs(random.int32()) % arr.length - return arr[index] - } - - var color = randomItem(d3.keys(color2fill)) - var size = randomItem(['small', 'large']) - var shape = randomItem(['circle', 'square', 'triangle']) - - if (colTargets && (i == 4 || i == 5)){ - color = 'green' - } - if (colTargets && (i == 4 || i == 15)){ - size = 'small' - } - if (colTargets && (i == 3 || i == 5)){ - shape = 'triangle' - } - - var displayIndex = randomIndex() - - return { - i, - displayIndex, - color, - fill: color2fill[color], - dFill: d3.color(color2fill[color]).darker(1), - size, - sizeVal: size == 'large' ? 1 : .4, - shape, - } -} - -var metrics = [ - { - str: 'Greens', - key: 'green', - field: 'color', - target: .3 - }, - { - str: 'Dot', - key: 'triangle', - field: 'shape', - target: .35 - }, - { - str: 'Smalls', - key: 'small', - field: 'size', - target: .60 - }, -] -window.metrics1 = metrics.map(d => ({...d})) -metrics1[2].target = .5 -window.metrics2 = metrics1.map(d => ({...d})) -metrics2[0].target = 1 - -metrics.forEach(d => { - d.scoreScale = d3.scaleLinear().domain([0, d.target, 1]).range([0, 1, 0]) -}) - - -var pctFmt = d3.format('.0%') -function addMetrics(metrics, {active, topSel, isSmall}){ - var metricSel = topSel - .st({textAlign: 'center'}) - .appendMany('div', metrics) - .st({textAlign: 'center', width: 200, display: 'inline-block'}) - - var width = 120 - - var svg = metricSel.append('svg') - .at({width: 120, height: 100}) - .append('g') - .translate([.5, 40.5]) - - if (isSmall){ - svg.translate((d, i) => [i ? -20.5 : 20.5, 40.5]) - } - - - var xScale = d3.scaleLinear().rangeRound([0, width]) - - var topText = svg.append('text') - .at({y: -20, fontWeight: 500, textAnchor: 'middle', x: width/2}) - - svg.append('path') - .at({d: 'M 0 0 H ' + width, stroke: '#000'}) - - var topTick = svg.append('path') - .at({d: 'M 0 0 V -12.5', stroke: '#000', strokeWidth: 3}) - - - var actualSel = svg.append('g').st({fill: highlightColor}) - - actualSel.append('path') - .at({d: 'M 0 0 V 12.5', stroke: highlightColor, strokeWidth: 3}) - - var actualPct = actualSel.append('text') - .translate(30, 1).at({textAnchor: 'middle'}).st({fontWeight: 300}) - - var actualScore = actualSel.append('text') - .translate(50, 1).at({textAnchor: 'middle'}).st({fontWeight: 300}) - - return () => { - var pcts = metrics.map(d => active.percents[d.key] || 0) - - topText.text(d => (d.str + ' Target: ').replace('s ', ' ') + pctFmt(d.target)) - - topTick.translate(d => xScale(d.target), 0) - actualSel.translate((d, i) => xScale(pcts[i]), 0) - - actualPct.text((d, i) => 'Actual: ' + pctFmt(pcts[i])) - actualScore.text((d, i) => 'Difference: ' + pctFmt(Math.abs(d.target - pcts[i]))) - } -} - - -function scoreActive(active){ - var numActive = d3.sum(active) - return metrics.map(m => { - var v = d3.sum(active, (d, i) => active[i] && shapes[i][m.field] == m.key) - return Math.abs(m.target - v/numActive); - // return m.scoreScale(v/numActive || 0) - }) -} - -var measures = [ - { - str: 'Utilitarian', - display_text: 'Minimize Mean Difference', - ranking_display_text: 'Mean Difference', - fn: s => d3.mean(s)*100, - ppFn: s => d3.format('.2%')(d3.mean(s)), - format: s => 'mean(' + s.map(d => d + '%').join(', ') + ')' - }, - { - str: 'Egalitarian', - display_text: 'Minimize Max Difference', - ranking_display_text: 'Max Difference', - fn: s => { - var srt = _.sortBy(s).map(d => Math.round(d*100)).reverse() - - return srt[0]*100000000 + srt[1]*10000 + srt[2] - }, - ppFn: s => { - var srt = _.sortBy(s).map(d => Math.round(d*100)).reverse() - - return srt[0] + '%' - }, - format: s => 'max(' + s.map(d => d + '%').join(', ') + ')' - } -] -measures2 = measures.map(d => ({...d})) - - -var randomActive = d3.range(10000).map(d => { - var active = shapes.map(d => random() < .3) - - if (d == 0) active = '111111111111101011100'.split('').map(d => +d) - - active.score = scoreActive(active) - measures.forEach(d => { - active[d.str] = d.fn(active.score) - }) - - return active -}) - -function addMetricBestButton(metricIndex, {active, sel, render}){ - var measureSel = sel - .append('div').st({textAlign: 'center', marginTop: 20, marginBottom: -20}) - .append('div.measure').st({width: 200, lineHeight: '1.8em', display: 'inline-block'}) - .html('Show Best') - .on('click', d => { - - // console.log(active) - var pcts = metrics.map(d => active.percents[d.key] || 0) - if (pcts[metricIndex] == metrics[metricIndex].target) return - - var nextActive = _.minBy(randomActive, a => a.score[metricIndex]) - active.forEach((d, i) => active[i] = nextActive[i]) - - measureSel.classed('active', e => e == d) - render() - }) -} - -function addMeasures(measures, {active, sel, render}){ - var measureSel = sel.selectAll('div.measure-container') - - measureSel - .append('div.measure') - .st({width: 200, lineHeight: '1.8em', display: 'inline-block', textAlign: 'center', }) - .html((d, i) => i ? 'Show the set where the highest difference is the smallest' : 'Show the set with
    lowest mean difference') - .html('Show Best') - .on('click', d => { - - var nextActive = _.minBy(randomActive, a => a[d.str]) - active.forEach((d, i) => active[i] = nextActive[i]) - - measureSel.classed('active', e => e == d) - render() - }) - - -} - -function addTotalMetrics(metrics, measures, {active, sel, render}){ - var metricSel = sel.classed('bot', 1).st({textAlign: 'center'}) - .appendMany('div.measure-container', measures) - .append('div', measures) - .st({textAlign: 'center', display: 'inline-block'}) - - - var headlineSel = metricSel.append('div') - var calcSel = metricSel.append('div')//.st({color: highlightColor}) - - return () => { - - measures.forEach(d => { - d.scores = scoreActive(active) - - d.score = Math.round(d.fn(d.scores)*100)/100 - if (d.ppFn) d.score = d.ppFn(d.scores) - }) - - headlineSel.st({fontWeight: 600}) - .text(d => d.ranking_display_text + ': ' + d.score) - - calcSel.text(d => { - var roundedScores = d.scores.map(s => Math.round(s * 100)) - - return d.format(roundedScores) - }) - } -} - - -window.shapeRandom = new Math.seedrandom('aaf') -var defaultActive = shapes.map(d => shapeRandom() < .4) -drawShape('all-shapes') - -drawShape('pick-green', ({active, topSel, sel, render}) => { - active.forEach((d, i) => active[i] = defaultActive[i]) - addMetricBestButton(0, {active, sel, render}) - return addMetrics(metrics.filter(d => d.key == 'green'), {active, topSel}) -}) - -drawShape('pick-triangle', ({active, topSel, sel, render}) => { - active.forEach((d, i) => active[i] = defaultActive[i]) - addMetricBestButton(1, {active, sel, render}) - return addMetrics(metrics.filter(d => d.key == 'triangle'), {active, topSel}) -}) - -drawShape('pick-metric', grid => { - grid.active.forEach((d, i) => grid.active[i] = defaultActive[i]) - - var metricRender = addMetrics(metrics, grid) - var totalMetricRender = addTotalMetrics(metrics, measures, grid) - addMeasures(measures, grid) - - return () => { - metricRender() - totalMetricRender() - } -}) - - -function drawShape(id, initFn=d => e => e){ - var active = shapes.map(d => true) - - var sel = d3.select('#' + id).html('') - - var s = 110 - - var topSel = sel.append('div.top') - var shapeSel = sel.appendMany('div.shape', _.sortBy(shapes, d => d.displayIndex)) - .st({width: s, height: s}) - .on('click', d => { - active[d.i] = !active[d.i] - render() - }) - - shapeSel.append('svg') - .at({width: s, height: s}) - .append('g').translate([s/2, s/2]) - .each(function(d){ - if (d.shape == 'square' || true){ - var rs = Math.round(d.sizeVal*s/3.5) - var shapeSel = d3.select(this).append('rect') - .at({x: -rs, y: -rs, width: rs*2, height: rs*2}) - } else if (d.shape == 'circle'){ - var shapeSel = d3.select(this).append('circle') - .at({r: d.sizeVal*s/3}) - } else if (d.shape == 'triangle'){ - var rs = Math.round(d.sizeVal*s/2.9) - var shapeSel = d3.select(this).append('path') - .translate(rs*Math.pow(3,1/2)/10, 1) - .at({d: [ - 'M', 0, -rs, - 'L', -rs*Math.pow(3,1/2)/2, rs/2, - 'L', +rs*Math.pow(3,1/2)/2, rs/2, - 'Z' - ].join(' ')}) - } - - if (d.shape == 'triangle'){ - d3.select(this).append('circle') - .at({r: 4, fill: '#fff', stroke: '#000', strokeWidth: 1}) - } - - shapeSel.at({fill: d.fill, stroke: d.dFill, strokeWidth: 2}) - }) - - var customRender = initFn({active, topSel, sel, render}) - - shapes.render = render - function render(){ - shapeSel.classed('active', d => active[d.i]) - // console.log(active.map(d => +d).join('')) - - active.percents = {} - active.shapes = shapes.filter(d => active[d.i]) - - d3.nestBy(active.shapes, d => d.color).forEach(d => { - active.percents[d.key] = d.length/active.shapes.length - }) - d3.nestBy(active.shapes, d => d.size).forEach(d => { - active.percents[d.key] = d.length/active.shapes.length - }) - d3.nestBy(active.shapes, d => d.shape).forEach(d => { - active.percents[d.key] = d.length/active.shapes.length - }) - - - customRender() - } - render() -} \ No newline at end of file diff --git a/spaces/miccull/clip-rgb-interpolation/app.py b/spaces/miccull/clip-rgb-interpolation/app.py deleted file mode 100644 index aa9803e6cfccb36e33da16fce29fa0602caf5622..0000000000000000000000000000000000000000 --- a/spaces/miccull/clip-rgb-interpolation/app.py +++ /dev/null @@ -1,114 +0,0 @@ -import pandas as pd -import numpy as np -from PIL import Image -import torch -import torchvision -import clip -import matplotlib.pyplot as plt -import seaborn as sns -import gradio as gr - - -DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' - -model_name = 'ViT-B/16' #@param ['RN50', 'RN101', 'RN50x4', 'RN50x16', 'ViT-B/32', 'ViT-B/16'] -model, preprocess = clip.load(model_name) - -model.to(DEVICE).eval() -resolution = model.visual.input_resolution -resizer = torchvision.transforms.Resize(size=(resolution, resolution)) - - -def create_rgb_tensor(color): - """color is e.g. [1,0,0]""" - return torch.tensor(color, device=DEVICE).reshape((1, 3, 1, 1)) - -def encode_color(color): - """color is e.g. [1,0,0]""" - rgb = create_rgb_tensor(color) - return model.encode_image( resizer(rgb) ) - -def encode_text(text): - tokenized_text = clip.tokenize(text).to(DEVICE) - return model.encode_text(tokenized_text) - -def lerp(x, y, steps=11): - """Linear interpolation between two tensors """ - - weights = torch.tensor(np.linspace(0,1,steps), device=DEVICE).reshape([-1, 1, 1, 1]) - - interpolated = x * (1 - weights) + y * weights - - return interpolated - -def get_interpolated_scores(x, y, encoded_text, steps=11): - interpolated = lerp(x, y, steps) - interpolated_encodings = model.encode_image(resizer(interpolated)) - - scores = torch.cosine_similarity(interpolated_encodings, encoded_text).detach().cpu().numpy() - - rgb = interpolated.detach().cpu().numpy().reshape(-1, 3) - interpolated_hex = [rgb2hex(x) for x in rgb] - - data = pd.DataFrame({ - 'similarity': scores, - 'color': interpolated_hex - }).reset_index().rename(columns={'index':'step'}) - - return data - -def rgb2hex(rgb): - rgb = (rgb * 255).astype(int) - r,g,b = rgb - return "#{:02x}{:02x}{:02x}".format(r,g,b) - - -def similarity_plot(data, text_prompt): - title = f'CLIP Cosine Similarity Prompt="{text_prompt}"' - - fig, ax = plt.subplots() - plot = data['similarity'].plot(kind='bar', - ax=ax, - stacked=True, - title=title, - color=data['color'], - width=1.0, - xlim=(0, 2), - grid=False) - - - plot.get_xaxis().set_visible(False) ; - return fig - - - -def interpolation_experiment(rgb_start, rgb_end, text_prompt, steps=11): - - start = create_rgb_tensor(rgb_start) - end = create_rgb_tensor(rgb_end) - encoded_text = encode_text(text_prompt) - - data = get_interpolated_scores(start, end, encoded_text, steps) - return similarity_plot(data, text_prompt) - - - - -start_input = gr.inputs.Textbox(lines=1, default="1, 0, 0", label="Start RGB") -end_input = gr.inputs.Textbox(lines=1, default="0, 1, 0", label="End RGB") -' (Comma separated numbers between 0 and 1)' - -text_input = gr.inputs.Textbox(lines=1, label="Text Prompt", default='A solid red square') - -steps_input = gr.inputs.Slider(minimum=1, maximum=100, step=1, default=11, label="Interpolation Steps") - -def gradio_fn(rgb_start, rgb_end, text_prompt, steps=11): - - rgb_start = [float(x.strip()) for x in rgb_start.split(',')] - rgb_end = [float(x.strip()) for x in rgb_end.split(',')] - out = interpolation_experiment(rgb_start, rgb_end, text_prompt, steps) - - return out - -iface = gr.Interface( fn=gradio_fn, inputs=[start_input, end_input, text_input, steps_input], outputs="plot") -iface.launch(debug=True, share=False) \ No newline at end of file diff --git a/spaces/mila-quebec/SAI/src/feedback.py b/spaces/mila-quebec/SAI/src/feedback.py deleted file mode 100644 index ce00ae2699baf0c2f577564aca6cfee7921f4dc4..0000000000000000000000000000000000000000 --- a/spaces/mila-quebec/SAI/src/feedback.py +++ /dev/null @@ -1,192 +0,0 @@ -from __future__ import annotations - -import logging -from dataclasses import dataclass -from typing import Any, Type - -import pandas as pd -import pymongo -from fastapi.encoders import jsonable_encoder -from pyparsing import Optional - -from buster.completers.base import Completion - -logger = logging.getLogger(__name__) -logging.basicConfig(level=logging.INFO) - - -@dataclass -class StandardForm: - def to_json(self) -> Any: - return jsonable_encoder(self) - - @classmethod - def from_dict(cls, interaction_dict: dict) -> StandardForm: - return cls(**interaction_dict) - - -@dataclass -class FeedbackForm(StandardForm): - """Form on the original Buster app.""" - - # Overall experience - overall_experience: str - - # Answer Quality - clear_answer: str - accurate_answer: str - - # Source Relevance - relevant_sources: str - relevant_sources_order: str - relevant_sources_selection: list - - # beginner, intermediate, expert at AI policy? - expertise: list[str] - - # Additional Feedback - extra_info: str - - -@dataclass -class ComparisonForm(StandardForm): - """Easily readable comparison result on the battle arena.""" - - question: str - model_left: str - model_right: str - vote: str - extra_info: str - - -@dataclass -class Interaction: - user_completions: list[Completion] - time: str - session_id: str # A unique identifier for each gradio session, e.g. UUID - username: Optional[str] = None - instance_type: Optional[str] = None # Dev or prod - instance_name: Optional[str] = None # Heroku, hf-space, etc. - data_version: Optional[str] = None # Which collection of the was used - form: Optional[StandardForm] = None - - def send(self, mongo_db: pymongo.database.Database, collection: str): - feedback_json = self.to_json() - logger.info(feedback_json) - - try: - mongo_db[collection].insert_one(feedback_json) - logger.info(f"response logged to mondogb {collection=}") - except Exception as err: - logger.exception(f"Something went wrong logging to mongodb {collection=}") - raise err - - def flatten(self) -> dict: - """Flattens the Interaction object into a dict for easier reading.""" - interaction_dict = self.to_json() - - # Flatten user completions, only keep the most recent interaction - if len(interaction_dict["user_completions"]) > 0: - completion_dict = interaction_dict["user_completions"][-1] - # # TODO: add test for this... - for k in completion_dict.keys(): - interaction_dict[f"completion_{k}"] = completion_dict[k] - del interaction_dict["user_completions"] - - if self.form is not None: - # Flatten feedback form - for k in interaction_dict["form"].keys(): - interaction_dict[f"form_{k}"] = interaction_dict["form"][k] - del interaction_dict["form"] - - # Flatten matched documents - interaction_dict["matched_documents"] = self.user_completions[-1].matched_documents - interaction_dict["matched_documents"].reset_index(inplace=True) - interaction_dict["matched_documents"].drop(columns=["index"], inplace=True) - interaction_dict["matched_documents"] = interaction_dict["matched_documents"].T - if len(interaction_dict["matched_documents"]) > 0: - for k in interaction_dict["matched_documents"].keys(): - interaction_dict[f"matched_documents_{k}"] = interaction_dict["matched_documents"][k].values - del interaction_dict["matched_documents"] - - return interaction_dict - - def to_json(self) -> Any: - custom_encoder = { - # Converts the matched_documents in the user_completions to json - Completion: lambda completion: completion.to_json(columns_to_ignore=["embedding", "_id"]), - } - - to_encode = { - "username": self.username, - "session_id": self.session_id, - "user_completions": self.user_completions, - "time": self.time, - "instance_type": self.instance_type, - "instance_name": self.instance_name, - "data_version": self.data_version, - } - - if self.form is not None: - to_encode["form"] = self.form.to_json() - - return jsonable_encoder(to_encode, custom_encoder=custom_encoder) - - @classmethod - def from_dict(cls, interaction_dict: dict, feedback_cls: Optional[Type[StandardForm]] = None) -> Interaction: - # remove the _id from mongodb - if "_id" in interaction_dict.keys(): - del interaction_dict["_id"] - - interaction_dict["user_completions"] = [Completion.from_dict(r) for r in interaction_dict["user_completions"]] - - if "form" in interaction_dict.keys(): - # The interaction contained a type of form, e.g. feedback form, parse it accordingly - - # Make sure the user specified a feedback_cls - assert feedback_cls is not None, "You must specify which type of feedback it is" - - interaction_dict["form"] = feedback_cls.from_dict(interaction_dict["form"]) - - return cls(**interaction_dict) - - -def read_collection( - mongo_db: pymongo.database.Database, - collection: str, - feedback_cls: Optional[Type[StandardForm]] = None, - filters: Optional[dict] = None, -) -> pd.DataFrame: - """ - Retrieve data from a MongoDB collection and return it as a pandas DataFrame. - - Parameters: - - mongo_db (pymongo.database.Database): The MongoDB database instance. - - collection (str): The name of the MongoDB collection to read from. - - feedback_cls (Optional[Type[StandardForm]]): A class to which the retrieved data might be mapped. - If the collection contains instances of Interaction, this is not needed. If a form is attached - (i.e., interaction["form"] exists), it should be provided. - - filters (Optional[dict]): A dictionary of filters to apply to the mongodb query. If not provided, - all items in the collection are returned. E.g., to get interactions from a specific user, - use `filters={"username": }`. - - Returns: - - pd.DataFrame: A DataFrame containing the retrieved data. Data is flattened for convenience. - - Notes: - - Interactions that cannot be processed are skipped, and a log message is generated with the - count of retrieved and skipped entries. - """ - flattened_interactions = [] - skipped_interactions = [] - interactions = mongo_db[collection].find(filters) - for interaction in interactions: - try: - flattened_interaction = Interaction.from_dict(interaction, feedback_cls=feedback_cls).flatten() - flattened_interactions.append(flattened_interaction) - except Exception as err: - skipped_interactions.append(interaction) - - logger.info(f"Retrieved {len(flattened_interactions)} entries. Skipped {len(skipped_interactions)} entries") - - return pd.DataFrame(flattened_interactions) diff --git a/spaces/momegas/megabots/megabots/bot.py b/spaces/momegas/megabots/megabots/bot.py deleted file mode 100644 index 5e9d346319464abe02db304d7c8957b20bd5e65c..0000000000000000000000000000000000000000 --- a/spaces/momegas/megabots/megabots/bot.py +++ /dev/null @@ -1,207 +0,0 @@ -from typing import Any -from langchain.llms import OpenAI -from langchain.chat_models import ChatOpenAI -from langchain.embeddings import OpenAIEmbeddings -from langchain.chains.qa_with_sources import load_qa_with_sources_chain -from langchain.vectorstores.faiss import FAISS -import pickle -import os -from langchain.prompts import PromptTemplate -from langchain.chains.question_answering import load_qa_chain -from langchain.chains.conversational_retrieval.prompts import QA_PROMPT -from langchain.document_loaders import DirectoryLoader -from megabots.prompt import QA_MEMORY_PROMPT -from megabots.vectorstore import VectorStore -from megabots.memory import Memory -import megabots - - -class Bot: - def __init__( - self, - model: str | None = None, - prompt: PromptTemplate | None = None, - index: str | None = None, - sources: bool | None = False, - vectorstore: VectorStore | None = None, - memory: Memory | None = None, - verbose: bool = False, - temperature: int = 0, - ): - self.vectorstore = vectorstore - self.memory = memory - self.prompt = prompt or QA_MEMORY_PROMPT if self.memory else QA_PROMPT - self.select_model(model, temperature) - self.create_loader(index) - self.load_or_create_index(index, vectorstore) - - # Load the question-answering chain for the selected model - self.chain = self.create_chain(sources=sources, verbose=verbose) - - def create_chain( - self, - sources: bool | None = False, - verbose: bool = False, - ): - # TODO: Changing the prompt here is not working. Leave it as is for now. - # Reference: https://github.com/hwchase17/langchain/issues/2858 - if sources: - return load_qa_with_sources_chain( - self.llm, - chain_type="stuff", - memory=self.memory.memory if self.memory else None, - verbose=verbose, - ) - return load_qa_chain( - self.llm, - chain_type="stuff", - verbose=verbose, - prompt=self.prompt, - memory=self.memory.memory if self.memory else None, - ) - - def select_model(self, model: str | None, temperature: float): - # Select and set the appropriate model based on the provided input - if model is None or model == "gpt-3.5-turbo": - print("Using model: gpt-3.5-turbo") - self.llm = ChatOpenAI(temperature=temperature) - - if model == "text-davinci-003": - print("Using model: text-davinci-003") - self.llm = OpenAI(temperature=temperature) - - def create_loader(self, index: str | None): - # Create a loader based on the provided directory (either local or S3) - if index is None: - raise RuntimeError( - """ - Impossible to find a valid index. - Either provide a valid path to a pickle file or a directory. - """ - ) - self.loader = DirectoryLoader(index, recursive=True) - - def load_or_create_index(self, index: str, vectorstore: VectorStore | None = None): - # Load an existing index from disk or create a new one if not available - if vectorstore is not None: - self.search_index = vectorstore.client.from_documents( - self.loader.load_and_split(), - OpenAIEmbeddings(), - connection_args={"host": vectorstore.host, "port": vectorstore.port}, - ) - return - - # Is pickle - if index is not None and "pkl" in index or "pickle" in index: - print("Loading path from pickle file: ", index, "...") - with open(index, "rb") as f: - self.search_index = pickle.load(f) - return - - # Is directory - if index is not None and os.path.isdir(index): - print("Creating index...") - self.search_index = FAISS.from_documents( - self.loader.load_and_split(), OpenAIEmbeddings() - ) - return - - raise RuntimeError( - """ - Impossible to find a valid index. - Either provide a valid path to a pickle file or a directory. - """ - ) - - def save_index(self, index_path: str): - # Save the index to the specified path - with open(index_path, "wb") as f: - pickle.dump(self.search_index, f) - - def ask(self, question: str, k=1) -> str: - # Retrieve the answer to the given question and return it - input_documents = self.search_index.similarity_search(question, k=k) - answer = self.chain.run(input_documents=input_documents, question=question) - return answer - - -SUPPORTED_TASKS = { - "qna-over-docs": { - "impl": Bot, - "default": { - "model": "gpt-3.5-turbo", - "temperature": 0, - "index": "./index", - "input_variables": ["context", "question"], - }, - } -} - -SUPPORTED_MODELS = {} - - -def bot( - task: str | None = None, - *, - model: str | None = None, - index: str | None = None, - prompt: str | None = None, - memory: str | Memory | None = None, - vectorstore: str | VectorStore | None = None, - verbose: bool = False, - temperature: int = 0, -) -> Bot: - """Instanciate a bot based on the provided task. Each supported tasks has it's own default sane defaults. - - Args: - task (str | None, optional): The given task. Can be one of the SUPPORTED_TASKS. - - model (str | None, optional): Model to be used. Can be one of the SUPPORTED_MODELS. - - index (str | None, optional): Data that the model will load and store index info. - Can be either a local file path, a pickle file, or a url of a vector database. - By default it will look for a local directory called "files" in the current working directory. - - prompt (str | None, optional): The prompt that the bot will take in. Mark variables like this: {variable}. - Variables are context, question, and history if the bot has memory. - - vectorstore: (str | VectorStore | None, optional): The vectorstore that the bot will save the index to. - If only a string is passed, the defaults values willl be used. - - verbose (bool, optional): Verbocity. Defaults to False. - - temperature (int, optional): Temperature. Defaults to 0. - - Raises: - RuntimeError: _description_ - ValueError: _description_ - - Returns: - Bot: Bot instance - """ - - if task is None: - raise RuntimeError("Impossible to instantiate a bot without a task.") - if task not in SUPPORTED_TASKS: - raise ValueError(f"Task {task} is not supported.") - - task_defaults = SUPPORTED_TASKS[task]["default"] - - if memory is not None: - task_defaults["input_variables"].append("history") - - return SUPPORTED_TASKS[task]["impl"]( - model=model or task_defaults["model"], - index=index or task_defaults["index"], - prompt=None - if prompt is None - else PromptTemplate( - template=prompt, input_variables=task_defaults["input_variables"] - ), - temperature=temperature, - verbose=verbose, - vectorstore=megabots.vectorstore(vectorstore) - if isinstance(vectorstore, str) - else vectorstore, - memory=megabots.memory(memory) if isinstance(memory, str) else memory, - ) diff --git a/spaces/mshukor/UnIVAL/fairseq/examples/textless_nlp/gslm/tools/resynthesize_speech.py b/spaces/mshukor/UnIVAL/fairseq/examples/textless_nlp/gslm/tools/resynthesize_speech.py deleted file mode 100644 index 2b6215d372035284f115b6eec0712a324246b67a..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/examples/textless_nlp/gslm/tools/resynthesize_speech.py +++ /dev/null @@ -1,138 +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 argparse -import gc -import logging - -import joblib -import soundfile as sf -import torch -from examples.textless_nlp.gslm.speech2unit.pretrained.utils import ( - get_feature_reader, -) -from examples.textless_nlp.gslm.unit2speech.tts_data import ( - TacotronInputDataset, -) -from examples.textless_nlp.gslm.unit2speech.utils import ( - load_tacotron, - load_waveglow, - synthesize_audio, -) - - -def get_logger(): - log_format = "[%(asctime)s] [%(levelname)s]: %(message)s" - logging.basicConfig(format=log_format, level=logging.INFO) - logger = logging.getLogger(__name__) - return logger - - -def get_parser(): - parser = argparse.ArgumentParser( - description="GSLM speech resynthesis tool." - ) - parser.add_argument( - "--feature_type", - type=str, - choices=["logmel", "hubert", "w2v2", "cpc"], - default=None, - required=True, - help="Acoustic feature type", - ) - parser.add_argument( - "--acoustic_model_path", - type=str, - help="Pretrained acoustic model checkpoint", - ) - parser.add_argument( - "--layer", type=int, help="Layer of acoustic model" - ) - parser.add_argument( - "--kmeans_model_path", - type=str, - required=True, - help="K-means model file path to use for inference", - ) - parser.add_argument( - "--tts_model_path", - type=str, - help="TTS model file path to use for inference", - ) - parser.add_argument( - "--waveglow_path", - type=str, - help="Waveglow (vocoder) model file path to use for inference", - ) - parser.add_argument("--max_decoder_steps", type=int, default=2000) - parser.add_argument("--denoiser_strength", type=float, default=0.1) - return parser - - -################################################ -def main(args, logger): - # Acoustic Model - logger.info(f"Loading acoustic model from {args.tts_model_path}...") - feature_reader_cls = get_feature_reader(args.feature_type) - reader = feature_reader_cls( - checkpoint_path=args.acoustic_model_path, layer=args.layer - ) - - # K-means Model - logger.info(f"Loading K-means model from {args.kmeans_model_path} ...") - kmeans_model = joblib.load(open(args.kmeans_model_path, "rb")) - kmeans_model.verbose = False - - # TTS Model - logger.info(f"Loading TTS model from {args.tts_model_path}...") - tacotron_model, sample_rate, hparams = load_tacotron( - tacotron_model_path=args.tts_model_path, - max_decoder_steps=args.max_decoder_steps, - ) - - # Waveglow Model - logger.info(f"Loading Waveglow model from {args.waveglow_path}...") - waveglow, denoiser = load_waveglow(waveglow_path=args.waveglow_path) - - # Dataset - tts_dataset = TacotronInputDataset(hparams) - - iters = 0 - while True: - in_file_path = input( - "Input: Enter the full file path of audio file...\n" - ) - out_file_path = input( - "Output: Enter the full file path of audio file...\n" - ) - feats = reader.get_feats(in_file_path).cpu().numpy() - iters += 1 - if iters == 1000: - gc.collect() - torch.cuda.empty_cache() - - quantized_units = kmeans_model.predict(feats) - quantized_units_str = " ".join(map(str, quantized_units)) - - tts_input = tts_dataset.get_tensor(quantized_units_str) - mel, aud, aud_dn, has_eos = synthesize_audio( - tacotron_model, - waveglow, - denoiser, - tts_input.unsqueeze(0), - strength=args.denoiser_strength, - ) - sf.write( - f"{out_file_path}", aud_dn[0].cpu().float().numpy(), sample_rate - ) - logger.info("Resynthesis done!\n") - - -if __name__ == "__main__": - parser = get_parser() - args = parser.parse_args() - logger = get_logger() - logger.info(args) - main(args, logger) diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/benchmark/dummy_masked_lm.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/benchmark/dummy_masked_lm.py deleted file mode 100644 index 12b9c5d0f55993bf8750564882a351fc3f8055f0..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/benchmark/dummy_masked_lm.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import logging -from dataclasses import dataclass, field -from typing import Optional - -import torch -from omegaconf import II - -from .dummy_dataset import DummyDataset -from fairseq.data import Dictionary -from fairseq.dataclass import FairseqDataclass -from fairseq.tasks import FairseqTask, register_task - -logger = logging.getLogger(__name__) - - -@dataclass -class DummyMaskedLMConfig(FairseqDataclass): - dict_size: int = 49996 - dataset_size: int = 100000 - tokens_per_sample: int = field( - default=512, - metadata={ - "help": "max number of total tokens over all" - " segments per sample for BERT dataset" - }, - ) - batch_size: Optional[int] = II("dataset.batch_size") - max_tokens: Optional[int] = II("dataset.max_tokens") - max_target_positions: int = II("task.tokens_per_sample") - - -@register_task("dummy_masked_lm", dataclass=DummyMaskedLMConfig) -class DummyMaskedLMTask(FairseqTask): - def __init__(self, cfg: DummyMaskedLMConfig): - super().__init__(cfg) - - self.dictionary = Dictionary() - for i in range(cfg.dict_size): - self.dictionary.add_symbol("word{}".format(i)) - logger.info("dictionary: {} types".format(len(self.dictionary))) - # add mask token - self.mask_idx = self.dictionary.add_symbol("") - self.dictionary.pad_to_multiple_(8) # often faster if divisible by 8 - - mask_idx = 0 - pad_idx = 1 - seq = torch.arange(cfg.tokens_per_sample) + pad_idx + 1 - mask = torch.arange(2, cfg.tokens_per_sample, 7) # ~15% - src = seq.clone() - src[mask] = mask_idx - tgt = torch.full_like(seq, pad_idx) - tgt[mask] = seq[mask] - - self.dummy_src = src - self.dummy_tgt = tgt - - def load_dataset(self, split, epoch=1, combine=False, **kwargs): - """Load a given dataset split. - Args: - split (str): name of the split (e.g., train, valid, test) - """ - if self.cfg.batch_size is not None: - bsz = self.cfg.batch_size - else: - bsz = max(1, self.cfg.max_tokens // self.cfg.tokens_per_sample) - self.datasets[split] = DummyDataset( - { - "id": 1, - "net_input": { - "src_tokens": torch.stack([self.dummy_src for _ in range(bsz)]), - "src_lengths": torch.full( - (bsz,), self.cfg.tokens_per_sample, dtype=torch.long - ), - }, - "target": torch.stack([self.dummy_tgt for _ in range(bsz)]), - "nsentences": bsz, - "ntokens": bsz * self.cfg.tokens_per_sample, - }, - num_items=self.cfg.dataset_size, - item_size=self.cfg.tokens_per_sample, - ) - - @property - def source_dictionary(self): - return self.dictionary - - @property - def target_dictionary(self): - return self.dictionary diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/criterions/fastspeech2_loss.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/criterions/fastspeech2_loss.py deleted file mode 100644 index 085d5628d4c4c242edee4aa3bc4a01aa4582eb21..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/criterions/fastspeech2_loss.py +++ /dev/null @@ -1,125 +0,0 @@ -# Copyright (c) 2017-present, Facebook, Inc. -# All rights reserved. -# -# This source code is licensed under the license found in the LICENSE file in -# the root directory of this source tree. An additional grant of patent rights -# can be found in the PATENTS file in the same directory. - -from typing import List, Dict, Any -from dataclasses import dataclass, field - -import torch -import torch.nn.functional as F - -from fairseq import metrics, utils -from fairseq.criterions import FairseqCriterion, register_criterion -from fairseq.dataclass import FairseqDataclass -from fairseq.data.data_utils import lengths_to_mask -from fairseq.models.fairseq_model import FairseqEncoderModel - - -@dataclass -class FastSpeech2CriterionConfig(FairseqDataclass): - ctc_weight: float = field( - default=0.0, metadata={"help": "weight for CTC loss"} - ) - - -@register_criterion("fastspeech2", dataclass=FastSpeech2CriterionConfig) -class FastSpeech2Loss(FairseqCriterion): - def __init__(self, task, ctc_weight): - super().__init__(task) - self.ctc_weight = ctc_weight - - def forward(self, model: FairseqEncoderModel, sample, reduction="mean"): - src_tokens = sample["net_input"]["src_tokens"] - src_lens = sample["net_input"]["src_lengths"] - tgt_lens = sample["target_lengths"] - _feat_out, _, log_dur_out, pitch_out, energy_out = model( - src_tokens=src_tokens, - src_lengths=src_lens, - prev_output_tokens=sample["net_input"]["prev_output_tokens"], - incremental_state=None, - target_lengths=tgt_lens, - speaker=sample["speaker"], - durations=sample["durations"], - pitches=sample["pitches"], - energies=sample["energies"] - ) - - src_mask = lengths_to_mask(sample["net_input"]["src_lengths"]) - tgt_mask = lengths_to_mask(sample["target_lengths"]) - - pitches, energies = sample["pitches"], sample["energies"] - pitch_out, pitches = pitch_out[src_mask], pitches[src_mask] - energy_out, energies = energy_out[src_mask], energies[src_mask] - - feat_out, feat = _feat_out[tgt_mask], sample["target"][tgt_mask] - l1_loss = F.l1_loss(feat_out, feat, reduction=reduction) - - pitch_loss = F.mse_loss(pitch_out, pitches, reduction=reduction) - energy_loss = F.mse_loss(energy_out, energies, reduction=reduction) - - log_dur_out = log_dur_out[src_mask] - dur = sample["durations"].float() - dur = dur.half() if log_dur_out.type().endswith(".HalfTensor") else dur - log_dur = torch.log(dur + 1)[src_mask] - dur_loss = F.mse_loss(log_dur_out, log_dur, reduction=reduction) - - ctc_loss = torch.tensor(0.).type_as(l1_loss) - if self.ctc_weight > 0.: - lprobs = model.get_normalized_probs((_feat_out,), log_probs=True) - lprobs = lprobs.transpose(0, 1) # T x B x C - src_mask = lengths_to_mask(src_lens) - src_tokens_flat = src_tokens.masked_select(src_mask) - ctc_loss = F.ctc_loss( - lprobs, src_tokens_flat, tgt_lens, src_lens, - reduction=reduction, zero_infinity=True - ) * self.ctc_weight - - loss = l1_loss + dur_loss + pitch_loss + energy_loss + ctc_loss - - sample_size = sample["nsentences"] - logging_output = { - "loss": utils.item(loss.data), - "ntokens": sample["ntokens"], - "nsentences": sample["nsentences"], - "sample_size": sample_size, - "l1_loss": utils.item(l1_loss.data), - "dur_loss": utils.item(dur_loss.data), - "pitch_loss": utils.item(pitch_loss.data), - "energy_loss": utils.item(energy_loss.data), - "ctc_loss": utils.item(ctc_loss.data), - } - return loss, sample_size, logging_output - - @classmethod - def reduce_metrics(cls, logging_outputs: List[Dict[str, Any]]) -> None: - ns = [log.get("sample_size", 0) for log in logging_outputs] - ntot = sum(ns) - ws = [n / (ntot + 1e-8) for n in ns] - for key in [ - "loss", "l1_loss", "dur_loss", "pitch_loss", "energy_loss", - "ctc_loss" - ]: - vals = [log.get(key, 0) for log in logging_outputs] - val = sum(val * w for val, w in zip(vals, ws)) - metrics.log_scalar(key, val, ntot, round=3) - metrics.log_scalar("sample_size", ntot, len(logging_outputs)) - - # inference metrics - if "targ_frames" not in logging_outputs[0]: - return - n = sum(log.get("targ_frames", 0) for log in logging_outputs) - for key, new_key in [ - ("mcd_loss", "mcd_loss"), - ("pred_frames", "pred_ratio"), - ("nins", "ins_rate"), - ("ndel", "del_rate"), - ]: - val = sum(log.get(key, 0) for log in logging_outputs) - metrics.log_scalar(new_key, val / n, n, round=3) - - @staticmethod - def logging_outputs_can_be_summed() -> bool: - return False diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/data/multilingual/multilingual_utils.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/data/multilingual/multilingual_utils.py deleted file mode 100644 index b4e0f9828cabfdbe375d05d9152b58bdbd6de7dc..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/data/multilingual/multilingual_utils.py +++ /dev/null @@ -1,63 +0,0 @@ -from enum import Enum -from typing import Dict, List, Optional, Sequence - -import torch -from fairseq.data import Dictionary - - -class EncoderLangtok(Enum): - """ - Prepend to the beginning of source sentence either the - source or target language token. (src/tgt). - """ - - src = "src" - tgt = "tgt" - - -class LangTokSpec(Enum): - main = "main" - mono_dae = "mono_dae" - - -class LangTokStyle(Enum): - multilingual = "multilingual" - mbart = "mbart" - - -@torch.jit.export -def get_lang_tok( - lang: str, lang_tok_style: str, spec: str = LangTokSpec.main.value -) -> str: - # TOKEN_STYLES can't be defined outside this fn since it needs to be - # TorchScriptable. - TOKEN_STYLES: Dict[str, str] = { - LangTokStyle.mbart.value: "[{}]", - LangTokStyle.multilingual.value: "__{}__", - } - - if spec.endswith("dae"): - lang = f"{lang}_dae" - elif spec.endswith("mined"): - lang = f"{lang}_mined" - style = TOKEN_STYLES[lang_tok_style] - return style.format(lang) - - -def augment_dictionary( - dictionary: Dictionary, - language_list: List[str], - lang_tok_style: str, - langtoks_specs: Sequence[str] = (LangTokSpec.main.value,), - extra_data: Optional[Dict[str, str]] = None, -) -> None: - for spec in langtoks_specs: - for language in language_list: - dictionary.add_symbol( - get_lang_tok(lang=language, lang_tok_style=lang_tok_style, spec=spec) - ) - - if lang_tok_style == LangTokStyle.mbart.value or ( - extra_data is not None and LangTokSpec.mono_dae.value in extra_data - ): - dictionary.add_symbol("") diff --git a/spaces/mshukor/UnIVAL/fairseq/fairseq/models/fconv_lm.py b/spaces/mshukor/UnIVAL/fairseq/fairseq/models/fconv_lm.py deleted file mode 100644 index 4b243d6669cb57880353b45a01843ec22010fb5f..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/fairseq/fairseq/models/fconv_lm.py +++ /dev/null @@ -1,136 +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 fairseq import utils -from fairseq.models import ( - FairseqLanguageModel, - register_model, - register_model_architecture, -) -from fairseq.models.fconv import FConvDecoder -from fairseq.utils import safe_hasattr - - -@register_model("fconv_lm") -class FConvLanguageModel(FairseqLanguageModel): - def __init__(self, decoder): - super().__init__(decoder) - - @staticmethod - def add_args(parser): - """Add model-specific arguments to the parser.""" - parser.add_argument( - "--dropout", type=float, metavar="D", help="dropout probability" - ) - parser.add_argument( - "--decoder-embed-dim", - type=int, - metavar="N", - help="decoder embedding dimension", - ) - parser.add_argument( - "--decoder-layers", - type=str, - metavar="EXPR", - help="decoder layers [(dim, kernel_size), ...]", - ) - parser.add_argument( - "--decoder-out-embed-dim", - type=int, - metavar="N", - help="decoder output embedding dimension", - ) - parser.add_argument( - "--adaptive-softmax-cutoff", - metavar="EXPR", - help="comma separated list of adaptive softmax cutoff points. " - "Must be used with adaptive_loss criterion", - ) - parser.add_argument( - "--adaptive-softmax-dropout", - type=float, - metavar="D", - help="sets adaptive softmax dropout for the tail projections", - ) - parser.add_argument( - "--decoder-attention", - type=str, - metavar="EXPR", - help="decoder attention [True, ...]", - ) - - @classmethod - def build_model(cls, args, task): - """Build a new model instance.""" - # make sure all arguments are present in older models - base_lm_architecture(args) - - if safe_hasattr(args, "max_target_positions") and not safe_hasattr( - args, "tokens_per_sample" - ): - args.tokens_per_sample = args.max_target_positions - - decoder = FConvDecoder( - dictionary=task.target_dictionary, - embed_dim=args.decoder_embed_dim, - convolutions=eval(args.decoder_layers), - out_embed_dim=args.decoder_embed_dim, - attention=eval(args.decoder_attention), - dropout=args.dropout, - max_positions=args.tokens_per_sample, - share_embed=False, - positional_embeddings=False, - adaptive_softmax_cutoff=( - utils.eval_str_list(args.adaptive_softmax_cutoff, type=int) - if args.criterion == "adaptive_loss" - else None - ), - adaptive_softmax_dropout=args.adaptive_softmax_dropout, - ) - return FConvLanguageModel(decoder) - - -@register_model_architecture("fconv_lm", "fconv_lm") -def base_lm_architecture(args): - args.dropout = getattr(args, "dropout", 0.1) - args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 128) - args.decoder_layers = getattr(args, "decoder_layers", "[(1268, 4)] * 13") - args.decoder_attention = getattr(args, "decoder_attention", "False") - args.adaptive_softmax_cutoff = getattr(args, "adaptive_softmax_cutoff", None) - args.adaptive_softmax_dropout = getattr(args, "adaptive_softmax_dropout", 0) - - -@register_model_architecture("fconv_lm", "fconv_lm_dauphin_wikitext103") -def fconv_lm_dauphin_wikitext103(args): - layers = "[(850, 6)] * 3" - layers += " + [(850, 1)] * 1" - layers += " + [(850, 5)] * 4" - layers += " + [(850, 1)] * 1" - layers += " + [(850, 4)] * 3" - layers += " + [(1024, 4)] * 1" - layers += " + [(2048, 4)] * 1" - args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 280) - args.decoder_layers = getattr(args, "decoder_layers", layers) - args.decoder_attention = getattr(args, "decoder_attention", "False") - args.adaptive_softmax_cutoff = getattr( - args, "adaptive_softmax_cutoff", "10000,20000,200000" - ) - base_lm_architecture(args) - - -@register_model_architecture("fconv_lm", "fconv_lm_dauphin_gbw") -def fconv_lm_dauphin_gbw(args): - layers = "[(512, 5)]" - layers += " + [(128, 1, 0), (128, 5, 0), (512, 1, 3)] * 3" - layers += " + [(512, 1, 0), (512, 5, 0), (1024, 1, 3)] * 3" - layers += " + [(1024, 1, 0), (1024, 5, 0), (2048, 1, 3)] * 6" - layers += " + [(1024, 1, 0), (1024, 5, 0), (4096, 1, 3)]" - args.decoder_embed_dim = getattr(args, "decoder_embed_dim", 128) - args.decoder_layers = getattr(args, "decoder_layers", layers) - args.decoder_attention = getattr(args, "decoder_attention", "False") - args.adaptive_softmax_cutoff = getattr( - args, "adaptive_softmax_cutoff", "10000,50000,200000" - ) - base_lm_architecture(args) diff --git a/spaces/mshukor/UnIVAL/models/unival/encoders/audio_utils.py b/spaces/mshukor/UnIVAL/models/unival/encoders/audio_utils.py deleted file mode 100644 index ad9801c0ac819473f738e2c1fbbdf711006ea440..0000000000000000000000000000000000000000 --- a/spaces/mshukor/UnIVAL/models/unival/encoders/audio_utils.py +++ /dev/null @@ -1,369 +0,0 @@ -import numpy as np -import torch -from torch import nn as nn -from torchvision.ops.misc import FrozenBatchNorm2d -import logging -import h5py -from tqdm import tqdm -import random -import json -import os -import pathlib - -# TODO: (yusong) this not a good place to store those information and does not scale. Need to be fixed later. -dataset_split = { - "audiocaps": ["train", "valid", "test"], - "audioset": ["balanced_train", "unbalanced_train", "eval"], - "BBCSoundEffects": ["train", "test"], - "Clotho": ["train", "test", "valid"], - "free_to_use_sounds": ["train", "test"], - "paramount_motion": ["train", "test"], - "sonniss_game_effects": ["train", "test"], - "wesoundeffects": ["train", "test"], - "MACS": ["train", "test"], - "freesound": ["train", "test"], - "FSD50K": ["train", "test", "valid"], - "fsd50k_class_label": ["train", "test", "valid"], - "esc50": ["train", "test"], - "audiostock": ["train", "test"], - "freesound_no_overlap_noesc50": ["train", "test"], - "epidemic_sound_effects": ["train", "test"], - "VGGSound": ["train", "test"], - "urbansound8k_class_label": ["train", "test"], - "audioset_t5": ["balanced_train", "unbalanced_train", "eval"], - "epidemic_sound_effects_t5": ["train", "test"], - "WavText5K": ["train", "test"], - "esc50_no_overlap": ["train", "test"], - "usd8k_no_overlap": ["train", "test"], - "fsd50k_200_class_label": ["train", "test", "valid"] -} - - -def freeze_batch_norm_2d(module, module_match={}, name=""): - """ - Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is - itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and - returned. Otherwise, the module is walked recursively and submodules are converted in place. - - Args: - module (torch.nn.Module): Any PyTorch module. - module_match (dict): Dictionary of full module names to freeze (all if empty) - name (str): Full module name (prefix) - - Returns: - torch.nn.Module: Resulting module - - Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 - """ - res = module - is_match = True - if module_match: - is_match = name in module_match - if is_match and isinstance( - module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm) - ): - res = FrozenBatchNorm2d(module.num_features) - res.num_features = module.num_features - res.affine = module.affine - if module.affine: - res.weight.data = module.weight.data.clone().detach() - res.bias.data = module.bias.data.clone().detach() - res.running_mean.data = module.running_mean.data - res.running_var.data = module.running_var.data - res.eps = module.eps - else: - for child_name, child in module.named_children(): - full_child_name = ".".join([name, child_name]) if name else child_name - new_child = freeze_batch_norm_2d(child, module_match, full_child_name) - if new_child is not child: - res.add_module(child_name, new_child) - return res - - -def exist(dataset_name, dataset_type): - """ - Check if dataset exists - """ - if dataset_type in dataset_split[dataset_name]: - return True - else: - return False - - -def get_tar_path_from_dataset_name( - dataset_names, - dataset_types, - islocal, - dataset_path, - proportion=1, - full_dataset=None -): - """ - Get tar path from dataset name and type - """ - output = [] - for n in dataset_names: - if full_dataset is not None and n in full_dataset: - current_dataset_types = dataset_split[n] - else: - current_dataset_types = dataset_types - for s in current_dataset_types: - tmp = [] - if islocal: - sizefilepath_ = f"{dataset_path}/{n}/{s}/sizes.json" - if not os.path.exists(sizefilepath_): - sizefilepath_ = f"./json_files/{n}/{s}/sizes.json" - else: - sizefilepath_ = f"./json_files/{n}/{s}/sizes.json" - if not os.path.exists(sizefilepath_): - continue - sizes = json.load(open(sizefilepath_, "r")) - for k in sizes.keys(): - if islocal: - tmp.append(f"{dataset_path}/{n}/{s}/{k}") - else: - tmp.append( - f"pipe:aws s3 --cli-connect-timeout 0 cp s3://s-laion-audio/webdataset_tar/{n}/{s}/{k} -" - ) - if proportion != 1: - tmp = random.sample(tmp, int(proportion * len(tmp))) - output.append(tmp) - return sum(output, []) - - -def get_tar_path_from_txts(txt_path, islocal, proportion=1): - """ - Get tar path from txt path - """ - if isinstance(txt_path, (list, tuple)): - return sum( - [ - get_tar_path_from_txts( - txt_path[i], islocal=islocal, proportion=proportion - ) - for i in range(len(txt_path)) - ], - [], - ) - if isinstance(txt_path, str): - with open(txt_path) as f: - lines = f.readlines() - if islocal: - lines = [ - lines[i] - .split("\n")[0] - .replace("pipe:aws s3 cp s3://s-laion-audio/", "/mnt/audio_clip/") - for i in range(len(lines)) - ] - else: - lines = [ - lines[i].split("\n")[0].replace(".tar", ".tar -") - for i in range(len(lines)) - ] - if proportion != 1: - print("Sampling tars with proportion of {}".format(proportion)) - lines = random.sample(lines, int(proportion * len(lines))) - return lines - - -def get_mix_lambda(mixup_alpha, batch_size): - mixup_lambdas = [ - np.random.beta(mixup_alpha, mixup_alpha, 1)[0] for _ in range(batch_size) - ] - return np.array(mixup_lambdas).astype(np.float32) - - -def do_mixup(x, mixup_lambda): - """ - Args: - x: (batch_size , ...) - mixup_lambda: (batch_size,) - Returns: - out: (batch_size, ...) - """ - out = ( - x.transpose(0, -1) * mixup_lambda - + torch.flip(x, dims=[0]).transpose(0, -1) * (1 - mixup_lambda) - ).transpose(0, -1) - return out - - -def interpolate(x, ratio): - """Interpolate data in time domain. This is used to compensate the - resolution reduction in downsampling of a CNN. - - Args: - x: (batch_size, time_steps, classes_num) - ratio: int, ratio to interpolate - Returns: - upsampled: (batch_size, time_steps * ratio, classes_num) - """ - (batch_size, time_steps, classes_num) = x.shape - upsampled = x[:, :, None, :].repeat(1, 1, ratio, 1) - upsampled = upsampled.reshape(batch_size, time_steps * ratio, classes_num) - return upsampled - - -def pad_framewise_output(framewise_output, frames_num): - """Pad framewise_output to the same length as input frames. The pad value - is the same as the value of the last frame. - Args: - framewise_output: (batch_size, frames_num, classes_num) - frames_num: int, number of frames to pad - Outputs: - output: (batch_size, frames_num, classes_num) - """ - pad = framewise_output[:, -1:, :].repeat( - 1, frames_num - framewise_output.shape[1], 1 - ) - """tensor for padding""" - - output = torch.cat((framewise_output, pad), dim=1) - """(batch_size, frames_num, classes_num)""" - - -def process_ipc(index_path, classes_num, filename): - # load data - logging.info("Load Data...............") - ipc = [[] for _ in range(classes_num)] - with h5py.File(index_path, "r") as f: - for i in tqdm(range(len(f["target"]))): - t_class = np.where(f["target"][i])[0] - for t in t_class: - ipc[t].append(i) - print(ipc) - np.save(filename, ipc) - logging.info("Load Data Succeed...............") - - -def save_to_dict(s, o_={}): - sp = s.split(": ") - o_.update({sp[0]: float(sp[1])}) - return o_ - - -def get_data_from_log(txt_path): - """ - Output dictionary from out.txt log file - """ - with open(txt_path) as f: - lines = f.readlines() - val_data = {} - train_data = {} - train_losses = [] - train_losses_epoch = [] - for i in range(len(lines)): - if "| INFO |" in lines[i]: - if "Eval Epoch" in lines[i]: - if "val_loss" in lines[i]: - # float(regex.sub("", lines[310].split(" ")[-1]).replace(" ", "")) - line = lines[i].split("Eval Epoch: ")[-1] - num_epoch = int(line.split(" ")[0].split(" ")[0]) - d = { - line.split(" ")[0] - .split(" ")[1] - .replace(":", ""): float(line.split(" ")[0].split(" ")[-1]) - } - for i in range(1, len(line.split(" "))): - d = save_to_dict(line.split(" ")[i], d) - val_data[num_epoch] = d - elif "Train Epoch" in lines[i]: - num_epoch = int(lines[i].split("Train Epoch: ")[1][0]) - loss = float(lines[i].split("Loss: ")[-1].split(" (")[0]) - train_losses.append(loss) - train_losses_epoch.append(num_epoch) - for i in range(len(train_losses)): - train_data[i] = { - "num_epoch": train_losses_epoch[i], - "train_loss": train_losses[i], - } - return train_data, val_data - - -def save_p(obj, filename): - import pickle - - try: - from deepdiff import DeepDiff - except: - os.system("pip install deepdiff") - from deepdiff import DeepDiff - with open(filename, "wb") as file: - pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL) # highest protocol - with open(filename, "rb") as file: - z = pickle.load(file) - assert ( - DeepDiff(obj, z, ignore_string_case=True) == {} - ), "there is something wrong with the saving process" - return - - -def load_p(filename): - import pickle - - with open(filename, "rb") as file: - z = pickle.load(file) - return z - - -def save_json(data, name="data.json"): - import json - with open(name, 'w') as fp: - json.dump(data, fp) - return - - -def load_json(name): - import json - with open(name, 'r') as fp: - data = json.load(fp) - return data - - -from multiprocessing import Process, Manager -from multiprocessing import Process, Value, Array -from ctypes import c_wchar - - -def load_class_label(path): - # https://stackoverflow.com/questions/48004243/how-to-share-large-read-only-dictionary-list-across-processes-in-multiprocessing - # https://stackoverflow.com/questions/45693949/storing-strings-in-a-multiprocessing-sharedctypes-array - out = None - if path is not None: - if pathlib.Path(path).suffix in [".pkl", ".pickle"]: - out = load_p(path) - elif pathlib.Path(path).suffix in [".json", ".txt"]: - out = load_json(path) - elif pathlib.Path(path).suffix in [".npy", ".npz"]: - out = np.load(path) - elif pathlib.Path(path).suffix in [".csv"]: - import pandas as pd - out = pd.read_csv(path) - return out - # if out is None: - # return None - # else: - # key = Array(c_wchar, '\n'.join(list(out.keys())), lock=False) - # val = Array('i', out.values(), lock=False) - # return (key, val) - - -from torch import optim - - -def get_optimizer(params, lr, betas, eps, momentum, optimizer_name): - if optimizer_name.lower() == "adamw": - optimizer = optim.AdamW( - params, lr=lr, betas=betas, eps=eps - ) - elif optimizer_name.lower() == "sgd": - optimizer = optim.SGD( - params, lr=lr, momentum=momentum - ) - elif optimizer_name.lower() == "adam": - optimizer = optim.Adam( - params, lr=lr, betas=betas, eps=eps - ) - else: - raise ValueError("optimizer name is not correct") - return optimizer diff --git a/spaces/muellerzr/accelerate-presentation/Accelerate_files/libs/quarto-diagram/mermaid.min.js b/spaces/muellerzr/accelerate-presentation/Accelerate_files/libs/quarto-diagram/mermaid.min.js deleted file mode 100644 index 8be75537a60af22b31980133b8ef6195322b234a..0000000000000000000000000000000000000000 --- a/spaces/muellerzr/accelerate-presentation/Accelerate_files/libs/quarto-diagram/mermaid.min.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see mermaid.min.js.LICENSE.txt */ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.mermaid=e():t.mermaid=e()}("undefined"!=typeof self?self:this,(()=>(()=>{var t={1362:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,3],n=[1,7],r=[1,8],i=[1,9],a=[1,10],o=[1,13],s=[1,12],c=[1,16,25],u=[1,20],l=[1,31],h=[1,32],f=[1,33],d=[1,35],p=[1,38],g=[1,36],y=[1,37],m=[1,39],v=[1,40],b=[1,41],_=[1,42],x=[1,45],w=[1,46],k=[1,47],T=[1,48],E=[16,25],C=[1,62],S=[1,63],A=[1,64],M=[1,65],N=[1,66],D=[1,67],L=[16,25,32,44,45,53,56,57,58,59,60,61,66,68],B=[16,25,30,32,44,45,49,53,56,57,58,59,60,61,66,68,83,84,85,86],O=[5,8,9,10,11,16,19,23,25],I=[53,83,84,85,86],R=[53,60,61,83,84,85,86],F=[53,56,57,58,59,83,84,85,86],P=[16,25,32],Y=[1,99],j={trace:function(){},yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statments:5,direction:6,directive:7,direction_tb:8,direction_bt:9,direction_rl:10,direction_lr:11,graphConfig:12,openDirective:13,typeDirective:14,closeDirective:15,NEWLINE:16,":":17,argDirective:18,open_directive:19,type_directive:20,arg_directive:21,close_directive:22,CLASS_DIAGRAM:23,statements:24,EOF:25,statement:26,className:27,alphaNumToken:28,classLiteralName:29,GENERICTYPE:30,relationStatement:31,LABEL:32,classStatement:33,methodStatement:34,annotationStatement:35,clickStatement:36,cssClassStatement:37,acc_title:38,acc_title_value:39,acc_descr:40,acc_descr_value:41,acc_descr_multiline_value:42,CLASS:43,STYLE_SEPARATOR:44,STRUCT_START:45,members:46,STRUCT_STOP:47,ANNOTATION_START:48,ANNOTATION_END:49,MEMBER:50,SEPARATOR:51,relation:52,STR:53,relationType:54,lineType:55,AGGREGATION:56,EXTENSION:57,COMPOSITION:58,DEPENDENCY:59,LINE:60,DOTTED_LINE:61,CALLBACK:62,LINK:63,LINK_TARGET:64,CLICK:65,CALLBACK_NAME:66,CALLBACK_ARGS:67,HREF:68,CSSCLASS:69,commentToken:70,textToken:71,graphCodeTokens:72,textNoTagsToken:73,TAGSTART:74,TAGEND:75,"==":76,"--":77,PCT:78,DEFAULT:79,SPACE:80,MINUS:81,keywords:82,UNICODE_TEXT:83,NUM:84,ALPHA:85,BQUOTE_STR:86,$accept:0,$end:1},terminals_:{2:"error",5:"statments",8:"direction_tb",9:"direction_bt",10:"direction_rl",11:"direction_lr",16:"NEWLINE",17:":",19:"open_directive",20:"type_directive",21:"arg_directive",22:"close_directive",23:"CLASS_DIAGRAM",25:"EOF",30:"GENERICTYPE",32:"LABEL",38:"acc_title",39:"acc_title_value",40:"acc_descr",41:"acc_descr_value",42:"acc_descr_multiline_value",43:"CLASS",44:"STYLE_SEPARATOR",45:"STRUCT_START",47:"STRUCT_STOP",48:"ANNOTATION_START",49:"ANNOTATION_END",50:"MEMBER",51:"SEPARATOR",53:"STR",56:"AGGREGATION",57:"EXTENSION",58:"COMPOSITION",59:"DEPENDENCY",60:"LINE",61:"DOTTED_LINE",62:"CALLBACK",63:"LINK",64:"LINK_TARGET",65:"CLICK",66:"CALLBACK_NAME",67:"CALLBACK_ARGS",68:"HREF",69:"CSSCLASS",72:"graphCodeTokens",74:"TAGSTART",75:"TAGEND",76:"==",77:"--",78:"PCT",79:"DEFAULT",80:"SPACE",81:"MINUS",82:"keywords",83:"UNICODE_TEXT",84:"NUM",85:"ALPHA",86:"BQUOTE_STR"},productions_:[0,[3,1],[3,1],[3,1],[3,2],[6,1],[6,1],[6,1],[6,1],[4,1],[7,4],[7,6],[13,1],[14,1],[18,1],[15,1],[12,4],[24,1],[24,2],[24,3],[27,1],[27,1],[27,2],[27,2],[27,2],[26,1],[26,2],[26,1],[26,1],[26,1],[26,1],[26,1],[26,1],[26,1],[26,2],[26,2],[26,1],[33,2],[33,4],[33,5],[33,7],[35,4],[46,1],[46,2],[34,1],[34,2],[34,1],[34,1],[31,3],[31,4],[31,4],[31,5],[52,3],[52,2],[52,2],[52,1],[54,1],[54,1],[54,1],[54,1],[55,1],[55,1],[36,3],[36,4],[36,3],[36,4],[36,4],[36,5],[36,3],[36,4],[36,4],[36,5],[36,3],[36,4],[36,4],[36,5],[37,3],[70,1],[70,1],[71,1],[71,1],[71,1],[71,1],[71,1],[71,1],[71,1],[73,1],[73,1],[73,1],[73,1],[28,1],[28,1],[28,1],[29,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 5:r.setDirection("TB");break;case 6:r.setDirection("BT");break;case 7:r.setDirection("RL");break;case 8:r.setDirection("LR");break;case 12:r.parseDirective("%%{","open_directive");break;case 13:r.parseDirective(a[s],"type_directive");break;case 14:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 15:r.parseDirective("}%%","close_directive","class");break;case 20:case 21:this.$=a[s];break;case 22:this.$=a[s-1]+a[s];break;case 23:case 24:this.$=a[s-1]+"~"+a[s];break;case 25:r.addRelation(a[s]);break;case 26:a[s-1].title=r.cleanupLabel(a[s]),r.addRelation(a[s-1]);break;case 34:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 35:case 36:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 37:r.addClass(a[s]);break;case 38:r.addClass(a[s-2]),r.setCssClass(a[s-2],a[s]);break;case 39:r.addClass(a[s-3]),r.addMembers(a[s-3],a[s-1]);break;case 40:r.addClass(a[s-5]),r.setCssClass(a[s-5],a[s-3]),r.addMembers(a[s-5],a[s-1]);break;case 41:r.addAnnotation(a[s],a[s-2]);break;case 42:this.$=[a[s]];break;case 43:a[s].push(a[s-1]),this.$=a[s];break;case 44:case 46:case 47:break;case 45:r.addMember(a[s-1],r.cleanupLabel(a[s]));break;case 48:this.$={id1:a[s-2],id2:a[s],relation:a[s-1],relationTitle1:"none",relationTitle2:"none"};break;case 49:this.$={id1:a[s-3],id2:a[s],relation:a[s-1],relationTitle1:a[s-2],relationTitle2:"none"};break;case 50:this.$={id1:a[s-3],id2:a[s],relation:a[s-2],relationTitle1:"none",relationTitle2:a[s-1]};break;case 51:this.$={id1:a[s-4],id2:a[s],relation:a[s-2],relationTitle1:a[s-3],relationTitle2:a[s-1]};break;case 52:this.$={type1:a[s-2],type2:a[s],lineType:a[s-1]};break;case 53:this.$={type1:"none",type2:a[s],lineType:a[s-1]};break;case 54:this.$={type1:a[s-1],type2:"none",lineType:a[s]};break;case 55:this.$={type1:"none",type2:"none",lineType:a[s]};break;case 56:this.$=r.relationType.AGGREGATION;break;case 57:this.$=r.relationType.EXTENSION;break;case 58:this.$=r.relationType.COMPOSITION;break;case 59:this.$=r.relationType.DEPENDENCY;break;case 60:this.$=r.lineType.LINE;break;case 61:this.$=r.lineType.DOTTED_LINE;break;case 62:case 68:this.$=a[s-2],r.setClickEvent(a[s-1],a[s]);break;case 63:case 69:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 64:case 72:this.$=a[s-2],r.setLink(a[s-1],a[s]);break;case 65:case 73:this.$=a[s-3],r.setLink(a[s-2],a[s-1],a[s]);break;case 66:case 74:this.$=a[s-3],r.setLink(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 67:case 75:this.$=a[s-4],r.setLink(a[s-3],a[s-2],a[s]),r.setTooltip(a[s-3],a[s-1]);break;case 70:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 71:this.$=a[s-4],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 76:r.setCssClass(a[s-1],a[s])}},table:[{3:1,4:2,5:e,6:4,7:5,8:n,9:r,10:i,11:a,12:6,13:11,19:o,23:s},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},{3:14,4:2,5:e,6:4,7:5,8:n,9:r,10:i,11:a,12:6,13:11,19:o,23:s},{1:[2,9]},t(c,[2,5]),t(c,[2,6]),t(c,[2,7]),t(c,[2,8]),{14:15,20:[1,16]},{16:[1,17]},{20:[2,12]},{1:[2,4]},{15:18,17:[1,19],22:u},t([17,22],[2,13]),{6:30,7:29,8:n,9:r,10:i,11:a,13:11,19:o,24:21,26:22,27:34,28:43,29:44,31:23,33:24,34:25,35:26,36:27,37:28,38:l,40:h,42:f,43:d,48:p,50:g,51:y,62:m,63:v,65:b,69:_,83:x,84:w,85:k,86:T},{16:[1,49]},{18:50,21:[1,51]},{16:[2,15]},{25:[1,52]},{16:[1,53],25:[2,17]},t(E,[2,25],{32:[1,54]}),t(E,[2,27]),t(E,[2,28]),t(E,[2,29]),t(E,[2,30]),t(E,[2,31]),t(E,[2,32]),t(E,[2,33]),{39:[1,55]},{41:[1,56]},t(E,[2,36]),t(E,[2,44],{52:57,54:60,55:61,32:[1,59],53:[1,58],56:C,57:S,58:A,59:M,60:N,61:D}),{27:68,28:43,29:44,83:x,84:w,85:k,86:T},t(E,[2,46]),t(E,[2,47]),{28:69,83:x,84:w,85:k},{27:70,28:43,29:44,83:x,84:w,85:k,86:T},{27:71,28:43,29:44,83:x,84:w,85:k,86:T},{27:72,28:43,29:44,83:x,84:w,85:k,86:T},{53:[1,73]},t(L,[2,20],{28:43,29:44,27:74,30:[1,75],83:x,84:w,85:k,86:T}),t(L,[2,21],{30:[1,76]}),t(B,[2,90]),t(B,[2,91]),t(B,[2,92]),t([16,25,30,32,44,45,53,56,57,58,59,60,61,66,68],[2,93]),t(O,[2,10]),{15:77,22:u},{22:[2,14]},{1:[2,16]},{6:30,7:29,8:n,9:r,10:i,11:a,13:11,19:o,24:78,25:[2,18],26:22,27:34,28:43,29:44,31:23,33:24,34:25,35:26,36:27,37:28,38:l,40:h,42:f,43:d,48:p,50:g,51:y,62:m,63:v,65:b,69:_,83:x,84:w,85:k,86:T},t(E,[2,26]),t(E,[2,34]),t(E,[2,35]),{27:79,28:43,29:44,53:[1,80],83:x,84:w,85:k,86:T},{52:81,54:60,55:61,56:C,57:S,58:A,59:M,60:N,61:D},t(E,[2,45]),{55:82,60:N,61:D},t(I,[2,55],{54:83,56:C,57:S,58:A,59:M}),t(R,[2,56]),t(R,[2,57]),t(R,[2,58]),t(R,[2,59]),t(F,[2,60]),t(F,[2,61]),t(E,[2,37],{44:[1,84],45:[1,85]}),{49:[1,86]},{53:[1,87]},{53:[1,88]},{66:[1,89],68:[1,90]},{28:91,83:x,84:w,85:k},t(L,[2,22]),t(L,[2,23]),t(L,[2,24]),{16:[1,92]},{25:[2,19]},t(P,[2,48]),{27:93,28:43,29:44,83:x,84:w,85:k,86:T},{27:94,28:43,29:44,53:[1,95],83:x,84:w,85:k,86:T},t(I,[2,54],{54:96,56:C,57:S,58:A,59:M}),t(I,[2,53]),{28:97,83:x,84:w,85:k},{46:98,50:Y},{27:100,28:43,29:44,83:x,84:w,85:k,86:T},t(E,[2,62],{53:[1,101]}),t(E,[2,64],{53:[1,103],64:[1,102]}),t(E,[2,68],{53:[1,104],67:[1,105]}),t(E,[2,72],{53:[1,107],64:[1,106]}),t(E,[2,76]),t(O,[2,11]),t(P,[2,50]),t(P,[2,49]),{27:108,28:43,29:44,83:x,84:w,85:k,86:T},t(I,[2,52]),t(E,[2,38],{45:[1,109]}),{47:[1,110]},{46:111,47:[2,42],50:Y},t(E,[2,41]),t(E,[2,63]),t(E,[2,65]),t(E,[2,66],{64:[1,112]}),t(E,[2,69]),t(E,[2,70],{53:[1,113]}),t(E,[2,73]),t(E,[2,74],{64:[1,114]}),t(P,[2,51]),{46:115,50:Y},t(E,[2,39]),{47:[2,43]},t(E,[2,67]),t(E,[2,71]),t(E,[2,75]),{47:[1,116]},t(E,[2,40])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],6:[2,9],13:[2,12],14:[2,4],20:[2,15],51:[2,14],52:[2,16],78:[2,19],111:[2,43]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},U={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),19;case 1:return 8;case 2:return 9;case 3:return 10;case 4:return 11;case 5:return this.begin("type_directive"),20;case 6:return this.popState(),this.begin("arg_directive"),17;case 7:return this.popState(),this.popState(),22;case 8:return 21;case 9:case 10:case 19:case 26:break;case 11:return this.begin("acc_title"),38;case 12:return this.popState(),"acc_title_value";case 13:return this.begin("acc_descr"),40;case 14:return this.popState(),"acc_descr_value";case 15:this.begin("acc_descr_multiline");break;case 16:case 36:case 39:case 42:case 45:case 48:case 51:this.popState();break;case 17:return"acc_descr_multiline_value";case 18:return 16;case 20:case 21:return 23;case 22:return this.begin("struct"),45;case 23:return"EOF_IN_STRUCT";case 24:return"OPEN_IN_STRUCT";case 25:return this.popState(),47;case 27:return"MEMBER";case 28:return 43;case 29:return 69;case 30:return 62;case 31:return 63;case 32:return 65;case 33:return 48;case 34:return 49;case 35:this.begin("generic");break;case 37:return"GENERICTYPE";case 38:this.begin("string");break;case 40:return"STR";case 41:this.begin("bqstring");break;case 43:return"BQUOTE_STR";case 44:this.begin("href");break;case 46:return 68;case 47:this.begin("callback_name");break;case 49:this.popState(),this.begin("callback_args");break;case 50:return 66;case 52:return 67;case 53:case 54:case 55:case 56:return 64;case 57:case 58:return 57;case 59:case 60:return 59;case 61:return 58;case 62:return 56;case 63:return 60;case 64:return 61;case 65:return 32;case 66:return 44;case 67:return 81;case 68:return"DOT";case 69:return"PLUS";case 70:return 78;case 71:case 72:return"EQUALS";case 73:return 85;case 74:return"PUNCTUATION";case 75:return 84;case 76:return 83;case 77:return 80;case 78:return 25}},rules:[/^(?:%%\{)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:((?:(?!\}%%)[^:.])*))/,/^(?::)/,/^(?:\}%%)/,/^(?:((?:(?!\}%%).|\n)*))/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:classDiagram-v2\b)/,/^(?:classDiagram\b)/,/^(?:[{])/,/^(?:$)/,/^(?:[{])/,/^(?:[}])/,/^(?:[\n])/,/^(?:[^{}\n]*)/,/^(?:class\b)/,/^(?:cssClass\b)/,/^(?:callback\b)/,/^(?:link\b)/,/^(?:click\b)/,/^(?:<<)/,/^(?:>>)/,/^(?:[~])/,/^(?:[~])/,/^(?:[^~]*)/,/^(?:["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:[`])/,/^(?:[`])/,/^(?:[^`]+)/,/^(?:href[\s]+["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:\s*<\|)/,/^(?:\s*\|>)/,/^(?:\s*>)/,/^(?:\s*<)/,/^(?:\s*\*)/,/^(?:\s*o\b)/,/^(?:--)/,/^(?:\.\.)/,/^(?::{1}[^:\n;]+)/,/^(?::{3})/,/^(?:-)/,/^(?:\.)/,/^(?:\+)/,/^(?:%)/,/^(?:=)/,/^(?:=)/,/^(?:\w+)/,/^(?:[!"#$%&'*+,-.`?\\/])/,/^(?:[0-9]+)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\s)/,/^(?:$)/],conditions:{acc_descr_multiline:{rules:[16,17],inclusive:!1},acc_descr:{rules:[14],inclusive:!1},acc_title:{rules:[12],inclusive:!1},arg_directive:{rules:[7,8],inclusive:!1},type_directive:{rules:[6,7],inclusive:!1},open_directive:{rules:[5],inclusive:!1},callback_args:{rules:[51,52],inclusive:!1},callback_name:{rules:[48,49,50],inclusive:!1},href:{rules:[45,46],inclusive:!1},struct:{rules:[23,24,25,26,27],inclusive:!1},generic:{rules:[36,37],inclusive:!1},bqstring:{rules:[42,43],inclusive:!1},string:{rules:[39,40],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,9,10,11,13,15,18,19,20,21,22,28,29,30,31,32,33,34,35,38,41,44,47,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78],inclusive:!0}}};function z(){this.yy={}}return j.lexer=U,z.prototype=j,j.Parser=z,new z}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8218).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},5890:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,5],r=[6,9,11,23,25,27,29,30,49],i=[1,17],a=[1,18],o=[1,19],s=[1,20],c=[1,21],u=[1,24],l=[1,29],h=[1,30],f=[1,31],d=[1,32],p=[6,9,11,15,20,23,25,27,29,30,42,43,44,45,49],g=[1,45],y=[30,46,47],m=[4,6,9,11,23,25,27,29,30,49],v=[42,43,44,45],b=[22,37],_=[1,64],x={trace:function(){},yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,directive:7,line:8,SPACE:9,statement:10,NEWLINE:11,openDirective:12,typeDirective:13,closeDirective:14,":":15,argDirective:16,entityName:17,relSpec:18,role:19,BLOCK_START:20,attributes:21,BLOCK_STOP:22,title:23,title_value:24,acc_title:25,acc_title_value:26,acc_descr:27,acc_descr_value:28,acc_descr_multiline_value:29,ALPHANUM:30,".":31,attribute:32,attributeType:33,attributeName:34,attributeKeyType:35,attributeComment:36,ATTRIBUTE_WORD:37,ATTRIBUTE_KEY:38,COMMENT:39,cardinality:40,relType:41,ZERO_OR_ONE:42,ZERO_OR_MORE:43,ONE_OR_MORE:44,ONLY_ONE:45,NON_IDENTIFYING:46,IDENTIFYING:47,WORD:48,open_directive:49,type_directive:50,arg_directive:51,close_directive:52,$accept:0,$end:1},terminals_:{2:"error",4:"ER_DIAGRAM",6:"EOF",9:"SPACE",11:"NEWLINE",15:":",20:"BLOCK_START",22:"BLOCK_STOP",23:"title",24:"title_value",25:"acc_title",26:"acc_title_value",27:"acc_descr",28:"acc_descr_value",29:"acc_descr_multiline_value",30:"ALPHANUM",31:".",37:"ATTRIBUTE_WORD",38:"ATTRIBUTE_KEY",39:"COMMENT",42:"ZERO_OR_ONE",43:"ZERO_OR_MORE",44:"ONE_OR_MORE",45:"ONLY_ONE",46:"NON_IDENTIFYING",47:"IDENTIFYING",48:"WORD",49:"open_directive",50:"type_directive",51:"arg_directive",52:"close_directive"},productions_:[0,[3,3],[3,2],[5,0],[5,2],[8,2],[8,1],[8,1],[8,1],[7,4],[7,6],[10,1],[10,5],[10,4],[10,3],[10,1],[10,2],[10,2],[10,2],[10,1],[17,1],[17,3],[21,1],[21,2],[32,2],[32,3],[32,3],[32,4],[33,1],[34,1],[35,1],[36,1],[18,3],[40,1],[40,1],[40,1],[40,1],[41,1],[41,1],[19,1],[19,1],[12,1],[13,1],[16,1],[14,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 1:break;case 3:case 7:case 8:this.$=[];break;case 4:a[s-1].push(a[s]),this.$=a[s-1];break;case 5:case 6:case 20:case 28:case 29:case 30:case 40:this.$=a[s];break;case 12:r.addEntity(a[s-4]),r.addEntity(a[s-2]),r.addRelationship(a[s-4],a[s],a[s-2],a[s-3]);break;case 13:r.addEntity(a[s-3]),r.addAttributes(a[s-3],a[s-1]);break;case 14:r.addEntity(a[s-2]);break;case 15:r.addEntity(a[s]);break;case 16:case 17:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 18:case 19:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 21:this.$=a[s-2]+a[s-1]+a[s];break;case 22:this.$=[a[s]];break;case 23:a[s].push(a[s-1]),this.$=a[s];break;case 24:this.$={attributeType:a[s-1],attributeName:a[s]};break;case 25:this.$={attributeType:a[s-2],attributeName:a[s-1],attributeKeyType:a[s]};break;case 26:this.$={attributeType:a[s-2],attributeName:a[s-1],attributeComment:a[s]};break;case 27:this.$={attributeType:a[s-3],attributeName:a[s-2],attributeKeyType:a[s-1],attributeComment:a[s]};break;case 31:case 39:this.$=a[s].replace(/"/g,"");break;case 32:this.$={cardA:a[s],relType:a[s-1],cardB:a[s-2]};break;case 33:this.$=r.Cardinality.ZERO_OR_ONE;break;case 34:this.$=r.Cardinality.ZERO_OR_MORE;break;case 35:this.$=r.Cardinality.ONE_OR_MORE;break;case 36:this.$=r.Cardinality.ONLY_ONE;break;case 37:this.$=r.Identification.NON_IDENTIFYING;break;case 38:this.$=r.Identification.IDENTIFYING;break;case 41:r.parseDirective("%%{","open_directive");break;case 42:r.parseDirective(a[s],"type_directive");break;case 43:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 44:r.parseDirective("}%%","close_directive","er")}},table:[{3:1,4:e,7:3,12:4,49:n},{1:[3]},t(r,[2,3],{5:6}),{3:7,4:e,7:3,12:4,49:n},{13:8,50:[1,9]},{50:[2,41]},{6:[1,10],7:15,8:11,9:[1,12],10:13,11:[1,14],12:4,17:16,23:i,25:a,27:o,29:s,30:c,49:n},{1:[2,2]},{14:22,15:[1,23],52:u},t([15,52],[2,42]),t(r,[2,8],{1:[2,1]}),t(r,[2,4]),{7:15,10:25,12:4,17:16,23:i,25:a,27:o,29:s,30:c,49:n},t(r,[2,6]),t(r,[2,7]),t(r,[2,11]),t(r,[2,15],{18:26,40:28,20:[1,27],42:l,43:h,44:f,45:d}),{24:[1,33]},{26:[1,34]},{28:[1,35]},t(r,[2,19]),t(p,[2,20],{31:[1,36]}),{11:[1,37]},{16:38,51:[1,39]},{11:[2,44]},t(r,[2,5]),{17:40,30:c},{21:41,22:[1,42],32:43,33:44,37:g},{41:46,46:[1,47],47:[1,48]},t(y,[2,33]),t(y,[2,34]),t(y,[2,35]),t(y,[2,36]),t(r,[2,16]),t(r,[2,17]),t(r,[2,18]),{17:49,30:c},t(m,[2,9]),{14:50,52:u},{52:[2,43]},{15:[1,51]},{22:[1,52]},t(r,[2,14]),{21:53,22:[2,22],32:43,33:44,37:g},{34:54,37:[1,55]},{37:[2,28]},{40:56,42:l,43:h,44:f,45:d},t(v,[2,37]),t(v,[2,38]),t(p,[2,21]),{11:[1,57]},{19:58,30:[1,60],48:[1,59]},t(r,[2,13]),{22:[2,23]},t(b,[2,24],{35:61,36:62,38:[1,63],39:_}),t([22,37,38,39],[2,29]),{30:[2,32]},t(m,[2,10]),t(r,[2,12]),t(r,[2,39]),t(r,[2,40]),t(b,[2,25],{36:65,39:_}),t(b,[2,26]),t([22,37,39],[2,30]),t(b,[2,31]),t(b,[2,27])],defaultActions:{5:[2,41],7:[2,2],24:[2,44],39:[2,43],45:[2,28],53:[2,23],56:[2,32]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},w={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("acc_title"),25;case 1:return this.popState(),"acc_title_value";case 2:return this.begin("acc_descr"),27;case 3:return this.popState(),"acc_descr_value";case 4:this.begin("acc_descr_multiline");break;case 5:this.popState();break;case 6:return"acc_descr_multiline_value";case 7:return this.begin("open_directive"),49;case 8:return this.begin("type_directive"),50;case 9:return this.popState(),this.begin("arg_directive"),15;case 10:return this.popState(),this.popState(),52;case 11:return 51;case 12:case 13:case 15:case 20:case 24:break;case 14:return 11;case 16:return 9;case 17:return 48;case 18:return 4;case 19:return this.begin("block"),20;case 21:return 38;case 22:return 37;case 23:return 39;case 25:return this.popState(),22;case 26:case 39:return e.yytext[0];case 27:case 31:return 42;case 28:case 32:return 43;case 29:case 33:return 44;case 30:return 45;case 34:case 36:case 37:return 46;case 35:return 47;case 38:return 30;case 40:return 6}},rules:[/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:[\s]+)/i,/^(?:"[^"]*")/i,/^(?:erDiagram\b)/i,/^(?:\{)/i,/^(?:\s+)/i,/^(?:(?:PK)|(?:FK))/i,/^(?:[A-Za-z][A-Za-z0-9\-_]*)/i,/^(?:"[^"]*")/i,/^(?:[\n]+)/i,/^(?:\})/i,/^(?:.)/i,/^(?:\|o\b)/i,/^(?:\}o\b)/i,/^(?:\}\|)/i,/^(?:\|\|)/i,/^(?:o\|)/i,/^(?:o\{)/i,/^(?:\|\{)/i,/^(?:\.\.)/i,/^(?:--)/i,/^(?:\.-)/i,/^(?:-\.)/i,/^(?:[A-Za-z][A-Za-z0-9\-_]*)/i,/^(?:.)/i,/^(?:$)/i],conditions:{acc_descr_multiline:{rules:[5,6],inclusive:!1},acc_descr:{rules:[3],inclusive:!1},acc_title:{rules:[1],inclusive:!1},open_directive:{rules:[8],inclusive:!1},type_directive:{rules:[9,10],inclusive:!1},arg_directive:{rules:[10,11],inclusive:!1},block:{rules:[20,21,22,23,24,25,26],inclusive:!1},INITIAL:{rules:[0,2,4,7,12,13,14,15,16,17,18,19,27,28,29,30,31,32,33,34,35,36,37,38,39,40],inclusive:!0}}};function k(){this.yy={}}return x.lexer=w,k.prototype=x,x.Parser=k,new k}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8009).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},3602:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,9],n=[1,7],r=[1,6],i=[1,8],a=[1,20,21,22,23,38,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],o=[2,10],s=[1,20],c=[1,21],u=[1,22],l=[1,23],h=[1,30],f=[1,32],d=[1,33],p=[1,34],g=[1,62],y=[1,48],m=[1,52],v=[1,36],b=[1,37],_=[1,38],x=[1,39],w=[1,40],k=[1,56],T=[1,63],E=[1,51],C=[1,53],S=[1,55],A=[1,59],M=[1,60],N=[1,41],D=[1,42],L=[1,43],B=[1,44],O=[1,61],I=[1,50],R=[1,54],F=[1,57],P=[1,58],Y=[1,49],j=[1,66],U=[1,71],z=[1,20,21,22,23,38,42,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],$=[1,75],q=[1,74],H=[1,76],W=[20,21,23,81,82],V=[1,99],G=[1,104],X=[1,107],Z=[1,108],K=[1,101],Q=[1,106],J=[1,109],tt=[1,102],et=[1,114],nt=[1,113],rt=[1,103],it=[1,105],at=[1,110],ot=[1,111],st=[1,112],ct=[1,115],ut=[20,21,22,23,81,82],lt=[20,21,22,23,53,81,82],ht=[20,21,22,23,40,52,53,55,57,59,61,63,65,66,67,69,71,73,74,76,81,82,91,95,105,106,109,111,112,122,123,124,125,126,127],ft=[20,21,23],dt=[20,21,23,52,66,67,81,82,91,95,105,106,109,111,112,122,123,124,125,126,127],pt=[1,12,20,21,22,23,24,38,42,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],gt=[52,66,67,91,95,105,106,109,111,112,122,123,124,125,126,127],yt=[1,149],mt=[1,157],vt=[1,158],bt=[1,159],_t=[1,160],xt=[1,144],wt=[1,145],kt=[1,141],Tt=[1,152],Et=[1,153],Ct=[1,154],St=[1,155],At=[1,156],Mt=[1,161],Nt=[1,162],Dt=[1,147],Lt=[1,150],Bt=[1,146],Ot=[1,143],It=[20,21,22,23,38,42,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],Rt=[1,165],Ft=[20,21,22,23,26,52,66,67,91,105,106,109,111,112,122,123,124,125,126,127],Pt=[20,21,22,23,24,26,38,40,41,42,52,56,58,60,62,64,66,67,68,70,72,73,75,77,81,82,86,87,88,89,90,91,92,95,105,106,109,111,112,113,114,122,123,124,125,126,127],Yt=[12,21,22,24],jt=[22,106],Ut=[1,250],zt=[1,245],$t=[1,246],qt=[1,254],Ht=[1,251],Wt=[1,248],Vt=[1,247],Gt=[1,249],Xt=[1,252],Zt=[1,253],Kt=[1,255],Qt=[1,273],Jt=[20,21,23,106],te=[20,21,22,23,66,67,86,102,105,106,109,110,111,112,113],ee={trace:function(){},yy:{},symbols_:{error:2,start:3,mermaidDoc:4,directive:5,openDirective:6,typeDirective:7,closeDirective:8,separator:9,":":10,argDirective:11,open_directive:12,type_directive:13,arg_directive:14,close_directive:15,graphConfig:16,document:17,line:18,statement:19,SEMI:20,NEWLINE:21,SPACE:22,EOF:23,GRAPH:24,NODIR:25,DIR:26,FirstStmtSeperator:27,ending:28,endToken:29,spaceList:30,spaceListNewline:31,verticeStatement:32,styleStatement:33,linkStyleStatement:34,classDefStatement:35,classStatement:36,clickStatement:37,subgraph:38,text:39,SQS:40,SQE:41,end:42,direction:43,acc_title:44,acc_title_value:45,acc_descr:46,acc_descr_value:47,acc_descr_multiline_value:48,link:49,node:50,vertex:51,AMP:52,STYLE_SEPARATOR:53,idString:54,DOUBLECIRCLESTART:55,DOUBLECIRCLEEND:56,PS:57,PE:58,"(-":59,"-)":60,STADIUMSTART:61,STADIUMEND:62,SUBROUTINESTART:63,SUBROUTINEEND:64,VERTEX_WITH_PROPS_START:65,ALPHA:66,COLON:67,PIPE:68,CYLINDERSTART:69,CYLINDEREND:70,DIAMOND_START:71,DIAMOND_STOP:72,TAGEND:73,TRAPSTART:74,TRAPEND:75,INVTRAPSTART:76,INVTRAPEND:77,linkStatement:78,arrowText:79,TESTSTR:80,START_LINK:81,LINK:82,textToken:83,STR:84,keywords:85,STYLE:86,LINKSTYLE:87,CLASSDEF:88,CLASS:89,CLICK:90,DOWN:91,UP:92,textNoTags:93,textNoTagsToken:94,DEFAULT:95,stylesOpt:96,alphaNum:97,CALLBACKNAME:98,CALLBACKARGS:99,HREF:100,LINK_TARGET:101,HEX:102,numList:103,INTERPOLATE:104,NUM:105,COMMA:106,style:107,styleComponent:108,MINUS:109,UNIT:110,BRKT:111,DOT:112,PCT:113,TAGSTART:114,alphaNumToken:115,idStringToken:116,alphaNumStatement:117,direction_tb:118,direction_bt:119,direction_rl:120,direction_lr:121,PUNCTUATION:122,UNICODE_TEXT:123,PLUS:124,EQUALS:125,MULT:126,UNDERSCORE:127,graphCodeTokens:128,ARROW_CROSS:129,ARROW_POINT:130,ARROW_CIRCLE:131,ARROW_OPEN:132,QUOTE:133,$accept:0,$end:1},terminals_:{2:"error",10:":",12:"open_directive",13:"type_directive",14:"arg_directive",15:"close_directive",20:"SEMI",21:"NEWLINE",22:"SPACE",23:"EOF",24:"GRAPH",25:"NODIR",26:"DIR",38:"subgraph",40:"SQS",41:"SQE",42:"end",44:"acc_title",45:"acc_title_value",46:"acc_descr",47:"acc_descr_value",48:"acc_descr_multiline_value",52:"AMP",53:"STYLE_SEPARATOR",55:"DOUBLECIRCLESTART",56:"DOUBLECIRCLEEND",57:"PS",58:"PE",59:"(-",60:"-)",61:"STADIUMSTART",62:"STADIUMEND",63:"SUBROUTINESTART",64:"SUBROUTINEEND",65:"VERTEX_WITH_PROPS_START",66:"ALPHA",67:"COLON",68:"PIPE",69:"CYLINDERSTART",70:"CYLINDEREND",71:"DIAMOND_START",72:"DIAMOND_STOP",73:"TAGEND",74:"TRAPSTART",75:"TRAPEND",76:"INVTRAPSTART",77:"INVTRAPEND",80:"TESTSTR",81:"START_LINK",82:"LINK",84:"STR",86:"STYLE",87:"LINKSTYLE",88:"CLASSDEF",89:"CLASS",90:"CLICK",91:"DOWN",92:"UP",95:"DEFAULT",98:"CALLBACKNAME",99:"CALLBACKARGS",100:"HREF",101:"LINK_TARGET",102:"HEX",104:"INTERPOLATE",105:"NUM",106:"COMMA",109:"MINUS",110:"UNIT",111:"BRKT",112:"DOT",113:"PCT",114:"TAGSTART",118:"direction_tb",119:"direction_bt",120:"direction_rl",121:"direction_lr",122:"PUNCTUATION",123:"UNICODE_TEXT",124:"PLUS",125:"EQUALS",126:"MULT",127:"UNDERSCORE",129:"ARROW_CROSS",130:"ARROW_POINT",131:"ARROW_CIRCLE",132:"ARROW_OPEN",133:"QUOTE"},productions_:[0,[3,1],[3,2],[5,4],[5,6],[6,1],[7,1],[11,1],[8,1],[4,2],[17,0],[17,2],[18,1],[18,1],[18,1],[18,1],[18,1],[16,2],[16,2],[16,2],[16,3],[28,2],[28,1],[29,1],[29,1],[29,1],[27,1],[27,1],[27,2],[31,2],[31,2],[31,1],[31,1],[30,2],[30,1],[19,2],[19,2],[19,2],[19,2],[19,2],[19,2],[19,9],[19,6],[19,4],[19,1],[19,2],[19,2],[19,1],[9,1],[9,1],[9,1],[32,3],[32,4],[32,2],[32,1],[50,1],[50,5],[50,3],[51,4],[51,4],[51,6],[51,4],[51,4],[51,4],[51,8],[51,4],[51,4],[51,4],[51,6],[51,4],[51,4],[51,4],[51,4],[51,4],[51,1],[49,2],[49,3],[49,3],[49,1],[49,3],[78,1],[79,3],[39,1],[39,2],[39,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[93,1],[93,2],[35,5],[35,5],[36,5],[37,2],[37,4],[37,3],[37,5],[37,2],[37,4],[37,4],[37,6],[37,2],[37,4],[37,2],[37,4],[37,4],[37,6],[33,5],[33,5],[34,5],[34,5],[34,9],[34,9],[34,7],[34,7],[103,1],[103,3],[96,1],[96,3],[107,1],[107,2],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[94,1],[94,1],[94,1],[94,1],[54,1],[54,2],[97,1],[97,2],[117,1],[117,1],[117,1],[117,1],[43,1],[43,1],[43,1],[43,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 5:r.parseDirective("%%{","open_directive");break;case 6:r.parseDirective(a[s],"type_directive");break;case 7:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 8:r.parseDirective("}%%","close_directive","flowchart");break;case 10:case 36:case 37:case 38:case 39:case 40:this.$=[];break;case 11:a[s]!==[]&&a[s-1].push(a[s]),this.$=a[s-1];break;case 12:case 82:case 84:case 96:case 152:case 154:case 155:case 78:case 150:this.$=a[s];break;case 19:r.setDirection("TB"),this.$="TB";break;case 20:r.setDirection(a[s-1]),this.$=a[s-1];break;case 35:this.$=a[s-1].nodes;break;case 41:this.$=r.addSubGraph(a[s-6],a[s-1],a[s-4]);break;case 42:this.$=r.addSubGraph(a[s-3],a[s-1],a[s-3]);break;case 43:this.$=r.addSubGraph(void 0,a[s-1],void 0);break;case 45:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 46:case 47:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 51:r.addLink(a[s-2].stmt,a[s],a[s-1]),this.$={stmt:a[s],nodes:a[s].concat(a[s-2].nodes)};break;case 52:r.addLink(a[s-3].stmt,a[s-1],a[s-2]),this.$={stmt:a[s-1],nodes:a[s-1].concat(a[s-3].nodes)};break;case 53:this.$={stmt:a[s-1],nodes:a[s-1]};break;case 54:this.$={stmt:a[s],nodes:a[s]};break;case 55:case 123:case 125:this.$=[a[s]];break;case 56:this.$=a[s-4].concat(a[s]);break;case 57:this.$=[a[s-2]],r.setClass(a[s-2],a[s]);break;case 58:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"square");break;case 59:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"doublecircle");break;case 60:this.$=a[s-5],r.addVertex(a[s-5],a[s-2],"circle");break;case 61:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"ellipse");break;case 62:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"stadium");break;case 63:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"subroutine");break;case 64:this.$=a[s-7],r.addVertex(a[s-7],a[s-1],"rect",void 0,void 0,void 0,Object.fromEntries([[a[s-5],a[s-3]]]));break;case 65:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"cylinder");break;case 66:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"round");break;case 67:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"diamond");break;case 68:this.$=a[s-5],r.addVertex(a[s-5],a[s-2],"hexagon");break;case 69:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"odd");break;case 70:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"trapezoid");break;case 71:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"inv_trapezoid");break;case 72:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"lean_right");break;case 73:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"lean_left");break;case 74:this.$=a[s],r.addVertex(a[s]);break;case 75:a[s-1].text=a[s],this.$=a[s-1];break;case 76:case 77:a[s-2].text=a[s-1],this.$=a[s-2];break;case 79:var c=r.destructLink(a[s],a[s-2]);this.$={type:c.type,stroke:c.stroke,length:c.length,text:a[s-1]};break;case 80:c=r.destructLink(a[s]),this.$={type:c.type,stroke:c.stroke,length:c.length};break;case 81:this.$=a[s-1];break;case 83:case 97:case 153:case 151:this.$=a[s-1]+""+a[s];break;case 98:case 99:this.$=a[s-4],r.addClass(a[s-2],a[s]);break;case 100:this.$=a[s-4],r.setClass(a[s-2],a[s]);break;case 101:case 109:this.$=a[s-1],r.setClickEvent(a[s-1],a[s]);break;case 102:case 110:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2]),r.setTooltip(a[s-3],a[s]);break;case 103:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 104:this.$=a[s-4],r.setClickEvent(a[s-4],a[s-3],a[s-2]),r.setTooltip(a[s-4],a[s]);break;case 105:case 111:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 106:case 112:this.$=a[s-3],r.setLink(a[s-3],a[s-2]),r.setTooltip(a[s-3],a[s]);break;case 107:case 113:this.$=a[s-3],r.setLink(a[s-3],a[s-2],a[s]);break;case 108:case 114:this.$=a[s-5],r.setLink(a[s-5],a[s-4],a[s]),r.setTooltip(a[s-5],a[s-2]);break;case 115:this.$=a[s-4],r.addVertex(a[s-2],void 0,void 0,a[s]);break;case 116:case 118:this.$=a[s-4],r.updateLink(a[s-2],a[s]);break;case 117:this.$=a[s-4],r.updateLink([a[s-2]],a[s]);break;case 119:this.$=a[s-8],r.updateLinkInterpolate([a[s-6]],a[s-2]),r.updateLink([a[s-6]],a[s]);break;case 120:this.$=a[s-8],r.updateLinkInterpolate(a[s-6],a[s-2]),r.updateLink(a[s-6],a[s]);break;case 121:this.$=a[s-6],r.updateLinkInterpolate([a[s-4]],a[s]);break;case 122:this.$=a[s-6],r.updateLinkInterpolate(a[s-4],a[s]);break;case 124:case 126:a[s-2].push(a[s]),this.$=a[s-2];break;case 128:this.$=a[s-1]+a[s];break;case 156:this.$="v";break;case 157:this.$="-";break;case 158:this.$={stmt:"dir",value:"TB"};break;case 159:this.$={stmt:"dir",value:"BT"};break;case 160:this.$={stmt:"dir",value:"RL"};break;case 161:this.$={stmt:"dir",value:"LR"}}},table:[{3:1,4:2,5:3,6:5,12:e,16:4,21:n,22:r,24:i},{1:[3]},{1:[2,1]},{3:10,4:2,5:3,6:5,12:e,16:4,21:n,22:r,24:i},t(a,o,{17:11}),{7:12,13:[1,13]},{16:14,21:n,22:r,24:i},{16:15,21:n,22:r,24:i},{25:[1,16],26:[1,17]},{13:[2,5]},{1:[2,2]},{1:[2,9],18:18,19:19,20:s,21:c,22:u,23:l,32:24,33:25,34:26,35:27,36:28,37:29,38:h,43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:v,87:b,88:_,89:x,90:w,91:k,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:D,120:L,121:B,122:O,123:I,124:R,125:F,126:P,127:Y},{8:64,10:[1,65],15:j},t([10,15],[2,6]),t(a,[2,17]),t(a,[2,18]),t(a,[2,19]),{20:[1,68],21:[1,69],22:U,27:67,30:70},t(z,[2,11]),t(z,[2,12]),t(z,[2,13]),t(z,[2,14]),t(z,[2,15]),t(z,[2,16]),{9:72,20:$,21:q,23:H,49:73,78:77,81:[1,78],82:[1,79]},{9:80,20:$,21:q,23:H},{9:81,20:$,21:q,23:H},{9:82,20:$,21:q,23:H},{9:83,20:$,21:q,23:H},{9:84,20:$,21:q,23:H},{9:86,20:$,21:q,22:[1,85],23:H},t(z,[2,44]),{45:[1,87]},{47:[1,88]},t(z,[2,47]),t(W,[2,54],{30:89,22:U}),{22:[1,90]},{22:[1,91]},{22:[1,92]},{22:[1,93]},{26:V,52:G,66:X,67:Z,84:[1,97],91:K,97:96,98:[1,94],100:[1,95],105:Q,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(z,[2,158]),t(z,[2,159]),t(z,[2,160]),t(z,[2,161]),t(ut,[2,55],{53:[1,116]}),t(lt,[2,74],{116:129,40:[1,117],52:g,55:[1,118],57:[1,119],59:[1,120],61:[1,121],63:[1,122],65:[1,123],66:y,67:m,69:[1,124],71:[1,125],73:[1,126],74:[1,127],76:[1,128],91:k,95:T,105:E,106:C,109:S,111:A,112:M,122:O,123:I,124:R,125:F,126:P,127:Y}),t(ht,[2,150]),t(ht,[2,175]),t(ht,[2,176]),t(ht,[2,177]),t(ht,[2,178]),t(ht,[2,179]),t(ht,[2,180]),t(ht,[2,181]),t(ht,[2,182]),t(ht,[2,183]),t(ht,[2,184]),t(ht,[2,185]),t(ht,[2,186]),t(ht,[2,187]),t(ht,[2,188]),t(ht,[2,189]),t(ht,[2,190]),{9:130,20:$,21:q,23:H},{11:131,14:[1,132]},t(ft,[2,8]),t(a,[2,20]),t(a,[2,26]),t(a,[2,27]),{21:[1,133]},t(dt,[2,34],{30:134,22:U}),t(z,[2,35]),{50:135,51:45,52:g,54:46,66:y,67:m,91:k,95:T,105:E,106:C,109:S,111:A,112:M,116:47,122:O,123:I,124:R,125:F,126:P,127:Y},t(pt,[2,48]),t(pt,[2,49]),t(pt,[2,50]),t(gt,[2,78],{79:136,68:[1,138],80:[1,137]}),{22:yt,24:mt,26:vt,38:bt,39:139,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t([52,66,67,68,80,91,95,105,106,109,111,112,122,123,124,125,126,127],[2,80]),t(z,[2,36]),t(z,[2,37]),t(z,[2,38]),t(z,[2,39]),t(z,[2,40]),{22:yt,24:mt,26:vt,38:bt,39:163,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(It,o,{17:164}),t(z,[2,45]),t(z,[2,46]),t(W,[2,53],{52:Rt}),{26:V,52:G,66:X,67:Z,91:K,97:166,102:[1,167],105:Q,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},{95:[1,168],103:169,105:[1,170]},{26:V,52:G,66:X,67:Z,91:K,95:[1,171],97:172,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},{26:V,52:G,66:X,67:Z,91:K,97:173,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ft,[2,101],{22:[1,174],99:[1,175]}),t(ft,[2,105],{22:[1,176]}),t(ft,[2,109],{115:100,117:178,22:[1,177],26:V,52:G,66:X,67:Z,91:K,105:Q,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),t(ft,[2,111],{22:[1,179]}),t(Ft,[2,152]),t(Ft,[2,154]),t(Ft,[2,155]),t(Ft,[2,156]),t(Ft,[2,157]),t(Pt,[2,162]),t(Pt,[2,163]),t(Pt,[2,164]),t(Pt,[2,165]),t(Pt,[2,166]),t(Pt,[2,167]),t(Pt,[2,168]),t(Pt,[2,169]),t(Pt,[2,170]),t(Pt,[2,171]),t(Pt,[2,172]),t(Pt,[2,173]),t(Pt,[2,174]),{52:g,54:180,66:y,67:m,91:k,95:T,105:E,106:C,109:S,111:A,112:M,116:47,122:O,123:I,124:R,125:F,126:P,127:Y},{22:yt,24:mt,26:vt,38:bt,39:181,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:182,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:184,42:_t,52:G,57:[1,183],66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:185,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:186,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:187,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{66:[1,188]},{22:yt,24:mt,26:vt,38:bt,39:189,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:190,42:_t,52:G,66:X,67:Z,71:[1,191],73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:192,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:193,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:194,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ht,[2,151]),t(Yt,[2,3]),{8:195,15:j},{15:[2,7]},t(a,[2,28]),t(dt,[2,33]),t(W,[2,51],{30:196,22:U}),t(gt,[2,75],{22:[1,197]}),{22:[1,198]},{22:yt,24:mt,26:vt,38:bt,39:199,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,66:X,67:Z,73:xt,81:wt,82:[1,200],83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(Pt,[2,82]),t(Pt,[2,84]),t(Pt,[2,140]),t(Pt,[2,141]),t(Pt,[2,142]),t(Pt,[2,143]),t(Pt,[2,144]),t(Pt,[2,145]),t(Pt,[2,146]),t(Pt,[2,147]),t(Pt,[2,148]),t(Pt,[2,149]),t(Pt,[2,85]),t(Pt,[2,86]),t(Pt,[2,87]),t(Pt,[2,88]),t(Pt,[2,89]),t(Pt,[2,90]),t(Pt,[2,91]),t(Pt,[2,92]),t(Pt,[2,93]),t(Pt,[2,94]),t(Pt,[2,95]),{9:203,20:$,21:q,22:yt,23:H,24:mt,26:vt,38:bt,40:[1,202],42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{18:18,19:19,20:s,21:c,22:u,23:l,32:24,33:25,34:26,35:27,36:28,37:29,38:h,42:[1,204],43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:v,87:b,88:_,89:x,90:w,91:k,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:D,120:L,121:B,122:O,123:I,124:R,125:F,126:P,127:Y},{22:U,30:205},{22:[1,206],26:V,52:G,66:X,67:Z,91:K,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:178,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:[1,207]},{22:[1,208]},{22:[1,209],106:[1,210]},t(jt,[2,123]),{22:[1,211]},{22:[1,212],26:V,52:G,66:X,67:Z,91:K,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:178,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:[1,213],26:V,52:G,66:X,67:Z,91:K,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:178,122:rt,123:it,124:at,125:ot,126:st,127:ct},{84:[1,214]},t(ft,[2,103],{22:[1,215]}),{84:[1,216],101:[1,217]},{84:[1,218]},t(Ft,[2,153]),{84:[1,219],101:[1,220]},t(ut,[2,57],{116:129,52:g,66:y,67:m,91:k,95:T,105:E,106:C,109:S,111:A,112:M,122:O,123:I,124:R,125:F,126:P,127:Y}),{22:yt,24:mt,26:vt,38:bt,41:[1,221],42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,56:[1,222],66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:223,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,58:[1,224],66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,60:[1,225],66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,62:[1,226],66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,64:[1,227],66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{67:[1,228]},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,66:X,67:Z,70:[1,229],73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,66:X,67:Z,72:[1,230],73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,39:231,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,41:[1,232],42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,66:X,67:Z,73:xt,75:[1,233],77:[1,234],81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,66:X,67:Z,73:xt,75:[1,236],77:[1,235],81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{9:237,20:$,21:q,23:H},t(W,[2,52],{52:Rt}),t(gt,[2,77]),t(gt,[2,76]),{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,66:X,67:Z,68:[1,238],73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(gt,[2,79]),t(Pt,[2,83]),{22:yt,24:mt,26:vt,38:bt,39:239,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(It,o,{17:240}),t(z,[2,43]),{51:241,52:g,54:46,66:y,67:m,91:k,95:T,105:E,106:C,109:S,111:A,112:M,116:47,122:O,123:I,124:R,125:F,126:P,127:Y},{22:Ut,66:zt,67:$t,86:qt,96:242,102:Ht,105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},{22:Ut,66:zt,67:$t,86:qt,96:256,102:Ht,105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},{22:Ut,66:zt,67:$t,86:qt,96:257,102:Ht,104:[1,258],105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},{22:Ut,66:zt,67:$t,86:qt,96:259,102:Ht,104:[1,260],105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},{105:[1,261]},{22:Ut,66:zt,67:$t,86:qt,96:262,102:Ht,105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},{22:Ut,66:zt,67:$t,86:qt,96:263,102:Ht,105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},{26:V,52:G,66:X,67:Z,91:K,97:264,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ft,[2,102]),{84:[1,265]},t(ft,[2,106],{22:[1,266]}),t(ft,[2,107]),t(ft,[2,110]),t(ft,[2,112],{22:[1,267]}),t(ft,[2,113]),t(lt,[2,58]),t(lt,[2,59]),{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,58:[1,268],66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(lt,[2,66]),t(lt,[2,61]),t(lt,[2,62]),t(lt,[2,63]),{66:[1,269]},t(lt,[2,65]),t(lt,[2,67]),{22:yt,24:mt,26:vt,38:bt,42:_t,52:G,66:X,67:Z,72:[1,270],73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(lt,[2,69]),t(lt,[2,70]),t(lt,[2,72]),t(lt,[2,71]),t(lt,[2,73]),t(Yt,[2,4]),t([22,52,66,67,91,95,105,106,109,111,112,122,123,124,125,126,127],[2,81]),{22:yt,24:mt,26:vt,38:bt,41:[1,271],42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{18:18,19:19,20:s,21:c,22:u,23:l,32:24,33:25,34:26,35:27,36:28,37:29,38:h,42:[1,272],43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:v,87:b,88:_,89:x,90:w,91:k,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:D,120:L,121:B,122:O,123:I,124:R,125:F,126:P,127:Y},t(ut,[2,56]),t(ft,[2,115],{106:Qt}),t(Jt,[2,125],{108:274,22:Ut,66:zt,67:$t,86:qt,102:Ht,105:Wt,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt}),t(te,[2,127]),t(te,[2,129]),t(te,[2,130]),t(te,[2,131]),t(te,[2,132]),t(te,[2,133]),t(te,[2,134]),t(te,[2,135]),t(te,[2,136]),t(te,[2,137]),t(te,[2,138]),t(te,[2,139]),t(ft,[2,116],{106:Qt}),t(ft,[2,117],{106:Qt}),{22:[1,275]},t(ft,[2,118],{106:Qt}),{22:[1,276]},t(jt,[2,124]),t(ft,[2,98],{106:Qt}),t(ft,[2,99],{106:Qt}),t(ft,[2,100],{115:100,117:178,26:V,52:G,66:X,67:Z,91:K,105:Q,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),t(ft,[2,104]),{101:[1,277]},{101:[1,278]},{58:[1,279]},{68:[1,280]},{72:[1,281]},{9:282,20:$,21:q,23:H},t(z,[2,42]),{22:Ut,66:zt,67:$t,86:qt,102:Ht,105:Wt,107:283,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},t(te,[2,128]),{26:V,52:G,66:X,67:Z,91:K,97:284,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},{26:V,52:G,66:X,67:Z,91:K,97:285,105:Q,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ft,[2,108]),t(ft,[2,114]),t(lt,[2,60]),{22:yt,24:mt,26:vt,38:bt,39:286,42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:140,84:kt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(lt,[2,68]),t(It,o,{17:287}),t(Jt,[2,126],{108:274,22:Ut,66:zt,67:$t,86:qt,102:Ht,105:Wt,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt}),t(ft,[2,121],{115:100,117:178,22:[1,288],26:V,52:G,66:X,67:Z,91:K,105:Q,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),t(ft,[2,122],{115:100,117:178,22:[1,289],26:V,52:G,66:X,67:Z,91:K,105:Q,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),{22:yt,24:mt,26:vt,38:bt,41:[1,290],42:_t,52:G,66:X,67:Z,73:xt,81:wt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Dt,105:Q,106:J,109:Lt,111:et,112:nt,113:Bt,114:Ot,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{18:18,19:19,20:s,21:c,22:u,23:l,32:24,33:25,34:26,35:27,36:28,37:29,38:h,42:[1,291],43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:v,87:b,88:_,89:x,90:w,91:k,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:D,120:L,121:B,122:O,123:I,124:R,125:F,126:P,127:Y},{22:Ut,66:zt,67:$t,86:qt,96:292,102:Ht,105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},{22:Ut,66:zt,67:$t,86:qt,96:293,102:Ht,105:Wt,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Kt},t(lt,[2,64]),t(z,[2,41]),t(ft,[2,119],{106:Qt}),t(ft,[2,120],{106:Qt})],defaultActions:{2:[2,1],9:[2,5],10:[2,2],132:[2,7]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},ne={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),12;case 1:return this.begin("type_directive"),13;case 2:return this.popState(),this.begin("arg_directive"),10;case 3:return this.popState(),this.popState(),15;case 4:return 14;case 5:case 6:break;case 7:return this.begin("acc_title"),44;case 8:return this.popState(),"acc_title_value";case 9:return this.begin("acc_descr"),46;case 10:return this.popState(),"acc_descr_value";case 11:this.begin("acc_descr_multiline");break;case 12:case 15:case 24:case 27:case 30:case 33:this.popState();break;case 13:return"acc_descr_multiline_value";case 14:this.begin("string");break;case 16:return"STR";case 17:return 86;case 18:return 95;case 19:return 87;case 20:return 104;case 21:return 88;case 22:return 89;case 23:this.begin("href");break;case 25:return 100;case 26:this.begin("callbackname");break;case 28:this.popState(),this.begin("callbackargs");break;case 29:return 98;case 31:return 99;case 32:this.begin("click");break;case 34:return 90;case 35:case 36:return t.lex.firstGraph()&&this.begin("dir"),24;case 37:return 38;case 38:return 42;case 39:case 40:case 41:case 42:return 101;case 43:return this.popState(),25;case 44:case 45:case 46:case 47:case 48:case 49:case 50:case 51:case 52:case 53:return this.popState(),26;case 54:return 118;case 55:return 119;case 56:return 120;case 57:return 121;case 58:return 105;case 59:return 111;case 60:return 53;case 61:return 67;case 62:return 52;case 63:return 20;case 64:return 106;case 65:return 126;case 66:case 67:case 68:return 82;case 69:case 70:case 71:return 81;case 72:return 59;case 73:return 60;case 74:return 61;case 75:return 62;case 76:return 63;case 77:return 64;case 78:return 65;case 79:return 69;case 80:return 70;case 81:return 55;case 82:return 56;case 83:return 109;case 84:return 112;case 85:return 127;case 86:return 124;case 87:return 113;case 88:case 89:return 125;case 90:return 114;case 91:return 73;case 92:return 92;case 93:return"SEP";case 94:return 91;case 95:return 66;case 96:return 75;case 97:return 74;case 98:return 77;case 99:return 76;case 100:return 122;case 101:return 123;case 102:return 68;case 103:return 57;case 104:return 58;case 105:return 40;case 106:return 41;case 107:return 71;case 108:return 72;case 109:return 133;case 110:return 21;case 111:return 22;case 112:return 23}},rules:[/^(?:%%\{)/,/^(?:((?:(?!\}%%)[^:.])*))/,/^(?::)/,/^(?:\}%%)/,/^(?:((?:(?!\}%%).|\n)*))/,/^(?:%%(?!\{)[^\n]*)/,/^(?:[^\}]%%[^\n]*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:style\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\b)/,/^(?:class\b)/,/^(?:href[\s]+["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:click[\s]+)/,/^(?:[\s\n])/,/^(?:[^\s\n]*)/,/^(?:graph\b)/,/^(?:flowchart\b)/,/^(?:subgraph\b)/,/^(?:end\b\s*)/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:(\r?\n)*\s*\n)/,/^(?:\s*LR\b)/,/^(?:\s*RL\b)/,/^(?:\s*TB\b)/,/^(?:\s*BT\b)/,/^(?:\s*TD\b)/,/^(?:\s*BR\b)/,/^(?:\s*<)/,/^(?:\s*>)/,/^(?:\s*\^)/,/^(?:\s*v\b)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:[0-9]+)/,/^(?:#)/,/^(?::::)/,/^(?::)/,/^(?:&)/,/^(?:;)/,/^(?:,)/,/^(?:\*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:\(-)/,/^(?:-\))/,/^(?:\(\[)/,/^(?:\]\))/,/^(?:\[\[)/,/^(?:\]\])/,/^(?:\[\|)/,/^(?:\[\()/,/^(?:\)\])/,/^(?:\(\(\()/,/^(?:\)\)\))/,/^(?:-)/,/^(?:\.)/,/^(?:[\_])/,/^(?:\+)/,/^(?:%)/,/^(?:=)/,/^(?:=)/,/^(?:<)/,/^(?:>)/,/^(?:\^)/,/^(?:\\\|)/,/^(?:v\b)/,/^(?:[A-Za-z]+)/,/^(?:\\\])/,/^(?:\[\/)/,/^(?:\/\])/,/^(?:\[\\)/,/^(?:[!"#$%&'*+,-.`?\\_/])/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\|)/,/^(?:\()/,/^(?:\))/,/^(?:\[)/,/^(?:\])/,/^(?:\{)/,/^(?:\})/,/^(?:")/,/^(?:(\r?\n)+)/,/^(?:\s)/,/^(?:$)/],conditions:{close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},callbackargs:{rules:[30,31],inclusive:!1},callbackname:{rules:[27,28,29],inclusive:!1},href:{rules:[24,25],inclusive:!1},click:{rules:[33,34],inclusive:!1},vertex:{rules:[],inclusive:!1},dir:{rules:[43,44,45,46,47,48,49,50,51,52,53],inclusive:!1},acc_descr_multiline:{rules:[12,13],inclusive:!1},acc_descr:{rules:[10],inclusive:!1},acc_title:{rules:[8],inclusive:!1},string:{rules:[15,16],inclusive:!1},INITIAL:{rules:[0,5,6,7,9,11,14,17,18,19,20,21,22,23,26,32,35,36,37,38,39,40,41,42,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112],inclusive:!0}}};function re(){this.yy={}}return ee.lexer=ne,re.prototype=ee,ee.Parser=re,new re}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(5354).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},9959:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,3],n=[1,5],r=[7,9,11,12,13,14,15,16,17,18,19,20,22,24,25,27,34,39],i=[1,15],a=[1,16],o=[1,17],s=[1,18],c=[1,19],u=[1,20],l=[1,21],h=[1,22],f=[1,23],d=[1,24],p=[1,25],g=[1,26],y=[1,28],m=[1,30],v=[1,33],b=[5,7,9,11,12,13,14,15,16,17,18,19,20,22,24,25,27,34,39],_={trace:function(){},yy:{},symbols_:{error:2,start:3,directive:4,gantt:5,document:6,EOF:7,line:8,SPACE:9,statement:10,NL:11,dateFormat:12,inclusiveEndDates:13,topAxis:14,axisFormat:15,excludes:16,includes:17,todayMarker:18,title:19,acc_title:20,acc_title_value:21,acc_descr:22,acc_descr_value:23,acc_descr_multiline_value:24,section:25,clickStatement:26,taskTxt:27,taskData:28,openDirective:29,typeDirective:30,closeDirective:31,":":32,argDirective:33,click:34,callbackname:35,callbackargs:36,href:37,clickStatementDebug:38,open_directive:39,type_directive:40,arg_directive:41,close_directive:42,$accept:0,$end:1},terminals_:{2:"error",5:"gantt",7:"EOF",9:"SPACE",11:"NL",12:"dateFormat",13:"inclusiveEndDates",14:"topAxis",15:"axisFormat",16:"excludes",17:"includes",18:"todayMarker",19:"title",20:"acc_title",21:"acc_title_value",22:"acc_descr",23:"acc_descr_value",24:"acc_descr_multiline_value",25:"section",27:"taskTxt",28:"taskData",32:":",34:"click",35:"callbackname",36:"callbackargs",37:"href",39:"open_directive",40:"type_directive",41:"arg_directive",42:"close_directive"},productions_:[0,[3,2],[3,3],[6,0],[6,2],[8,2],[8,1],[8,1],[8,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[10,1],[10,1],[10,2],[10,1],[4,4],[4,6],[26,2],[26,3],[26,3],[26,4],[26,3],[26,4],[26,2],[38,2],[38,3],[38,3],[38,4],[38,3],[38,4],[38,2],[29,1],[30,1],[33,1],[31,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 2:return a[s-1];case 3:case 7:case 8:this.$=[];break;case 4:a[s-1].push(a[s]),this.$=a[s-1];break;case 5:case 6:this.$=a[s];break;case 9:r.setDateFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 10:r.enableInclusiveEndDates(),this.$=a[s].substr(18);break;case 11:r.TopAxis(),this.$=a[s].substr(8);break;case 12:r.setAxisFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 13:r.setExcludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 14:r.setIncludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 15:r.setTodayMarker(a[s].substr(12)),this.$=a[s].substr(12);break;case 16:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 17:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 18:case 19:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 20:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 22:r.addTask(a[s-1],a[s]),this.$="task";break;case 26:this.$=a[s-1],r.setClickEvent(a[s-1],a[s],null);break;case 27:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 28:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],null),r.setLink(a[s-2],a[s]);break;case 29:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setLink(a[s-3],a[s]);break;case 30:this.$=a[s-2],r.setClickEvent(a[s-2],a[s],null),r.setLink(a[s-2],a[s-1]);break;case 31:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-1],a[s]),r.setLink(a[s-3],a[s-2]);break;case 32:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 33:case 39:this.$=a[s-1]+" "+a[s];break;case 34:case 35:case 37:this.$=a[s-2]+" "+a[s-1]+" "+a[s];break;case 36:case 38:this.$=a[s-3]+" "+a[s-2]+" "+a[s-1]+" "+a[s];break;case 40:r.parseDirective("%%{","open_directive");break;case 41:r.parseDirective(a[s],"type_directive");break;case 42:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 43:r.parseDirective("}%%","close_directive","gantt")}},table:[{3:1,4:2,5:e,29:4,39:n},{1:[3]},{3:6,4:2,5:e,29:4,39:n},t(r,[2,3],{6:7}),{30:8,40:[1,9]},{40:[2,40]},{1:[2,1]},{4:29,7:[1,10],8:11,9:[1,12],10:13,11:[1,14],12:i,13:a,14:o,15:s,16:c,17:u,18:l,19:h,20:f,22:d,24:p,25:g,26:27,27:y,29:4,34:m,39:n},{31:31,32:[1,32],42:v},t([32,42],[2,41]),t(r,[2,8],{1:[2,2]}),t(r,[2,4]),{4:29,10:34,12:i,13:a,14:o,15:s,16:c,17:u,18:l,19:h,20:f,22:d,24:p,25:g,26:27,27:y,29:4,34:m,39:n},t(r,[2,6]),t(r,[2,7]),t(r,[2,9]),t(r,[2,10]),t(r,[2,11]),t(r,[2,12]),t(r,[2,13]),t(r,[2,14]),t(r,[2,15]),t(r,[2,16]),{21:[1,35]},{23:[1,36]},t(r,[2,19]),t(r,[2,20]),t(r,[2,21]),{28:[1,37]},t(r,[2,23]),{35:[1,38],37:[1,39]},{11:[1,40]},{33:41,41:[1,42]},{11:[2,43]},t(r,[2,5]),t(r,[2,17]),t(r,[2,18]),t(r,[2,22]),t(r,[2,26],{36:[1,43],37:[1,44]}),t(r,[2,32],{35:[1,45]}),t(b,[2,24]),{31:46,42:v},{42:[2,42]},t(r,[2,27],{37:[1,47]}),t(r,[2,28]),t(r,[2,30],{36:[1,48]}),{11:[1,49]},t(r,[2,29]),t(r,[2,31]),t(b,[2,25])],defaultActions:{5:[2,40],6:[2,1],33:[2,43],42:[2,42]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},x={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),39;case 1:return this.begin("type_directive"),40;case 2:return this.popState(),this.begin("arg_directive"),32;case 3:return this.popState(),this.popState(),42;case 4:return 41;case 5:return this.begin("acc_title"),20;case 6:return this.popState(),"acc_title_value";case 7:return this.begin("acc_descr"),22;case 8:return this.popState(),"acc_descr_value";case 9:this.begin("acc_descr_multiline");break;case 10:case 20:case 23:case 26:case 29:this.popState();break;case 11:return"acc_descr_multiline_value";case 12:case 13:case 14:case 16:case 17:case 18:break;case 15:return 11;case 19:this.begin("href");break;case 21:return 37;case 22:this.begin("callbackname");break;case 24:this.popState(),this.begin("callbackargs");break;case 25:return 35;case 27:return 36;case 28:this.begin("click");break;case 30:return 34;case 31:return 5;case 32:return 12;case 33:return 13;case 34:return 14;case 35:return 15;case 36:return 17;case 37:return 16;case 38:return 18;case 39:return"date";case 40:return 19;case 41:return"accDescription";case 42:return 25;case 43:return 27;case 44:return 28;case 45:return 32;case 46:return 7;case 47:return"INVALID"}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:%%(?!\{)*[^\n]*)/i,/^(?:[^\}]%%*[^\n]*)/i,/^(?:%%*[^\n]*[\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:href[\s]+["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:call[\s]+)/i,/^(?:\([\s]*\))/i,/^(?:\()/i,/^(?:[^(]*)/i,/^(?:\))/i,/^(?:[^)]*)/i,/^(?:click[\s]+)/i,/^(?:[\s\n])/i,/^(?:[^\s\n]*)/i,/^(?:gantt\b)/i,/^(?:dateFormat\s[^#\n;]+)/i,/^(?:inclusiveEndDates\b)/i,/^(?:topAxis\b)/i,/^(?:axisFormat\s[^#\n;]+)/i,/^(?:includes\s[^#\n;]+)/i,/^(?:excludes\s[^#\n;]+)/i,/^(?:todayMarker\s[^\n;]+)/i,/^(?:\d\d\d\d-\d\d-\d\d\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:accDescription\s[^#\n;]+)/i,/^(?:section\s[^#:\n;]+)/i,/^(?:[^#:\n;]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[10,11],inclusive:!1},acc_descr:{rules:[8],inclusive:!1},acc_title:{rules:[6],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},callbackargs:{rules:[26,27],inclusive:!1},callbackname:{rules:[23,24,25],inclusive:!1},href:{rules:[20,21],inclusive:!1},click:{rules:[29,30],inclusive:!1},INITIAL:{rules:[0,5,7,9,12,13,14,15,16,17,18,19,22,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],inclusive:!0}}};function w(){this.yy={}}return _.lexer=x,w.prototype=_,_.Parser=w,new w}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(6878).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},2553:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,4],n=[1,7],r=[1,5],i=[1,9],a=[1,6],o=[2,6],s=[1,16],c=[6,8,14,19,21,23,24,26,28,31,34,47,51],u=[8,14,19,21,23,24,26,28,31,34],l=[8,13,14,19,21,23,24,26,28,31,34],h=[1,26],f=[6,8,14,47,51],d=[8,14,51],p=[1,61],g=[1,62],y=[1,63],m=[8,14,32,38,39,51],v={trace:function(){},yy:{},symbols_:{error:2,start:3,eol:4,directive:5,GG:6,document:7,EOF:8,":":9,DIR:10,options:11,body:12,OPT:13,NL:14,line:15,statement:16,commitStatement:17,mergeStatement:18,acc_title:19,acc_title_value:20,acc_descr:21,acc_descr_value:22,acc_descr_multiline_value:23,section:24,branchStatement:25,CHECKOUT:26,ID:27,BRANCH:28,ORDER:29,NUM:30,MERGE:31,COMMIT_TAG:32,STR:33,COMMIT:34,commit_arg:35,COMMIT_TYPE:36,commitType:37,COMMIT_ID:38,COMMIT_MSG:39,NORMAL:40,REVERSE:41,HIGHLIGHT:42,openDirective:43,typeDirective:44,closeDirective:45,argDirective:46,open_directive:47,type_directive:48,arg_directive:49,close_directive:50,";":51,$accept:0,$end:1},terminals_:{2:"error",6:"GG",8:"EOF",9:":",10:"DIR",13:"OPT",14:"NL",19:"acc_title",20:"acc_title_value",21:"acc_descr",22:"acc_descr_value",23:"acc_descr_multiline_value",24:"section",26:"CHECKOUT",27:"ID",28:"BRANCH",29:"ORDER",30:"NUM",31:"MERGE",32:"COMMIT_TAG",33:"STR",34:"COMMIT",36:"COMMIT_TYPE",38:"COMMIT_ID",39:"COMMIT_MSG",40:"NORMAL",41:"REVERSE",42:"HIGHLIGHT",47:"open_directive",48:"type_directive",49:"arg_directive",50:"close_directive",51:";"},productions_:[0,[3,2],[3,2],[3,3],[3,4],[3,5],[7,0],[7,2],[11,2],[11,1],[12,0],[12,2],[15,2],[15,1],[16,1],[16,1],[16,2],[16,2],[16,1],[16,1],[16,1],[16,2],[25,2],[25,4],[18,2],[18,4],[17,2],[17,3],[17,3],[17,5],[17,5],[17,3],[17,5],[17,5],[17,5],[17,5],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,3],[17,5],[17,5],[17,5],[17,5],[17,5],[17,5],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[35,0],[35,1],[37,1],[37,1],[37,1],[5,3],[5,5],[43,1],[44,1],[46,1],[45,1],[4,1],[4,1],[4,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return a[s];case 4:return a[s-1];case 5:return r.setDirection(a[s-3]),a[s-1];case 7:r.setOptions(a[s-1]),this.$=a[s];break;case 8:a[s-1]+=a[s],this.$=a[s-1];break;case 10:this.$=[];break;case 11:a[s-1].push(a[s]),this.$=a[s-1];break;case 12:this.$=a[s-1];break;case 16:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 17:case 18:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 19:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 21:r.checkout(a[s]);break;case 22:r.branch(a[s]);break;case 23:r.branch(a[s-2],a[s]);break;case 24:r.merge(a[s]);break;case 25:r.merge(a[s-2],a[s]);break;case 26:r.commit(a[s]);break;case 27:r.commit("","",r.commitType.NORMAL,a[s]);break;case 28:r.commit("","",a[s],"");break;case 29:r.commit("","",a[s],a[s-2]);break;case 30:r.commit("","",a[s-2],a[s]);break;case 31:r.commit("",a[s],r.commitType.NORMAL,"");break;case 32:r.commit("",a[s-2],r.commitType.NORMAL,a[s]);break;case 33:r.commit("",a[s],r.commitType.NORMAL,a[s-2]);break;case 34:r.commit("",a[s-2],a[s],"");break;case 35:r.commit("",a[s],a[s-2],"");break;case 36:r.commit("",a[s-4],a[s-2],a[s]);break;case 37:r.commit("",a[s-4],a[s],a[s-2]);break;case 38:r.commit("",a[s-2],a[s-4],a[s]);break;case 39:r.commit("",a[s],a[s-4],a[s-2]);break;case 40:r.commit("",a[s],a[s-2],a[s-4]);break;case 41:r.commit("",a[s-2],a[s],a[s-4]);break;case 42:r.commit(a[s],"",r.commitType.NORMAL,"");break;case 43:r.commit(a[s],"",r.commitType.NORMAL,a[s-2]);break;case 44:r.commit(a[s-2],"",r.commitType.NORMAL,a[s]);break;case 45:r.commit(a[s-2],"",a[s],"");break;case 46:r.commit(a[s],"",a[s-2],"");break;case 47:r.commit(a[s],a[s-2],r.commitType.NORMAL,"");break;case 48:r.commit(a[s-2],a[s],r.commitType.NORMAL,"");break;case 49:r.commit(a[s-4],"",a[s-2],a[s]);break;case 50:r.commit(a[s-4],"",a[s],a[s-2]);break;case 51:r.commit(a[s-2],"",a[s-4],a[s]);break;case 52:r.commit(a[s],"",a[s-4],a[s-2]);break;case 53:r.commit(a[s],"",a[s-2],a[s-4]);break;case 54:r.commit(a[s-2],"",a[s],a[s-4]);break;case 55:r.commit(a[s-4],a[s],a[s-2],"");break;case 56:r.commit(a[s-4],a[s-2],a[s],"");break;case 57:r.commit(a[s-2],a[s],a[s-4],"");break;case 58:r.commit(a[s],a[s-2],a[s-4],"");break;case 59:r.commit(a[s],a[s-4],a[s-2],"");break;case 60:r.commit(a[s-2],a[s-4],a[s],"");break;case 61:r.commit(a[s-4],a[s],r.commitType.NORMAL,a[s-2]);break;case 62:r.commit(a[s-4],a[s-2],r.commitType.NORMAL,a[s]);break;case 63:r.commit(a[s-2],a[s],r.commitType.NORMAL,a[s-4]);break;case 64:r.commit(a[s],a[s-2],r.commitType.NORMAL,a[s-4]);break;case 65:r.commit(a[s],a[s-4],r.commitType.NORMAL,a[s-2]);break;case 66:r.commit(a[s-2],a[s-4],r.commitType.NORMAL,a[s]);break;case 67:r.commit(a[s-6],a[s-4],a[s-2],a[s]);break;case 68:r.commit(a[s-6],a[s-4],a[s],a[s-2]);break;case 69:r.commit(a[s-6],a[s-2],a[s-4],a[s]);break;case 70:r.commit(a[s-6],a[s],a[s-4],a[s-2]);break;case 71:r.commit(a[s-6],a[s-2],a[s],a[s-4]);break;case 72:r.commit(a[s-6],a[s],a[s-2],a[s-4]);break;case 73:r.commit(a[s-4],a[s-6],a[s-2],a[s]);break;case 74:r.commit(a[s-4],a[s-6],a[s],a[s-2]);break;case 75:r.commit(a[s-2],a[s-6],a[s-4],a[s]);break;case 76:r.commit(a[s],a[s-6],a[s-4],a[s-2]);break;case 77:r.commit(a[s-2],a[s-6],a[s],a[s-4]);break;case 78:r.commit(a[s],a[s-6],a[s-2],a[s-4]);break;case 79:r.commit(a[s],a[s-4],a[s-2],a[s-6]);break;case 80:r.commit(a[s-2],a[s-4],a[s],a[s-6]);break;case 81:r.commit(a[s],a[s-2],a[s-4],a[s-6]);break;case 82:r.commit(a[s-2],a[s],a[s-4],a[s-6]);break;case 83:r.commit(a[s-4],a[s-2],a[s],a[s-6]);break;case 84:r.commit(a[s-4],a[s],a[s-2],a[s-6]);break;case 85:r.commit(a[s-2],a[s-4],a[s-6],a[s]);break;case 86:r.commit(a[s],a[s-4],a[s-6],a[s-2]);break;case 87:r.commit(a[s-2],a[s],a[s-6],a[s-4]);break;case 88:r.commit(a[s],a[s-2],a[s-6],a[s-4]);break;case 89:r.commit(a[s-4],a[s-2],a[s-6],a[s]);break;case 90:r.commit(a[s-4],a[s],a[s-6],a[s-2]);break;case 91:this.$="";break;case 92:this.$=a[s];break;case 93:this.$=r.commitType.NORMAL;break;case 94:this.$=r.commitType.REVERSE;break;case 95:this.$=r.commitType.HIGHLIGHT;break;case 98:r.parseDirective("%%{","open_directive");break;case 99:r.parseDirective(a[s],"type_directive");break;case 100:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 101:r.parseDirective("}%%","close_directive","gitGraph")}},table:[{3:1,4:2,5:3,6:e,8:n,14:r,43:8,47:i,51:a},{1:[3]},{3:10,4:2,5:3,6:e,8:n,14:r,43:8,47:i,51:a},{3:11,4:2,5:3,6:e,8:n,14:r,43:8,47:i,51:a},{7:12,8:o,9:[1,13],10:[1,14],11:15,14:s},t(c,[2,102]),t(c,[2,103]),t(c,[2,104]),{44:17,48:[1,18]},{48:[2,98]},{1:[2,1]},{1:[2,2]},{8:[1,19]},{7:20,8:o,11:15,14:s},{9:[1,21]},t(u,[2,10],{12:22,13:[1,23]}),t(l,[2,9]),{9:[1,25],45:24,50:h},t([9,50],[2,99]),{1:[2,3]},{8:[1,27]},{7:28,8:o,11:15,14:s},{8:[2,7],14:[1,31],15:29,16:30,17:32,18:33,19:[1,34],21:[1,35],23:[1,36],24:[1,37],25:38,26:[1,39],28:[1,42],31:[1,41],34:[1,40]},t(l,[2,8]),t(f,[2,96]),{46:43,49:[1,44]},t(f,[2,101]),{1:[2,4]},{8:[1,45]},t(u,[2,11]),{4:46,8:n,14:r,51:a},t(u,[2,13]),t(d,[2,14]),t(d,[2,15]),{20:[1,47]},{22:[1,48]},t(d,[2,18]),t(d,[2,19]),t(d,[2,20]),{27:[1,49]},t(d,[2,91],{35:50,32:[1,51],33:[1,55],36:[1,52],38:[1,53],39:[1,54]}),{27:[1,56]},{27:[1,57]},{45:58,50:h},{50:[2,100]},{1:[2,5]},t(u,[2,12]),t(d,[2,16]),t(d,[2,17]),t(d,[2,21]),t(d,[2,26]),{33:[1,59]},{37:60,40:p,41:g,42:y},{33:[1,64]},{33:[1,65]},t(d,[2,92]),t(d,[2,24],{32:[1,66]}),t(d,[2,22],{29:[1,67]}),t(f,[2,97]),t(d,[2,27],{36:[1,68],38:[1,69],39:[1,70]}),t(d,[2,28],{32:[1,71],38:[1,72],39:[1,73]}),t(m,[2,93]),t(m,[2,94]),t(m,[2,95]),t(d,[2,31],{32:[1,74],36:[1,75],39:[1,76]}),t(d,[2,42],{32:[1,77],36:[1,78],38:[1,79]}),{33:[1,80]},{30:[1,81]},{37:82,40:p,41:g,42:y},{33:[1,83]},{33:[1,84]},{33:[1,85]},{33:[1,86]},{33:[1,87]},{33:[1,88]},{37:89,40:p,41:g,42:y},{33:[1,90]},{33:[1,91]},{37:92,40:p,41:g,42:y},{33:[1,93]},t(d,[2,25]),t(d,[2,23]),t(d,[2,29],{38:[1,94],39:[1,95]}),t(d,[2,33],{36:[1,96],39:[1,97]}),t(d,[2,43],{36:[1,98],38:[1,99]}),t(d,[2,30],{38:[1,100],39:[1,101]}),t(d,[2,35],{32:[1,102],39:[1,103]}),t(d,[2,46],{32:[1,104],38:[1,105]}),t(d,[2,32],{36:[1,106],39:[1,107]}),t(d,[2,34],{32:[1,108],39:[1,109]}),t(d,[2,47],{32:[1,111],36:[1,110]}),t(d,[2,44],{36:[1,112],38:[1,113]}),t(d,[2,45],{32:[1,114],38:[1,115]}),t(d,[2,48],{32:[1,117],36:[1,116]}),{33:[1,118]},{33:[1,119]},{37:120,40:p,41:g,42:y},{33:[1,121]},{37:122,40:p,41:g,42:y},{33:[1,123]},{33:[1,124]},{33:[1,125]},{33:[1,126]},{33:[1,127]},{33:[1,128]},{33:[1,129]},{37:130,40:p,41:g,42:y},{33:[1,131]},{33:[1,132]},{33:[1,133]},{37:134,40:p,41:g,42:y},{33:[1,135]},{37:136,40:p,41:g,42:y},{33:[1,137]},{33:[1,138]},{33:[1,139]},{37:140,40:p,41:g,42:y},{33:[1,141]},t(d,[2,40],{39:[1,142]}),t(d,[2,53],{38:[1,143]}),t(d,[2,41],{39:[1,144]}),t(d,[2,64],{36:[1,145]}),t(d,[2,54],{38:[1,146]}),t(d,[2,63],{36:[1,147]}),t(d,[2,39],{39:[1,148]}),t(d,[2,52],{38:[1,149]}),t(d,[2,38],{39:[1,150]}),t(d,[2,58],{32:[1,151]}),t(d,[2,51],{38:[1,152]}),t(d,[2,57],{32:[1,153]}),t(d,[2,37],{39:[1,154]}),t(d,[2,65],{36:[1,155]}),t(d,[2,36],{39:[1,156]}),t(d,[2,59],{32:[1,157]}),t(d,[2,60],{32:[1,158]}),t(d,[2,66],{36:[1,159]}),t(d,[2,50],{38:[1,160]}),t(d,[2,61],{36:[1,161]}),t(d,[2,49],{38:[1,162]}),t(d,[2,55],{32:[1,163]}),t(d,[2,56],{32:[1,164]}),t(d,[2,62],{36:[1,165]}),{33:[1,166]},{33:[1,167]},{33:[1,168]},{37:169,40:p,41:g,42:y},{33:[1,170]},{37:171,40:p,41:g,42:y},{33:[1,172]},{33:[1,173]},{33:[1,174]},{33:[1,175]},{33:[1,176]},{33:[1,177]},{33:[1,178]},{37:179,40:p,41:g,42:y},{33:[1,180]},{33:[1,181]},{33:[1,182]},{37:183,40:p,41:g,42:y},{33:[1,184]},{37:185,40:p,41:g,42:y},{33:[1,186]},{33:[1,187]},{33:[1,188]},{37:189,40:p,41:g,42:y},t(d,[2,81]),t(d,[2,82]),t(d,[2,79]),t(d,[2,80]),t(d,[2,84]),t(d,[2,83]),t(d,[2,88]),t(d,[2,87]),t(d,[2,86]),t(d,[2,85]),t(d,[2,90]),t(d,[2,89]),t(d,[2,78]),t(d,[2,77]),t(d,[2,76]),t(d,[2,75]),t(d,[2,73]),t(d,[2,74]),t(d,[2,72]),t(d,[2,71]),t(d,[2,70]),t(d,[2,69]),t(d,[2,67]),t(d,[2,68])],defaultActions:{9:[2,98],10:[2,1],11:[2,2],19:[2,3],27:[2,4],44:[2,100],45:[2,5]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},b={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),47;case 1:return this.begin("type_directive"),48;case 2:return this.popState(),this.begin("arg_directive"),9;case 3:return this.popState(),this.popState(),50;case 4:return 49;case 5:return this.begin("acc_title"),19;case 6:return this.popState(),"acc_title_value";case 7:return this.begin("acc_descr"),21;case 8:return this.popState(),"acc_descr_value";case 9:this.begin("acc_descr_multiline");break;case 10:case 34:case 37:this.popState();break;case 11:return"acc_descr_multiline_value";case 12:return 14;case 13:case 14:case 15:break;case 16:return 6;case 17:return 34;case 18:return 38;case 19:return 36;case 20:return 39;case 21:return 40;case 22:return 41;case 23:return 42;case 24:return 32;case 25:return 28;case 26:return 29;case 27:return 31;case 28:return 26;case 29:case 30:return 10;case 31:return 9;case 32:return"CARET";case 33:this.begin("options");break;case 35:return 13;case 36:this.begin("string");break;case 38:return 33;case 39:return 30;case 40:return 27;case 41:return 8}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:(\r?\n)+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:gitGraph\b)/i,/^(?:commit\b)/i,/^(?:id:)/i,/^(?:type:)/i,/^(?:msg:)/i,/^(?:NORMAL\b)/i,/^(?:REVERSE\b)/i,/^(?:HIGHLIGHT\b)/i,/^(?:tag:)/i,/^(?:branch\b)/i,/^(?:order:)/i,/^(?:merge\b)/i,/^(?:checkout\b)/i,/^(?:LR\b)/i,/^(?:BT\b)/i,/^(?::)/i,/^(?:\^)/i,/^(?:options\r?\n)/i,/^(?:[ \r\n\t]+end\b)/i,/^(?:[\s\S]+(?=[ \r\n\t]+end))/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[0-9]+)/i,/^(?:[a-zA-Z][-_\./a-zA-Z0-9]*[-_a-zA-Z0-9])/i,/^(?:$)/i],conditions:{acc_descr_multiline:{rules:[10,11],inclusive:!1},acc_descr:{rules:[8],inclusive:!1},acc_title:{rules:[6],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},options:{rules:[34,35],inclusive:!1},string:{rules:[37,38],inclusive:!1},INITIAL:{rules:[0,5,7,9,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,36,39,40,41],inclusive:!0}}};function _(){this.yy={}}return v.lexer=b,_.prototype=v,v.Parser=_,new _}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8183).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},6765:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[6,9,10],n={trace:function(){},yy:{},symbols_:{error:2,start:3,info:4,document:5,EOF:6,line:7,statement:8,NL:9,showInfo:10,$accept:0,$end:1},terminals_:{2:"error",4:"info",6:"EOF",9:"NL",10:"showInfo"},productions_:[0,[3,3],[5,0],[5,2],[7,1],[7,1],[8,1]],performAction:function(t,e,n,r,i,a,o){switch(a.length,i){case 1:return r;case 4:break;case 6:r.setInfo(!0)}},table:[{3:1,4:[1,2]},{1:[3]},t(e,[2,2],{5:3}),{6:[1,4],7:5,8:6,9:[1,7],10:[1,8]},{1:[2,1]},t(e,[2,3]),t(e,[2,4]),t(e,[2,5]),t(e,[2,6])],defaultActions:{4:[2,1]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},r={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return 4;case 1:return 9;case 2:return"space";case 3:return 10;case 4:return 6;case 5:return"TXT"}},rules:[/^(?:info\b)/i,/^(?:[\s\n\r]+)/i,/^(?:[\s]+)/i,/^(?:showInfo\b)/i,/^(?:$)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5],inclusive:!0}}};function i(){this.yy={}}return n.lexer=r,i.prototype=n,n.Parser=i,new i}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(1428).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},7062:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,4],n=[1,5],r=[1,6],i=[1,7],a=[1,9],o=[1,11,13,15,17,19,20,26,27,28,29],s=[2,5],c=[1,6,11,13,15,17,19,20,26,27,28,29],u=[26,27,28],l=[2,8],h=[1,18],f=[1,19],d=[1,20],p=[1,21],g=[1,22],y=[1,23],m=[1,28],v=[6,26,27,28,29],b={trace:function(){},yy:{},symbols_:{error:2,start:3,eol:4,directive:5,PIE:6,document:7,showData:8,line:9,statement:10,txt:11,value:12,title:13,title_value:14,acc_title:15,acc_title_value:16,acc_descr:17,acc_descr_value:18,acc_descr_multiline_value:19,section:20,openDirective:21,typeDirective:22,closeDirective:23,":":24,argDirective:25,NEWLINE:26,";":27,EOF:28,open_directive:29,type_directive:30,arg_directive:31,close_directive:32,$accept:0,$end:1},terminals_:{2:"error",6:"PIE",8:"showData",11:"txt",12:"value",13:"title",14:"title_value",15:"acc_title",16:"acc_title_value",17:"acc_descr",18:"acc_descr_value",19:"acc_descr_multiline_value",20:"section",24:":",26:"NEWLINE",27:";",28:"EOF",29:"open_directive",30:"type_directive",31:"arg_directive",32:"close_directive"},productions_:[0,[3,2],[3,2],[3,2],[3,3],[7,0],[7,2],[9,2],[10,0],[10,2],[10,2],[10,2],[10,2],[10,1],[10,1],[10,1],[5,3],[5,5],[4,1],[4,1],[4,1],[21,1],[22,1],[25,1],[23,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 4:r.setShowData(!0);break;case 7:this.$=a[s-1];break;case 9:r.addSection(a[s-1],r.cleanupValue(a[s]));break;case 10:this.$=a[s].trim(),r.setDiagramTitle(this.$);break;case 11:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 12:case 13:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 14:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 21:r.parseDirective("%%{","open_directive");break;case 22:r.parseDirective(a[s],"type_directive");break;case 23:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 24:r.parseDirective("}%%","close_directive","pie")}},table:[{3:1,4:2,5:3,6:e,21:8,26:n,27:r,28:i,29:a},{1:[3]},{3:10,4:2,5:3,6:e,21:8,26:n,27:r,28:i,29:a},{3:11,4:2,5:3,6:e,21:8,26:n,27:r,28:i,29:a},t(o,s,{7:12,8:[1,13]}),t(c,[2,18]),t(c,[2,19]),t(c,[2,20]),{22:14,30:[1,15]},{30:[2,21]},{1:[2,1]},{1:[2,2]},t(u,l,{21:8,9:16,10:17,5:24,1:[2,3],11:h,13:f,15:d,17:p,19:g,20:y,29:a}),t(o,s,{7:25}),{23:26,24:[1,27],32:m},t([24,32],[2,22]),t(o,[2,6]),{4:29,26:n,27:r,28:i},{12:[1,30]},{14:[1,31]},{16:[1,32]},{18:[1,33]},t(u,[2,13]),t(u,[2,14]),t(u,[2,15]),t(u,l,{21:8,9:16,10:17,5:24,1:[2,4],11:h,13:f,15:d,17:p,19:g,20:y,29:a}),t(v,[2,16]),{25:34,31:[1,35]},t(v,[2,24]),t(o,[2,7]),t(u,[2,9]),t(u,[2,10]),t(u,[2,11]),t(u,[2,12]),{23:36,32:m},{32:[2,23]},t(v,[2,17])],defaultActions:{9:[2,21],10:[2,1],11:[2,2],35:[2,23]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},_={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),29;case 1:return this.begin("type_directive"),30;case 2:return this.popState(),this.begin("arg_directive"),24;case 3:return this.popState(),this.popState(),32;case 4:return 31;case 5:case 6:case 8:case 9:break;case 7:return 26;case 10:return this.begin("title"),13;case 11:return this.popState(),"title_value";case 12:return this.begin("acc_title"),15;case 13:return this.popState(),"acc_title_value";case 14:return this.begin("acc_descr"),17;case 15:return this.popState(),"acc_descr_value";case 16:this.begin("acc_descr_multiline");break;case 17:case 20:this.popState();break;case 18:return"acc_descr_multiline_value";case 19:this.begin("string");break;case 21:return"txt";case 22:return 6;case 23:return 8;case 24:return"value";case 25:return 28}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:[\s]+)/i,/^(?:title\b)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:pie\b)/i,/^(?:showData\b)/i,/^(?::[\s]*[\d]+(?:\.[\d]+)?)/i,/^(?:$)/i],conditions:{acc_descr_multiline:{rules:[17,18],inclusive:!1},acc_descr:{rules:[15],inclusive:!1},acc_title:{rules:[13],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},title:{rules:[11],inclusive:!1},string:{rules:[20,21],inclusive:!1},INITIAL:{rules:[0,5,6,7,8,9,10,12,14,16,19,22,23,24,25],inclusive:!0}}};function x(){this.yy={}}return b.lexer=_,x.prototype=b,b.Parser=x,new x}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(4551).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},3176:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,3],n=[1,5],r=[1,6],i=[1,7],a=[1,8],o=[5,6,8,14,16,18,19,40,41,42,43,44,45,53,71,72],s=[1,22],c=[2,13],u=[1,26],l=[1,27],h=[1,28],f=[1,29],d=[1,30],p=[1,31],g=[1,24],y=[1,32],m=[1,33],v=[1,36],b=[71,72],_=[5,8,14,16,18,19,40,41,42,43,44,45,53,60,62,71,72],x=[1,56],w=[1,57],k=[1,58],T=[1,59],E=[1,60],C=[1,61],S=[1,62],A=[62,63],M=[1,74],N=[1,70],D=[1,71],L=[1,72],B=[1,73],O=[1,75],I=[1,79],R=[1,80],F=[1,77],P=[1,78],Y=[5,8,14,16,18,19,40,41,42,43,44,45,53,71,72],j={trace:function(){},yy:{},symbols_:{error:2,start:3,directive:4,NEWLINE:5,RD:6,diagram:7,EOF:8,openDirective:9,typeDirective:10,closeDirective:11,":":12,argDirective:13,acc_title:14,acc_title_value:15,acc_descr:16,acc_descr_value:17,acc_descr_multiline_value:18,open_directive:19,type_directive:20,arg_directive:21,close_directive:22,requirementDef:23,elementDef:24,relationshipDef:25,requirementType:26,requirementName:27,STRUCT_START:28,requirementBody:29,ID:30,COLONSEP:31,id:32,TEXT:33,text:34,RISK:35,riskLevel:36,VERIFYMTHD:37,verifyType:38,STRUCT_STOP:39,REQUIREMENT:40,FUNCTIONAL_REQUIREMENT:41,INTERFACE_REQUIREMENT:42,PERFORMANCE_REQUIREMENT:43,PHYSICAL_REQUIREMENT:44,DESIGN_CONSTRAINT:45,LOW_RISK:46,MED_RISK:47,HIGH_RISK:48,VERIFY_ANALYSIS:49,VERIFY_DEMONSTRATION:50,VERIFY_INSPECTION:51,VERIFY_TEST:52,ELEMENT:53,elementName:54,elementBody:55,TYPE:56,type:57,DOCREF:58,ref:59,END_ARROW_L:60,relationship:61,LINE:62,END_ARROW_R:63,CONTAINS:64,COPIES:65,DERIVES:66,SATISFIES:67,VERIFIES:68,REFINES:69,TRACES:70,unqString:71,qString:72,$accept:0,$end:1},terminals_:{2:"error",5:"NEWLINE",6:"RD",8:"EOF",12:":",14:"acc_title",15:"acc_title_value",16:"acc_descr",17:"acc_descr_value",18:"acc_descr_multiline_value",19:"open_directive",20:"type_directive",21:"arg_directive",22:"close_directive",28:"STRUCT_START",30:"ID",31:"COLONSEP",33:"TEXT",35:"RISK",37:"VERIFYMTHD",39:"STRUCT_STOP",40:"REQUIREMENT",41:"FUNCTIONAL_REQUIREMENT",42:"INTERFACE_REQUIREMENT",43:"PERFORMANCE_REQUIREMENT",44:"PHYSICAL_REQUIREMENT",45:"DESIGN_CONSTRAINT",46:"LOW_RISK",47:"MED_RISK",48:"HIGH_RISK",49:"VERIFY_ANALYSIS",50:"VERIFY_DEMONSTRATION",51:"VERIFY_INSPECTION",52:"VERIFY_TEST",53:"ELEMENT",56:"TYPE",58:"DOCREF",60:"END_ARROW_L",62:"LINE",63:"END_ARROW_R",64:"CONTAINS",65:"COPIES",66:"DERIVES",67:"SATISFIES",68:"VERIFIES",69:"REFINES",70:"TRACES",71:"unqString",72:"qString"},productions_:[0,[3,3],[3,2],[3,4],[4,3],[4,5],[4,2],[4,2],[4,1],[9,1],[10,1],[13,1],[11,1],[7,0],[7,2],[7,2],[7,2],[7,2],[7,2],[23,5],[29,5],[29,5],[29,5],[29,5],[29,2],[29,1],[26,1],[26,1],[26,1],[26,1],[26,1],[26,1],[36,1],[36,1],[36,1],[38,1],[38,1],[38,1],[38,1],[24,5],[55,5],[55,5],[55,2],[55,1],[25,5],[25,5],[61,1],[61,1],[61,1],[61,1],[61,1],[61,1],[61,1],[27,1],[27,1],[32,1],[32,1],[34,1],[34,1],[54,1],[54,1],[57,1],[57,1],[59,1],[59,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 6:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 7:case 8:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 9:r.parseDirective("%%{","open_directive");break;case 10:r.parseDirective(a[s],"type_directive");break;case 11:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 12:r.parseDirective("}%%","close_directive","pie");break;case 13:this.$=[];break;case 19:r.addRequirement(a[s-3],a[s-4]);break;case 20:r.setNewReqId(a[s-2]);break;case 21:r.setNewReqText(a[s-2]);break;case 22:r.setNewReqRisk(a[s-2]);break;case 23:r.setNewReqVerifyMethod(a[s-2]);break;case 26:this.$=r.RequirementType.REQUIREMENT;break;case 27:this.$=r.RequirementType.FUNCTIONAL_REQUIREMENT;break;case 28:this.$=r.RequirementType.INTERFACE_REQUIREMENT;break;case 29:this.$=r.RequirementType.PERFORMANCE_REQUIREMENT;break;case 30:this.$=r.RequirementType.PHYSICAL_REQUIREMENT;break;case 31:this.$=r.RequirementType.DESIGN_CONSTRAINT;break;case 32:this.$=r.RiskLevel.LOW_RISK;break;case 33:this.$=r.RiskLevel.MED_RISK;break;case 34:this.$=r.RiskLevel.HIGH_RISK;break;case 35:this.$=r.VerifyType.VERIFY_ANALYSIS;break;case 36:this.$=r.VerifyType.VERIFY_DEMONSTRATION;break;case 37:this.$=r.VerifyType.VERIFY_INSPECTION;break;case 38:this.$=r.VerifyType.VERIFY_TEST;break;case 39:r.addElement(a[s-3]);break;case 40:r.setNewElementType(a[s-2]);break;case 41:r.setNewElementDocRef(a[s-2]);break;case 44:r.addRelationship(a[s-2],a[s],a[s-4]);break;case 45:r.addRelationship(a[s-2],a[s-4],a[s]);break;case 46:this.$=r.Relationships.CONTAINS;break;case 47:this.$=r.Relationships.COPIES;break;case 48:this.$=r.Relationships.DERIVES;break;case 49:this.$=r.Relationships.SATISFIES;break;case 50:this.$=r.Relationships.VERIFIES;break;case 51:this.$=r.Relationships.REFINES;break;case 52:this.$=r.Relationships.TRACES}},table:[{3:1,4:2,6:e,9:4,14:n,16:r,18:i,19:a},{1:[3]},{3:10,4:2,5:[1,9],6:e,9:4,14:n,16:r,18:i,19:a},{5:[1,11]},{10:12,20:[1,13]},{15:[1,14]},{17:[1,15]},t(o,[2,8]),{20:[2,9]},{3:16,4:2,6:e,9:4,14:n,16:r,18:i,19:a},{1:[2,2]},{4:21,5:s,7:17,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:u,41:l,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{11:34,12:[1,35],22:v},t([12,22],[2,10]),t(o,[2,6]),t(o,[2,7]),{1:[2,1]},{8:[1,37]},{4:21,5:s,7:38,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:u,41:l,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:39,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:u,41:l,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:40,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:u,41:l,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:41,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:u,41:l,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:42,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:u,41:l,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{27:43,71:[1,44],72:[1,45]},{54:46,71:[1,47],72:[1,48]},{60:[1,49],62:[1,50]},t(b,[2,26]),t(b,[2,27]),t(b,[2,28]),t(b,[2,29]),t(b,[2,30]),t(b,[2,31]),t(_,[2,55]),t(_,[2,56]),t(o,[2,4]),{13:51,21:[1,52]},t(o,[2,12]),{1:[2,3]},{8:[2,14]},{8:[2,15]},{8:[2,16]},{8:[2,17]},{8:[2,18]},{28:[1,53]},{28:[2,53]},{28:[2,54]},{28:[1,54]},{28:[2,59]},{28:[2,60]},{61:55,64:x,65:w,66:k,67:T,68:E,69:C,70:S},{61:63,64:x,65:w,66:k,67:T,68:E,69:C,70:S},{11:64,22:v},{22:[2,11]},{5:[1,65]},{5:[1,66]},{62:[1,67]},t(A,[2,46]),t(A,[2,47]),t(A,[2,48]),t(A,[2,49]),t(A,[2,50]),t(A,[2,51]),t(A,[2,52]),{63:[1,68]},t(o,[2,5]),{5:M,29:69,30:N,33:D,35:L,37:B,39:O},{5:I,39:R,55:76,56:F,58:P},{32:81,71:y,72:m},{32:82,71:y,72:m},t(Y,[2,19]),{31:[1,83]},{31:[1,84]},{31:[1,85]},{31:[1,86]},{5:M,29:87,30:N,33:D,35:L,37:B,39:O},t(Y,[2,25]),t(Y,[2,39]),{31:[1,88]},{31:[1,89]},{5:I,39:R,55:90,56:F,58:P},t(Y,[2,43]),t(Y,[2,44]),t(Y,[2,45]),{32:91,71:y,72:m},{34:92,71:[1,93],72:[1,94]},{36:95,46:[1,96],47:[1,97],48:[1,98]},{38:99,49:[1,100],50:[1,101],51:[1,102],52:[1,103]},t(Y,[2,24]),{57:104,71:[1,105],72:[1,106]},{59:107,71:[1,108],72:[1,109]},t(Y,[2,42]),{5:[1,110]},{5:[1,111]},{5:[2,57]},{5:[2,58]},{5:[1,112]},{5:[2,32]},{5:[2,33]},{5:[2,34]},{5:[1,113]},{5:[2,35]},{5:[2,36]},{5:[2,37]},{5:[2,38]},{5:[1,114]},{5:[2,61]},{5:[2,62]},{5:[1,115]},{5:[2,63]},{5:[2,64]},{5:M,29:116,30:N,33:D,35:L,37:B,39:O},{5:M,29:117,30:N,33:D,35:L,37:B,39:O},{5:M,29:118,30:N,33:D,35:L,37:B,39:O},{5:M,29:119,30:N,33:D,35:L,37:B,39:O},{5:I,39:R,55:120,56:F,58:P},{5:I,39:R,55:121,56:F,58:P},t(Y,[2,20]),t(Y,[2,21]),t(Y,[2,22]),t(Y,[2,23]),t(Y,[2,40]),t(Y,[2,41])],defaultActions:{8:[2,9],10:[2,2],16:[2,1],37:[2,3],38:[2,14],39:[2,15],40:[2,16],41:[2,17],42:[2,18],44:[2,53],45:[2,54],47:[2,59],48:[2,60],52:[2,11],93:[2,57],94:[2,58],96:[2,32],97:[2,33],98:[2,34],100:[2,35],101:[2,36],102:[2,37],103:[2,38],105:[2,61],106:[2,62],108:[2,63],109:[2,64]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},U={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),19;case 1:return this.begin("type_directive"),20;case 2:return this.popState(),this.begin("arg_directive"),12;case 3:return this.popState(),this.popState(),22;case 4:return 21;case 5:return"title";case 6:return this.begin("acc_title"),14;case 7:return this.popState(),"acc_title_value";case 8:return this.begin("acc_descr"),16;case 9:return this.popState(),"acc_descr_value";case 10:this.begin("acc_descr_multiline");break;case 11:case 53:this.popState();break;case 12:return"acc_descr_multiline_value";case 13:return 5;case 14:case 15:case 16:break;case 17:return 8;case 18:return 6;case 19:return 28;case 20:return 39;case 21:return 31;case 22:return 30;case 23:return 33;case 24:return 35;case 25:return 37;case 26:return 40;case 27:return 41;case 28:return 42;case 29:return 43;case 30:return 44;case 31:return 45;case 32:return 46;case 33:return 47;case 34:return 48;case 35:return 49;case 36:return 50;case 37:return 51;case 38:return 52;case 39:return 53;case 40:return 64;case 41:return 65;case 42:return 66;case 43:return 67;case 44:return 68;case 45:return 69;case 46:return 70;case 47:return 56;case 48:return 58;case 49:return 60;case 50:return 63;case 51:return 62;case 52:this.begin("string");break;case 54:return"qString";case 55:return e.yytext=e.yytext.trim(),71}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:(\r?\n)+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:$)/i,/^(?:requirementDiagram\b)/i,/^(?:\{)/i,/^(?:\})/i,/^(?::)/i,/^(?:id\b)/i,/^(?:text\b)/i,/^(?:risk\b)/i,/^(?:verifyMethod\b)/i,/^(?:requirement\b)/i,/^(?:functionalRequirement\b)/i,/^(?:interfaceRequirement\b)/i,/^(?:performanceRequirement\b)/i,/^(?:physicalRequirement\b)/i,/^(?:designConstraint\b)/i,/^(?:low\b)/i,/^(?:medium\b)/i,/^(?:high\b)/i,/^(?:analysis\b)/i,/^(?:demonstration\b)/i,/^(?:inspection\b)/i,/^(?:test\b)/i,/^(?:element\b)/i,/^(?:contains\b)/i,/^(?:copies\b)/i,/^(?:derives\b)/i,/^(?:satisfies\b)/i,/^(?:verifies\b)/i,/^(?:refines\b)/i,/^(?:traces\b)/i,/^(?:type\b)/i,/^(?:docref\b)/i,/^(?:<-)/i,/^(?:->)/i,/^(?:-)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[\w][^\r\n\{\<\>\-\=]*)/i],conditions:{acc_descr_multiline:{rules:[11,12],inclusive:!1},acc_descr:{rules:[9],inclusive:!1},acc_title:{rules:[7],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},unqString:{rules:[],inclusive:!1},token:{rules:[],inclusive:!1},string:{rules:[53,54],inclusive:!1},INITIAL:{rules:[0,5,6,8,10,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,55],inclusive:!0}}};function z(){this.yy={}}return j.lexer=U,z.prototype=j,j.Parser=z,new z}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8800).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},6876:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,3],r=[1,5],i=[1,7],a=[2,5],o=[1,15],s=[1,17],c=[1,18],u=[1,19],l=[1,21],h=[1,22],f=[1,23],d=[1,29],p=[1,30],g=[1,31],y=[1,32],m=[1,33],v=[1,34],b=[1,35],_=[1,36],x=[1,37],w=[1,38],k=[1,39],T=[1,40],E=[1,43],C=[1,44],S=[1,45],A=[1,46],M=[1,47],N=[1,48],D=[1,51],L=[1,4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,50,51,52,53,58,59,60,61,69,79],B=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,53,58,59,60,61,69,79],O=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,52,53,58,59,60,61,69,79],I=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,51,53,58,59,60,61,69,79],R=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,50,53,58,59,60,61,69,79],F=[67,68,69],P=[1,121],Y=[1,4,5,7,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,50,51,52,53,58,59,60,61,69,79],j={trace:function(){},yy:{},symbols_:{error:2,start:3,SPACE:4,NEWLINE:5,directive:6,SD:7,document:8,line:9,statement:10,openDirective:11,typeDirective:12,closeDirective:13,":":14,argDirective:15,participant:16,actor:17,AS:18,restOfLine:19,participant_actor:20,signal:21,autonumber:22,NUM:23,off:24,activate:25,deactivate:26,note_statement:27,links_statement:28,link_statement:29,properties_statement:30,details_statement:31,title:32,legacy_title:33,acc_title:34,acc_title_value:35,acc_descr:36,acc_descr_value:37,acc_descr_multiline_value:38,loop:39,end:40,rect:41,opt:42,alt:43,else_sections:44,par:45,par_sections:46,critical:47,option_sections:48,break:49,option:50,and:51,else:52,note:53,placement:54,text2:55,over:56,actor_pair:57,links:58,link:59,properties:60,details:61,spaceList:62,",":63,left_of:64,right_of:65,signaltype:66,"+":67,"-":68,ACTOR:69,SOLID_OPEN_ARROW:70,DOTTED_OPEN_ARROW:71,SOLID_ARROW:72,DOTTED_ARROW:73,SOLID_CROSS:74,DOTTED_CROSS:75,SOLID_POINT:76,DOTTED_POINT:77,TXT:78,open_directive:79,type_directive:80,arg_directive:81,close_directive:82,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NEWLINE",7:"SD",14:":",16:"participant",18:"AS",19:"restOfLine",20:"participant_actor",22:"autonumber",23:"NUM",24:"off",25:"activate",26:"deactivate",32:"title",33:"legacy_title",34:"acc_title",35:"acc_title_value",36:"acc_descr",37:"acc_descr_value",38:"acc_descr_multiline_value",39:"loop",40:"end",41:"rect",42:"opt",43:"alt",45:"par",47:"critical",49:"break",50:"option",51:"and",52:"else",53:"note",56:"over",58:"links",59:"link",60:"properties",61:"details",63:",",64:"left_of",65:"right_of",67:"+",68:"-",69:"ACTOR",70:"SOLID_OPEN_ARROW",71:"DOTTED_OPEN_ARROW",72:"SOLID_ARROW",73:"DOTTED_ARROW",74:"SOLID_CROSS",75:"DOTTED_CROSS",76:"SOLID_POINT",77:"DOTTED_POINT",78:"TXT",79:"open_directive",80:"type_directive",81:"arg_directive",82:"close_directive"},productions_:[0,[3,2],[3,2],[3,2],[3,2],[8,0],[8,2],[9,2],[9,1],[9,1],[6,4],[6,6],[10,5],[10,3],[10,5],[10,3],[10,2],[10,4],[10,3],[10,3],[10,2],[10,3],[10,3],[10,2],[10,2],[10,2],[10,2],[10,2],[10,1],[10,1],[10,2],[10,2],[10,1],[10,4],[10,4],[10,4],[10,4],[10,4],[10,4],[10,4],[10,1],[48,1],[48,4],[46,1],[46,4],[44,1],[44,4],[27,4],[27,4],[28,3],[29,3],[30,3],[31,3],[62,2],[62,1],[57,3],[57,1],[54,1],[54,1],[21,5],[21,5],[21,4],[17,1],[66,1],[66,1],[66,1],[66,1],[66,1],[66,1],[66,1],[66,1],[55,1],[11,1],[12,1],[15,1],[13,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 4:return r.apply(a[s]),a[s];case 5:case 9:this.$=[];break;case 6:a[s-1].push(a[s]),this.$=a[s-1];break;case 7:case 8:case 56:this.$=a[s];break;case 12:a[s-3].type="addParticipant",a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 13:a[s-1].type="addParticipant",this.$=a[s-1];break;case 14:a[s-3].type="addActor",a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 15:a[s-1].type="addActor",this.$=a[s-1];break;case 17:this.$={type:"sequenceIndex",sequenceIndex:Number(a[s-2]),sequenceIndexStep:Number(a[s-1]),sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 18:this.$={type:"sequenceIndex",sequenceIndex:Number(a[s-1]),sequenceIndexStep:1,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 19:this.$={type:"sequenceIndex",sequenceVisible:!1,signalType:r.LINETYPE.AUTONUMBER};break;case 20:this.$={type:"sequenceIndex",sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 21:this.$={type:"activeStart",signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1]};break;case 22:this.$={type:"activeEnd",signalType:r.LINETYPE.ACTIVE_END,actor:a[s-1]};break;case 28:r.setDiagramTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 29:r.setDiagramTitle(a[s].substring(7)),this.$=a[s].substring(7);break;case 30:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 31:case 32:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 33:a[s-1].unshift({type:"loopStart",loopText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.LOOP_START}),a[s-1].push({type:"loopEnd",loopText:a[s-2],signalType:r.LINETYPE.LOOP_END}),this.$=a[s-1];break;case 34:a[s-1].unshift({type:"rectStart",color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_START}),a[s-1].push({type:"rectEnd",color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_END}),this.$=a[s-1];break;case 35:a[s-1].unshift({type:"optStart",optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_START}),a[s-1].push({type:"optEnd",optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_END}),this.$=a[s-1];break;case 36:a[s-1].unshift({type:"altStart",altText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.ALT_START}),a[s-1].push({type:"altEnd",signalType:r.LINETYPE.ALT_END}),this.$=a[s-1];break;case 37:a[s-1].unshift({type:"parStart",parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_START}),a[s-1].push({type:"parEnd",signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 38:a[s-1].unshift({type:"criticalStart",criticalText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.CRITICAL_START}),a[s-1].push({type:"criticalEnd",signalType:r.LINETYPE.CRITICAL_END}),this.$=a[s-1];break;case 39:a[s-1].unshift({type:"breakStart",breakText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_START}),a[s-1].push({type:"breakEnd",optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_END}),this.$=a[s-1];break;case 42:this.$=a[s-3].concat([{type:"option",optionText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.CRITICAL_OPTION},a[s]]);break;case 44:this.$=a[s-3].concat([{type:"and",parText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.PAR_AND},a[s]]);break;case 46:this.$=a[s-3].concat([{type:"else",altText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.ALT_ELSE},a[s]]);break;case 47:this.$=[a[s-1],{type:"addNote",placement:a[s-2],actor:a[s-1].actor,text:a[s]}];break;case 48:a[s-2]=[].concat(a[s-1],a[s-1]).slice(0,2),a[s-2][0]=a[s-2][0].actor,a[s-2][1]=a[s-2][1].actor,this.$=[a[s-1],{type:"addNote",placement:r.PLACEMENT.OVER,actor:a[s-2].slice(0,2),text:a[s]}];break;case 49:this.$=[a[s-1],{type:"addLinks",actor:a[s-1].actor,text:a[s]}];break;case 50:this.$=[a[s-1],{type:"addALink",actor:a[s-1].actor,text:a[s]}];break;case 51:this.$=[a[s-1],{type:"addProperties",actor:a[s-1].actor,text:a[s]}];break;case 52:this.$=[a[s-1],{type:"addDetails",actor:a[s-1].actor,text:a[s]}];break;case 55:this.$=[a[s-2],a[s]];break;case 57:this.$=r.PLACEMENT.LEFTOF;break;case 58:this.$=r.PLACEMENT.RIGHTOF;break;case 59:this.$=[a[s-4],a[s-1],{type:"addMessage",from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s]},{type:"activeStart",signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1]}];break;case 60:this.$=[a[s-4],a[s-1],{type:"addMessage",from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s]},{type:"activeEnd",signalType:r.LINETYPE.ACTIVE_END,actor:a[s-4]}];break;case 61:this.$=[a[s-3],a[s-1],{type:"addMessage",from:a[s-3].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s]}];break;case 62:this.$={type:"addParticipant",actor:a[s]};break;case 63:this.$=r.LINETYPE.SOLID_OPEN;break;case 64:this.$=r.LINETYPE.DOTTED_OPEN;break;case 65:this.$=r.LINETYPE.SOLID;break;case 66:this.$=r.LINETYPE.DOTTED;break;case 67:this.$=r.LINETYPE.SOLID_CROSS;break;case 68:this.$=r.LINETYPE.DOTTED_CROSS;break;case 69:this.$=r.LINETYPE.SOLID_POINT;break;case 70:this.$=r.LINETYPE.DOTTED_POINT;break;case 71:this.$=r.parseMessage(a[s].trim().substring(1));break;case 72:r.parseDirective("%%{","open_directive");break;case 73:r.parseDirective(a[s],"type_directive");break;case 74:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 75:r.parseDirective("}%%","close_directive","sequence")}},table:[{3:1,4:e,5:n,6:4,7:r,11:6,79:i},{1:[3]},{3:8,4:e,5:n,6:4,7:r,11:6,79:i},{3:9,4:e,5:n,6:4,7:r,11:6,79:i},{3:10,4:e,5:n,6:4,7:r,11:6,79:i},t([1,4,5,16,20,22,25,26,32,33,34,36,38,39,41,42,43,45,47,49,53,58,59,60,61,69,79],a,{8:11}),{12:12,80:[1,13]},{80:[2,72]},{1:[2,1]},{1:[2,2]},{1:[2,3]},{1:[2,4],4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,41:b,42:_,43:x,45:w,47:k,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{13:49,14:[1,50],82:D},t([14,82],[2,73]),t(L,[2,6]),{6:41,10:52,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,41:b,42:_,43:x,45:w,47:k,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},t(L,[2,8]),t(L,[2,9]),{17:53,69:N},{17:54,69:N},{5:[1,55]},{5:[1,58],23:[1,56],24:[1,57]},{17:59,69:N},{17:60,69:N},{5:[1,61]},{5:[1,62]},{5:[1,63]},{5:[1,64]},{5:[1,65]},t(L,[2,28]),t(L,[2,29]),{35:[1,66]},{37:[1,67]},t(L,[2,32]),{19:[1,68]},{19:[1,69]},{19:[1,70]},{19:[1,71]},{19:[1,72]},{19:[1,73]},{19:[1,74]},t(L,[2,40]),{66:75,70:[1,76],71:[1,77],72:[1,78],73:[1,79],74:[1,80],75:[1,81],76:[1,82],77:[1,83]},{54:84,56:[1,85],64:[1,86],65:[1,87]},{17:88,69:N},{17:89,69:N},{17:90,69:N},{17:91,69:N},t([5,18,63,70,71,72,73,74,75,76,77,78],[2,62]),{5:[1,92]},{15:93,81:[1,94]},{5:[2,75]},t(L,[2,7]),{5:[1,96],18:[1,95]},{5:[1,98],18:[1,97]},t(L,[2,16]),{5:[1,100],23:[1,99]},{5:[1,101]},t(L,[2,20]),{5:[1,102]},{5:[1,103]},t(L,[2,23]),t(L,[2,24]),t(L,[2,25]),t(L,[2,26]),t(L,[2,27]),t(L,[2,30]),t(L,[2,31]),t(B,a,{8:104}),t(B,a,{8:105}),t(B,a,{8:106}),t(O,a,{44:107,8:108}),t(I,a,{46:109,8:110}),t(R,a,{48:111,8:112}),t(B,a,{8:113}),{17:116,67:[1,114],68:[1,115],69:N},t(F,[2,63]),t(F,[2,64]),t(F,[2,65]),t(F,[2,66]),t(F,[2,67]),t(F,[2,68]),t(F,[2,69]),t(F,[2,70]),{17:117,69:N},{17:119,57:118,69:N},{69:[2,57]},{69:[2,58]},{55:120,78:P},{55:122,78:P},{55:123,78:P},{55:124,78:P},t(Y,[2,10]),{13:125,82:D},{82:[2,74]},{19:[1,126]},t(L,[2,13]),{19:[1,127]},t(L,[2,15]),{5:[1,128]},t(L,[2,18]),t(L,[2,19]),t(L,[2,21]),t(L,[2,22]),{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,40:[1,129],41:b,42:_,43:x,45:w,47:k,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,40:[1,130],41:b,42:_,43:x,45:w,47:k,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,40:[1,131],41:b,42:_,43:x,45:w,47:k,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{40:[1,132]},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,40:[2,45],41:b,42:_,43:x,45:w,47:k,49:T,52:[1,133],53:E,58:C,59:S,60:A,61:M,69:N,79:i},{40:[1,134]},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,40:[2,43],41:b,42:_,43:x,45:w,47:k,49:T,51:[1,135],53:E,58:C,59:S,60:A,61:M,69:N,79:i},{40:[1,136]},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,40:[2,41],41:b,42:_,43:x,45:w,47:k,49:T,50:[1,137],53:E,58:C,59:S,60:A,61:M,69:N,79:i},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:u,21:20,22:l,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:v,40:[1,138],41:b,42:_,43:x,45:w,47:k,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{17:139,69:N},{17:140,69:N},{55:141,78:P},{55:142,78:P},{55:143,78:P},{63:[1,144],78:[2,56]},{5:[2,49]},{5:[2,71]},{5:[2,50]},{5:[2,51]},{5:[2,52]},{5:[1,145]},{5:[1,146]},{5:[1,147]},t(L,[2,17]),t(L,[2,33]),t(L,[2,34]),t(L,[2,35]),t(L,[2,36]),{19:[1,148]},t(L,[2,37]),{19:[1,149]},t(L,[2,38]),{19:[1,150]},t(L,[2,39]),{55:151,78:P},{55:152,78:P},{5:[2,61]},{5:[2,47]},{5:[2,48]},{17:153,69:N},t(Y,[2,11]),t(L,[2,12]),t(L,[2,14]),t(O,a,{8:108,44:154}),t(I,a,{8:110,46:155}),t(R,a,{8:112,48:156}),{5:[2,59]},{5:[2,60]},{78:[2,55]},{40:[2,46]},{40:[2,44]},{40:[2,42]}],defaultActions:{7:[2,72],8:[2,1],9:[2,2],10:[2,3],51:[2,75],86:[2,57],87:[2,58],94:[2,74],120:[2,49],121:[2,71],122:[2,50],123:[2,51],124:[2,52],141:[2,61],142:[2,47],143:[2,48],151:[2,59],152:[2,60],153:[2,55],154:[2,46],155:[2,44],156:[2,42]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},U={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),79;case 1:return this.begin("type_directive"),80;case 2:return this.popState(),this.begin("arg_directive"),14;case 3:return this.popState(),this.popState(),82;case 4:return 81;case 5:case 52:case 65:return 5;case 6:case 7:case 8:case 9:case 10:break;case 11:return 23;case 12:return this.begin("ID"),16;case 13:return this.begin("ID"),20;case 14:return e.yytext=e.yytext.trim(),this.begin("ALIAS"),69;case 15:return this.popState(),this.popState(),this.begin("LINE"),18;case 16:return this.popState(),this.popState(),5;case 17:return this.begin("LINE"),39;case 18:return this.begin("LINE"),41;case 19:return this.begin("LINE"),42;case 20:return this.begin("LINE"),43;case 21:return this.begin("LINE"),52;case 22:return this.begin("LINE"),45;case 23:return this.begin("LINE"),51;case 24:return this.begin("LINE"),47;case 25:return this.begin("LINE"),50;case 26:return this.begin("LINE"),49;case 27:return this.popState(),19;case 28:return 40;case 29:return 64;case 30:return 65;case 31:return 58;case 32:return 59;case 33:return 60;case 34:return 61;case 35:return 56;case 36:return 53;case 37:return this.begin("ID"),25;case 38:return this.begin("ID"),26;case 39:return 32;case 40:return 33;case 41:return this.begin("acc_title"),34;case 42:return this.popState(),"acc_title_value";case 43:return this.begin("acc_descr"),36;case 44:return this.popState(),"acc_descr_value";case 45:this.begin("acc_descr_multiline");break;case 46:this.popState();break;case 47:return"acc_descr_multiline_value";case 48:return 7;case 49:return 22;case 50:return 24;case 51:return 63;case 53:return e.yytext=e.yytext.trim(),69;case 54:return 72;case 55:return 73;case 56:return 70;case 57:return 71;case 58:return 74;case 59:return 75;case 60:return 76;case 61:return 77;case 62:return 78;case 63:return 67;case 64:return 68;case 66:return"INVALID"}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[0-9]+(?=[ \n]+))/i,/^(?:participant\b)/i,/^(?:actor\b)/i,/^(?:[^\->:\n,;]+?(?=((?!\n)\s)+as(?!\n)\s|[#\n;]|$))/i,/^(?:as\b)/i,/^(?:(?:))/i,/^(?:loop\b)/i,/^(?:rect\b)/i,/^(?:opt\b)/i,/^(?:alt\b)/i,/^(?:else\b)/i,/^(?:par\b)/i,/^(?:and\b)/i,/^(?:critical\b)/i,/^(?:option\b)/i,/^(?:break\b)/i,/^(?:(?:[:]?(?:no)?wrap)?[^#\n;]*)/i,/^(?:end\b)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:links\b)/i,/^(?:link\b)/i,/^(?:properties\b)/i,/^(?:details\b)/i,/^(?:over\b)/i,/^(?:note\b)/i,/^(?:activate\b)/i,/^(?:deactivate\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:title:\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:sequenceDiagram\b)/i,/^(?:autonumber\b)/i,/^(?:off\b)/i,/^(?:,)/i,/^(?:;)/i,/^(?:[^\+\->:\n,;]+((?!(-x|--x|-\)|--\)))[\-]*[^\+\->:\n,;]+)*)/i,/^(?:->>)/i,/^(?:-->>)/i,/^(?:->)/i,/^(?:-->)/i,/^(?:-[x])/i,/^(?:--[x])/i,/^(?:-[\)])/i,/^(?:--[\)])/i,/^(?::(?:(?:no)?wrap)?[^#\n;]+)/i,/^(?:\+)/i,/^(?:-)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[46,47],inclusive:!1},acc_descr:{rules:[44],inclusive:!1},acc_title:{rules:[42],inclusive:!1},open_directive:{rules:[1,8],inclusive:!1},type_directive:{rules:[2,3,8],inclusive:!1},arg_directive:{rules:[3,4,8],inclusive:!1},ID:{rules:[7,8,14],inclusive:!1},ALIAS:{rules:[7,8,15,16],inclusive:!1},LINE:{rules:[7,8,27],inclusive:!1},INITIAL:{rules:[0,5,6,8,9,10,11,12,13,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,43,45,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66],inclusive:!0}}};function z(){this.yy={}}return j.lexer=U,z.prototype=j,j.Parser=z,new z}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(1993).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},3584:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,3],r=[1,5],i=[1,7],a=[2,5],o=[1,15],s=[1,17],c=[1,19],u=[1,20],l=[1,21],h=[1,22],f=[1,33],d=[1,23],p=[1,24],g=[1,25],y=[1,26],m=[1,27],v=[1,30],b=[1,31],_=[1,32],x=[1,35],w=[1,36],k=[1,37],T=[1,38],E=[1,34],C=[1,41],S=[1,4,5,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],A=[1,4,5,12,13,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],M=[1,4,5,7,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],N=[4,5,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],D={trace:function(){},yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,directive:6,SD:7,document:8,line:9,statement:10,idStatement:11,DESCR:12,"--\x3e":13,HIDE_EMPTY:14,scale:15,WIDTH:16,COMPOSIT_STATE:17,STRUCT_START:18,STRUCT_STOP:19,STATE_DESCR:20,AS:21,ID:22,FORK:23,JOIN:24,CHOICE:25,CONCURRENT:26,note:27,notePosition:28,NOTE_TEXT:29,direction:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,openDirective:36,typeDirective:37,closeDirective:38,":":39,argDirective:40,direction_tb:41,direction_bt:42,direction_rl:43,direction_lr:44,eol:45,";":46,EDGE_STATE:47,left_of:48,right_of:49,open_directive:50,type_directive:51,arg_directive:52,close_directive:53,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NL",7:"SD",12:"DESCR",13:"--\x3e",14:"HIDE_EMPTY",15:"scale",16:"WIDTH",17:"COMPOSIT_STATE",18:"STRUCT_START",19:"STRUCT_STOP",20:"STATE_DESCR",21:"AS",22:"ID",23:"FORK",24:"JOIN",25:"CHOICE",26:"CONCURRENT",27:"note",29:"NOTE_TEXT",31:"acc_title",32:"acc_title_value",33:"acc_descr",34:"acc_descr_value",35:"acc_descr_multiline_value",39:":",41:"direction_tb",42:"direction_bt",43:"direction_rl",44:"direction_lr",46:";",47:"EDGE_STATE",48:"left_of",49:"right_of",50:"open_directive",51:"type_directive",52:"arg_directive",53:"close_directive"},productions_:[0,[3,2],[3,2],[3,2],[3,2],[8,0],[8,2],[9,2],[9,1],[9,1],[10,1],[10,2],[10,3],[10,4],[10,1],[10,2],[10,1],[10,4],[10,3],[10,6],[10,1],[10,1],[10,1],[10,1],[10,4],[10,4],[10,1],[10,1],[10,2],[10,2],[10,1],[6,3],[6,5],[30,1],[30,1],[30,1],[30,1],[45,1],[45,1],[11,1],[11,1],[28,1],[28,1],[36,1],[37,1],[40,1],[38,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 4:return r.setRootDoc(a[s]),a[s];case 5:this.$=[];break;case 6:"nl"!=a[s]&&(a[s-1].push(a[s]),this.$=a[s-1]);break;case 7:case 8:case 39:case 40:this.$=a[s];break;case 9:this.$="nl";break;case 10:this.$={stmt:"state",id:a[s],type:"default",description:""};break;case 11:this.$={stmt:"state",id:a[s-1],type:"default",description:r.trimColon(a[s])};break;case 12:this.$={stmt:"relation",state1:{stmt:"state",id:a[s-2],type:"default",description:""},state2:{stmt:"state",id:a[s],type:"default",description:""}};break;case 13:this.$={stmt:"relation",state1:{stmt:"state",id:a[s-3],type:"default",description:""},state2:{stmt:"state",id:a[s-1],type:"default",description:""},description:a[s].substr(1).trim()};break;case 17:this.$={stmt:"state",id:a[s-3],type:"default",description:"",doc:a[s-1]};break;case 18:var c=a[s],u=a[s-2].trim();if(a[s].match(":")){var l=a[s].split(":");c=l[0],u=[u,l[1]]}this.$={stmt:"state",id:c,type:"default",description:u};break;case 19:this.$={stmt:"state",id:a[s-3],type:"default",description:a[s-5],doc:a[s-1]};break;case 20:this.$={stmt:"state",id:a[s],type:"fork"};break;case 21:this.$={stmt:"state",id:a[s],type:"join"};break;case 22:this.$={stmt:"state",id:a[s],type:"choice"};break;case 23:this.$={stmt:"state",id:r.getDividerId(),type:"divider"};break;case 24:this.$={stmt:"state",id:a[s-1].trim(),note:{position:a[s-2].trim(),text:a[s].trim()}};break;case 28:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 29:case 30:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 33:r.setDirection("TB"),this.$={stmt:"dir",value:"TB"};break;case 34:r.setDirection("BT"),this.$={stmt:"dir",value:"BT"};break;case 35:r.setDirection("RL"),this.$={stmt:"dir",value:"RL"};break;case 36:r.setDirection("LR"),this.$={stmt:"dir",value:"LR"};break;case 43:r.parseDirective("%%{","open_directive");break;case 44:r.parseDirective(a[s],"type_directive");break;case 45:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 46:r.parseDirective("}%%","close_directive","state")}},table:[{3:1,4:e,5:n,6:4,7:r,36:6,50:i},{1:[3]},{3:8,4:e,5:n,6:4,7:r,36:6,50:i},{3:9,4:e,5:n,6:4,7:r,36:6,50:i},{3:10,4:e,5:n,6:4,7:r,36:6,50:i},t([1,4,5,14,15,17,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],a,{8:11}),{37:12,51:[1,13]},{51:[2,43]},{1:[2,1]},{1:[2,2]},{1:[2,3]},{1:[2,4],4:o,5:s,6:28,9:14,10:16,11:18,14:c,15:u,17:l,20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:v,33:b,35:_,36:6,41:x,42:w,43:k,44:T,47:E,50:i},{38:39,39:[1,40],53:C},t([39,53],[2,44]),t(S,[2,6]),{6:28,10:42,11:18,14:c,15:u,17:l,20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:v,33:b,35:_,36:6,41:x,42:w,43:k,44:T,47:E,50:i},t(S,[2,8]),t(S,[2,9]),t(S,[2,10],{12:[1,43],13:[1,44]}),t(S,[2,14]),{16:[1,45]},t(S,[2,16],{18:[1,46]}),{21:[1,47]},t(S,[2,20]),t(S,[2,21]),t(S,[2,22]),t(S,[2,23]),{28:48,29:[1,49],48:[1,50],49:[1,51]},t(S,[2,26]),t(S,[2,27]),{32:[1,52]},{34:[1,53]},t(S,[2,30]),t(A,[2,39]),t(A,[2,40]),t(S,[2,33]),t(S,[2,34]),t(S,[2,35]),t(S,[2,36]),t(M,[2,31]),{40:54,52:[1,55]},t(M,[2,46]),t(S,[2,7]),t(S,[2,11]),{11:56,22:f,47:E},t(S,[2,15]),t(N,a,{8:57}),{22:[1,58]},{22:[1,59]},{21:[1,60]},{22:[2,41]},{22:[2,42]},t(S,[2,28]),t(S,[2,29]),{38:61,53:C},{53:[2,45]},t(S,[2,12],{12:[1,62]}),{4:o,5:s,6:28,9:14,10:16,11:18,14:c,15:u,17:l,19:[1,63],20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:v,33:b,35:_,36:6,41:x,42:w,43:k,44:T,47:E,50:i},t(S,[2,18],{18:[1,64]}),{29:[1,65]},{22:[1,66]},t(M,[2,32]),t(S,[2,13]),t(S,[2,17]),t(N,a,{8:67}),t(S,[2,24]),t(S,[2,25]),{4:o,5:s,6:28,9:14,10:16,11:18,14:c,15:u,17:l,19:[1,68],20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:v,33:b,35:_,36:6,41:x,42:w,43:k,44:T,47:E,50:i},t(S,[2,19])],defaultActions:{7:[2,43],8:[2,1],9:[2,2],10:[2,3],50:[2,41],51:[2,42],55:[2,45]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},L={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:case 33:return 41;case 1:case 34:return 42;case 2:case 35:return 43;case 3:case 36:return 44;case 4:return this.begin("open_directive"),50;case 5:return this.begin("type_directive"),51;case 6:return this.popState(),this.begin("arg_directive"),39;case 7:return this.popState(),this.popState(),53;case 8:return 52;case 9:case 10:case 12:case 13:case 14:case 15:case 46:case 52:break;case 11:case 66:return 5;case 16:return this.pushState("SCALE"),15;case 17:return 16;case 18:case 24:case 40:case 43:this.popState();break;case 19:return this.begin("acc_title"),31;case 20:return this.popState(),"acc_title_value";case 21:return this.begin("acc_descr"),33;case 22:return this.popState(),"acc_descr_value";case 23:this.begin("acc_descr_multiline");break;case 25:return"acc_descr_multiline_value";case 26:this.pushState("STATE");break;case 27:case 30:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),23;case 28:case 31:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),24;case 29:case 32:return this.popState(),e.yytext=e.yytext.slice(0,-10).trim(),25;case 37:this.begin("STATE_STRING");break;case 38:return this.popState(),this.pushState("STATE_ID"),"AS";case 39:case 54:return this.popState(),"ID";case 41:return"STATE_DESCR";case 42:return 17;case 44:return this.popState(),this.pushState("struct"),18;case 45:return this.popState(),19;case 47:return this.begin("NOTE"),27;case 48:return this.popState(),this.pushState("NOTE_ID"),48;case 49:return this.popState(),this.pushState("NOTE_ID"),49;case 50:this.popState(),this.pushState("FLOATING_NOTE");break;case 51:return this.popState(),this.pushState("FLOATING_NOTE_ID"),"AS";case 53:return"NOTE_TEXT";case 55:return this.popState(),this.pushState("NOTE_TEXT"),22;case 56:return this.popState(),e.yytext=e.yytext.substr(2).trim(),29;case 57:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),29;case 58:case 59:return 7;case 60:return 14;case 61:return 47;case 62:return 22;case 63:return e.yytext=e.yytext.trim(),12;case 64:return 13;case 65:return 26;case 67:return"INVALID"}},rules:[/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:state\s+)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*\[\[fork\]\])/i,/^(?:.*\[\[join\]\])/i,/^(?:.*\[\[choice\]\])/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:["])/i,/^(?:\s*as\s+)/i,/^(?:[^\n\{]*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n\s\{]+)/i,/^(?:\n)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:[\n])/i,/^(?:note\s+)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:")/i,/^(?:\s*as\s*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n]*)/i,/^(?:\s*[^:\n\s\-]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:[\s\S]*?end note\b)/i,/^(?:stateDiagram\s+)/i,/^(?:stateDiagram-v2\s+)/i,/^(?:hide empty description\b)/i,/^(?:\[\*\])/i,/^(?:[^:\n\s\-\{]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:-->)/i,/^(?:--)/i,/^(?:$)/i,/^(?:.)/i],conditions:{LINE:{rules:[13,14],inclusive:!1},close_directive:{rules:[13,14],inclusive:!1},arg_directive:{rules:[7,8,13,14],inclusive:!1},type_directive:{rules:[6,7,13,14],inclusive:!1},open_directive:{rules:[5,13,14],inclusive:!1},struct:{rules:[13,14,26,33,34,35,36,45,46,47,61,62,63,64,65],inclusive:!1},FLOATING_NOTE_ID:{rules:[54],inclusive:!1},FLOATING_NOTE:{rules:[51,52,53],inclusive:!1},NOTE_TEXT:{rules:[56,57],inclusive:!1},NOTE_ID:{rules:[55],inclusive:!1},NOTE:{rules:[48,49,50],inclusive:!1},acc_descr_multiline:{rules:[24,25],inclusive:!1},acc_descr:{rules:[22],inclusive:!1},acc_title:{rules:[20],inclusive:!1},SCALE:{rules:[17,18],inclusive:!1},ALIAS:{rules:[],inclusive:!1},STATE_ID:{rules:[39],inclusive:!1},STATE_STRING:{rules:[40,41],inclusive:!1},FORK_STATE:{rules:[],inclusive:!1},STATE:{rules:[13,14,27,28,29,30,31,32,37,38,42,43,44],inclusive:!1},ID:{rules:[13,14],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,9,10,11,12,14,15,16,19,21,23,26,44,47,58,59,60,61,62,63,64,66,67],inclusive:!0}}};function B(){this.yy={}}return D.lexer=L,B.prototype=D,D.Parser=B,new B}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(3069).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},9763:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,5],r=[6,9,11,17,18,20,22,23,24,26],i=[1,15],a=[1,16],o=[1,17],s=[1,18],c=[1,19],u=[1,20],l=[1,24],h=[4,6,9,11,17,18,20,22,23,24,26],f={trace:function(){},yy:{},symbols_:{error:2,start:3,journey:4,document:5,EOF:6,directive:7,line:8,SPACE:9,statement:10,NEWLINE:11,openDirective:12,typeDirective:13,closeDirective:14,":":15,argDirective:16,title:17,acc_title:18,acc_title_value:19,acc_descr:20,acc_descr_value:21,acc_descr_multiline_value:22,section:23,taskName:24,taskData:25,open_directive:26,type_directive:27,arg_directive:28,close_directive:29,$accept:0,$end:1},terminals_:{2:"error",4:"journey",6:"EOF",9:"SPACE",11:"NEWLINE",15:":",17:"title",18:"acc_title",19:"acc_title_value",20:"acc_descr",21:"acc_descr_value",22:"acc_descr_multiline_value",23:"section",24:"taskName",25:"taskData",26:"open_directive",27:"type_directive",28:"arg_directive",29:"close_directive"},productions_:[0,[3,3],[3,2],[5,0],[5,2],[8,2],[8,1],[8,1],[8,1],[7,4],[7,6],[10,1],[10,2],[10,2],[10,1],[10,1],[10,2],[10,1],[12,1],[13,1],[16,1],[14,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 3:case 7:case 8:this.$=[];break;case 4:a[s-1].push(a[s]),this.$=a[s-1];break;case 5:case 6:this.$=a[s];break;case 11:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 12:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 13:case 14:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 15:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 16:r.addTask(a[s-1],a[s]),this.$="task";break;case 18:r.parseDirective("%%{","open_directive");break;case 19:r.parseDirective(a[s],"type_directive");break;case 20:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 21:r.parseDirective("}%%","close_directive","journey")}},table:[{3:1,4:e,7:3,12:4,26:n},{1:[3]},t(r,[2,3],{5:6}),{3:7,4:e,7:3,12:4,26:n},{13:8,27:[1,9]},{27:[2,18]},{6:[1,10],7:21,8:11,9:[1,12],10:13,11:[1,14],12:4,17:i,18:a,20:o,22:s,23:c,24:u,26:n},{1:[2,2]},{14:22,15:[1,23],29:l},t([15,29],[2,19]),t(r,[2,8],{1:[2,1]}),t(r,[2,4]),{7:21,10:25,12:4,17:i,18:a,20:o,22:s,23:c,24:u,26:n},t(r,[2,6]),t(r,[2,7]),t(r,[2,11]),{19:[1,26]},{21:[1,27]},t(r,[2,14]),t(r,[2,15]),{25:[1,28]},t(r,[2,17]),{11:[1,29]},{16:30,28:[1,31]},{11:[2,21]},t(r,[2,5]),t(r,[2,12]),t(r,[2,13]),t(r,[2,16]),t(h,[2,9]),{14:32,29:l},{29:[2,20]},{11:[1,33]},t(h,[2,10])],defaultActions:{5:[2,18],7:[2,2],24:[2,21],31:[2,20]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t)},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,u=0,l=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var v=p.options&&p.options.ranges;function b(){var t;return"number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,w,k,T,E,C,S,A,M={};;){if(w=n[n.length-1],this.defaultActions[w]?k=this.defaultActions[w]:(null==_&&(_=b()),k=o[w]&&o[w][_]),void 0===k||!k.length||!k[0]){var N="";for(E in A=[],o[w])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A})}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+w+", token: "+_);switch(k[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(k[1]),_=null,x?(_=x,x=null):(u=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,l>0&&l--);break;case 2:if(C=this.productions_[k[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},v&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,u,c,g.yy,k[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[k[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return!0}}return!0}},d={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e)},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t))},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return(t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return!1}return!1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;ae[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return!1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return(t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t)},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),26;case 1:return this.begin("type_directive"),27;case 2:return this.popState(),this.begin("arg_directive"),15;case 3:return this.popState(),this.popState(),29;case 4:return 28;case 5:case 6:case 8:case 9:break;case 7:return 11;case 10:return 4;case 11:return 17;case 12:return this.begin("acc_title"),18;case 13:return this.popState(),"acc_title_value";case 14:return this.begin("acc_descr"),20;case 15:return this.popState(),"acc_descr_value";case 16:this.begin("acc_descr_multiline");break;case 17:this.popState();break;case 18:return"acc_descr_multiline_value";case 19:return 23;case 20:return 24;case 21:return 25;case 22:return 15;case 23:return 6;case 24:return"INVALID"}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:journey\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:section\s[^#:\n;]+)/i,/^(?:[^#:\n;]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{open_directive:{rules:[1],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},acc_descr_multiline:{rules:[17,18],inclusive:!1},acc_descr:{rules:[15],inclusive:!1},acc_title:{rules:[13],inclusive:!1},INITIAL:{rules:[0,5,6,7,8,9,10,11,12,14,16,19,20,21,22,23,24],inclusive:!0}}};function p(){this.yy={}}return f.lexer=d,p.prototype=f,f.Parser=p,new p}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(9143).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1))},7967:(t,e)=>{"use strict";e.N=void 0;var n=/^([^\w]*)(javascript|data|vbscript)/im,r=/&#(\w+)(^\w|;)?/g,i=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,a=/^([^:]+):/gm,o=[".","/"];e.N=function(t){var e,s=(e=t||"",e.replace(r,(function(t,e){return String.fromCharCode(e)}))).replace(i,"").trim();if(!s)return"about:blank";if(function(t){return o.indexOf(t[0])>-1}(s))return s;var c=s.match(a);if(!c)return s;var u=c[0];return n.test(u)?"about:blank":s}},3841:t=>{t.exports=function(t,e){return t.intersect(e)}},8968:(t,e,n)=>{"use strict";n.d(e,{default:()=>VC});var r=n(1941),i=n.n(r),a={debug:1,info:2,warn:3,error:4,fatal:5},o={debug:function(){},info:function(){},warn:function(){},error:function(){},fatal:function(){}},s=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"fatal";isNaN(t)&&(t=t.toLowerCase(),void 0!==a[t]&&(t=a[t])),o.trace=function(){},o.debug=function(){},o.info=function(){},o.warn=function(){},o.error=function(){},o.fatal=function(){},t<=a.fatal&&(o.fatal=console.error?console.error.bind(console,c("FATAL"),"color: orange"):console.log.bind(console,"",c("FATAL"))),t<=a.error&&(o.error=console.error?console.error.bind(console,c("ERROR"),"color: orange"):console.log.bind(console,"",c("ERROR"))),t<=a.warn&&(o.warn=console.warn?console.warn.bind(console,c("WARN"),"color: orange"):console.log.bind(console,"",c("WARN"))),t<=a.info&&(o.info=console.info?console.info.bind(console,c("INFO"),"color: lightblue"):console.log.bind(console,"",c("INFO"))),t<=a.debug&&(o.debug=console.debug?console.debug.bind(console,c("DEBUG"),"color: lightgreen"):console.log.bind(console,"",c("DEBUG")))},c=function(t){var e=i()().format("ss.SSS");return"%c".concat(e," : ").concat(t," : ")};function u(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n=e)&&(n=e);else{let r=-1;for(let i of t)null!=(i=e(i,++r,t))&&(n=i)&&(n=i)}return n}function l(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n>e||void 0===n&&e>=e)&&(n=e);else{let r=-1;for(let i of t)null!=(i=e(i,++r,t))&&(n>i||void 0===n&&i>=i)&&(n=i)}return n}function h(t){return t}var f=1e-6;function d(t){return"translate("+t+",0)"}function p(t){return"translate(0,"+t+")"}function g(t){return e=>+t(e)}function y(t,e){return e=Math.max(0,t.bandwidth()-2*e)/2,t.round()&&(e=Math.round(e)),n=>+t(n)+e}function m(){return!this.__axis}function v(t,e){var n=[],r=null,i=null,a=6,o=6,s=3,c="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,u=1===t||4===t?-1:1,l=4===t||2===t?"x":"y",v=1===t||3===t?d:p;function b(d){var p=null==r?e.ticks?e.ticks.apply(e,n):e.domain():r,b=null==i?e.tickFormat?e.tickFormat.apply(e,n):h:i,_=Math.max(a,0)+s,x=e.range(),w=+x[0]+c,k=+x[x.length-1]+c,T=(e.bandwidth?y:g)(e.copy(),c),E=d.selection?d.selection():d,C=E.selectAll(".domain").data([null]),S=E.selectAll(".tick").data(p,e).order(),A=S.exit(),M=S.enter().append("g").attr("class","tick"),N=S.select("line"),D=S.select("text");C=C.merge(C.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),S=S.merge(M),N=N.merge(M.append("line").attr("stroke","currentColor").attr(l+"2",u*a)),D=D.merge(M.append("text").attr("fill","currentColor").attr(l,u*_).attr("dy",1===t?"0em":3===t?"0.71em":"0.32em")),d!==E&&(C=C.transition(d),S=S.transition(d),N=N.transition(d),D=D.transition(d),A=A.transition(d).attr("opacity",f).attr("transform",(function(t){return isFinite(t=T(t))?v(t+c):this.getAttribute("transform")})),M.attr("opacity",f).attr("transform",(function(t){var e=this.parentNode.__axis;return v((e&&isFinite(e=e(t))?e:T(t))+c)}))),A.remove(),C.attr("d",4===t||2===t?o?"M"+u*o+","+w+"H"+c+"V"+k+"H"+u*o:"M"+c+","+w+"V"+k:o?"M"+w+","+u*o+"V"+c+"H"+k+"V"+u*o:"M"+w+","+c+"H"+k),S.attr("opacity",1).attr("transform",(function(t){return v(T(t)+c)})),N.attr(l+"2",u*a),D.attr(l,u*_).text(b),E.filter(m).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",2===t?"start":4===t?"end":"middle"),E.each((function(){this.__axis=T}))}return b.scale=function(t){return arguments.length?(e=t,b):e},b.ticks=function(){return n=Array.from(arguments),b},b.tickArguments=function(t){return arguments.length?(n=null==t?[]:Array.from(t),b):n.slice()},b.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),b):r&&r.slice()},b.tickFormat=function(t){return arguments.length?(i=t,b):i},b.tickSize=function(t){return arguments.length?(a=o=+t,b):a},b.tickSizeInner=function(t){return arguments.length?(a=+t,b):a},b.tickSizeOuter=function(t){return arguments.length?(o=+t,b):o},b.tickPadding=function(t){return arguments.length?(s=+t,b):s},b.offset=function(t){return arguments.length?(c=+t,b):c},b}function b(){}function _(t){return null==t?b:function(){return this.querySelector(t)}}function x(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function w(){return[]}function k(t){return null==t?w:function(){return this.querySelectorAll(t)}}function T(t){return function(){return this.matches(t)}}function E(t){return function(e){return e.matches(t)}}var C=Array.prototype.find;function S(){return this.firstElementChild}var A=Array.prototype.filter;function M(){return Array.from(this.children)}function N(t){return new Array(t.length)}function D(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}function L(t){return function(){return t}}function B(t,e,n,r,i,a){for(var o,s=0,c=e.length,u=a.length;se?1:t>=e?0:NaN}D.prototype={constructor:D,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var P="http://www.w3.org/1999/xhtml";const Y={svg:"http://www.w3.org/2000/svg",xhtml:P,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function j(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),Y.hasOwnProperty(e)?{space:Y[e],local:t}:t}function U(t){return function(){this.removeAttribute(t)}}function z(t){return function(){this.removeAttributeNS(t.space,t.local)}}function $(t,e){return function(){this.setAttribute(t,e)}}function q(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function H(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function W(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function V(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function G(t){return function(){this.style.removeProperty(t)}}function X(t,e,n){return function(){this.style.setProperty(t,e,n)}}function Z(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function K(t,e){return t.style.getPropertyValue(e)||V(t).getComputedStyle(t,null).getPropertyValue(e)}function Q(t){return function(){delete this[t]}}function J(t,e){return function(){this[t]=e}}function tt(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function et(t){return t.trim().split(/^|\s+/)}function nt(t){return t.classList||new rt(t)}function rt(t){this._node=t,this._names=et(t.getAttribute("class")||"")}function it(t,e){for(var n=nt(t),r=-1,i=e.length;++r=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}function Et(t){return function(){var e=this.__on;if(e){for(var n,r=0,i=-1,a=e.length;r=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Nt=[null];function Dt(t,e){this._groups=t,this._parents=e}function Lt(){return new Dt([[document.documentElement]],Nt)}Dt.prototype=Lt.prototype={constructor:Dt,select:function(t){"function"!=typeof t&&(t=_(t));for(var e=this._groups,n=e.length,r=new Array(n),i=0;i=x&&(x=_+1);!(b=y[x])&&++x=0;)(r=i[a])&&(o&&4^r.compareDocumentPosition(o)&&o.parentNode.insertBefore(r,o),o=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=F);for(var n=this._groups,r=n.length,i=new Array(r),a=0;a1?this.each((null==e?G:"function"==typeof e?Z:X)(t,e,null==n?"":n)):K(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?Q:"function"==typeof e?tt:J)(t,e)):this.node()[t]},classed:function(t,e){var n=et(t+"");if(arguments.length<2){for(var r=nt(this.node()),i=-1,a=n.length;++i{}};function It(){for(var t,e=0,n=arguments.length,r={};e=0&&(n=t.slice(r+1),t=t.slice(0,r)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))}function Pt(t,e){for(var n,r=0,i=t.length;r0)for(var n,r,i=new Array(n),a=0;a=0&&e._call.call(void 0,t),e=e._next;--$t}()}finally{$t=0,function(){for(var t,e,n=Ut,r=1/0;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:Ut=e);zt=t,re(r)}(),Vt=0}}function ne(){var t=Xt.now(),e=t-Wt;e>1e3&&(Gt-=e,Wt=t)}function re(t){$t||(qt&&(qt=clearTimeout(qt)),t-Vt>24?(t<1/0&&(qt=setTimeout(ee,t-Xt.now()-Gt)),Ht&&(Ht=clearInterval(Ht))):(Ht||(Wt=Xt.now(),Ht=setInterval(ne,1e3)),$t=1,Zt(ee)))}function ie(t,e,n){var r=new Jt;return e=null==e?0:+e,r.restart((n=>{r.stop(),t(n+e)}),e,n),r}Jt.prototype=te.prototype={constructor:Jt,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?Kt():+n)+(null==e?0:+e),this._next||zt===this||(zt?zt._next=this:Ut=this,zt=this),this._call=t,this._time=n,re()},stop:function(){this._call&&(this._call=null,this._time=1/0,re())}};var ae=jt("start","end","cancel","interrupt"),oe=[];function se(t,e,n,r,i,a){var o=t.__transition;if(o){if(n in o)return}else t.__transition={};!function(t,e,n){var r,i=t.__transition;function a(c){var u,l,h,f;if(1!==n.state)return s();for(u in i)if((f=i[u]).name===n.name){if(3===f.state)return ie(a);4===f.state?(f.state=6,f.timer.stop(),f.on.call("interrupt",t,t.__data__,f.index,f.group),delete i[u]):+u0)throw new Error("too late; already scheduled");return n}function ue(t,e){var n=le(t,e);if(n.state>3)throw new Error("too late; already running");return n}function le(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function he(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}var fe,de=180/Math.PI,pe={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function ge(t,e,n,r,i,a){var o,s,c;return(o=Math.sqrt(t*t+e*e))&&(t/=o,e/=o),(c=t*n+e*r)&&(n-=t*c,r-=e*c),(s=Math.sqrt(n*n+r*r))&&(n/=s,r/=s,c/=s),t*r180?e+=360:e-t>180&&(t+=360),a.push({i:n.push(i(n)+"rotate(",null,r)-2,x:he(t,e)})):e&&n.push(i(n)+"rotate("+e+r)}(a.rotate,o.rotate,s,c),function(t,e,n,a){t!==e?a.push({i:n.push(i(n)+"skewX(",null,r)-2,x:he(t,e)}):e&&n.push(i(n)+"skewX("+e+r)}(a.skewX,o.skewX,s,c),function(t,e,n,r,a,o){if(t!==n||e!==r){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:he(t,n)},{i:s-2,x:he(e,r)})}else 1===n&&1===r||a.push(i(a)+"scale("+n+","+r+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,c),a=o=null,function(t){for(var e,n=-1,r=c.length;++n>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?ze(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?ze(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=De.exec(t))?new He(e[1],e[2],e[3],1):(e=Le.exec(t))?new He(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=Be.exec(t))?ze(e[1],e[2],e[3],e[4]):(e=Oe.exec(t))?ze(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=Ie.exec(t))?Xe(e[1],e[2]/100,e[3]/100,1):(e=Re.exec(t))?Xe(e[1],e[2]/100,e[3]/100,e[4]):Fe.hasOwnProperty(t)?Ue(Fe[t]):"transparent"===t?new He(NaN,NaN,NaN,0):null}function Ue(t){return new He(t>>16&255,t>>8&255,255&t,1)}function ze(t,e,n,r){return r<=0&&(t=e=n=NaN),new He(t,e,n,r)}function $e(t){return t instanceof Te||(t=je(t)),t?new He((t=t.rgb()).r,t.g,t.b,t.opacity):new He}function qe(t,e,n,r){return 1===arguments.length?$e(t):new He(t,e,n,null==r?1:r)}function He(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function We(){return"#"+Ge(this.r)+Ge(this.g)+Ge(this.b)}function Ve(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function Ge(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function Xe(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new Ke(t,e,n,r)}function Ze(t){if(t instanceof Ke)return new Ke(t.h,t.s,t.l,t.opacity);if(t instanceof Te||(t=je(t)),!t)return new Ke;if(t instanceof Ke)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),a=Math.max(e,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=e===a?(n-r)/s+6*(n0&&c<1?0:o,new Ke(o,s,c,t.opacity)}function Ke(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function Qe(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}function Je(t,e,n,r,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*n+(1+3*t+3*a-3*o)*r+o*i)/6}we(Te,je,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:Pe,formatHex:Pe,formatHsl:function(){return Ze(this).formatHsl()},formatRgb:Ye,toString:Ye}),we(He,qe,ke(Te,{brighter:function(t){return t=null==t?Ce:Math.pow(Ce,t),new He(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?Ee:Math.pow(Ee,t),new He(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:We,formatHex:We,formatRgb:Ve,toString:Ve})),we(Ke,(function(t,e,n,r){return 1===arguments.length?Ze(t):new Ke(t,e,n,null==r?1:r)}),ke(Te,{brighter:function(t){return t=null==t?Ce:Math.pow(Ce,t),new Ke(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?Ee:Math.pow(Ee,t),new Ke(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new He(Qe(t>=240?t-240:t+120,i,r),Qe(t,i,r),Qe(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const tn=t=>()=>t;function en(t,e){var n=e-t;return n?function(t,e){return function(n){return t+n*e}}(t,n):tn(isNaN(t)?e:t)}const nn=function t(e){var n=function(t){return 1==(t=+t)?en:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):tn(isNaN(e)?n:e)}}(e);function r(t,e){var r=n((t=qe(t)).r,(e=qe(e)).r),i=n(t.g,e.g),a=n(t.b,e.b),o=en(t.opacity,e.opacity);return function(e){return t.r=r(e),t.g=i(e),t.b=a(e),t.opacity=o(e),t+""}}return r.gamma=t,r}(1);function rn(t){return function(e){var n,r,i=e.length,a=new Array(i),o=new Array(i),s=new Array(i);for(n=0;n=1?(n=1,e-1):Math.floor(n*e),i=t[r],a=t[r+1],o=r>0?t[r-1]:2*i-a,s=ra&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(n=n[0])===(r=r[0])?s[o]?s[o]+=r:s[++o]=r:(s[++o]=null,c.push({i:o,x:he(n,r)})),a=on.lastIndex;return a=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?ce:ue;return function(){var o=a(this,t),s=o.on;s!==r&&(i=(r=s).copy()).on(e,n),o.on=i}}var En=Bt.prototype.constructor;function Cn(t){return function(){this.style.removeProperty(t)}}function Sn(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}function An(t,e,n){var r,i;function a(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&Sn(t,a,n)),r}return a._value=e,a}function Mn(t){return function(e){this.textContent=t.call(this,e)}}function Nn(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&Mn(r)),e}return r._value=t,r}var Dn=0;function Ln(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function Bn(){return++Dn}var On=Bt.prototype;Ln.prototype=function(t){return Bt().transition(t)}.prototype={constructor:Ln,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=_(t));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete a[i]):o=!1;o&&delete t.__transition}}(this,t)}))},Bt.prototype.transition=function(t){var e,n;t instanceof Ln?(e=t._id,t=t._name):(e=Bn(),(n=In).time=Kt(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,a=0;a>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?sr(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?sr(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=Zn.exec(t))?new lr(e[1],e[2],e[3],1):(e=Kn.exec(t))?new lr(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=Qn.exec(t))?sr(e[1],e[2],e[3],e[4]):(e=Jn.exec(t))?sr(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=tr.exec(t))?pr(e[1],e[2]/100,e[3]/100,1):(e=er.exec(t))?pr(e[1],e[2]/100,e[3]/100,e[4]):nr.hasOwnProperty(t)?or(nr[t]):"transparent"===t?new lr(NaN,NaN,NaN,0):null}function or(t){return new lr(t>>16&255,t>>8&255,255&t,1)}function sr(t,e,n,r){return r<=0&&(t=e=n=NaN),new lr(t,e,n,r)}function cr(t){return t instanceof $n||(t=ar(t)),t?new lr((t=t.rgb()).r,t.g,t.b,t.opacity):new lr}function ur(t,e,n,r){return 1===arguments.length?cr(t):new lr(t,e,n,null==r?1:r)}function lr(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function hr(){return"#"+dr(this.r)+dr(this.g)+dr(this.b)}function fr(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function dr(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function pr(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new yr(t,e,n,r)}function gr(t){if(t instanceof yr)return new yr(t.h,t.s,t.l,t.opacity);if(t instanceof $n||(t=ar(t)),!t)return new yr;if(t instanceof yr)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),a=Math.max(e,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=e===a?(n-r)/s+6*(n0&&c<1?0:o,new yr(o,s,c,t.opacity)}function yr(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function mr(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}Un($n,ar,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:rr,formatHex:rr,formatHsl:function(){return gr(this).formatHsl()},formatRgb:ir,toString:ir}),Un(lr,ur,zn($n,{brighter:function(t){return t=null==t?Hn:Math.pow(Hn,t),new lr(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?qn:Math.pow(qn,t),new lr(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:hr,formatHex:hr,formatRgb:fr,toString:fr})),Un(yr,(function(t,e,n,r){return 1===arguments.length?gr(t):new yr(t,e,n,null==r?1:r)}),zn($n,{brighter:function(t){return t=null==t?Hn:Math.pow(Hn,t),new yr(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?qn:Math.pow(qn,t),new yr(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new lr(mr(t>=240?t-240:t+120,i,r),mr(t,i,r),mr(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const vr=Math.PI/180,br=180/Math.PI,_r=.96422,xr=.82521,wr=4/29,kr=6/29,Tr=3*kr*kr;function Er(t){if(t instanceof Cr)return new Cr(t.l,t.a,t.b,t.opacity);if(t instanceof Br)return Or(t);t instanceof lr||(t=cr(t));var e,n,r=Nr(t.r),i=Nr(t.g),a=Nr(t.b),o=Sr((.2225045*r+.7168786*i+.0606169*a)/1);return r===i&&i===a?e=n=o:(e=Sr((.4360747*r+.3850649*i+.1430804*a)/_r),n=Sr((.0139322*r+.0971045*i+.7141733*a)/xr)),new Cr(116*o-16,500*(e-o),200*(o-n),t.opacity)}function Cr(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r}function Sr(t){return t>.008856451679035631?Math.pow(t,1/3):t/Tr+wr}function Ar(t){return t>kr?t*t*t:Tr*(t-wr)}function Mr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Nr(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Dr(t){if(t instanceof Br)return new Br(t.h,t.c,t.l,t.opacity);if(t instanceof Cr||(t=Er(t)),0===t.a&&0===t.b)return new Br(NaN,0()=>t;function Rr(t,e){return function(n){return t+n*e}}function Fr(t,e){var n=e-t;return n?Rr(t,n):Ir(isNaN(t)?e:t)}function Pr(t){return function(e,n){var r=t((e=Lr(e)).h,(n=Lr(n)).h),i=Fr(e.c,n.c),a=Fr(e.l,n.l),o=Fr(e.opacity,n.opacity);return function(t){return e.h=r(t),e.c=i(t),e.l=a(t),e.opacity=o(t),e+""}}}const Yr=Pr((function(t,e){var n=e-t;return n?Rr(t,n>180||n<-180?n-360*Math.round(n/360):n):Ir(isNaN(t)?e:t)}));Pr(Fr);var jr=Math.sqrt(50),Ur=Math.sqrt(10),zr=Math.sqrt(2);function $r(t,e,n){var r=(e-t)/Math.max(0,n),i=Math.floor(Math.log(r)/Math.LN10),a=r/Math.pow(10,i);return i>=0?(a>=jr?10:a>=Ur?5:a>=zr?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=jr?10:a>=Ur?5:a>=zr?2:1)}function qr(t,e,n){var r=Math.abs(e-t)/Math.max(0,n),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),a=r/i;return a>=jr?i*=10:a>=Ur?i*=5:a>=zr&&(i*=2),ee?1:t>=e?0:NaN}function Wr(t){let e=t,n=t,r=t;function i(t,e,i=0,a=t.length){if(i>>1;r(t[n],e)<0?i=n+1:a=n}while(it(e)-n,n=Hr,r=(e,n)=>Hr(t(e),n)),{left:i,center:function(t,n,r=0,a=t.length){const o=i(t,n,r,a-1);return o>r&&e(t[o-1],n)>-e(t[o],n)?o-1:o},right:function(t,e,i=0,a=t.length){if(i>>1;r(t[n],e)<=0?i=n+1:a=n}while(i>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?yi(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?yi(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=ai.exec(t))?new bi(e[1],e[2],e[3],1):(e=oi.exec(t))?new bi(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=si.exec(t))?yi(e[1],e[2],e[3],e[4]):(e=ci.exec(t))?yi(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=ui.exec(t))?ki(e[1],e[2]/100,e[3]/100,1):(e=li.exec(t))?ki(e[1],e[2]/100,e[3]/100,e[4]):hi.hasOwnProperty(t)?gi(hi[t]):"transparent"===t?new bi(NaN,NaN,NaN,0):null}function gi(t){return new bi(t>>16&255,t>>8&255,255&t,1)}function yi(t,e,n,r){return r<=0&&(t=e=n=NaN),new bi(t,e,n,r)}function mi(t){return t instanceof Qr||(t=pi(t)),t?new bi((t=t.rgb()).r,t.g,t.b,t.opacity):new bi}function vi(t,e,n,r){return 1===arguments.length?mi(t):new bi(t,e,n,null==r?1:r)}function bi(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function _i(){return"#"+wi(this.r)+wi(this.g)+wi(this.b)}function xi(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function wi(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function ki(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new Ei(t,e,n,r)}function Ti(t){if(t instanceof Ei)return new Ei(t.h,t.s,t.l,t.opacity);if(t instanceof Qr||(t=pi(t)),!t)return new Ei;if(t instanceof Ei)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),a=Math.max(e,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=e===a?(n-r)/s+6*(n0&&c<1?0:o,new Ei(o,s,c,t.opacity)}function Ei(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function Ci(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}function Si(t,e,n,r,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*n+(1+3*t+3*a-3*o)*r+o*i)/6}Zr(Qr,pi,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:fi,formatHex:fi,formatHsl:function(){return Ti(this).formatHsl()},formatRgb:di,toString:di}),Zr(bi,vi,Kr(Qr,{brighter:function(t){return t=null==t?ti:Math.pow(ti,t),new bi(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?Jr:Math.pow(Jr,t),new bi(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:_i,formatHex:_i,formatRgb:xi,toString:xi})),Zr(Ei,(function(t,e,n,r){return 1===arguments.length?Ti(t):new Ei(t,e,n,null==r?1:r)}),Kr(Qr,{brighter:function(t){return t=null==t?ti:Math.pow(ti,t),new Ei(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?Jr:Math.pow(Jr,t),new Ei(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new bi(Ci(t>=240?t-240:t+120,i,r),Ci(t,i,r),Ci(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const Ai=t=>()=>t;function Mi(t,e){var n=e-t;return n?function(t,e){return function(n){return t+n*e}}(t,n):Ai(isNaN(t)?e:t)}const Ni=function t(e){var n=function(t){return 1==(t=+t)?Mi:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):Ai(isNaN(e)?n:e)}}(e);function r(t,e){var r=n((t=vi(t)).r,(e=vi(e)).r),i=n(t.g,e.g),a=n(t.b,e.b),o=Mi(t.opacity,e.opacity);return function(e){return t.r=r(e),t.g=i(e),t.b=a(e),t.opacity=o(e),t+""}}return r.gamma=t,r}(1);function Di(t){return function(e){var n,r,i=e.length,a=new Array(i),o=new Array(i),s=new Array(i);for(n=0;n=1?(n=1,e-1):Math.floor(n*e),i=t[r],a=t[r+1],o=r>0?t[r-1]:2*i-a,s=ra&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(n=n[0])===(r=r[0])?s[o]?s[o]+=r:s[++o]=r:(s[++o]=null,c.push({i:o,x:Oi(n,r)})),a=Fi.lastIndex;return ae&&(n=t,t=e,e=n),u=function(n){return Math.max(t,Math.min(e,n))}),r=c>2?Vi:Wi,i=a=null,h}function h(e){return null==e||isNaN(e=+e)?n:(i||(i=r(o.map(t),s,c)))(t(u(e)))}return h.invert=function(n){return u(e((a||(a=r(s,o.map(t),Oi)))(n)))},h.domain=function(t){return arguments.length?(o=Array.from(t,zi),l()):o.slice()},h.range=function(t){return arguments.length?(s=Array.from(t),l()):s.slice()},h.rangeRound=function(t){return s=Array.from(t),c=Ui,l()},h.clamp=function(t){return arguments.length?(u=!!t||qi,l()):u!==qi},h.interpolate=function(t){return arguments.length?(c=t,l()):c},h.unknown=function(t){return arguments.length?(n=t,h):n},function(n,r){return t=n,e=r,l()}}()(qi,qi)}function Zi(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t)}return this}var Ki,Qi=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Ji(t){if(!(e=Qi.exec(t)))throw new Error("invalid format: "+t);var e;return new ta({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function ta(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function ea(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function na(t){return(t=ea(Math.abs(t)))?t[1]:NaN}function ra(t,e){var n=ea(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}Ji.prototype=ta.prototype,ta.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};const ia={"%":(t,e)=>(100*t).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>ra(100*t,e),r:ra,s:function(t,e){var n=ea(t,e);if(!n)return t+"";var r=n[0],i=n[1],a=i-(Ki=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,o=r.length;return a===o?r:a>o?r+new Array(a-o+1).join("0"):a>0?r.slice(0,a)+"."+r.slice(a):"0."+new Array(1-a).join("0")+ea(t,Math.max(0,e+a-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function aa(t){return t}var oa,sa,ca,ua=Array.prototype.map,la=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function ha(t){var e=t.domain;return t.ticks=function(t){var n=e();return function(t,e,n){var r,i,a,o,s=-1;if(n=+n,(t=+t)==(e=+e)&&n>0)return[t];if((r=e0){let n=Math.round(t/o),r=Math.round(e/o);for(n*oe&&--r,a=new Array(i=r-n+1);++se&&--r,a=new Array(i=r-n+1);++s0;){if((i=$r(c,u,n))===r)return a[o]=c,a[s]=u,e(a);if(i>0)c=Math.floor(c/i)*i,u=Math.ceil(u/i)*i;else{if(!(i<0))break;c=Math.ceil(c*i)/i,u=Math.floor(u*i)/i}r=i}return t},t}function fa(){var t=Xi();return t.copy=function(){return Gi(t,fa())},Zi.apply(t,arguments),ha(t)}oa=function(t){var e,n,r=void 0===t.grouping||void 0===t.thousands?aa:(e=ua.call(t.grouping,Number),n=t.thousands+"",function(t,r){for(var i=t.length,a=[],o=0,s=e[0],c=0;i>0&&s>0&&(c+s+1>r&&(s=Math.max(1,r-c)),a.push(t.substring(i-=s,i+s)),!((c+=s+1)>r));)s=e[o=(o+1)%e.length];return a.reverse().join(n)}),i=void 0===t.currency?"":t.currency[0]+"",a=void 0===t.currency?"":t.currency[1]+"",o=void 0===t.decimal?".":t.decimal+"",s=void 0===t.numerals?aa:function(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}(ua.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",u=void 0===t.minus?"−":t.minus+"",l=void 0===t.nan?"NaN":t.nan+"";function h(t){var e=(t=Ji(t)).fill,n=t.align,h=t.sign,f=t.symbol,d=t.zero,p=t.width,g=t.comma,y=t.precision,m=t.trim,v=t.type;"n"===v?(g=!0,v="g"):ia[v]||(void 0===y&&(y=12),m=!0,v="g"),(d||"0"===e&&"="===n)&&(d=!0,e="0",n="=");var b="$"===f?i:"#"===f&&/[boxX]/.test(v)?"0"+v.toLowerCase():"",_="$"===f?a:/[%p]/.test(v)?c:"",x=ia[v],w=/[defgprs%]/.test(v);function k(t){var i,a,c,f=b,k=_;if("c"===v)k=x(t)+k,t="";else{var T=(t=+t)<0||1/t<0;if(t=isNaN(t)?l:x(Math.abs(t),y),m&&(t=function(t){t:for(var e,n=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(e+1):t}(t)),T&&0==+t&&"+"!==h&&(T=!1),f=(T?"("===h?h:u:"-"===h||"("===h?"":h)+f,k=("s"===v?la[8+Ki/3]:"")+k+(T&&"("===h?")":""),w)for(i=-1,a=t.length;++i(c=t.charCodeAt(i))||c>57){k=(46===c?o+t.slice(i+1):t.slice(i))+k,t=t.slice(0,i);break}}g&&!d&&(t=r(t,1/0));var E=f.length+t.length+k.length,C=E>1)+f+t+k+C.slice(E);break;default:t=C+f+t+k}return s(t)}return y=void 0===y?6:/[gprs]/.test(v)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),k.toString=function(){return t+""},k}return{format:h,formatPrefix:function(t,e){var n=h(((t=Ji(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(na(e)/3))),i=Math.pow(10,-r),a=la[8+r/3];return function(t){return n(i*t)+a}}}}({thousands:",",grouping:[3],currency:["$",""]}),sa=oa.format,ca=oa.formatPrefix;class da extends Map{constructor(t,e=ga){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const[e,n]of t)this.set(e,n)}get(t){return super.get(pa(this,t))}has(t){return super.has(pa(this,t))}set(t,e){return super.set(function({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}(this,t),e)}delete(t){return super.delete(function({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}(this,t))}}function pa({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function ga(t){return null!==t&&"object"==typeof t?t.valueOf():t}Set;const ya=Symbol("implicit");function ma(){var t=new da,e=[],n=[],r=ya;function i(i){let a=t.get(i);if(void 0===a){if(r!==ya)return r;t.set(i,a=e.push(i)-1)}return n[a%n.length]}return i.domain=function(n){if(!arguments.length)return e.slice();e=[],t=new da;for(const r of n)t.has(r)||t.set(r,e.push(r)-1);return i},i.range=function(t){return arguments.length?(n=Array.from(t),i):n.slice()},i.unknown=function(t){return arguments.length?(r=t,i):r},i.copy=function(){return ma(e,n).unknown(r)},Zi.apply(i,arguments),i}const va=1e3,ba=6e4,_a=36e5,xa=864e5,wa=6048e5,ka=31536e6;var Ta=new Date,Ea=new Date;function Ca(t,e,n,r){function i(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return i.floor=function(e){return t(e=new Date(+e)),e},i.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},i.round=function(t){var e=i(t),n=i.ceil(t);return t-e0))return s;do{s.push(o=new Date(+n)),e(n,a),t(n)}while(o=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(i.count=function(e,r){return Ta.setTime(+e),Ea.setTime(+r),t(Ta),t(Ea),Math.floor(n(Ta,Ea))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(e){return r(e)%t==0}:function(e){return i.count(0,e)%t==0}):i:null}),i}var Sa=Ca((function(){}),(function(t,e){t.setTime(+t+e)}),(function(t,e){return e-t}));Sa.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?Ca((function(e){e.setTime(Math.floor(e/t)*t)}),(function(e,n){e.setTime(+e+n*t)}),(function(e,n){return(n-e)/t})):Sa:null};const Aa=Sa;Sa.range;var Ma=Ca((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,e){t.setTime(+t+e*va)}),(function(t,e){return(e-t)/va}),(function(t){return t.getUTCSeconds()}));const Na=Ma;Ma.range;var Da=Ca((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*va)}),(function(t,e){t.setTime(+t+e*ba)}),(function(t,e){return(e-t)/ba}),(function(t){return t.getMinutes()}));const La=Da;Da.range;var Ba=Ca((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*va-t.getMinutes()*ba)}),(function(t,e){t.setTime(+t+e*_a)}),(function(t,e){return(e-t)/_a}),(function(t){return t.getHours()}));const Oa=Ba;Ba.range;var Ia=Ca((t=>t.setHours(0,0,0,0)),((t,e)=>t.setDate(t.getDate()+e)),((t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*ba)/xa),(t=>t.getDate()-1));const Ra=Ia;function Fa(t){return Ca((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*ba)/wa}))}Ia.range;var Pa=Fa(0),Ya=Fa(1),ja=Fa(2),Ua=Fa(3),za=Fa(4),$a=Fa(5),qa=Fa(6),Ha=(Pa.range,Ya.range,ja.range,Ua.range,za.range,$a.range,qa.range,Ca((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,e){t.setMonth(t.getMonth()+e)}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()})));const Wa=Ha;Ha.range;var Va=Ca((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));Va.every=function(t){return isFinite(t=Math.floor(t))&&t>0?Ca((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const Ga=Va;Va.range;var Xa=Ca((function(t){t.setUTCSeconds(0,0)}),(function(t,e){t.setTime(+t+e*ba)}),(function(t,e){return(e-t)/ba}),(function(t){return t.getUTCMinutes()}));const Za=Xa;Xa.range;var Ka=Ca((function(t){t.setUTCMinutes(0,0,0)}),(function(t,e){t.setTime(+t+e*_a)}),(function(t,e){return(e-t)/_a}),(function(t){return t.getUTCHours()}));const Qa=Ka;Ka.range;var Ja=Ca((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/xa}),(function(t){return t.getUTCDate()-1}));const to=Ja;function eo(t){return Ca((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/wa}))}Ja.range;var no=eo(0),ro=eo(1),io=eo(2),ao=eo(3),oo=eo(4),so=eo(5),co=eo(6),uo=(no.range,ro.range,io.range,ao.range,oo.range,so.range,co.range,Ca((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCMonth(t.getUTCMonth()+e)}),(function(t,e){return e.getUTCMonth()-t.getUTCMonth()+12*(e.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()})));const lo=uo;uo.range;var ho=Ca((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));ho.every=function(t){return isFinite(t=Math.floor(t))&&t>0?Ca((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const fo=ho;function po(t,e,n,r,i,a){const o=[[Na,1,va],[Na,5,5e3],[Na,15,15e3],[Na,30,3e4],[a,1,ba],[a,5,3e5],[a,15,9e5],[a,30,18e5],[i,1,_a],[i,3,108e5],[i,6,216e5],[i,12,432e5],[r,1,xa],[r,2,1728e5],[n,1,wa],[e,1,2592e6],[e,3,7776e6],[t,1,ka]];function s(e,n,r){const i=Math.abs(n-e)/r,a=Wr((([,,t])=>t)).right(o,i);if(a===o.length)return t.every(qr(e/ka,n/ka,r));if(0===a)return Aa.every(Math.max(qr(e,n,r),1));const[s,c]=o[i/o[a-1][2][t.toLowerCase(),e])))}function Lo(t,e,n){var r=Eo.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function Bo(t,e,n){var r=Eo.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function Oo(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function Io(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function Ro(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function Fo(t,e,n){var r=Eo.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function Po(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Yo(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function jo(t,e,n){var r=Eo.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function Uo(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function zo(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function $o(t,e,n){var r=Eo.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function qo(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function Ho(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function Wo(t,e,n){var r=Eo.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function Vo(t,e,n){var r=Eo.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function Go(t,e,n){var r=Eo.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Xo(t,e,n){var r=Co.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function Zo(t,e,n){var r=Eo.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function Ko(t,e,n){var r=Eo.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function Qo(t,e){return Ao(t.getDate(),e,2)}function Jo(t,e){return Ao(t.getHours(),e,2)}function ts(t,e){return Ao(t.getHours()%12||12,e,2)}function es(t,e){return Ao(1+Ra.count(Ga(t),t),e,3)}function ns(t,e){return Ao(t.getMilliseconds(),e,3)}function rs(t,e){return ns(t,e)+"000"}function is(t,e){return Ao(t.getMonth()+1,e,2)}function as(t,e){return Ao(t.getMinutes(),e,2)}function os(t,e){return Ao(t.getSeconds(),e,2)}function ss(t){var e=t.getDay();return 0===e?7:e}function cs(t,e){return Ao(Pa.count(Ga(t)-1,t),e,2)}function us(t){var e=t.getDay();return e>=4||0===e?za(t):za.ceil(t)}function ls(t,e){return t=us(t),Ao(za.count(Ga(t),t)+(4===Ga(t).getDay()),e,2)}function hs(t){return t.getDay()}function fs(t,e){return Ao(Ya.count(Ga(t)-1,t),e,2)}function ds(t,e){return Ao(t.getFullYear()%100,e,2)}function ps(t,e){return Ao((t=us(t)).getFullYear()%100,e,2)}function gs(t,e){return Ao(t.getFullYear()%1e4,e,4)}function ys(t,e){var n=t.getDay();return Ao((t=n>=4||0===n?za(t):za.ceil(t)).getFullYear()%1e4,e,4)}function ms(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+Ao(e/60|0,"0",2)+Ao(e%60,"0",2)}function vs(t,e){return Ao(t.getUTCDate(),e,2)}function bs(t,e){return Ao(t.getUTCHours(),e,2)}function _s(t,e){return Ao(t.getUTCHours()%12||12,e,2)}function xs(t,e){return Ao(1+to.count(fo(t),t),e,3)}function ws(t,e){return Ao(t.getUTCMilliseconds(),e,3)}function ks(t,e){return ws(t,e)+"000"}function Ts(t,e){return Ao(t.getUTCMonth()+1,e,2)}function Es(t,e){return Ao(t.getUTCMinutes(),e,2)}function Cs(t,e){return Ao(t.getUTCSeconds(),e,2)}function Ss(t){var e=t.getUTCDay();return 0===e?7:e}function As(t,e){return Ao(no.count(fo(t)-1,t),e,2)}function Ms(t){var e=t.getUTCDay();return e>=4||0===e?oo(t):oo.ceil(t)}function Ns(t,e){return t=Ms(t),Ao(oo.count(fo(t),t)+(4===fo(t).getUTCDay()),e,2)}function Ds(t){return t.getUTCDay()}function Ls(t,e){return Ao(ro.count(fo(t)-1,t),e,2)}function Bs(t,e){return Ao(t.getUTCFullYear()%100,e,2)}function Os(t,e){return Ao((t=Ms(t)).getUTCFullYear()%100,e,2)}function Is(t,e){return Ao(t.getUTCFullYear()%1e4,e,4)}function Rs(t,e){var n=t.getUTCDay();return Ao((t=n>=4||0===n?oo(t):oo.ceil(t)).getUTCFullYear()%1e4,e,4)}function Fs(){return"+0000"}function Ps(){return"%"}function Ys(t){return+t}function js(t){return Math.floor(+t/1e3)}function Us(t){return new Date(t)}function zs(t){return t instanceof Date?+t:+new Date(+t)}function $s(t,e,n,r,i,a,o,s,c,u){var l=Xi(),h=l.invert,f=l.domain,d=u(".%L"),p=u(":%S"),g=u("%I:%M"),y=u("%I %p"),m=u("%a %d"),v=u("%b %d"),b=u("%B"),_=u("%Y");function x(t){return(c(t)=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:Ys,s:js,S:os,u:ss,U:cs,V:ls,w:hs,W:fs,x:null,X:null,y:ds,Y:gs,Z:ms,"%":Ps},_={a:function(t){return o[t.getUTCDay()]},A:function(t){return a[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return s[t.getUTCMonth()]},c:null,d:vs,e:vs,f:ks,g:Os,G:Rs,H:bs,I:_s,j:xs,L:ws,m:Ts,M:Es,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:Ys,s:js,S:Cs,u:Ss,U:As,V:Ns,w:Ds,W:Ls,x:null,X:null,y:Bs,Y:Is,Z:Fs,"%":Ps},x={a:function(t,e,n){var r=d.exec(e.slice(n));return r?(t.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(t,e,n){var r=h.exec(e.slice(n));return r?(t.w=f.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(t,e,n){var r=m.exec(e.slice(n));return r?(t.m=v.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(t,e,n){var r=g.exec(e.slice(n));return r?(t.m=y.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(t,n,r){return T(t,e,n,r)},d:zo,e:zo,f:Go,g:Po,G:Fo,H:qo,I:qo,j:$o,L:Vo,m:Uo,M:Ho,p:function(t,e,n){var r=u.exec(e.slice(n));return r?(t.p=l.get(r[0].toLowerCase()),n+r[0].length):-1},q:jo,Q:Zo,s:Ko,S:Wo,u:Bo,U:Oo,V:Io,w:Lo,W:Ro,x:function(t,e,r){return T(t,n,e,r)},X:function(t,e,n){return T(t,r,e,n)},y:Po,Y:Fo,Z:Yo,"%":Xo};function w(t,e){return function(n){var r,i,a,o=[],s=-1,c=0,u=t.length;for(n instanceof Date||(n=new Date(+n));++s53)return null;"w"in a||(a.w=1),"Z"in a?(i=(r=_o(xo(a.y,0,1))).getUTCDay(),r=i>4||0===i?ro.ceil(r):ro(r),r=to.offset(r,7*(a.V-1)),a.y=r.getUTCFullYear(),a.m=r.getUTCMonth(),a.d=r.getUTCDate()+(a.w+6)%7):(i=(r=bo(xo(a.y,0,1))).getDay(),r=i>4||0===i?Ya.ceil(r):Ya(r),r=Ra.offset(r,7*(a.V-1)),a.y=r.getFullYear(),a.m=r.getMonth(),a.d=r.getDate()+(a.w+6)%7)}else("W"in a||"U"in a)&&("w"in a||(a.w="u"in a?a.u%7:"W"in a?1:0),i="Z"in a?_o(xo(a.y,0,1)).getUTCDay():bo(xo(a.y,0,1)).getDay(),a.m=0,a.d="W"in a?(a.w+6)%7+7*a.W-(i+5)%7:a.w+7*a.U-(i+6)%7);return"Z"in a?(a.H+=a.Z/100|0,a.M+=a.Z%100,_o(a)):bo(a)}}function T(t,e,n,r){for(var i,a,o=0,s=e.length,c=n.length;o=c)return-1;if(37===(i=e.charCodeAt(o++))){if(i=e.charAt(o++),!(a=x[i in To?e.charAt(o++):i])||(r=a(t,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}return b.x=w(n,b),b.X=w(r,b),b.c=w(e,b),_.x=w(n,_),_.X=w(r,_),_.c=w(e,_),{format:function(t){var e=w(t+="",b);return e.toString=function(){return t},e},parse:function(t){var e=k(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=w(t+="",_);return e.toString=function(){return t},e},utcParse:function(t){var e=k(t+="",!0);return e.toString=function(){return t},e}}}({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}),ko=wo.format,wo.parse,wo.utcFormat,wo.utcParse;var Ks=Array.prototype.find;function Qs(){return this.firstElementChild}var Js=Array.prototype.filter;function tc(){return Array.from(this.children)}function ec(t){return new Array(t.length)}function nc(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}function rc(t){return function(){return t}}function ic(t,e,n,r,i,a){for(var o,s=0,c=e.length,u=a.length;se?1:t>=e?0:NaN}nc.prototype={constructor:nc,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var uc="http://www.w3.org/1999/xhtml";const lc={svg:"http://www.w3.org/2000/svg",xhtml:uc,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function hc(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),lc.hasOwnProperty(e)?{space:lc[e],local:t}:t}function fc(t){return function(){this.removeAttribute(t)}}function dc(t){return function(){this.removeAttributeNS(t.space,t.local)}}function pc(t,e){return function(){this.setAttribute(t,e)}}function gc(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function yc(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function mc(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function vc(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function bc(t){return function(){this.style.removeProperty(t)}}function _c(t,e,n){return function(){this.style.setProperty(t,e,n)}}function xc(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function wc(t,e){return t.style.getPropertyValue(e)||vc(t).getComputedStyle(t,null).getPropertyValue(e)}function kc(t){return function(){delete this[t]}}function Tc(t,e){return function(){this[t]=e}}function Ec(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function Cc(t){return t.trim().split(/^|\s+/)}function Sc(t){return t.classList||new Ac(t)}function Ac(t){this._node=t,this._names=Cc(t.getAttribute("class")||"")}function Mc(t,e){for(var n=Sc(t),r=-1,i=e.length;++r=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}function Zc(t){return function(){var e=this.__on;if(e){for(var n,r=0,i=-1,a=e.length;r=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var eu=[null];function nu(t,e){this._groups=t,this._parents=e}function ru(){return new nu([[document.documentElement]],eu)}nu.prototype=ru.prototype={constructor:nu,select:function(t){"function"!=typeof t&&(t=Hs(t));for(var e=this._groups,n=e.length,r=new Array(n),i=0;i=x&&(x=_+1);!(b=y[x])&&++x=0;)(r=i[a])&&(o&&4^r.compareDocumentPosition(o)&&o.parentNode.insertBefore(r,o),o=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=cc);for(var n=this._groups,r=n.length,i=new Array(r),a=0;a1?this.each((null==e?bc:"function"==typeof e?xc:_c)(t,e,null==n?"":n)):wc(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?kc:"function"==typeof e?Ec:Tc)(t,e)):this.node()[t]},classed:function(t,e){var n=Cc(t+"");if(arguments.length<2){for(var r=Sc(this.node()),i=-1,a=n.length;++iuu)if(Math.abs(l*s-c*u)>uu&&i){var f=n-a,d=r-o,p=s*s+c*c,g=f*f+d*d,y=Math.sqrt(p),m=Math.sqrt(h),v=i*Math.tan((su-Math.acos((p+h-g)/(2*y*m)))/2),b=v/m,_=v/y;Math.abs(b-1)>uu&&(this._+="L"+(t+b*u)+","+(e+b*l)),this._+="A"+i+","+i+",0,0,"+ +(l*f>u*d)+","+(this._x1=t+_*s)+","+(this._y1=e+_*c)}else this._+="L"+(this._x1=t)+","+(this._y1=e)},arc:function(t,e,n,r,i,a){t=+t,e=+e,a=!!a;var o=(n=+n)*Math.cos(r),s=n*Math.sin(r),c=t+o,u=e+s,l=1^a,h=a?r-i:i-r;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+c+","+u:(Math.abs(this._x1-c)>uu||Math.abs(this._y1-u)>uu)&&(this._+="L"+c+","+u),n&&(h<0&&(h=h%cu+cu),h>lu?this._+="A"+n+","+n+",0,1,"+l+","+(t-o)+","+(e-s)+"A"+n+","+n+",0,1,"+l+","+(this._x1=c)+","+(this._y1=u):h>uu&&(this._+="A"+n+","+n+",0,"+ +(h>=su)+","+l+","+(this._x1=t+n*Math.cos(i))+","+(this._y1=e+n*Math.sin(i))))},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z"},toString:function(){return this._}};const du=fu;function pu(t){return function(){return t}}var gu=Math.abs,yu=Math.atan2,mu=Math.cos,vu=Math.max,bu=Math.min,_u=Math.sin,xu=Math.sqrt,wu=1e-12,ku=Math.PI,Tu=ku/2,Eu=2*ku;function Cu(t){return t>1?0:t<-1?ku:Math.acos(t)}function Su(t){return t>=1?Tu:t<=-1?-Tu:Math.asin(t)}function Au(t){return t.innerRadius}function Mu(t){return t.outerRadius}function Nu(t){return t.startAngle}function Du(t){return t.endAngle}function Lu(t){return t&&t.padAngle}function Bu(t,e,n,r,i,a,o,s){var c=n-t,u=r-e,l=o-i,h=s-a,f=h*c-l*u;if(!(f*fN*N+D*D&&(T=C,E=S),{cx:T,cy:E,x01:-l,y01:-h,x11:T*(i/x-1),y11:E*(i/x-1)}}function Iu(){var t=Au,e=Mu,n=pu(0),r=null,i=Nu,a=Du,o=Lu,s=null;function c(){var c,u,l=+t.apply(this,arguments),h=+e.apply(this,arguments),f=i.apply(this,arguments)-Tu,d=a.apply(this,arguments)-Tu,p=gu(d-f),g=d>f;if(s||(s=c=du()),hwu)if(p>Eu-wu)s.moveTo(h*mu(f),h*_u(f)),s.arc(0,0,h,f,d,!g),l>wu&&(s.moveTo(l*mu(d),l*_u(d)),s.arc(0,0,l,d,f,g));else{var y,m,v=f,b=d,_=f,x=d,w=p,k=p,T=o.apply(this,arguments)/2,E=T>wu&&(r?+r.apply(this,arguments):xu(l*l+h*h)),C=bu(gu(h-l)/2,+n.apply(this,arguments)),S=C,A=C;if(E>wu){var M=Su(E/l*_u(T)),N=Su(E/h*_u(T));(w-=2*M)>wu?(_+=M*=g?1:-1,x-=M):(w=0,_=x=(f+d)/2),(k-=2*N)>wu?(v+=N*=g?1:-1,b-=N):(k=0,v=b=(f+d)/2)}var D=h*mu(v),L=h*_u(v),B=l*mu(x),O=l*_u(x);if(C>wu){var I,R=h*mu(b),F=h*_u(b),P=l*mu(_),Y=l*_u(_);if(pwu?A>wu?(y=Ou(P,Y,D,L,h,A,g),m=Ou(R,F,B,O,h,A,g),s.moveTo(y.cx+y.x01,y.cy+y.y01),Awu&&w>wu?S>wu?(y=Ou(B,O,R,F,l,-S,g),m=Ou(D,L,P,Y,l,-S,g),s.lineTo(y.cx+y.x01,y.cy+y.y01),St?1:e>=t?0:NaN}function $u(t){return t}function qu(){}function Hu(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function Wu(t){this._context=t}function Vu(t){return new Wu(t)}function Gu(t){this._context=t}function Xu(t){this._context=t}function Zu(t){this._context=t}function Ku(t){return t<0?-1:1}function Qu(t,e,n){var r=t._x1-t._x0,i=e-t._x1,a=(t._y1-t._y0)/(r||i<0&&-0),o=(n-t._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(Ku(a)+Ku(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function Ju(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function tl(t,e,n){var r=t._x0,i=t._y0,a=t._x1,o=t._y1,s=(a-r)/3;t._context.bezierCurveTo(r+s,i+s*e,a-s,o-s*n,a,o)}function el(t){this._context=t}function nl(t){this._context=new rl(t)}function rl(t){this._context=t}function il(t){this._context=t}function al(t){var e,n,r=t.length-1,i=new Array(r),a=new Array(r),o=new Array(r);for(i[0]=0,a[0]=2,o[0]=t[0]+2*t[1],e=1;e=0;--e)i[e]=(o[e]-i[e+1])/a[e];for(a[r-1]=(t[r]+i[r-1])/2,e=0;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}}this._x=t,this._y=e}};var sl=new Date,cl=new Date;function ul(t,e,n,r){function i(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return i.floor=function(e){return t(e=new Date(+e)),e},i.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},i.round=function(t){var e=i(t),n=i.ceil(t);return t-e0))return s;do{s.push(o=new Date(+n)),e(n,a),t(n)}while(o=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(i.count=function(e,r){return sl.setTime(+e),cl.setTime(+r),t(sl),t(cl),Math.floor(n(sl,cl))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(e){return r(e)%t==0}:function(e){return i.count(0,e)%t==0}):i:null}),i}const ll=864e5,hl=6048e5;function fl(t){return ul((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/hl}))}var dl=fl(0),pl=fl(1),gl=fl(2),yl=fl(3),ml=fl(4),vl=fl(5),bl=fl(6),_l=(dl.range,pl.range,gl.range,yl.range,ml.range,vl.range,bl.range,ul((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/ll}),(function(t){return t.getUTCDate()-1})));const xl=_l;function wl(t){return ul((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-6e4*(e.getTimezoneOffset()-t.getTimezoneOffset()))/hl}))}_l.range;var kl=wl(0),Tl=wl(1),El=wl(2),Cl=wl(3),Sl=wl(4),Al=wl(5),Ml=wl(6),Nl=(kl.range,Tl.range,El.range,Cl.range,Sl.range,Al.range,Ml.range,ul((t=>t.setHours(0,0,0,0)),((t,e)=>t.setDate(t.getDate()+e)),((t,e)=>(e-t-6e4*(e.getTimezoneOffset()-t.getTimezoneOffset()))/ll),(t=>t.getDate()-1)));const Dl=Nl;Nl.range;var Ll=ul((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));Ll.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ul((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const Bl=Ll;Ll.range;var Ol=ul((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));Ol.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ul((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const Il=Ol;function Rl(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function Fl(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function Pl(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}Ol.range;var Yl,jl,Ul={"-":"",_:" ",0:"0"},zl=/^\s*\d+/,$l=/^%/,ql=/[\\^$*+?|[\]().{}]/g;function Hl(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",a=i.length;return r+(a[t.toLowerCase(),e])))}function Xl(t,e,n){var r=zl.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function Zl(t,e,n){var r=zl.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function Kl(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function Ql(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function Jl(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function th(t,e,n){var r=zl.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function eh(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function nh(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function rh(t,e,n){var r=zl.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function ih(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function ah(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function oh(t,e,n){var r=zl.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function sh(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function ch(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function uh(t,e,n){var r=zl.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function lh(t,e,n){var r=zl.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function hh(t,e,n){var r=zl.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function fh(t,e,n){var r=$l.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function dh(t,e,n){var r=zl.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function ph(t,e,n){var r=zl.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function gh(t,e){return Hl(t.getDate(),e,2)}function yh(t,e){return Hl(t.getHours(),e,2)}function mh(t,e){return Hl(t.getHours()%12||12,e,2)}function vh(t,e){return Hl(1+Dl.count(Bl(t),t),e,3)}function bh(t,e){return Hl(t.getMilliseconds(),e,3)}function _h(t,e){return bh(t,e)+"000"}function xh(t,e){return Hl(t.getMonth()+1,e,2)}function wh(t,e){return Hl(t.getMinutes(),e,2)}function kh(t,e){return Hl(t.getSeconds(),e,2)}function Th(t){var e=t.getDay();return 0===e?7:e}function Eh(t,e){return Hl(kl.count(Bl(t)-1,t),e,2)}function Ch(t){var e=t.getDay();return e>=4||0===e?Sl(t):Sl.ceil(t)}function Sh(t,e){return t=Ch(t),Hl(Sl.count(Bl(t),t)+(4===Bl(t).getDay()),e,2)}function Ah(t){return t.getDay()}function Mh(t,e){return Hl(Tl.count(Bl(t)-1,t),e,2)}function Nh(t,e){return Hl(t.getFullYear()%100,e,2)}function Dh(t,e){return Hl((t=Ch(t)).getFullYear()%100,e,2)}function Lh(t,e){return Hl(t.getFullYear()%1e4,e,4)}function Bh(t,e){var n=t.getDay();return Hl((t=n>=4||0===n?Sl(t):Sl.ceil(t)).getFullYear()%1e4,e,4)}function Oh(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+Hl(e/60|0,"0",2)+Hl(e%60,"0",2)}function Ih(t,e){return Hl(t.getUTCDate(),e,2)}function Rh(t,e){return Hl(t.getUTCHours(),e,2)}function Fh(t,e){return Hl(t.getUTCHours()%12||12,e,2)}function Ph(t,e){return Hl(1+xl.count(Il(t),t),e,3)}function Yh(t,e){return Hl(t.getUTCMilliseconds(),e,3)}function jh(t,e){return Yh(t,e)+"000"}function Uh(t,e){return Hl(t.getUTCMonth()+1,e,2)}function zh(t,e){return Hl(t.getUTCMinutes(),e,2)}function $h(t,e){return Hl(t.getUTCSeconds(),e,2)}function qh(t){var e=t.getUTCDay();return 0===e?7:e}function Hh(t,e){return Hl(dl.count(Il(t)-1,t),e,2)}function Wh(t){var e=t.getUTCDay();return e>=4||0===e?ml(t):ml.ceil(t)}function Vh(t,e){return t=Wh(t),Hl(ml.count(Il(t),t)+(4===Il(t).getUTCDay()),e,2)}function Gh(t){return t.getUTCDay()}function Xh(t,e){return Hl(pl.count(Il(t)-1,t),e,2)}function Zh(t,e){return Hl(t.getUTCFullYear()%100,e,2)}function Kh(t,e){return Hl((t=Wh(t)).getUTCFullYear()%100,e,2)}function Qh(t,e){return Hl(t.getUTCFullYear()%1e4,e,4)}function Jh(t,e){var n=t.getUTCDay();return Hl((t=n>=4||0===n?ml(t):ml.ceil(t)).getUTCFullYear()%1e4,e,4)}function tf(){return"+0000"}function ef(){return"%"}function nf(t){return+t}function rf(t){return Math.floor(+t/1e3)}Yl=function(t){var e=t.dateTime,n=t.date,r=t.time,i=t.periods,a=t.days,o=t.shortDays,s=t.months,c=t.shortMonths,u=Vl(i),l=Gl(i),h=Vl(a),f=Gl(a),d=Vl(o),p=Gl(o),g=Vl(s),y=Gl(s),m=Vl(c),v=Gl(c),b={a:function(t){return o[t.getDay()]},A:function(t){return a[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return s[t.getMonth()]},c:null,d:gh,e:gh,f:_h,g:Dh,G:Bh,H:yh,I:mh,j:vh,L:bh,m:xh,M:wh,p:function(t){return i[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:nf,s:rf,S:kh,u:Th,U:Eh,V:Sh,w:Ah,W:Mh,x:null,X:null,y:Nh,Y:Lh,Z:Oh,"%":ef},_={a:function(t){return o[t.getUTCDay()]},A:function(t){return a[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return s[t.getUTCMonth()]},c:null,d:Ih,e:Ih,f:jh,g:Kh,G:Jh,H:Rh,I:Fh,j:Ph,L:Yh,m:Uh,M:zh,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:nf,s:rf,S:$h,u:qh,U:Hh,V:Vh,w:Gh,W:Xh,x:null,X:null,y:Zh,Y:Qh,Z:tf,"%":ef},x={a:function(t,e,n){var r=d.exec(e.slice(n));return r?(t.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(t,e,n){var r=h.exec(e.slice(n));return r?(t.w=f.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(t,e,n){var r=m.exec(e.slice(n));return r?(t.m=v.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(t,e,n){var r=g.exec(e.slice(n));return r?(t.m=y.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(t,n,r){return T(t,e,n,r)},d:ah,e:ah,f:hh,g:eh,G:th,H:sh,I:sh,j:oh,L:lh,m:ih,M:ch,p:function(t,e,n){var r=u.exec(e.slice(n));return r?(t.p=l.get(r[0].toLowerCase()),n+r[0].length):-1},q:rh,Q:dh,s:ph,S:uh,u:Zl,U:Kl,V:Ql,w:Xl,W:Jl,x:function(t,e,r){return T(t,n,e,r)},X:function(t,e,n){return T(t,r,e,n)},y:eh,Y:th,Z:nh,"%":fh};function w(t,e){return function(n){var r,i,a,o=[],s=-1,c=0,u=t.length;for(n instanceof Date||(n=new Date(+n));++s53)return null;"w"in a||(a.w=1),"Z"in a?(i=(r=Fl(Pl(a.y,0,1))).getUTCDay(),r=i>4||0===i?pl.ceil(r):pl(r),r=xl.offset(r,7*(a.V-1)),a.y=r.getUTCFullYear(),a.m=r.getUTCMonth(),a.d=r.getUTCDate()+(a.w+6)%7):(i=(r=Rl(Pl(a.y,0,1))).getDay(),r=i>4||0===i?Tl.ceil(r):Tl(r),r=Dl.offset(r,7*(a.V-1)),a.y=r.getFullYear(),a.m=r.getMonth(),a.d=r.getDate()+(a.w+6)%7)}else("W"in a||"U"in a)&&("w"in a||(a.w="u"in a?a.u%7:"W"in a?1:0),i="Z"in a?Fl(Pl(a.y,0,1)).getUTCDay():Rl(Pl(a.y,0,1)).getDay(),a.m=0,a.d="W"in a?(a.w+6)%7+7*a.W-(i+5)%7:a.w+7*a.U-(i+6)%7);return"Z"in a?(a.H+=a.Z/100|0,a.M+=a.Z%100,Fl(a)):Rl(a)}}function T(t,e,n,r){for(var i,a,o=0,s=e.length,c=n.length;o=c)return-1;if(37===(i=e.charCodeAt(o++))){if(i=e.charAt(o++),!(a=x[i in Ul?e.charAt(o++):i])||(r=a(t,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}return b.x=w(n,b),b.X=w(r,b),b.c=w(e,b),_.x=w(n,_),_.X=w(r,_),_.c=w(e,_),{format:function(t){var e=w(t+="",b);return e.toString=function(){return t},e},parse:function(t){var e=k(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=w(t+="",_);return e.toString=function(){return t},e},utcParse:function(t){var e=k(t+="",!0);return e.toString=function(){return t},e}}}({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}),jl=Yl.format,Yl.parse,Yl.utcFormat,Yl.utcParse;var af={value:()=>{}};function of(){for(var t,e=0,n=arguments.length,r={};e=0&&(n=t.slice(r+1),t=t.slice(0,r)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))}function uf(t,e){for(var n,r=0,i=t.length;r0)for(var n,r,i=new Array(n),a=0;a=0&&e._call.call(void 0,t),e=e._next;--pf}()}finally{pf=0,function(){for(var t,e,n=ff,r=1/0;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:ff=e);df=t,Af(r)}(),vf=0}}function Sf(){var t=_f.now(),e=t-mf;e>1e3&&(bf-=e,mf=t)}function Af(t){pf||(gf&&(gf=clearTimeout(gf)),t-vf>24?(t<1/0&&(gf=setTimeout(Cf,t-_f.now()-bf)),yf&&(yf=clearInterval(yf))):(yf||(mf=_f.now(),yf=setInterval(Sf,1e3)),pf=1,xf(Cf)))}function Mf(t,e,n){var r=new Tf;return e=null==e?0:+e,r.restart((n=>{r.stop(),t(n+e)}),e,n),r}Tf.prototype=Ef.prototype={constructor:Tf,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?wf():+n)+(null==e?0:+e),this._next||df===this||(df?df._next=this:ff=this,df=this),this._call=t,this._time=n,Af()},stop:function(){this._call&&(this._call=null,this._time=1/0,Af())}};var Nf=hf("start","end","cancel","interrupt"),Df=[];function Lf(t,e,n,r,i,a){var o=t.__transition;if(o){if(n in o)return}else t.__transition={};!function(t,e,n){var r,i=t.__transition;function a(c){var u,l,h,f;if(1!==n.state)return s();for(u in i)if((f=i[u]).name===n.name){if(3===f.state)return Mf(a);4===f.state?(f.state=6,f.timer.stop(),f.on.call("interrupt",t,t.__data__,f.index,f.group),delete i[u]):+u0)throw new Error("too late; already scheduled");return n}function Of(t,e){var n=If(t,e);if(n.state>3)throw new Error("too late; already running");return n}function If(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function Rf(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}var Ff,Pf=180/Math.PI,Yf={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function jf(t,e,n,r,i,a){var o,s,c;return(o=Math.sqrt(t*t+e*e))&&(t/=o,e/=o),(c=t*n+e*r)&&(n-=t*c,r-=e*c),(s=Math.sqrt(n*n+r*r))&&(n/=s,r/=s,c/=s),t*r180?e+=360:e-t>180&&(t+=360),a.push({i:n.push(i(n)+"rotate(",null,r)-2,x:Rf(t,e)})):e&&n.push(i(n)+"rotate("+e+r)}(a.rotate,o.rotate,s,c),function(t,e,n,a){t!==e?a.push({i:n.push(i(n)+"skewX(",null,r)-2,x:Rf(t,e)}):e&&n.push(i(n)+"skewX("+e+r)}(a.skewX,o.skewX,s,c),function(t,e,n,r,a,o){if(t!==n||e!==r){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:Rf(t,n)},{i:s-2,x:Rf(e,r)})}else 1===n&&1===r||a.push(i(a)+"scale("+n+","+r+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,c),a=o=null,function(t){for(var e,n=-1,r=c.length;++n=1?(n=1,e-1):Math.floor(n*e),i=t[r],a=t[r+1],o=r>0?t[r-1]:2*i-a,s=ra&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(n=n[0])===(r=r[0])?s[o]?s[o]+=r:s[++o]=r:(s[++o]=null,c.push({i:o,x:Rf(n,r)})),a=Kf.lastIndex;return a=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?Bf:Of;return function(){var o=a(this,t),s=o.on;s!==r&&(i=(r=s).copy()).on(e,n),o.on=i}}var yd=iu.prototype.constructor;function md(t){return function(){this.style.removeProperty(t)}}function vd(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}function bd(t,e,n){var r,i;function a(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&vd(t,a,n)),r}return a._value=e,a}function _d(t){return function(e){this.textContent=t.call(this,e)}}function xd(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&_d(r)),e}return r._value=t,r}var wd=0;function kd(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function Td(){return++wd}var Ed=iu.prototype;kd.prototype=function(t){return iu().transition(t)}.prototype={constructor:kd,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=Hs(t));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete a[i]):o=!1;o&&delete t.__transition}}(this,t)}))},iu.prototype.transition=function(t){var e,n;t instanceof kd?(e=t._id,t=t._name):(e=Td(),(n=Cd).time=wf(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,a=0;ae?1:t>=e?0:NaN}jd.prototype={constructor:jd,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var Vd="http://www.w3.org/1999/xhtml";const Gd={svg:"http://www.w3.org/2000/svg",xhtml:Vd,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Xd(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),Gd.hasOwnProperty(e)?{space:Gd[e],local:t}:t}function Zd(t){return function(){this.removeAttribute(t)}}function Kd(t){return function(){this.removeAttributeNS(t.space,t.local)}}function Qd(t,e){return function(){this.setAttribute(t,e)}}function Jd(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function tp(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function ep(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function np(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function rp(t){return function(){this.style.removeProperty(t)}}function ip(t,e,n){return function(){this.style.setProperty(t,e,n)}}function ap(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function op(t,e){return t.style.getPropertyValue(e)||np(t).getComputedStyle(t,null).getPropertyValue(e)}function sp(t){return function(){delete this[t]}}function cp(t,e){return function(){this[t]=e}}function up(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function lp(t){return t.trim().split(/^|\s+/)}function hp(t){return t.classList||new fp(t)}function fp(t){this._node=t,this._names=lp(t.getAttribute("class")||"")}function dp(t,e){for(var n=hp(t),r=-1,i=e.length;++r=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}function Op(t){return function(){var e=this.__on;if(e){for(var n,r=0,i=-1,a=e.length;r=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Yp=[null];function jp(t,e){this._groups=t,this._parents=e}function Up(){return new jp([[document.documentElement]],Yp)}jp.prototype=Up.prototype={constructor:jp,select:function(t){"function"!=typeof t&&(t=Md(t));for(var e=this._groups,n=e.length,r=new Array(n),i=0;i=x&&(x=_+1);!(b=y[x])&&++x=0;)(r=i[a])&&(o&&4^r.compareDocumentPosition(o)&&o.parentNode.insertBefore(r,o),o=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=Wd);for(var n=this._groups,r=n.length,i=new Array(r),a=0;a1?this.each((null==e?rp:"function"==typeof e?ap:ip)(t,e,null==n?"":n)):op(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?sp:"function"==typeof e?up:cp)(t,e)):this.node()[t]},classed:function(t,e){var n=lp(t+"");if(arguments.length<2){for(var r=hp(this.node()),i=-1,a=n.length;++i{}};function qp(){for(var t,e=0,n=arguments.length,r={};e=0&&(n=t.slice(r+1),t=t.slice(0,r)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))}function Vp(t,e){for(var n,r=0,i=t.length;r0)for(var n,r,i=new Array(n),a=0;a=0&&e._call.call(void 0,t),e=e._next;--Qp}()}finally{Qp=0,function(){for(var t,e,n=Zp,r=1/0;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:Zp=e);Kp=t,fg(r)}(),ng=0}}function hg(){var t=ig.now(),e=t-eg;e>1e3&&(rg-=e,eg=t)}function fg(t){Qp||(Jp&&(Jp=clearTimeout(Jp)),t-ng>24?(t<1/0&&(Jp=setTimeout(lg,t-ig.now()-rg)),tg&&(tg=clearInterval(tg))):(tg||(eg=ig.now(),tg=setInterval(hg,1e3)),Qp=1,ag(lg)))}function dg(t,e,n){var r=new cg;return e=null==e?0:+e,r.restart((n=>{r.stop(),t(n+e)}),e,n),r}cg.prototype=ug.prototype={constructor:cg,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?og():+n)+(null==e?0:+e),this._next||Kp===this||(Kp?Kp._next=this:Zp=this,Kp=this),this._call=t,this._time=n,fg()},stop:function(){this._call&&(this._call=null,this._time=1/0,fg())}};var pg=Xp("start","end","cancel","interrupt"),gg=[];function yg(t,e,n,r,i,a){var o=t.__transition;if(o){if(n in o)return}else t.__transition={};!function(t,e,n){var r,i=t.__transition;function a(c){var u,l,h,f;if(1!==n.state)return s();for(u in i)if((f=i[u]).name===n.name){if(3===f.state)return dg(a);4===f.state?(f.state=6,f.timer.stop(),f.on.call("interrupt",t,t.__data__,f.index,f.group),delete i[u]):+u0)throw new Error("too late; already scheduled");return n}function vg(t,e){var n=bg(t,e);if(n.state>3)throw new Error("too late; already running");return n}function bg(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function _g(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}var xg,wg=180/Math.PI,kg={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Tg(t,e,n,r,i,a){var o,s,c;return(o=Math.sqrt(t*t+e*e))&&(t/=o,e/=o),(c=t*n+e*r)&&(n-=t*c,r-=e*c),(s=Math.sqrt(n*n+r*r))&&(n/=s,r/=s,c/=s),t*r180?e+=360:e-t>180&&(t+=360),a.push({i:n.push(i(n)+"rotate(",null,r)-2,x:_g(t,e)})):e&&n.push(i(n)+"rotate("+e+r)}(a.rotate,o.rotate,s,c),function(t,e,n,a){t!==e?a.push({i:n.push(i(n)+"skewX(",null,r)-2,x:_g(t,e)}):e&&n.push(i(n)+"skewX("+e+r)}(a.skewX,o.skewX,s,c),function(t,e,n,r,a,o){if(t!==n||e!==r){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:_g(t,n)},{i:s-2,x:_g(e,r)})}else 1===n&&1===r||a.push(i(a)+"scale("+n+","+r+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,c),a=o=null,function(t){for(var e,n=-1,r=c.length;++n>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?Kg(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?Kg(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=jg.exec(t))?new ty(e[1],e[2],e[3],1):(e=Ug.exec(t))?new ty(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=zg.exec(t))?Kg(e[1],e[2],e[3],e[4]):(e=$g.exec(t))?Kg(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=qg.exec(t))?iy(e[1],e[2]/100,e[3]/100,1):(e=Hg.exec(t))?iy(e[1],e[2]/100,e[3]/100,e[4]):Wg.hasOwnProperty(t)?Zg(Wg[t]):"transparent"===t?new ty(NaN,NaN,NaN,0):null}function Zg(t){return new ty(t>>16&255,t>>8&255,255&t,1)}function Kg(t,e,n,r){return r<=0&&(t=e=n=NaN),new ty(t,e,n,r)}function Qg(t){return t instanceof Bg||(t=Xg(t)),t?new ty((t=t.rgb()).r,t.g,t.b,t.opacity):new ty}function Jg(t,e,n,r){return 1===arguments.length?Qg(t):new ty(t,e,n,null==r?1:r)}function ty(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function ey(){return"#"+ry(this.r)+ry(this.g)+ry(this.b)}function ny(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function ry(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function iy(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new oy(t,e,n,r)}function ay(t){if(t instanceof oy)return new oy(t.h,t.s,t.l,t.opacity);if(t instanceof Bg||(t=Xg(t)),!t)return new oy;if(t instanceof oy)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),a=Math.max(e,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=e===a?(n-r)/s+6*(n0&&c<1?0:o,new oy(o,s,c,t.opacity)}function oy(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function sy(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}function cy(t,e,n,r,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*n+(1+3*t+3*a-3*o)*r+o*i)/6}Dg(Bg,Xg,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:Vg,formatHex:Vg,formatHsl:function(){return ay(this).formatHsl()},formatRgb:Gg,toString:Gg}),Dg(ty,Jg,Lg(Bg,{brighter:function(t){return t=null==t?Ig:Math.pow(Ig,t),new ty(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?Og:Math.pow(Og,t),new ty(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:ey,formatHex:ey,formatRgb:ny,toString:ny})),Dg(oy,(function(t,e,n,r){return 1===arguments.length?ay(t):new oy(t,e,n,null==r?1:r)}),Lg(Bg,{brighter:function(t){return t=null==t?Ig:Math.pow(Ig,t),new oy(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?Og:Math.pow(Og,t),new oy(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new ty(sy(t>=240?t-240:t+120,i,r),sy(t,i,r),sy(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const uy=t=>()=>t;function ly(t,e){var n=e-t;return n?function(t,e){return function(n){return t+n*e}}(t,n):uy(isNaN(t)?e:t)}const hy=function t(e){var n=function(t){return 1==(t=+t)?ly:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):uy(isNaN(e)?n:e)}}(e);function r(t,e){var r=n((t=Jg(t)).r,(e=Jg(e)).r),i=n(t.g,e.g),a=n(t.b,e.b),o=ly(t.opacity,e.opacity);return function(e){return t.r=r(e),t.g=i(e),t.b=a(e),t.opacity=o(e),t+""}}return r.gamma=t,r}(1);function fy(t){return function(e){var n,r,i=e.length,a=new Array(i),o=new Array(i),s=new Array(i);for(n=0;n=1?(n=1,e-1):Math.floor(n*e),i=t[r],a=t[r+1],o=r>0?t[r-1]:2*i-a,s=ra&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(n=n[0])===(r=r[0])?s[o]?s[o]+=r:s[++o]=r:(s[++o]=null,c.push({i:o,x:_g(n,r)})),a=py.lastIndex;return a=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?mg:vg;return function(){var o=a(this,t),s=o.on;s!==r&&(i=(r=s).copy()).on(e,n),o.on=i}}var By=zp.prototype.constructor;function Oy(t){return function(){this.style.removeProperty(t)}}function Iy(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}function Ry(t,e,n){var r,i;function a(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&Iy(t,a,n)),r}return a._value=e,a}function Fy(t){return function(e){this.textContent=t.call(this,e)}}function Py(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&Fy(r)),e}return r._value=t,r}var Yy=0;function jy(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function Uy(){return++Yy}var zy=zp.prototype;jy.prototype=function(t){return zp().transition(t)}.prototype={constructor:jy,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=Md(t));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete a[i]):o=!1;o&&delete t.__transition}}(this,t)}))},zp.prototype.transition=function(t){var e,n;t instanceof jy?(e=t._id,t=t._name):(e=Uy(),(n=$y).time=og(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,a=0;a0?tm(fm,--lm):0,cm--,10===hm&&(cm=1,sm--),hm}function gm(){return hm=lm2||bm(hm)>3?"":" "}function wm(t,e){for(;--e&&gm()&&!(hm<48||hm>102||hm>57&&hm<65||hm>70&&hm<97););return vm(t,mm()+(e<6&&32==ym()&&32==gm()))}function km(t){for(;gm();)switch(hm){case t:return lm;case 34:case 39:34!==t&&39!==t&&km(hm);break;case 40:41===t&&km(t);break;case 92:gm()}return lm}function Tm(t,e){for(;gm()&&t+hm!==57&&(t+hm!==84||47!==ym()););return"/*"+vm(e,lm-1)+"*"+Zy(47===t?t:gm())}function Em(t){for(;!bm(ym());)gm();return vm(t,lm)}function Cm(t){return function(t){return fm="",t}(Sm("",null,null,null,[""],t=function(t){return sm=cm=1,um=nm(fm=t),lm=0,[]}(t),0,[0],t))}function Sm(t,e,n,r,i,a,o,s,c){for(var u=0,l=0,h=o,f=0,d=0,p=0,g=1,y=1,m=1,v=0,b="",_=i,x=a,w=r,k=b;y;)switch(p=v,v=gm()){case 40:if(108!=p&&58==k.charCodeAt(h-1)){-1!=Jy(k+=Qy(_m(v),"&","&\f"),"&\f")&&(m=-1);break}case 34:case 39:case 91:k+=_m(v);break;case 9:case 10:case 13:case 32:k+=xm(p);break;case 92:k+=wm(mm()-1,7);continue;case 47:switch(ym()){case 42:case 47:im(Mm(Tm(gm(),mm()),e,n),c);break;default:k+="/"}break;case 123*g:s[u++]=nm(k)*m;case 125*g:case 59:case 0:switch(v){case 0:case 125:y=0;case 59+l:d>0&&nm(k)-h&&im(d>32?Nm(k+";",r,n,h-1):Nm(Qy(k," ","")+";",r,n,h-2),c);break;case 59:k+=";";default:if(im(w=Am(k,e,n,u,l,i,s,b,_=[],x=[],h),a),123===v)if(0===l)Sm(k,e,w,w,_,a,h,s,x);else switch(f){case 100:case 109:case 115:Sm(t,w,w,r&&im(Am(t,w,w,0,0,i,s,b,i,_=[],h),x),i,x,h,s,r?_:x);break;default:Sm(k,w,w,w,[""],x,0,s,x)}}u=l=d=0,g=m=1,b=k="",h=o;break;case 58:h=1+nm(k),d=p;default:if(g<1)if(123==v)--g;else if(125==v&&0==g++&&125==pm())continue;switch(k+=Zy(v),v*g){case 38:m=l>0?1:(k+="\f",-1);break;case 44:s[u++]=(nm(k)-1)*m,m=1;break;case 64:45===ym()&&(k+=_m(gm())),f=ym(),l=h=nm(b=k+=Em(mm())),v++;break;case 45:45===p&&2==nm(k)&&(g=0)}}return a}function Am(t,e,n,r,i,a,o,s,c,u,l){for(var h=i-1,f=0===i?a:[""],d=rm(f),p=0,g=0,y=0;p0?f[m]+" "+v:Qy(v,/&\f/g,f[m])))&&(c[y++]=b);return dm(t,e,n,0===i?Vy:s,c,u,l)}function Mm(t,e,n){return dm(t,e,n,Wy,Zy(hm),em(t,2,-2),0)}function Nm(t,e,n,r){return dm(t,e,n,Gy,em(t,0,r),em(t,r+1,-1),r)}const Dm="9.1.1";var Lm=n(7967),Bm=n(7856),Om=n.n(Bm),Im=function(t){var e=t.replace(/\\u[\dA-F]{4}/gi,(function(t){return String.fromCharCode(parseInt(t.replace(/\\u/g,""),16))}));return e=(e=(e=e.replace(/\\x([0-9a-f]{2})/gi,(function(t,e){return String.fromCharCode(parseInt(e,16))}))).replace(/\\[\d\d\d]{3}/gi,(function(t){return String.fromCharCode(parseInt(t.replace(/\\/g,""),8))}))).replace(/\\[\d\d\d]{2}/gi,(function(t){return String.fromCharCode(parseInt(t.replace(/\\/g,""),8))}))},Rm=function(t){for(var e="",n=0;n>=0;){if(!((n=t.indexOf("=0)){e+=t,n=-1;break}e+=t.substr(0,n),(n=(t=t.substr(n+1)).indexOf("<\/script>"))>=0&&(n+=9,t=t.substr(n))}var r=Im(e);return(r=(r=(r=(r=r.replaceAll(/script>/gi,"#")).replaceAll(/javascript:/gi,"#")).replaceAll(/javascript&colon/gi,"#")).replaceAll(/onerror=/gi,"onerror:")).replaceAll(/')}else"loose"!==s.securityLevel&&(T=Om().sanitize(T,{ADD_TAGS:["foreignobject"],ADD_ATTR:["dominant-baseline"]}));if(void 0!==n)switch(g){case"flowchart":case"flowchart-v2":n(T,Kx.bindFunctions);break;case"gantt":n(T,tk.bindFunctions);break;case"class":case"classDiagram":n(T,Jb.bindFunctions);break;default:n(T)}else o.debug("CB = undefined!");FT.forEach((function(t){t()})),FT=[];var S="sandbox"===s.securityLevel?"#i"+t:"#d"+t,A=au(S).node();return null!==A&&"function"==typeof A.remove&&au(S).node().remove(),T},parse:function(t){var e=!1;try{t+="\n";var n=wb(),r=db.detectInit(t,n);r&&o.info("reinit ",r);var i,a=db.detectType(t,n);switch(o.debug("Type "+a),a){case"gitGraph":Ck.clear(),(i=Ak()).parser.yy=Ck;break;case"flowchart":case"flowchart-v2":Kx.clear(),(i=Jx()).parser.yy=Kx;break;case"sequence":RT.clear(),(i=mT()).parser.yy=RT;break;case"gantt":(i=ik()).parser.yy=tk;break;case"class":case"classDiagram":(i=a_()).parser.yy=Jb;break;case"state":case"stateDiagram":(i=AE()).parser.yy=$E;break;case"info":o.debug("info info info"),(i=Uk()).parser.yy=Yk;break;case"pie":o.debug("pie"),(i=Hk()).parser.yy=Gk;break;case"er":o.debug("er"),(i=mx()).parser.yy=gx;break;case"journey":o.debug("Journey"),(i=yC()).parser.yy=pC;break;case"requirement":case"requirementDiagram":o.debug("RequirementDiagram"),(i=Jk()).parser.yy=aT}i.parser.yy.graphType=a,i.parser.yy.parseError=function(t,e){throw{str:t,hash:e}},i.parse(t)}catch(t){if(e=!0,!VC.parseError)throw t;null!=t.str?VC.parseError(t.str,t.hash):VC.parseError(t)}return!e},parseDirective:function(t,e,n,r){try{if(void 0!==e)switch(e=e.trim(),n){case"open_directive":jC={};break;case"type_directive":jC.type=e.toLowerCase();break;case"arg_directive":jC.args=JSON.parse(e);break;case"close_directive":(function(t,e,n){switch(o.debug("Directive type=".concat(e.type," with args:"),e.args),e.type){case"init":case"initialize":["config"].forEach((function(t){void 0!==e.args[t]&&("flowchart-v2"===n&&(n="flowchart"),e.args[n]=e.args[t],delete e.args[t])})),o.debug("sanitize in handleDirective",e.args),hb(e.args),o.debug("sanitize in handleDirective (done)",e.args),e.args,Tb(e.args);break;case"wrap":case"nowrap":t&&t.setWrap&&t.setWrap("wrap"===e.type);break;case"themeCss":o.warn("themeCss encountered");break;default:o.warn("Unhandled directive: source: '%%{".concat(e.type,": ").concat(JSON.stringify(e.args?e.args:{}),"}%%"),e)}})(t,jC,r),jC=null}}catch(t){o.error("Error while rendering sequenceDiagram directive: ".concat(e," jison context: ").concat(n)),o.error(t.message)}},initialize:function(t){t&&t.fontFamily&&(t.themeVariables&&t.themeVariables.fontFamily||(t.themeVariables={fontFamily:t.fontFamily})),function(t){gb=rb({},t)}(t),t&&t.theme&&Mv[t.theme]?t.themeVariables=Mv[t.theme].getThemeVariables(t.themeVariables):t&&(t.themeVariables=Mv.default.getThemeVariables(t.themeVariables));var e="object"===PC(t)?function(t){return mb=rb({},yb),mb=rb(mb,t),t.theme&&Mv[t.theme]&&(mb.themeVariables=Mv[t.theme].getThemeVariables(t.themeVariables)),bb=_b(mb,vb),mb}(t):xb();UC(e),s(e.logLevel)},reinitialize:function(){},getConfig:wb,setConfig:function(t){return rb(bb,t),wb()},getSiteConfig:xb,updateSiteConfig:function(t){return mb=rb(mb,t),_b(mb,vb),mb},reset:function(){Eb()},globalReset:function(){Eb(),UC(wb())},defaultConfig:yb});s(wb().logLevel),Eb(wb());const $C=zC;var qC=function(){var t,e,n=$C.getConfig();arguments.length>=2?(void 0!==arguments[0]&&(WC.sequenceConfig=arguments[0]),t=arguments[1]):t=arguments[0],"function"==typeof arguments[arguments.length-1]?(e=arguments[arguments.length-1],o.debug("Callback function found")):void 0!==n.mermaid&&("function"==typeof n.mermaid.callback?(e=n.mermaid.callback,o.debug("Callback function found")):o.debug("No Callback function found")),t=void 0===t?document.querySelectorAll(".mermaid"):"string"==typeof t?document.querySelectorAll(t):t instanceof window.Node?[t]:t,o.debug("Start On Load before: "+WC.startOnLoad),void 0!==WC.startOnLoad&&(o.debug("Start On Load inner: "+WC.startOnLoad),$C.updateSiteConfig({startOnLoad:WC.startOnLoad})),void 0!==WC.ganttConfig&&$C.updateSiteConfig({gantt:WC.ganttConfig});for(var r,i=new db.initIdGeneratior(n.deterministicIds,n.deterministicIDSeed),a=function(n){var a=t[n];if(a.getAttribute("data-processed"))return"continue";a.setAttribute("data-processed",!0);var s="mermaid-".concat(i.next());r=a.innerHTML,r=db.entityDecode(r).trim().replace(//gi,"
    ");var c=db.detectInit(r);c&&o.debug("Detected early reinit: ",c),$C.render(s,r,(function(t,n){a.innerHTML=t,void 0!==e&&e(s),n&&n(a)}),a)},s=0;s{t.exports={graphlib:n(6614),dagre:n(1463),intersect:n(8114),render:n(5787),util:n(8355),version:n(5689)}},9144:(t,e,n)=>{var r=n(8355);function i(t,e,n,i){var a=t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").style("stroke-width",1).style("stroke-dasharray","1,0");r.applyStyle(a,n[i+"Style"]),n[i+"Class"]&&a.attr("class",n[i+"Class"])}t.exports={default:i,normal:i,vee:function(t,e,n,i){var a=t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 L 4 5 z").style("stroke-width",1).style("stroke-dasharray","1,0");r.applyStyle(a,n[i+"Style"]),n[i+"Class"]&&a.attr("class",n[i+"Class"])},undirected:function(t,e,n,i){var a=t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 5 L 10 5").style("stroke-width",1).style("stroke-dasharray","1,0");r.applyStyle(a,n[i+"Style"]),n[i+"Class"]&&a.attr("class",n[i+"Class"])}}},5632:(t,e,n)=>{var r=n(8355),i=n(4322),a=n(1322);t.exports=function(t,e){var n,o=e.nodes().filter((function(t){return r.isSubgraph(e,t)})),s=t.selectAll("g.cluster").data(o,(function(t){return t}));return s.selectAll("*").remove(),s.enter().append("g").attr("class","cluster").attr("id",(function(t){return e.node(t).id})).style("opacity",0),s=t.selectAll("g.cluster"),r.applyTransition(s,e).style("opacity",1),s.each((function(t){var n=e.node(t),r=i.select(this);i.select(this).append("rect");var o=r.append("g").attr("class","label");a(o,n,n.clusterLabelPos)})),s.selectAll("rect").each((function(t){var n=e.node(t),a=i.select(this);r.applyStyle(a,n.style)})),n=s.exit?s.exit():s.selectAll(null),r.applyTransition(n,e).style("opacity",0).remove(),s}},6315:(t,e,n)=>{"use strict";var r=n(1034),i=n(1322),a=n(8355),o=n(4322);t.exports=function(t,e){var n,s=t.selectAll("g.edgeLabel").data(e.edges(),(function(t){return a.edgeToId(t)})).classed("update",!0);return s.exit().remove(),s.enter().append("g").classed("edgeLabel",!0).style("opacity",0),(s=t.selectAll("g.edgeLabel")).each((function(t){var n=o.select(this);n.select(".label").remove();var a=e.edge(t),s=i(n,e.edge(t),0,0).classed("label",!0),c=s.node().getBBox();a.labelId&&s.attr("id",a.labelId),r.has(a,"width")||(a.width=c.width),r.has(a,"height")||(a.height=c.height)})),n=s.exit?s.exit():s.selectAll(null),a.applyTransition(n,e).style("opacity",0).remove(),s}},940:(t,e,n)=>{"use strict";var r=n(1034),i=n(3042),a=n(8355),o=n(4322);function s(t,e){var n=(o.line||o.svg.line)().x((function(t){return t.x})).y((function(t){return t.y}));return(n.curve||n.interpolate)(t.curve),n(e)}t.exports=function(t,e,n){var c=t.selectAll("g.edgePath").data(e.edges(),(function(t){return a.edgeToId(t)})).classed("update",!0),u=function(t,e){var n=t.enter().append("g").attr("class","edgePath").style("opacity",0);return n.append("path").attr("class","path").attr("d",(function(t){var n=e.edge(t),i=e.node(t.v).elem;return s(n,r.range(n.points.length).map((function(){return e=(t=i).getBBox(),{x:(n=t.ownerSVGElement.getScreenCTM().inverse().multiply(t.getScreenCTM()).translate(e.width/2,e.height/2)).e,y:n.f};var t,e,n})))})),n.append("defs"),n}(c,e);!function(t,e){var n=t.exit();a.applyTransition(n,e).style("opacity",0).remove()}(c,e);var l=void 0!==c.merge?c.merge(u):c;return a.applyTransition(l,e).style("opacity",1),l.each((function(t){var n=o.select(this),r=e.edge(t);r.elem=this,r.id&&n.attr("id",r.id),a.applyClass(n,r.class,(n.classed("update")?"update ":"")+"edgePath")})),l.selectAll("path.path").each((function(t){var n=e.edge(t);n.arrowheadId=r.uniqueId("arrowhead");var c=o.select(this).attr("marker-end",(function(){return"url("+(t=location.href,e=n.arrowheadId,t.split("#")[0]+"#"+e+")");var t,e})).style("fill","none");a.applyTransition(c,e).attr("d",(function(t){return function(t,e){var n=t.edge(e),r=t.node(e.v),a=t.node(e.w),o=n.points.slice(1,n.points.length-1);return o.unshift(i(r,o[0])),o.push(i(a,o[o.length-1])),s(n,o)}(e,t)})),a.applyStyle(c,n.style)})),l.selectAll("defs *").remove(),l.selectAll("defs").each((function(t){var r=e.edge(t);(0,n[r.arrowhead])(o.select(this),r.arrowheadId,r,"arrowhead")})),l}},607:(t,e,n)=>{"use strict";var r=n(1034),i=n(1322),a=n(8355),o=n(4322);t.exports=function(t,e,n){var s,c=e.nodes().filter((function(t){return!a.isSubgraph(e,t)})),u=t.selectAll("g.node").data(c,(function(t){return t})).classed("update",!0);return u.exit().remove(),u.enter().append("g").attr("class","node").style("opacity",0),(u=t.selectAll("g.node")).each((function(t){var s=e.node(t),c=o.select(this);a.applyClass(c,s.class,(c.classed("update")?"update ":"")+"node"),c.select("g.label").remove();var u=c.append("g").attr("class","label"),l=i(u,s),h=n[s.shape],f=r.pick(l.node().getBBox(),"width","height");s.elem=this,s.id&&c.attr("id",s.id),s.labelId&&u.attr("id",s.labelId),r.has(s,"width")&&(f.width=s.width),r.has(s,"height")&&(f.height=s.height),f.width+=s.paddingLeft+s.paddingRight,f.height+=s.paddingTop+s.paddingBottom,u.attr("transform","translate("+(s.paddingLeft-s.paddingRight)/2+","+(s.paddingTop-s.paddingBottom)/2+")");var d=o.select(this);d.select(".label-container").remove();var p=h(d,f,s).classed("label-container",!0);a.applyStyle(p,s.style);var g=p.node().getBBox();s.width=g.width,s.height=g.height})),s=u.exit?u.exit():u.selectAll(null),a.applyTransition(s,e).style("opacity",0).remove(),u}},4322:(t,e,n)=>{var r;if(!r)try{r=n(7188)}catch(t){}r||(r=window.d3),t.exports=r},1463:(t,e,n)=>{var r;try{r=n(681)}catch(t){}r||(r=window.dagre),t.exports=r},6614:(t,e,n)=>{var r;try{r=n(8282)}catch(t){}r||(r=window.graphlib),t.exports=r},8114:(t,e,n)=>{t.exports={node:n(3042),circle:n(6587),ellipse:n(3260),polygon:n(5337),rect:n(8049)}},6587:(t,e,n)=>{var r=n(3260);t.exports=function(t,e,n){return r(t,e,e,n)}},3260:t=>{t.exports=function(t,e,n,r){var i=t.x,a=t.y,o=i-r.x,s=a-r.y,c=Math.sqrt(e*e*s*s+n*n*o*o),u=Math.abs(e*n*o/c);r.x{function e(t,e){return t*e>0}t.exports=function(t,n,r,i){var a,o,s,c,u,l,h,f,d,p,g,y,m;if(!(a=n.y-t.y,s=t.x-n.x,u=n.x*t.y-t.x*n.y,d=a*r.x+s*r.y+u,p=a*i.x+s*i.y+u,0!==d&&0!==p&&e(d,p)||(o=i.y-r.y,c=r.x-i.x,l=i.x*r.y-r.x*i.y,h=o*t.x+c*t.y+l,f=o*n.x+c*n.y+l,0!==h&&0!==f&&e(h,f)||0==(g=a*c-o*s))))return y=Math.abs(g/2),{x:(m=s*l-c*u)<0?(m-y)/g:(m+y)/g,y:(m=o*u-a*l)<0?(m-y)/g:(m+y)/g}}},3042:t=>{t.exports=function(t,e){return t.intersect(e)}},5337:(t,e,n)=>{var r=n(6808);t.exports=function(t,e,n){var i=t.x,a=t.y,o=[],s=Number.POSITIVE_INFINITY,c=Number.POSITIVE_INFINITY;e.forEach((function(t){s=Math.min(s,t.x),c=Math.min(c,t.y)}));for(var u=i-t.width/2-s,l=a-t.height/2-c,h=0;h1&&o.sort((function(t,e){var r=t.x-n.x,i=t.y-n.y,a=Math.sqrt(r*r+i*i),o=e.x-n.x,s=e.y-n.y,c=Math.sqrt(o*o+s*s);return a{t.exports=function(t,e){var n,r,i=t.x,a=t.y,o=e.x-i,s=e.y-a,c=t.width/2,u=t.height/2;return Math.abs(s)*c>Math.abs(o)*u?(s<0&&(u=-u),n=0===s?0:u*o/s,r=u):(o<0&&(c=-c),n=c,r=0===o?0:c*s/o),{x:i+n,y:a+r}}},8284:(t,e,n)=>{var r=n(8355);t.exports=function(t,e){var n=t.append("foreignObject").attr("width","100000"),i=n.append("xhtml:div");i.attr("xmlns","http://www.w3.org/1999/xhtml");var a=e.label;switch(typeof a){case"function":i.insert(a);break;case"object":i.insert((function(){return a}));break;default:i.html(a)}r.applyStyle(i,e.labelStyle),i.style("display","inline-block"),i.style("white-space","nowrap");var o=i.node().getBoundingClientRect();return n.attr("width",o.width).attr("height",o.height),n}},1322:(t,e,n)=>{var r=n(7318),i=n(8284),a=n(8287);t.exports=function(t,e,n){var o=e.label,s=t.append("g");"svg"===e.labelType?a(s,e):"string"!=typeof o||"html"===e.labelType?i(s,e):r(s,e);var c,u=s.node().getBBox();switch(n){case"top":c=-e.height/2;break;case"bottom":c=e.height/2-u.height;break;default:c=-u.height/2}return s.attr("transform","translate("+-u.width/2+","+c+")"),s}},8287:(t,e,n)=>{var r=n(8355);t.exports=function(t,e){var n=t;return n.node().appendChild(e.label),r.applyStyle(n,e.labelStyle),n}},7318:(t,e,n)=>{var r=n(8355);t.exports=function(t,e){for(var n=t.append("text"),i=function(t){for(var e,n="",r=!1,i=0;i{var r;try{r={defaults:n(1747),each:n(6073),isFunction:n(3560),isPlainObject:n(8630),pick:n(9722),has:n(8721),range:n(6026),uniqueId:n(3955)}}catch(t){}r||(r=window._),t.exports=r},6381:(t,e,n)=>{"use strict";var r=n(8355),i=n(4322);t.exports=function(t,e){var n=t.filter((function(){return!i.select(this).classed("update")}));function a(t){var n=e.node(t);return"translate("+n.x+","+n.y+")"}n.attr("transform",a),r.applyTransition(t,e).style("opacity",1).attr("transform",a),r.applyTransition(n.selectAll("rect"),e).attr("width",(function(t){return e.node(t).width})).attr("height",(function(t){return e.node(t).height})).attr("x",(function(t){return-e.node(t).width/2})).attr("y",(function(t){return-e.node(t).height/2}))}},4577:(t,e,n)=>{"use strict";var r=n(8355),i=n(4322),a=n(1034);t.exports=function(t,e){function n(t){var n=e.edge(t);return a.has(n,"x")?"translate("+n.x+","+n.y+")":""}t.filter((function(){return!i.select(this).classed("update")})).attr("transform",n),r.applyTransition(t,e).style("opacity",1).attr("transform",n)}},4849:(t,e,n)=>{"use strict";var r=n(8355),i=n(4322);t.exports=function(t,e){function n(t){var n=e.node(t);return"translate("+n.x+","+n.y+")"}t.filter((function(){return!i.select(this).classed("update")})).attr("transform",n),r.applyTransition(t,e).style("opacity",1).attr("transform",n)}},5787:(t,e,n)=>{var r=n(1034),i=n(4322),a=n(1463).layout;t.exports=function(){var t=n(607),e=n(5632),i=n(6315),u=n(940),l=n(4849),h=n(4577),f=n(6381),d=n(4418),p=n(9144),g=function(n,g){!function(t){t.nodes().forEach((function(e){var n=t.node(e);r.has(n,"label")||t.children(e).length||(n.label=e),r.has(n,"paddingX")&&r.defaults(n,{paddingLeft:n.paddingX,paddingRight:n.paddingX}),r.has(n,"paddingY")&&r.defaults(n,{paddingTop:n.paddingY,paddingBottom:n.paddingY}),r.has(n,"padding")&&r.defaults(n,{paddingLeft:n.padding,paddingRight:n.padding,paddingTop:n.padding,paddingBottom:n.padding}),r.defaults(n,o),r.each(["paddingLeft","paddingRight","paddingTop","paddingBottom"],(function(t){n[t]=Number(n[t])})),r.has(n,"width")&&(n._prevWidth=n.width),r.has(n,"height")&&(n._prevHeight=n.height)})),t.edges().forEach((function(e){var n=t.edge(e);r.has(n,"label")||(n.label=""),r.defaults(n,s)}))}(g);var y=c(n,"output"),m=c(y,"clusters"),v=c(y,"edgePaths"),b=i(c(y,"edgeLabels"),g),_=t(c(y,"nodes"),g,d);a(g),l(_,g),h(b,g),u(v,g,p);var x=e(m,g);f(x,g),function(t){r.each(t.nodes(),(function(e){var n=t.node(e);r.has(n,"_prevWidth")?n.width=n._prevWidth:delete n.width,r.has(n,"_prevHeight")?n.height=n._prevHeight:delete n.height,delete n._prevWidth,delete n._prevHeight}))}(g)};return g.createNodes=function(e){return arguments.length?(t=e,g):t},g.createClusters=function(t){return arguments.length?(e=t,g):e},g.createEdgeLabels=function(t){return arguments.length?(i=t,g):i},g.createEdgePaths=function(t){return arguments.length?(u=t,g):u},g.shapes=function(t){return arguments.length?(d=t,g):d},g.arrows=function(t){return arguments.length?(p=t,g):p},g};var o={paddingLeft:10,paddingRight:10,paddingTop:10,paddingBottom:10,rx:0,ry:0,shape:"rect"},s={arrowhead:"normal",curve:i.curveLinear};function c(t,e){var n=t.select("g."+e);return n.empty()&&(n=t.append("g").attr("class",e)),n}},4418:(t,e,n)=>{"use strict";var r=n(8049),i=n(3260),a=n(6587),o=n(5337);t.exports={rect:function(t,e,n){var i=t.insert("rect",":first-child").attr("rx",n.rx).attr("ry",n.ry).attr("x",-e.width/2).attr("y",-e.height/2).attr("width",e.width).attr("height",e.height);return n.intersect=function(t){return r(n,t)},i},ellipse:function(t,e,n){var r=e.width/2,a=e.height/2,o=t.insert("ellipse",":first-child").attr("x",-e.width/2).attr("y",-e.height/2).attr("rx",r).attr("ry",a);return n.intersect=function(t){return i(n,r,a,t)},o},circle:function(t,e,n){var r=Math.max(e.width,e.height)/2,i=t.insert("circle",":first-child").attr("x",-e.width/2).attr("y",-e.height/2).attr("r",r);return n.intersect=function(t){return a(n,r,t)},i},diamond:function(t,e,n){var r=e.width*Math.SQRT2/2,i=e.height*Math.SQRT2/2,a=[{x:0,y:-i},{x:-r,y:0},{x:0,y:i},{x:r,y:0}],s=t.insert("polygon",":first-child").attr("points",a.map((function(t){return t.x+","+t.y})).join(" "));return n.intersect=function(t){return o(n,a,t)},s}}},8355:(t,e,n)=>{var r=n(1034);t.exports={isSubgraph:function(t,e){return!!t.children(e).length},edgeToId:function(t){return a(t.v)+":"+a(t.w)+":"+a(t.name)},applyStyle:function(t,e){e&&t.attr("style",e)},applyClass:function(t,e,n){e&&t.attr("class",e).attr("class",n+" "+t.attr("class"))},applyTransition:function(t,e){var n=e.graph();if(r.isPlainObject(n)){var i=n.transition;if(r.isFunction(i))return i(t)}return t}};var i=/:/g;function a(t){return t?String(t).replace(i,"\\:"):""}},5689:t=>{t.exports="0.6.4"},7188:(t,e,n)=>{"use strict";n.r(e),n.d(e,{FormatSpecifier:()=>uc,active:()=>Jr,arc:()=>fx,area:()=>vx,areaRadial:()=>Sx,ascending:()=>i,autoType:()=>Fo,axisBottom:()=>it,axisLeft:()=>at,axisRight:()=>rt,axisTop:()=>nt,bisect:()=>u,bisectLeft:()=>c,bisectRight:()=>s,bisector:()=>a,blob:()=>ms,brush:()=>Ai,brushSelection:()=>Ei,brushX:()=>Ci,brushY:()=>Si,buffer:()=>bs,chord:()=>Fi,clientPoint:()=>Dn,cluster:()=>Sd,color:()=>Ve,contourDensity:()=>oo,contours:()=>to,create:()=>Y_,creator:()=>ie,cross:()=>f,csv:()=>Ts,csvFormat:()=>To,csvFormatBody:()=>Eo,csvFormatRow:()=>So,csvFormatRows:()=>Co,csvFormatValue:()=>Ao,csvParse:()=>wo,csvParseRows:()=>ko,cubehelix:()=>qa,curveBasis:()=>sw,curveBasisClosed:()=>uw,curveBasisOpen:()=>hw,curveBundle:()=>dw,curveCardinal:()=>yw,curveCardinalClosed:()=>vw,curveCardinalOpen:()=>_w,curveCatmullRom:()=>kw,curveCatmullRomClosed:()=>Ew,curveCatmullRomOpen:()=>Sw,curveLinear:()=>px,curveLinearClosed:()=>Mw,curveMonotoneX:()=>Fw,curveMonotoneY:()=>Pw,curveNatural:()=>Uw,curveStep:()=>$w,curveStepAfter:()=>Hw,curveStepBefore:()=>qw,customEvent:()=>ye,descending:()=>d,deviation:()=>y,dispatch:()=>ft,drag:()=>po,dragDisable:()=>Se,dragEnable:()=>Ae,dsv:()=>ks,dsvFormat:()=>_o,easeBack:()=>hs,easeBackIn:()=>us,easeBackInOut:()=>hs,easeBackOut:()=>ls,easeBounce:()=>os,easeBounceIn:()=>as,easeBounceInOut:()=>ss,easeBounceOut:()=>os,easeCircle:()=>rs,easeCircleIn:()=>es,easeCircleInOut:()=>rs,easeCircleOut:()=>ns,easeCubic:()=>Xr,easeCubicIn:()=>Vr,easeCubicInOut:()=>Xr,easeCubicOut:()=>Gr,easeElastic:()=>ps,easeElasticIn:()=>ds,easeElasticInOut:()=>gs,easeElasticOut:()=>ps,easeExp:()=>ts,easeExpIn:()=>Qo,easeExpInOut:()=>ts,easeExpOut:()=>Jo,easeLinear:()=>Yo,easePoly:()=>Ho,easePolyIn:()=>$o,easePolyInOut:()=>Ho,easePolyOut:()=>qo,easeQuad:()=>zo,easeQuadIn:()=>jo,easeQuadInOut:()=>zo,easeQuadOut:()=>Uo,easeSin:()=>Zo,easeSinIn:()=>Go,easeSinInOut:()=>Zo,easeSinOut:()=>Xo,entries:()=>pa,event:()=>le,extent:()=>m,forceCenter:()=>Bs,forceCollide:()=>Ws,forceLink:()=>Xs,forceManyBody:()=>tc,forceRadial:()=>ec,forceSimulation:()=>Js,forceX:()=>nc,forceY:()=>rc,format:()=>pc,formatDefaultLocale:()=>bc,formatLocale:()=>vc,formatPrefix:()=>gc,formatSpecifier:()=>cc,geoAlbers:()=>zf,geoAlbersUsa:()=>$f,geoArea:()=>gu,geoAzimuthalEqualArea:()=>Vf,geoAzimuthalEqualAreaRaw:()=>Wf,geoAzimuthalEquidistant:()=>Xf,geoAzimuthalEquidistantRaw:()=>Gf,geoBounds:()=>sl,geoCentroid:()=>bl,geoCircle:()=>Nl,geoClipAntimeridian:()=>zl,geoClipCircle:()=>$l,geoClipExtent:()=>Vl,geoClipRectangle:()=>Wl,geoConicConformal:()=>ed,geoConicConformalRaw:()=>td,geoConicEqualArea:()=>Uf,geoConicEqualAreaRaw:()=>jf,geoConicEquidistant:()=>ad,geoConicEquidistantRaw:()=>id,geoContains:()=>ph,geoDistance:()=>ah,geoEqualEarth:()=>fd,geoEqualEarthRaw:()=>hd,geoEquirectangular:()=>rd,geoEquirectangularRaw:()=>nd,geoGnomonic:()=>pd,geoGnomonicRaw:()=>dd,geoGraticule:()=>mh,geoGraticule10:()=>vh,geoIdentity:()=>gd,geoInterpolate:()=>bh,geoLength:()=>nh,geoMercator:()=>Kf,geoMercatorRaw:()=>Zf,geoNaturalEarth1:()=>md,geoNaturalEarth1Raw:()=>yd,geoOrthographic:()=>bd,geoOrthographicRaw:()=>vd,geoPath:()=>kf,geoProjection:()=>Ff,geoProjectionMutator:()=>Pf,geoRotation:()=>Sl,geoStereographic:()=>xd,geoStereographicRaw:()=>_d,geoStream:()=>nu,geoTransform:()=>Tf,geoTransverseMercator:()=>kd,geoTransverseMercatorRaw:()=>wd,gray:()=>ka,hcl:()=>La,hierarchy:()=>Md,histogram:()=>D,hsl:()=>an,html:()=>Ds,image:()=>Cs,interpolate:()=>Mn,interpolateArray:()=>xn,interpolateBasis:()=>un,interpolateBasisClosed:()=>ln,interpolateBlues:()=>f_,interpolateBrBG:()=>Tb,interpolateBuGn:()=>zb,interpolateBuPu:()=>qb,interpolateCividis:()=>k_,interpolateCool:()=>C_,interpolateCubehelix:()=>Up,interpolateCubehelixDefault:()=>T_,interpolateCubehelixLong:()=>zp,interpolateDate:()=>kn,interpolateDiscrete:()=>Sp,interpolateGnBu:()=>Wb,interpolateGreens:()=>p_,interpolateGreys:()=>y_,interpolateHcl:()=>Pp,interpolateHclLong:()=>Yp,interpolateHsl:()=>Op,interpolateHslLong:()=>Ip,interpolateHue:()=>Ap,interpolateInferno:()=>F_,interpolateLab:()=>Rp,interpolateMagma:()=>R_,interpolateNumber:()=>Tn,interpolateNumberArray:()=>bn,interpolateObject:()=>En,interpolateOrRd:()=>Gb,interpolateOranges:()=>w_,interpolatePRGn:()=>Cb,interpolatePiYG:()=>Ab,interpolatePlasma:()=>P_,interpolatePuBu:()=>Qb,interpolatePuBuGn:()=>Zb,interpolatePuOr:()=>Nb,interpolatePuRd:()=>t_,interpolatePurples:()=>v_,interpolateRainbow:()=>A_,interpolateRdBu:()=>Lb,interpolateRdGy:()=>Ob,interpolateRdPu:()=>n_,interpolateRdYlBu:()=>Rb,interpolateRdYlGn:()=>Pb,interpolateReds:()=>__,interpolateRgb:()=>gn,interpolateRgbBasis:()=>mn,interpolateRgbBasisClosed:()=>vn,interpolateRound:()=>Mp,interpolateSinebow:()=>L_,interpolateSpectral:()=>jb,interpolateString:()=>An,interpolateTransformCss:()=>pr,interpolateTransformSvg:()=>gr,interpolateTurbo:()=>B_,interpolateViridis:()=>I_,interpolateWarm:()=>E_,interpolateYlGn:()=>o_,interpolateYlGnBu:()=>i_,interpolateYlOrBr:()=>c_,interpolateYlOrRd:()=>l_,interpolateZoom:()=>Lp,interrupt:()=>ar,interval:()=>fk,isoFormat:()=>uk,isoParse:()=>hk,json:()=>As,keys:()=>fa,lab:()=>Ta,lch:()=>Da,line:()=>mx,lineRadial:()=>Cx,linkHorizontal:()=>Rx,linkRadial:()=>Px,linkVertical:()=>Fx,local:()=>U_,map:()=>na,matcher:()=>mt,max:()=>I,mean:()=>R,median:()=>F,merge:()=>P,min:()=>Y,mouse:()=>Bn,namespace:()=>Et,namespaces:()=>Tt,nest:()=>ra,now:()=>qn,pack:()=>tp,packEnclose:()=>Id,packSiblings:()=>Gd,pairs:()=>l,partition:()=>op,path:()=>Wi,permute:()=>j,pie:()=>xx,piecewise:()=>$p,pointRadial:()=>Ax,polygonArea:()=>Hp,polygonCentroid:()=>Wp,polygonContains:()=>Kp,polygonHull:()=>Zp,polygonLength:()=>Qp,precisionFixed:()=>_c,precisionPrefix:()=>xc,precisionRound:()=>wc,quadtree:()=>js,quantile:()=>L,quantize:()=>qp,radialArea:()=>Sx,radialLine:()=>Cx,randomBates:()=>ig,randomExponential:()=>ag,randomIrwinHall:()=>rg,randomLogNormal:()=>ng,randomNormal:()=>eg,randomUniform:()=>tg,range:()=>k,rgb:()=>Ke,ribbon:()=>Qi,scaleBand:()=>dg,scaleDiverging:()=>ob,scaleDivergingLog:()=>sb,scaleDivergingPow:()=>ub,scaleDivergingSqrt:()=>lb,scaleDivergingSymlog:()=>cb,scaleIdentity:()=>Mg,scaleImplicit:()=>hg,scaleLinear:()=>Ag,scaleLog:()=>Pg,scaleOrdinal:()=>fg,scalePoint:()=>gg,scalePow:()=>Vg,scaleQuantile:()=>Xg,scaleQuantize:()=>Zg,scaleSequential:()=>Jv,scaleSequentialLog:()=>tb,scaleSequentialPow:()=>nb,scaleSequentialQuantile:()=>ib,scaleSequentialSqrt:()=>rb,scaleSequentialSymlog:()=>eb,scaleSqrt:()=>Gg,scaleSymlog:()=>zg,scaleThreshold:()=>Kg,scaleTime:()=>jv,scaleUtc:()=>Zv,scan:()=>U,schemeAccent:()=>db,schemeBlues:()=>h_,schemeBrBG:()=>kb,schemeBuGn:()=>Ub,schemeBuPu:()=>$b,schemeCategory10:()=>fb,schemeDark2:()=>pb,schemeGnBu:()=>Hb,schemeGreens:()=>d_,schemeGreys:()=>g_,schemeOrRd:()=>Vb,schemeOranges:()=>x_,schemePRGn:()=>Eb,schemePaired:()=>gb,schemePastel1:()=>yb,schemePastel2:()=>mb,schemePiYG:()=>Sb,schemePuBu:()=>Kb,schemePuBuGn:()=>Xb,schemePuOr:()=>Mb,schemePuRd:()=>Jb,schemePurples:()=>m_,schemeRdBu:()=>Db,schemeRdGy:()=>Bb,schemeRdPu:()=>e_,schemeRdYlBu:()=>Ib,schemeRdYlGn:()=>Fb,schemeReds:()=>b_,schemeSet1:()=>vb,schemeSet2:()=>bb,schemeSet3:()=>_b,schemeSpectral:()=>Yb,schemeTableau10:()=>xb,schemeYlGn:()=>a_,schemeYlGnBu:()=>r_,schemeYlOrBr:()=>s_,schemeYlOrRd:()=>u_,select:()=>Te,selectAll:()=>$_,selection:()=>ke,selector:()=>pt,selectorAll:()=>yt,set:()=>ha,shuffle:()=>z,stack:()=>Xw,stackOffsetDiverging:()=>Kw,stackOffsetExpand:()=>Zw,stackOffsetNone:()=>Ww,stackOffsetSilhouette:()=>Qw,stackOffsetWiggle:()=>Jw,stackOrderAppearance:()=>tk,stackOrderAscending:()=>nk,stackOrderDescending:()=>ik,stackOrderInsideOut:()=>ak,stackOrderNone:()=>Vw,stackOrderReverse:()=>ok,stratify:()=>hp,style:()=>Rt,sum:()=>$,svg:()=>Ls,symbol:()=>rw,symbolCircle:()=>Yx,symbolCross:()=>jx,symbolDiamond:()=>$x,symbolSquare:()=>Gx,symbolStar:()=>Vx,symbolTriangle:()=>Zx,symbolWye:()=>ew,symbols:()=>nw,text:()=>xs,thresholdFreedmanDiaconis:()=>B,thresholdScott:()=>O,thresholdSturges:()=>N,tickFormat:()=>Cg,tickIncrement:()=>A,tickStep:()=>M,ticks:()=>S,timeDay:()=>Ay,timeDays:()=>My,timeFormat:()=>pm,timeFormatDefaultLocale:()=>Iv,timeFormatLocale:()=>fm,timeFriday:()=>vy,timeFridays:()=>Ey,timeHour:()=>Dy,timeHours:()=>Ly,timeInterval:()=>ty,timeMillisecond:()=>jy,timeMilliseconds:()=>Uy,timeMinute:()=>Oy,timeMinutes:()=>Iy,timeMonday:()=>py,timeMondays:()=>xy,timeMonth:()=>ay,timeMonths:()=>oy,timeParse:()=>gm,timeSaturday:()=>by,timeSaturdays:()=>Cy,timeSecond:()=>Fy,timeSeconds:()=>Py,timeSunday:()=>dy,timeSundays:()=>_y,timeThursday:()=>my,timeThursdays:()=>Ty,timeTuesday:()=>gy,timeTuesdays:()=>wy,timeWednesday:()=>yy,timeWednesdays:()=>ky,timeWeek:()=>dy,timeWeeks:()=>_y,timeYear:()=>ny,timeYears:()=>ry,timeout:()=>Qn,timer:()=>Vn,timerFlush:()=>Gn,touch:()=>Ln,touches:()=>q_,transition:()=>qr,transpose:()=>q,tree:()=>vp,treemap:()=>kp,treemapBinary:()=>Tp,treemapDice:()=>ap,treemapResquarify:()=>Cp,treemapSlice:()=>bp,treemapSliceDice:()=>Ep,treemapSquarify:()=>wp,tsv:()=>Es,tsvFormat:()=>Lo,tsvFormatBody:()=>Bo,tsvFormatRow:()=>Io,tsvFormatRows:()=>Oo,tsvFormatValue:()=>Ro,tsvParse:()=>No,tsvParseRows:()=>Do,utcDay:()=>im,utcDays:()=>am,utcFormat:()=>ym,utcFriday:()=>Gy,utcFridays:()=>em,utcHour:()=>Hv,utcHours:()=>Wv,utcMillisecond:()=>jy,utcMilliseconds:()=>Uy,utcMinute:()=>Gv,utcMinutes:()=>Xv,utcMonday:()=>qy,utcMondays:()=>Ky,utcMonth:()=>zv,utcMonths:()=>$v,utcParse:()=>mm,utcSaturday:()=>Xy,utcSaturdays:()=>nm,utcSecond:()=>Fy,utcSeconds:()=>Py,utcSunday:()=>$y,utcSundays:()=>Zy,utcThursday:()=>Vy,utcThursdays:()=>tm,utcTuesday:()=>Hy,utcTuesdays:()=>Qy,utcWednesday:()=>Wy,utcWednesdays:()=>Jy,utcWeek:()=>$y,utcWeeks:()=>Zy,utcYear:()=>sm,utcYears:()=>cm,values:()=>da,variance:()=>g,version:()=>r,voronoi:()=>Qk,window:()=>Lt,xml:()=>Ns,zip:()=>W,zoom:()=>fT,zoomIdentity:()=>nT,zoomTransform:()=>rT});var r="5.16.0";function i(t,e){return te?1:t>=e?0:NaN}function a(t){var e;return 1===t.length&&(e=t,t=function(t,n){return i(e(t),n)}),{left:function(e,n,r,i){for(null==r&&(r=0),null==i&&(i=e.length);r>>1;t(e[a],n)<0?r=a+1:i=a}return r},right:function(e,n,r,i){for(null==r&&(r=0),null==i&&(i=e.length);r>>1;t(e[a],n)>0?i=a:r=a+1}return r}}}var o=a(i),s=o.right,c=o.left;const u=s;function l(t,e){null==e&&(e=h);for(var n=0,r=t.length-1,i=t[0],a=new Array(r<0?0:r);nt?1:e>=t?0:NaN}function p(t){return null===t?NaN:+t}function g(t,e){var n,r,i=t.length,a=0,o=-1,s=0,c=0;if(null==e)for(;++o1)return c/(a-1)}function y(t,e){var n=g(t,e);return n?Math.sqrt(n):n}function m(t,e){var n,r,i,a=t.length,o=-1;if(null==e){for(;++o=n)for(r=i=n;++on&&(r=n),i=n)for(r=i=n;++on&&(r=n),i0)return[t];if((r=e0)for(t=Math.ceil(t/o),e=Math.floor(e/o),a=new Array(i=Math.ceil(e-t+1));++s=0?(a>=T?10:a>=E?5:a>=C?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=T?10:a>=E?5:a>=C?2:1)}function M(t,e,n){var r=Math.abs(e-t)/Math.max(0,n),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),a=r/i;return a>=T?i*=10:a>=E?i*=5:a>=C&&(i*=2),eh;)f.pop(),--d;var p,g=new Array(d+1);for(i=0;i<=d;++i)(p=g[i]=[]).x0=i>0?f[i-1]:l,p.x1=i=1)return+n(t[r-1],r-1,t);var r,i=(r-1)*e,a=Math.floor(i),o=+n(t[a],a,t);return o+(+n(t[a+1],a+1,t)-o)*(i-a)}}function B(t,e,n){return t=_.call(t,p).sort(i),Math.ceil((n-e)/(2*(L(t,.75)-L(t,.25))*Math.pow(t.length,-1/3)))}function O(t,e,n){return Math.ceil((n-e)/(3.5*y(t)*Math.pow(t.length,-1/3)))}function I(t,e){var n,r,i=t.length,a=-1;if(null==e){for(;++a=n)for(r=n;++ar&&(r=n)}else for(;++a=n)for(r=n;++ar&&(r=n);return r}function R(t,e){var n,r=t.length,i=r,a=-1,o=0;if(null==e)for(;++a=0;)for(e=(r=t[i]).length;--e>=0;)n[--o]=r[e];return n}function Y(t,e){var n,r,i=t.length,a=-1;if(null==e){for(;++a=n)for(r=n;++an&&(r=n)}else for(;++a=n)for(r=n;++an&&(r=n);return r}function j(t,e){for(var n=e.length,r=new Array(n);n--;)r[n]=t[e[n]];return r}function U(t,e){if(n=t.length){var n,r,a=0,o=0,s=t[o];for(null==e&&(e=i);++a=0&&(n=t.slice(r+1),t=t.slice(0,r)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))}function lt(t,e){for(var n,r=0,i=t.length;r0)for(var n,r,i=new Array(n),a=0;ae?1:t>=e?0:NaN}bt.prototype={constructor:bt,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var kt="http://www.w3.org/1999/xhtml";const Tt={svg:"http://www.w3.org/2000/svg",xhtml:kt,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Et(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),Tt.hasOwnProperty(e)?{space:Tt[e],local:t}:t}function Ct(t){return function(){this.removeAttribute(t)}}function St(t){return function(){this.removeAttributeNS(t.space,t.local)}}function At(t,e){return function(){this.setAttribute(t,e)}}function Mt(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function Nt(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}}function Dt(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}}function Lt(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function Bt(t){return function(){this.style.removeProperty(t)}}function Ot(t,e,n){return function(){this.style.setProperty(t,e,n)}}function It(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}}function Rt(t,e){return t.style.getPropertyValue(e)||Lt(t).getComputedStyle(t,null).getPropertyValue(e)}function Ft(t){return function(){delete this[t]}}function Pt(t,e){return function(){this[t]=e}}function Yt(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}}function jt(t){return t.trim().split(/^|\s+/)}function Ut(t){return t.classList||new zt(t)}function zt(t){this._node=t,this._names=jt(t.getAttribute("class")||"")}function $t(t,e){for(var n=Ut(t),r=-1,i=e.length;++r=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var ue={},le=null;function he(t,e,n){return t=fe(t,e,n),function(e){var n=e.relatedTarget;n&&(n===this||8&n.compareDocumentPosition(this))||t.call(this,e)}}function fe(t,e,n){return function(r){var i=le;le=r;try{t.call(this,this.__data__,e,n)}finally{le=i}}}function de(t){return t.trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");return n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}function pe(t){return function(){var e=this.__on;if(e){for(var n,r=0,i=-1,a=e.length;r=x&&(x=_+1);!(b=m[x])&&++x=0;)(r=i[a])&&(o&&4^r.compareDocumentPosition(o)&&o.parentNode.insertBefore(r,o),o=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=wt);for(var n=this._groups,r=n.length,i=new Array(r),a=0;a1?this.each((null==e?Bt:"function"==typeof e?It:Ot)(t,e,null==n?"":n)):Rt(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?Ft:"function"==typeof e?Yt:Pt)(t,e)):this.node()[t]},classed:function(t,e){var n=jt(t+"");if(arguments.length<2){for(var r=Ut(this.node()),i=-1,a=n.length;++i>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?Xe(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?Xe(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=Pe.exec(t))?new Qe(e[1],e[2],e[3],1):(e=Ye.exec(t))?new Qe(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=je.exec(t))?Xe(e[1],e[2],e[3],e[4]):(e=Ue.exec(t))?Xe(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=ze.exec(t))?nn(e[1],e[2]/100,e[3]/100,1):(e=$e.exec(t))?nn(e[1],e[2]/100,e[3]/100,e[4]):qe.hasOwnProperty(t)?Ge(qe[t]):"transparent"===t?new Qe(NaN,NaN,NaN,0):null}function Ge(t){return new Qe(t>>16&255,t>>8&255,255&t,1)}function Xe(t,e,n,r){return r<=0&&(t=e=n=NaN),new Qe(t,e,n,r)}function Ze(t){return t instanceof De||(t=Ve(t)),t?new Qe((t=t.rgb()).r,t.g,t.b,t.opacity):new Qe}function Ke(t,e,n,r){return 1===arguments.length?Ze(t):new Qe(t,e,n,null==r?1:r)}function Qe(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r}function Je(){return"#"+en(this.r)+en(this.g)+en(this.b)}function tn(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function en(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function nn(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new on(t,e,n,r)}function rn(t){if(t instanceof on)return new on(t.h,t.s,t.l,t.opacity);if(t instanceof De||(t=Ve(t)),!t)return new on;if(t instanceof on)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),a=Math.max(e,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=e===a?(n-r)/s+6*(n0&&c<1?0:o,new on(o,s,c,t.opacity)}function an(t,e,n,r){return 1===arguments.length?rn(t):new on(t,e,n,null==r?1:r)}function on(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r}function sn(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}function cn(t,e,n,r,i){var a=t*t,o=a*t;return((1-3*t+3*a-o)*e+(4-6*a+3*o)*n+(1+3*t+3*a-3*o)*r+o*i)/6}function un(t){var e=t.length-1;return function(n){var r=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),i=t[r],a=t[r+1],o=r>0?t[r-1]:2*i-a,s=r180||n<-180?n-360*Math.round(n/360):n):hn(isNaN(t)?e:t)}function pn(t,e){var n=e-t;return n?fn(t,n):hn(isNaN(t)?e:t)}Me(De,Ve,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:He,formatHex:He,formatHsl:function(){return rn(this).formatHsl()},formatRgb:We,toString:We}),Me(Qe,Ke,Ne(De,{brighter:function(t){return t=null==t?Be:Math.pow(Be,t),new Qe(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?Le:Math.pow(Le,t),new Qe(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Je,formatHex:Je,formatRgb:tn,toString:tn})),Me(on,an,Ne(De,{brighter:function(t){return t=null==t?Be:Math.pow(Be,t),new on(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?Le:Math.pow(Le,t),new on(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new Qe(sn(t>=240?t-240:t+120,i,r),sn(t,i,r),sn(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const gn=function t(e){var n=function(t){return 1==(t=+t)?pn:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):hn(isNaN(e)?n:e)}}(e);function r(t,e){var r=n((t=Ke(t)).r,(e=Ke(e)).r),i=n(t.g,e.g),a=n(t.b,e.b),o=pn(t.opacity,e.opacity);return function(e){return t.r=r(e),t.g=i(e),t.b=a(e),t.opacity=o(e),t+""}}return r.gamma=t,r}(1);function yn(t){return function(e){var n,r,i=e.length,a=new Array(i),o=new Array(i),s=new Array(i);for(n=0;na&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(n=n[0])===(r=r[0])?s[o]?s[o]+=r:s[++o]=r:(s[++o]=null,c.push({i:o,x:Tn(n,r)})),a=Sn.lastIndex;return a=0&&e._call.call(null,t),e=e._next;--Rn}function Xn(){jn=(Yn=zn.now())+Un,Rn=Fn=0;try{Gn()}finally{Rn=0,function(){for(var t,e,n=On,r=1/0;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:On=e);In=t,Kn(r)}(),jn=0}}function Zn(){var t=zn.now(),e=t-Yn;e>1e3&&(Un-=e,Yn=t)}function Kn(t){Rn||(Fn&&(Fn=clearTimeout(Fn)),t-jn>24?(t<1/0&&(Fn=setTimeout(Xn,t-zn.now()-Un)),Pn&&(Pn=clearInterval(Pn))):(Pn||(Yn=zn.now(),Pn=setInterval(Zn,1e3)),Rn=1,$n(Xn)))}function Qn(t,e,n){var r=new Wn;return e=null==e?0:+e,r.restart((function(n){r.stop(),t(n+e)}),e,n),r}Wn.prototype=Vn.prototype={constructor:Wn,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?qn():+n)+(null==e?0:+e),this._next||In===this||(In?In._next=this:On=this,In=this),this._call=t,this._time=n,Kn()},stop:function(){this._call&&(this._call=null,this._time=1/0,Kn())}};var Jn=ft("start","end","cancel","interrupt"),tr=[];function er(t,e,n,r,i,a){var o=t.__transition;if(o){if(n in o)return}else t.__transition={};!function(t,e,n){var r,i=t.__transition;function a(c){var u,l,h,f;if(1!==n.state)return s();for(u in i)if((f=i[u]).name===n.name){if(3===f.state)return Qn(a);4===f.state?(f.state=6,f.timer.stop(),f.on.call("interrupt",t,t.__data__,f.index,f.group),delete i[u]):+u0)throw new Error("too late; already scheduled");return n}function rr(t,e){var n=ir(t,e);if(n.state>3)throw new Error("too late; already running");return n}function ir(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function ar(t,e){var n,r,i,a=t.__transition,o=!0;if(a){for(i in e=null==e?null:e+"",a)(n=a[i]).name===e?(r=n.state>2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete a[i]):o=!1;o&&delete t.__transition}}var or,sr,cr,ur,lr=180/Math.PI,hr={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function fr(t,e,n,r,i,a){var o,s,c;return(o=Math.sqrt(t*t+e*e))&&(t/=o,e/=o),(c=t*n+e*r)&&(n-=t*c,r-=e*c),(s=Math.sqrt(n*n+r*r))&&(n/=s,r/=s,c/=s),t*r180?e+=360:e-t>180&&(t+=360),a.push({i:n.push(i(n)+"rotate(",null,r)-2,x:Tn(t,e)})):e&&n.push(i(n)+"rotate("+e+r)}(a.rotate,o.rotate,s,c),function(t,e,n,a){t!==e?a.push({i:n.push(i(n)+"skewX(",null,r)-2,x:Tn(t,e)}):e&&n.push(i(n)+"skewX("+e+r)}(a.skewX,o.skewX,s,c),function(t,e,n,r,a,o){if(t!==n||e!==r){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:Tn(t,n)},{i:s-2,x:Tn(e,r)})}else 1===n&&1===r||a.push(i(a)+"scale("+n+","+r+")")}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,c),a=o=null,function(t){for(var e,n=-1,r=c.length;++n=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?nr:rr;return function(){var o=a(this,t),s=o.on;s!==r&&(i=(r=s).copy()).on(e,n),o.on=i}}var Rr=ke.prototype.constructor;function Fr(t){return function(){this.style.removeProperty(t)}}function Pr(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n)}}function Yr(t,e,n){var r,i;function a(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&Pr(t,a,n)),r}return a._value=e,a}function jr(t){return function(e){this.textContent=t.call(this,e)}}function Ur(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&jr(r)),e}return r._value=t,r}var zr=0;function $r(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r}function qr(t){return ke().transition(t)}function Hr(){return++zr}var Wr=ke.prototype;function Vr(t){return t*t*t}function Gr(t){return--t*t*t+1}function Xr(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}$r.prototype=qr.prototype={constructor:$r,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=pt(t));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o1&&n.name===e)return new $r([[t]],Qr,e,+r);return null}function ti(t){return function(){return t}}function ei(t,e,n){this.target=t,this.type=e,this.selection=n}function ni(){le.stopImmediatePropagation()}function ri(){le.preventDefault(),le.stopImmediatePropagation()}var ii={name:"drag"},ai={name:"space"},oi={name:"handle"},si={name:"center"};function ci(t){return[+t[0],+t[1]]}function ui(t){return[ci(t[0]),ci(t[1])]}function li(t){return function(e){return Ln(e,le.touches,t)}}var hi={name:"x",handles:["w","e"].map(bi),input:function(t,e){return null==t?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},fi={name:"y",handles:["n","s"].map(bi),input:function(t,e){return null==t?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},di={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(bi),input:function(t){return null==t?null:ui(t)},output:function(t){return t}},pi={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},gi={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},yi={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},mi={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},vi={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function bi(t){return{type:t}}function _i(){return!le.ctrlKey&&!le.button}function xi(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function wi(){return navigator.maxTouchPoints||"ontouchstart"in this}function ki(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function Ti(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}function Ei(t){var e=t.__brush;return e?e.dim.output(e.selection):null}function Ci(){return Mi(hi)}function Si(){return Mi(fi)}function Ai(){return Mi(di)}function Mi(t){var e,n=xi,r=_i,i=wi,a=!0,o=ft("start","brush","end"),s=6;function c(e){var n=e.property("__brush",g).selectAll(".overlay").data([bi("overlay")]);n.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",pi.overlay).merge(n).each((function(){var t=ki(this).extent;Te(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),e.selectAll(".selection").data([bi("selection")]).enter().append("rect").attr("class","selection").attr("cursor",pi.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=e.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return pi[t.type]})),e.each(u).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",f).filter(i).on("touchstart.brush",f).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function u(){var t=Te(this),e=ki(this).selection;e?(t.selectAll(".selection").style("display",null).attr("x",e[0][0]).attr("y",e[0][1]).attr("width",e[1][0]-e[0][0]).attr("height",e[1][1]-e[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?e[1][0]-s/2:e[0][0]-s/2})).attr("y",(function(t){return"s"===t.type[0]?e[1][1]-s/2:e[0][1]-s/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?e[1][0]-e[0][0]+s:s})).attr("height",(function(t){return"e"===t.type||"w"===t.type?e[1][1]-e[0][1]+s:s}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function l(t,e,n){var r=t.__brush.emitter;return!r||n&&r.clean?new h(t,e,n):r}function h(t,e,n){this.that=t,this.args=e,this.state=t.__brush,this.active=0,this.clean=n}function f(){if((!e||le.touches)&&r.apply(this,arguments)){var n,i,o,s,c,h,f,d,p,g,y,m=this,v=le.target.__data__.type,b="selection"===(a&&le.metaKey?v="overlay":v)?ii:a&&le.altKey?si:oi,_=t===fi?null:mi[v],x=t===hi?null:vi[v],w=ki(m),k=w.extent,T=w.selection,E=k[0][0],C=k[0][1],S=k[1][0],A=k[1][1],M=0,N=0,D=_&&x&&a&&le.shiftKey,L=le.touches?li(le.changedTouches[0].identifier):Bn,B=L(m),O=B,I=l(m,arguments,!0).beforestart();"overlay"===v?(T&&(p=!0),w.selection=T=[[n=t===fi?E:B[0],o=t===hi?C:B[1]],[c=t===fi?S:n,f=t===hi?A:o]]):(n=T[0][0],o=T[0][1],c=T[1][0],f=T[1][1]),i=n,s=o,h=c,d=f;var R=Te(m).attr("pointer-events","none"),F=R.selectAll(".overlay").attr("cursor",pi[v]);if(le.touches)I.moved=Y,I.ended=U;else{var P=Te(le.view).on("mousemove.brush",Y,!0).on("mouseup.brush",U,!0);a&&P.on("keydown.brush",z,!0).on("keyup.brush",$,!0),Se(le.view)}ni(),ar(m),u.call(m),I.start()}function Y(){var t=L(m);!D||g||y||(Math.abs(t[0]-O[0])>Math.abs(t[1]-O[1])?y=!0:g=!0),O=t,p=!0,ri(),j()}function j(){var t;switch(M=O[0]-B[0],N=O[1]-B[1],b){case ai:case ii:_&&(M=Math.max(E-n,Math.min(S-c,M)),i=n+M,h=c+M),x&&(N=Math.max(C-o,Math.min(A-f,N)),s=o+N,d=f+N);break;case oi:_<0?(M=Math.max(E-n,Math.min(S-n,M)),i=n+M,h=c):_>0&&(M=Math.max(E-c,Math.min(S-c,M)),i=n,h=c+M),x<0?(N=Math.max(C-o,Math.min(A-o,N)),s=o+N,d=f):x>0&&(N=Math.max(C-f,Math.min(A-f,N)),s=o,d=f+N);break;case si:_&&(i=Math.max(E,Math.min(S,n-M*_)),h=Math.max(E,Math.min(S,c+M*_))),x&&(s=Math.max(C,Math.min(A,o-N*x)),d=Math.max(C,Math.min(A,f+N*x)))}h0&&(n=i-M),x<0?f=d-N:x>0&&(o=s-N),b=ai,F.attr("cursor",pi.selection),j());break;default:return}ri()}function $(){switch(le.keyCode){case 16:D&&(g=y=D=!1,j());break;case 18:b===si&&(_<0?c=h:_>0&&(n=i),x<0?f=d:x>0&&(o=s),b=oi,j());break;case 32:b===ai&&(le.altKey?(_&&(c=h-M*_,n=i+M*_),x&&(f=d-N*x,o=s+N*x),b=si):(_<0?c=h:_>0&&(n=i),x<0?f=d:x>0&&(o=s),b=oi),F.attr("cursor",pi[v]),j());break;default:return}ri()}}function d(){l(this,arguments).moved()}function p(){l(this,arguments).ended()}function g(){var e=this.__brush||{selection:null};return e.extent=ui(n.apply(this,arguments)),e.dim=t,e}return c.move=function(e,n){e.selection?e.on("start.brush",(function(){l(this,arguments).beforestart().start()})).on("interrupt.brush end.brush",(function(){l(this,arguments).end()})).tween("brush",(function(){var e=this,r=e.__brush,i=l(e,arguments),a=r.selection,o=t.input("function"==typeof n?n.apply(this,arguments):n,r.extent),s=Mn(a,o);function c(t){r.selection=1===t&&null===o?null:s(t),u.call(e),i.brush()}return null!==a&&null!==o?c:c(1)})):e.each((function(){var e=this,r=arguments,i=e.__brush,a=t.input("function"==typeof n?n.apply(e,r):n,i.extent),o=l(e,r).beforestart();ar(e),i.selection=null===a?null:a,u.call(e),o.start().brush().end()}))},c.clear=function(t){c.move(t,null)},h.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(){return this.starting?(this.starting=!1,this.emit("start")):this.emit("brush"),this},brush:function(){return this.emit("brush"),this},end:function(){return 0==--this.active&&(delete this.state.emitter,this.emit("end")),this},emit:function(e){ye(new ei(c,e,t.output(this.state.selection)),o.apply,o,[e,this.that,this.args])}},c.extent=function(t){return arguments.length?(n="function"==typeof t?t:ti(ui(t)),c):n},c.filter=function(t){return arguments.length?(r="function"==typeof t?t:ti(!!t),c):r},c.touchable=function(t){return arguments.length?(i="function"==typeof t?t:ti(!!t),c):i},c.handleSize=function(t){return arguments.length?(s=+t,c):s},c.keyModifiers=function(t){return arguments.length?(a=!!t,c):a},c.on=function(){var t=o.on.apply(o,arguments);return t===o?c:t},c}var Ni=Math.cos,Di=Math.sin,Li=Math.PI,Bi=Li/2,Oi=2*Li,Ii=Math.max;function Ri(t){return function(e,n){return t(e.source.value+e.target.value,n.source.value+n.target.value)}}function Fi(){var t=0,e=null,n=null,r=null;function i(i){var a,o,s,c,u,l,h=i.length,f=[],d=k(h),p=[],g=[],y=g.groups=new Array(h),m=new Array(h*h);for(a=0,u=-1;++uzi)if(Math.abs(l*s-c*u)>zi&&i){var f=n-a,d=r-o,p=s*s+c*c,g=f*f+d*d,y=Math.sqrt(p),m=Math.sqrt(h),v=i*Math.tan((ji-Math.acos((p+h-g)/(2*y*m)))/2),b=v/m,_=v/y;Math.abs(b-1)>zi&&(this._+="L"+(t+b*u)+","+(e+b*l)),this._+="A"+i+","+i+",0,0,"+ +(l*f>u*d)+","+(this._x1=t+_*s)+","+(this._y1=e+_*c)}else this._+="L"+(this._x1=t)+","+(this._y1=e)},arc:function(t,e,n,r,i,a){t=+t,e=+e,a=!!a;var o=(n=+n)*Math.cos(r),s=n*Math.sin(r),c=t+o,u=e+s,l=1^a,h=a?r-i:i-r;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+c+","+u:(Math.abs(this._x1-c)>zi||Math.abs(this._y1-u)>zi)&&(this._+="L"+c+","+u),n&&(h<0&&(h=h%Ui+Ui),h>$i?this._+="A"+n+","+n+",0,1,"+l+","+(t-o)+","+(e-s)+"A"+n+","+n+",0,1,"+l+","+(this._x1=c)+","+(this._y1=u):h>zi&&(this._+="A"+n+","+n+",0,"+ +(h>=ji)+","+l+","+(this._x1=t+n*Math.cos(i))+","+(this._y1=e+n*Math.sin(i))))},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z"},toString:function(){return this._}};const Wi=Hi;function Vi(t){return t.source}function Gi(t){return t.target}function Xi(t){return t.radius}function Zi(t){return t.startAngle}function Ki(t){return t.endAngle}function Qi(){var t=Vi,e=Gi,n=Xi,r=Zi,i=Ki,a=null;function o(){var o,s=Pi.call(arguments),c=t.apply(this,s),u=e.apply(this,s),l=+n.apply(this,(s[0]=c,s)),h=r.apply(this,s)-Bi,f=i.apply(this,s)-Bi,d=l*Ni(h),p=l*Di(h),g=+n.apply(this,(s[0]=u,s)),y=r.apply(this,s)-Bi,m=i.apply(this,s)-Bi;if(a||(a=o=Wi()),a.moveTo(d,p),a.arc(0,0,l,h,f),h===y&&f===m||(a.quadraticCurveTo(0,0,g*Ni(y),g*Di(y)),a.arc(0,0,g,y,m)),a.quadraticCurveTo(0,0,d,p),a.closePath(),o)return a=null,o+""||null}return o.radius=function(t){return arguments.length?(n="function"==typeof t?t:Yi(+t),o):n},o.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:Yi(+t),o):r},o.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:Yi(+t),o):i},o.source=function(e){return arguments.length?(t=e,o):t},o.target=function(t){return arguments.length?(e=t,o):e},o.context=function(t){return arguments.length?(a=null==t?null:t,o):a},o}var Ji="$";function ta(){}function ea(t,e){var n=new ta;if(t instanceof ta)t.each((function(t,e){n.set(e,t)}));else if(Array.isArray(t)){var r,i=-1,a=t.length;if(null==e)for(;++i=r.length)return null!=t&&n.sort(t),null!=e?e(n):n;for(var c,u,l,h=-1,f=n.length,d=r[i++],p=na(),g=o();++hr.length)return t;var a,s=i[n-1];return null!=e&&n>=r.length?a=t.entries():(a=[],t.each((function(t,e){a.push({key:e,values:o(t,n)})}))),null!=s?a.sort((function(t,e){return s(t.key,e.key)})):a}return n={object:function(t){return a(t,0,ia,aa)},map:function(t){return a(t,0,oa,sa)},entries:function(t){return o(a(t,0,oa,sa),0)},key:function(t){return r.push(t),n},sortKeys:function(t){return i[r.length-1]=t,n},sortValues:function(e){return t=e,n},rollup:function(t){return e=t,n}}}function ia(){return{}}function aa(t,e,n){t[e]=n}function oa(){return na()}function sa(t,e,n){t.set(e,n)}function ca(){}var ua=na.prototype;function la(t,e){var n=new ca;if(t instanceof ca)t.each((function(t){n.add(t)}));else if(t){var r=-1,i=t.length;if(null==e)for(;++r.008856451679035631?Math.pow(t,1/3):t/xa+ba}function Sa(t){return t>_a?t*t*t:xa*(t-ba)}function Aa(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function Ma(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Na(t){if(t instanceof Ba)return new Ba(t.h,t.c,t.l,t.opacity);if(t instanceof Ea||(t=wa(t)),0===t.a&&0===t.b)return new Ba(NaN,0r!=d>r&&n<(f-u)*(r-l)/(d-l)+u&&(i=-i)}return i}function Ka(t,e,n){var r,i,a,o;return function(t,e,n){return(e[0]-t[0])*(n[1]-t[1])==(n[0]-t[0])*(e[1]-t[1])}(t,e,n)&&(i=t[r=+(t[0]===e[0])],a=n[r],o=e[r],i<=a&&a<=o||o<=a&&a<=i)}function Qa(){}var Ja=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function to(){var t=1,e=1,n=N,r=s;function i(t){var e=n(t);if(Array.isArray(e))e=e.slice().sort(Va);else{var r=m(t),i=r[0],o=r[1];e=M(i,o,e),e=k(Math.floor(i/e)*e,Math.floor(o/e)*e,e)}return e.map((function(e){return a(t,e)}))}function a(n,i){var a=[],s=[];return function(n,r,i){var a,s,c,u,l,h,f=new Array,d=new Array;for(a=s=-1,u=n[0]>=r,Ja[u<<1].forEach(p);++a=r,Ja[c|u<<1].forEach(p);for(Ja[u<<0].forEach(p);++s=r,l=n[s*t]>=r,Ja[u<<1|l<<2].forEach(p);++a=r,h=l,l=n[s*t+a+1]>=r,Ja[c|u<<1|l<<2|h<<3].forEach(p);Ja[u|l<<3].forEach(p)}for(a=-1,l=n[s*t]>=r,Ja[l<<2].forEach(p);++a=r,Ja[l<<2|h<<3].forEach(p);function p(t){var e,n,r=[t[0][0]+a,t[0][1]+s],c=[t[1][0]+a,t[1][1]+s],u=o(r),l=o(c);(e=d[u])?(n=f[l])?(delete d[e.end],delete f[n.start],e===n?(e.ring.push(c),i(e.ring)):f[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete d[e.end],e.ring.push(c),d[e.end=l]=e):(e=f[l])?(n=d[u])?(delete f[e.start],delete d[n.end],e===n?(e.ring.push(c),i(e.ring)):f[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete f[e.start],e.ring.unshift(r),f[e.start=u]=e):f[u]=d[l]={start:u,end:l,ring:[r,c]}}Ja[l<<3].forEach(p)}(n,i,(function(t){r(t,n,i),function(t){for(var e=0,n=t.length,r=t[n-1][1]*t[0][0]-t[n-1][0]*t[0][1];++e0?a.push([t]):s.push(t)})),s.forEach((function(t){for(var e,n=0,r=a.length;n0&&o0&&s0&&a>0))throw new Error("invalid size");return t=r,e=a,i},i.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?Ga(Wa.call(t)):Ga(t),i):n},i.smooth=function(t){return arguments.length?(r=t?s:Qa,i):r===s},i}function eo(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o=n&&(s>=a&&(c-=t.data[s-a+o*r]),e.data[s-n+o*r]=c/Math.min(s+1,r-1+a-s,a))}function no(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o=n&&(s>=a&&(c-=t.data[o+(s-a)*r]),e.data[o+(s-n)*r]=c/Math.min(s+1,i-1+a-s,a))}function ro(t){return t[0]}function io(t){return t[1]}function ao(){return 1}function oo(){var t=ro,e=io,n=ao,r=960,i=500,a=20,o=2,s=3*a,c=r+2*s>>o,u=i+2*s>>o,l=Ga(20);function h(r){var i=new Float32Array(c*u),h=new Float32Array(c*u);r.forEach((function(r,a,l){var h=+t(r,a,l)+s>>o,f=+e(r,a,l)+s>>o,d=+n(r,a,l);h>=0&&h=0&&f>o),no({width:c,height:u,data:h},{width:c,height:u,data:i},a>>o),eo({width:c,height:u,data:i},{width:c,height:u,data:h},a>>o),no({width:c,height:u,data:h},{width:c,height:u,data:i},a>>o),eo({width:c,height:u,data:i},{width:c,height:u,data:h},a>>o),no({width:c,height:u,data:h},{width:c,height:u,data:i},a>>o);var d=l(i);if(!Array.isArray(d)){var p=I(i);d=M(0,p,d),(d=k(0,Math.floor(p/d)*d,d)).shift()}return to().thresholds(d).size([c,u])(i).map(f)}function f(t){return t.value*=Math.pow(2,-2*o),t.coordinates.forEach(d),t}function d(t){t.forEach(p)}function p(t){t.forEach(g)}function g(t){t[0]=t[0]*Math.pow(2,o)-s,t[1]=t[1]*Math.pow(2,o)-s}function y(){return c=r+2*(s=3*a)>>o,u=i+2*s>>o,h}return h.x=function(e){return arguments.length?(t="function"==typeof e?e:Ga(+e),h):t},h.y=function(t){return arguments.length?(e="function"==typeof t?t:Ga(+t),h):e},h.weight=function(t){return arguments.length?(n="function"==typeof t?t:Ga(+t),h):n},h.size=function(t){if(!arguments.length)return[r,i];var e=Math.ceil(t[0]),n=Math.ceil(t[1]);if(!(e>=0||e>=0))throw new Error("invalid size");return r=e,i=n,y()},h.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return o=Math.floor(Math.log(t)/Math.LN2),y()},h.thresholds=function(t){return arguments.length?(l="function"==typeof t?t:Array.isArray(t)?Ga(Wa.call(t)):Ga(t),h):l},h.bandwidth=function(t){if(!arguments.length)return Math.sqrt(a*(a+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return a=Math.round((Math.sqrt(4*t*t+1)-1)/2),y()},h}function so(t){return function(){return t}}function co(t,e,n,r,i,a,o,s,c,u){this.target=t,this.type=e,this.subject=n,this.identifier=r,this.active=i,this.x=a,this.y=o,this.dx=s,this.dy=c,this._=u}function uo(){return!le.ctrlKey&&!le.button}function lo(){return this.parentNode}function ho(t){return null==t?{x:le.x,y:le.y}:t}function fo(){return navigator.maxTouchPoints||"ontouchstart"in this}function po(){var t,e,n,r,i=uo,a=lo,o=ho,s=fo,c={},u=ft("start","drag","end"),l=0,h=0;function f(t){t.on("mousedown.drag",d).filter(s).on("touchstart.drag",y).on("touchmove.drag",m).on("touchend.drag touchcancel.drag",v).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(){if(!r&&i.apply(this,arguments)){var o=b("mouse",a.apply(this,arguments),Bn,this,arguments);o&&(Te(le.view).on("mousemove.drag",p,!0).on("mouseup.drag",g,!0),Se(le.view),Ee(),n=!1,t=le.clientX,e=le.clientY,o("start"))}}function p(){if(Ce(),!n){var r=le.clientX-t,i=le.clientY-e;n=r*r+i*i>h}c.mouse("drag")}function g(){Te(le.view).on("mousemove.drag mouseup.drag",null),Ae(le.view,n),Ce(),c.mouse("end")}function y(){if(i.apply(this,arguments)){var t,e,n=le.changedTouches,r=a.apply(this,arguments),o=n.length;for(t=0;t=a?c=!0:10===(r=t.charCodeAt(o++))?u=!0:13===r&&(u=!0,10===t.charCodeAt(o)&&++o),t.slice(i+1,e-1).replace(/""/g,'"')}for(;o9999?"+"+bo(t,6):bo(t,4)}(t.getUTCFullYear())+"-"+bo(t.getUTCMonth()+1,2)+"-"+bo(t.getUTCDate(),2)+(i?"T"+bo(e,2)+":"+bo(n,2)+":"+bo(r,2)+"."+bo(i,3)+"Z":r?"T"+bo(e,2)+":"+bo(n,2)+":"+bo(r,2)+"Z":n||e?"T"+bo(e,2)+":"+bo(n,2)+"Z":"")}(t):e.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t}return{parse:function(t,e){var n,i,a=r(t,(function(t,r){if(n)return n(t,r-1);i=t,n=e?function(t,e){var n=mo(t);return function(r,i){return e(n(r),i,t)}}(t,e):mo(t)}));return a.columns=i||[],a},parseRows:r,format:function(e,n){return null==n&&(n=vo(e)),[n.map(o).join(t)].concat(i(e,n)).join("\n")},formatBody:function(t,e){return null==e&&(e=vo(t)),i(t,e).join("\n")},formatRows:function(t){return t.map(a).join("\n")},formatRow:a,formatValue:o}}var xo=_o(","),wo=xo.parse,ko=xo.parseRows,To=xo.format,Eo=xo.formatBody,Co=xo.formatRows,So=xo.formatRow,Ao=xo.formatValue,Mo=_o("\t"),No=Mo.parse,Do=Mo.parseRows,Lo=Mo.format,Bo=Mo.formatBody,Oo=Mo.formatRows,Io=Mo.formatRow,Ro=Mo.formatValue;function Fo(t){for(var e in t){var n,r,i=t[e].trim();if(i)if("true"===i)i=!0;else if("false"===i)i=!1;else if("NaN"===i)i=NaN;else if(isNaN(n=+i)){if(!(r=i.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;Po&&r[4]&&!r[7]&&(i=i.replace(/-/g,"/").replace(/T/," ")),i=new Date(i)}else i=n;else i=null;t[e]=i}return t}var Po=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours();function Yo(t){return+t}function jo(t){return t*t}function Uo(t){return t*(2-t)}function zo(t){return((t*=2)<=1?t*t:--t*(2-t)+1)/2}var $o=function t(e){function n(t){return Math.pow(t,e)}return e=+e,n.exponent=t,n}(3),qo=function t(e){function n(t){return 1-Math.pow(1-t,e)}return e=+e,n.exponent=t,n}(3),Ho=function t(e){function n(t){return((t*=2)<=1?Math.pow(t,e):2-Math.pow(2-t,e))/2}return e=+e,n.exponent=t,n}(3),Wo=Math.PI,Vo=Wo/2;function Go(t){return 1==+t?1:1-Math.cos(t*Vo)}function Xo(t){return Math.sin(t*Vo)}function Zo(t){return(1-Math.cos(Wo*t))/2}function Ko(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}function Qo(t){return Ko(1-+t)}function Jo(t){return 1-Ko(t)}function ts(t){return((t*=2)<=1?Ko(1-t):2-Ko(t-1))/2}function es(t){return 1-Math.sqrt(1-t*t)}function ns(t){return Math.sqrt(1- --t*t)}function rs(t){return((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}var is=7.5625;function as(t){return 1-os(1-t)}function os(t){return(t=+t)<.36363636363636365?is*t*t:t<.7272727272727273?is*(t-=.5454545454545454)*t+.75:t<.9090909090909091?is*(t-=.8181818181818182)*t+.9375:is*(t-=.9545454545454546)*t+.984375}function ss(t){return((t*=2)<=1?1-os(1-t):os(t-1)+1)/2}var cs=1.70158,us=function t(e){function n(t){return(t=+t)*t*(e*(t-1)+t)}return e=+e,n.overshoot=t,n}(cs),ls=function t(e){function n(t){return--t*t*((t+1)*e+t)+1}return e=+e,n.overshoot=t,n}(cs),hs=function t(e){function n(t){return((t*=2)<1?t*t*((e+1)*t-e):(t-=2)*t*((e+1)*t+e)+2)/2}return e=+e,n.overshoot=t,n}(cs),fs=2*Math.PI,ds=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=fs);function i(t){return e*Ko(- --t)*Math.sin((r-t)/n)}return i.amplitude=function(e){return t(e,n*fs)},i.period=function(n){return t(e,n)},i}(1,.3),ps=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=fs);function i(t){return 1-e*Ko(t=+t)*Math.sin((t+r)/n)}return i.amplitude=function(e){return t(e,n*fs)},i.period=function(n){return t(e,n)},i}(1,.3),gs=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=fs);function i(t){return((t=2*t-1)<0?e*Ko(-t)*Math.sin((r-t)/n):2-e*Ko(t)*Math.sin((r+t)/n))/2}return i.amplitude=function(e){return t(e,n*fs)},i.period=function(n){return t(e,n)},i}(1,.3);function ys(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function ms(t,e){return fetch(t,e).then(ys)}function vs(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function bs(t,e){return fetch(t,e).then(vs)}function _s(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function xs(t,e){return fetch(t,e).then(_s)}function ws(t){return function(e,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=void 0),xs(e,n).then((function(e){return t(e,r)}))}}function ks(t,e,n,r){3===arguments.length&&"function"==typeof n&&(r=n,n=void 0);var i=_o(t);return xs(e,n).then((function(t){return i.parse(t,r)}))}var Ts=ws(wo),Es=ws(No);function Cs(t,e){return new Promise((function(n,r){var i=new Image;for(var a in e)i[a]=e[a];i.onerror=r,i.onload=function(){n(i)},i.src=t}))}function Ss(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function As(t,e){return fetch(t,e).then(Ss)}function Ms(t){return function(e,n){return xs(e,n).then((function(e){return(new DOMParser).parseFromString(e,t)}))}}const Ns=Ms("application/xml");var Ds=Ms("text/html"),Ls=Ms("image/svg+xml");function Bs(t,e){var n;function r(){var r,i,a=n.length,o=0,s=0;for(r=0;r=(a=(g+m)/2))?g=a:m=a,(l=n>=(o=(y+v)/2))?y=o:v=o,i=d,!(d=d[h=l<<1|u]))return i[h]=p,t;if(s=+t._x.call(null,d.data),c=+t._y.call(null,d.data),e===s&&n===c)return p.next=d,i?i[h]=p:t._root=p,t;do{i=i?i[h]=new Array(4):t._root=new Array(4),(u=e>=(a=(g+m)/2))?g=a:m=a,(l=n>=(o=(y+v)/2))?y=o:v=o}while((h=l<<1|u)==(f=(c>=o)<<1|s>=a));return i[f]=d,i[h]=p,t}function Fs(t,e,n,r,i){this.node=t,this.x0=e,this.y0=n,this.x1=r,this.y1=i}function Ps(t){return t[0]}function Ys(t){return t[1]}function js(t,e,n){var r=new Us(null==e?Ps:e,null==n?Ys:n,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Us(t,e,n,r,i,a){this._x=t,this._y=e,this._x0=n,this._y0=r,this._x1=i,this._y1=a,this._root=void 0}function zs(t){for(var e={data:t.data},n=e;t=t.next;)n=n.next={data:t.data};return e}var $s=js.prototype=Us.prototype;function qs(t){return t.x+t.vx}function Hs(t){return t.y+t.vy}function Ws(t){var e,n,r=1,i=1;function a(){for(var t,a,s,c,u,l,h,f=e.length,d=0;dc+d||iu+d||as.index){var p=c-o.x-o.vx,g=u-o.y-o.vy,y=p*p+g*g;yt.r&&(t.r=t[e].r)}function s(){if(e){var r,i,a=e.length;for(n=new Array(a),r=0;rl&&(l=r),ih&&(h=i));if(c>l||u>h)return this;for(this.cover(c,u).cover(l,h),n=0;nt||t>=i||r>e||e>=a;)switch(s=(ef||(a=c.y0)>d||(o=c.x1)=m)<<1|t>=y)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-u],p[p.length-1-u]=c)}else{var v=t-+this._x.call(null,g.data),b=e-+this._y.call(null,g.data),_=v*v+b*b;if(_=(s=(p+y)/2))?p=s:y=s,(l=o>=(c=(g+m)/2))?g=c:m=c,e=d,!(d=d[h=l<<1|u]))return this;if(!d.length)break;(e[h+1&3]||e[h+2&3]||e[h+3&3])&&(n=e,f=h)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):e?(i?e[h]=i:delete e[h],(d=e[0]||e[1]||e[2]||e[3])&&d===(e[3]||e[2]||e[1]||e[0])&&!d.length&&(n?n[f]=d:this._root=d),this):(this._root=i,this)},$s.removeAll=function(t){for(var e=0,n=t.length;e1?(null==n?s.remove(t):s.set(t,d(n)),e):s.get(t)},find:function(e,n,r){var i,a,o,s,c,u=0,l=t.length;for(null==r?r=1/0:r*=r,u=0;u1?(u.on(t,n),e):u.on(t)}}}function tc(){var t,e,n,r,i=Os(-30),a=1,o=1/0,s=.81;function c(r){var i,a=t.length,o=js(t,Zs,Ks).visitAfter(l);for(n=r,i=0;i=o)){(t.data!==e||t.next)&&(0===l&&(d+=(l=Is())*l),0===h&&(d+=(h=Is())*h),d1?r[0]+r.slice(2):r,+t.slice(n+1)]}function ac(t){return(t=ic(Math.abs(t)))?t[1]:NaN}var oc,sc=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function cc(t){if(!(e=sc.exec(t)))throw new Error("invalid format: "+t);var e;return new uc({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function uc(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function lc(t,e){var n=ic(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}cc.prototype=uc.prototype,uc.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};const hc={"%":function(t,e){return(100*t).toFixed(e)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},g:function(t,e){return t.toPrecision(e)},o:function(t){return Math.round(t).toString(8)},p:function(t,e){return lc(100*t,e)},r:lc,s:function(t,e){var n=ic(t,e);if(!n)return t+"";var r=n[0],i=n[1],a=i-(oc=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,o=r.length;return a===o?r:a>o?r+new Array(a-o+1).join("0"):a>0?r.slice(0,a)+"."+r.slice(a):"0."+new Array(1-a).join("0")+ic(t,Math.max(0,e+a-1))[0]},X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}};function fc(t){return t}var dc,pc,gc,yc=Array.prototype.map,mc=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function vc(t){var e,n,r=void 0===t.grouping||void 0===t.thousands?fc:(e=yc.call(t.grouping,Number),n=t.thousands+"",function(t,r){for(var i=t.length,a=[],o=0,s=e[0],c=0;i>0&&s>0&&(c+s+1>r&&(s=Math.max(1,r-c)),a.push(t.substring(i-=s,i+s)),!((c+=s+1)>r));)s=e[o=(o+1)%e.length];return a.reverse().join(n)}),i=void 0===t.currency?"":t.currency[0]+"",a=void 0===t.currency?"":t.currency[1]+"",o=void 0===t.decimal?".":t.decimal+"",s=void 0===t.numerals?fc:function(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}(yc.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",u=void 0===t.minus?"-":t.minus+"",l=void 0===t.nan?"NaN":t.nan+"";function h(t){var e=(t=cc(t)).fill,n=t.align,h=t.sign,f=t.symbol,d=t.zero,p=t.width,g=t.comma,y=t.precision,m=t.trim,v=t.type;"n"===v?(g=!0,v="g"):hc[v]||(void 0===y&&(y=12),m=!0,v="g"),(d||"0"===e&&"="===n)&&(d=!0,e="0",n="=");var b="$"===f?i:"#"===f&&/[boxX]/.test(v)?"0"+v.toLowerCase():"",_="$"===f?a:/[%p]/.test(v)?c:"",x=hc[v],w=/[defgprs%]/.test(v);function k(t){var i,a,c,f=b,k=_;if("c"===v)k=x(t)+k,t="";else{var T=(t=+t)<0||1/t<0;if(t=isNaN(t)?l:x(Math.abs(t),y),m&&(t=function(t){t:for(var e,n=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(e+1):t}(t)),T&&0==+t&&"+"!==h&&(T=!1),f=(T?"("===h?h:u:"-"===h||"("===h?"":h)+f,k=("s"===v?mc[8+oc/3]:"")+k+(T&&"("===h?")":""),w)for(i=-1,a=t.length;++i(c=t.charCodeAt(i))||c>57){k=(46===c?o+t.slice(i+1):t.slice(i))+k,t=t.slice(0,i);break}}g&&!d&&(t=r(t,1/0));var E=f.length+t.length+k.length,C=E>1)+f+t+k+C.slice(E);break;default:t=C+f+t+k}return s(t)}return y=void 0===y?6:/[gprs]/.test(v)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),k.toString=function(){return t+""},k}return{format:h,formatPrefix:function(t,e){var n=h(((t=cc(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(ac(e)/3))),i=Math.pow(10,-r),a=mc[8+r/3];return function(t){return n(i*t)+a}}}}function bc(t){return dc=vc(t),pc=dc.format,gc=dc.formatPrefix,dc}function _c(t){return Math.max(0,-ac(Math.abs(t)))}function xc(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(ac(e)/3)))-ac(Math.abs(t)))}function wc(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,ac(e)-ac(t))+1}function kc(){return new Tc}function Tc(){this.reset()}bc({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"}),Tc.prototype={constructor:Tc,reset:function(){this.s=this.t=0},add:function(t){Cc(Ec,t,this.t),Cc(this,Ec.s,this.s),this.s?this.t+=Ec.t:this.s=Ec.t},valueOf:function(){return this.s}};var Ec=new Tc;function Cc(t,e,n){var r=t.s=e+n,i=r-e,a=r-i;t.t=e-a+(n-i)}var Sc=1e-6,Ac=1e-12,Mc=Math.PI,Nc=Mc/2,Dc=Mc/4,Lc=2*Mc,Bc=180/Mc,Oc=Mc/180,Ic=Math.abs,Rc=Math.atan,Fc=Math.atan2,Pc=Math.cos,Yc=Math.ceil,jc=Math.exp,Uc=(Math.floor,Math.log),zc=Math.pow,$c=Math.sin,qc=Math.sign||function(t){return t>0?1:t<0?-1:0},Hc=Math.sqrt,Wc=Math.tan;function Vc(t){return t>1?0:t<-1?Mc:Math.acos(t)}function Gc(t){return t>1?Nc:t<-1?-Nc:Math.asin(t)}function Xc(t){return(t=$c(t/2))*t}function Zc(){}function Kc(t,e){t&&Jc.hasOwnProperty(t.type)&&Jc[t.type](t,e)}var Qc={Feature:function(t,e){Kc(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r=0?1:-1,i=r*n,a=Pc(e=(e*=Oc)/2+Dc),o=$c(e),s=su*o,c=ou*a+s*Pc(i),u=s*r*$c(i);cu.add(Fc(u,c)),au=t,ou=a,su=o}function gu(t){return uu.reset(),nu(t,lu),2*uu}function yu(t){return[Fc(t[1],t[0]),Gc(t[2])]}function mu(t){var e=t[0],n=t[1],r=Pc(n);return[r*Pc(e),r*$c(e),$c(n)]}function vu(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function bu(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function _u(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function xu(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function wu(t){var e=Hc(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}var ku,Tu,Eu,Cu,Su,Au,Mu,Nu,Du,Lu,Bu,Ou,Iu,Ru,Fu,Pu,Yu,ju,Uu,zu,$u,qu,Hu,Wu,Vu,Gu,Xu=kc(),Zu={point:Ku,lineStart:Ju,lineEnd:tl,polygonStart:function(){Zu.point=el,Zu.lineStart=nl,Zu.lineEnd=rl,Xu.reset(),lu.polygonStart()},polygonEnd:function(){lu.polygonEnd(),Zu.point=Ku,Zu.lineStart=Ju,Zu.lineEnd=tl,cu<0?(ku=-(Eu=180),Tu=-(Cu=90)):Xu>Sc?Cu=90:Xu<-1e-6&&(Tu=-90),Lu[0]=ku,Lu[1]=Eu},sphere:function(){ku=-(Eu=180),Tu=-(Cu=90)}};function Ku(t,e){Du.push(Lu=[ku=t,Eu=t]),eCu&&(Cu=e)}function Qu(t,e){var n=mu([t*Oc,e*Oc]);if(Nu){var r=bu(Nu,n),i=bu([r[1],-r[0],0],r);wu(i),i=yu(i);var a,o=t-Su,s=o>0?1:-1,c=i[0]*Bc*s,u=Ic(o)>180;u^(s*SuCu&&(Cu=a):u^(s*Su<(c=(c+360)%360-180)&&cCu&&(Cu=e)),u?til(ku,Eu)&&(Eu=t):il(t,Eu)>il(ku,Eu)&&(ku=t):Eu>=ku?(tEu&&(Eu=t)):t>Su?il(ku,t)>il(ku,Eu)&&(Eu=t):il(t,Eu)>il(ku,Eu)&&(ku=t)}else Du.push(Lu=[ku=t,Eu=t]);eCu&&(Cu=e),Nu=n,Su=t}function Ju(){Zu.point=Qu}function tl(){Lu[0]=ku,Lu[1]=Eu,Zu.point=Ku,Nu=null}function el(t,e){if(Nu){var n=t-Su;Xu.add(Ic(n)>180?n+(n>0?360:-360):n)}else Au=t,Mu=e;lu.point(t,e),Qu(t,e)}function nl(){lu.lineStart()}function rl(){el(Au,Mu),lu.lineEnd(),Ic(Xu)>Sc&&(ku=-(Eu=180)),Lu[0]=ku,Lu[1]=Eu,Nu=null}function il(t,e){return(e-=t)<0?e+360:e}function al(t,e){return t[0]-e[0]}function ol(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:eil(r[0],r[1])&&(r[1]=i[1]),il(i[0],r[1])>il(r[0],r[1])&&(r[0]=i[0])):a.push(r=i);for(o=-1/0,e=0,r=a[n=a.length-1];e<=n;r=i,++e)i=a[e],(s=il(r[1],i[0]))>o&&(o=s,ku=i[0],Eu=r[1])}return Du=Lu=null,ku===1/0||Tu===1/0?[[NaN,NaN],[NaN,NaN]]:[[ku,Tu],[Eu,Cu]]}var cl={sphere:Zc,point:ul,lineStart:hl,lineEnd:pl,polygonStart:function(){cl.lineStart=gl,cl.lineEnd=yl},polygonEnd:function(){cl.lineStart=hl,cl.lineEnd=pl}};function ul(t,e){t*=Oc;var n=Pc(e*=Oc);ll(n*Pc(t),n*$c(t),$c(e))}function ll(t,e,n){++Bu,Iu+=(t-Iu)/Bu,Ru+=(e-Ru)/Bu,Fu+=(n-Fu)/Bu}function hl(){cl.point=fl}function fl(t,e){t*=Oc;var n=Pc(e*=Oc);Wu=n*Pc(t),Vu=n*$c(t),Gu=$c(e),cl.point=dl,ll(Wu,Vu,Gu)}function dl(t,e){t*=Oc;var n=Pc(e*=Oc),r=n*Pc(t),i=n*$c(t),a=$c(e),o=Fc(Hc((o=Vu*a-Gu*i)*o+(o=Gu*r-Wu*a)*o+(o=Wu*i-Vu*r)*o),Wu*r+Vu*i+Gu*a);Ou+=o,Pu+=o*(Wu+(Wu=r)),Yu+=o*(Vu+(Vu=i)),ju+=o*(Gu+(Gu=a)),ll(Wu,Vu,Gu)}function pl(){cl.point=ul}function gl(){cl.point=ml}function yl(){vl(qu,Hu),cl.point=ul}function ml(t,e){qu=t,Hu=e,t*=Oc,e*=Oc,cl.point=vl;var n=Pc(e);Wu=n*Pc(t),Vu=n*$c(t),Gu=$c(e),ll(Wu,Vu,Gu)}function vl(t,e){t*=Oc;var n=Pc(e*=Oc),r=n*Pc(t),i=n*$c(t),a=$c(e),o=Vu*a-Gu*i,s=Gu*r-Wu*a,c=Wu*i-Vu*r,u=Hc(o*o+s*s+c*c),l=Gc(u),h=u&&-l/u;Uu+=h*o,zu+=h*s,$u+=h*c,Ou+=l,Pu+=l*(Wu+(Wu=r)),Yu+=l*(Vu+(Vu=i)),ju+=l*(Gu+(Gu=a)),ll(Wu,Vu,Gu)}function bl(t){Bu=Ou=Iu=Ru=Fu=Pu=Yu=ju=Uu=zu=$u=0,nu(t,cl);var e=Uu,n=zu,r=$u,i=e*e+n*n+r*r;return iMc?t+Math.round(-t/Lc)*Lc:t,e]}function kl(t,e,n){return(t%=Lc)?e||n?xl(El(t),Cl(e,n)):El(t):e||n?Cl(e,n):wl}function Tl(t){return function(e,n){return[(e+=t)>Mc?e-Lc:e<-Mc?e+Lc:e,n]}}function El(t){var e=Tl(t);return e.invert=Tl(-t),e}function Cl(t,e){var n=Pc(t),r=$c(t),i=Pc(e),a=$c(e);function o(t,e){var o=Pc(e),s=Pc(t)*o,c=$c(t)*o,u=$c(e),l=u*n+s*r;return[Fc(c*i-l*a,s*n-u*r),Gc(l*i+c*a)]}return o.invert=function(t,e){var o=Pc(e),s=Pc(t)*o,c=$c(t)*o,u=$c(e),l=u*i-c*a;return[Fc(c*i+u*a,s*n+l*r),Gc(l*n-s*r)]},o}function Sl(t){function e(e){return(e=t(e[0]*Oc,e[1]*Oc))[0]*=Bc,e[1]*=Bc,e}return t=kl(t[0]*Oc,t[1]*Oc,t.length>2?t[2]*Oc:0),e.invert=function(e){return(e=t.invert(e[0]*Oc,e[1]*Oc))[0]*=Bc,e[1]*=Bc,e},e}function Al(t,e,n,r,i,a){if(n){var o=Pc(e),s=$c(e),c=r*n;null==i?(i=e+r*Lc,a=e-c/2):(i=Ml(o,i),a=Ml(o,a),(r>0?ia)&&(i+=r*Lc));for(var u,l=i;r>0?l>a:l1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Ll(t,e){return Ic(t[0]-e[0])=0;--a)i.point((l=u[a])[0],l[1]);else r(f.x,f.p.x,-1,i);f=f.p}u=(f=f.o).z,d=!d}while(!f.v);i.lineEnd()}}}function Il(t){if(e=t.length){for(var e,n,r=0,i=t[0];++r=0?1:-1,E=T*k,C=E>Mc,S=g*x;if(Rl.add(Fc(S*T*$c(E),y*w+S*Pc(E))),o+=C?k+T*Lc:k,C^d>=n^b>=n){var A=bu(mu(f),mu(v));wu(A);var M=bu(a,A);wu(M);var N=(C^k>=0?-1:1)*Gc(M[2]);(r>N||r===N&&(A[0]||A[1]))&&(s+=C^k>=0?1:-1)}}return(o<-1e-6||o0){for(h||(i.polygonStart(),h=!0),i.lineStart(),t=0;t1&&2&c&&f.push(f.pop().concat(f.shift())),o.push(f.filter(jl))}return f}}function jl(t){return t.length>1}function Ul(t,e){return((t=t.x)[0]<0?t[1]-Nc-Sc:Nc-t[1])-((e=e.x)[0]<0?e[1]-Nc-Sc:Nc-e[1])}const zl=Yl((function(){return!0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Mc:-Mc,c=Ic(a-n);Ic(c-Mc)0?Nc:-Nc),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(s,r),t.point(a,r),e=0):i!==s&&c>=Mc&&(Ic(n-i)Sc?Rc(($c(e)*(a=Pc(r))*$c(n)-$c(r)*(i=Pc(e))*$c(t))/(i*a*o)):(e+r)/2}(n,r,a,o),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(s,r),e=0),t.point(n=a,r=o),i=s},lineEnd:function(){t.lineEnd(),n=r=NaN},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Nc,r.point(-Mc,i),r.point(0,i),r.point(Mc,i),r.point(Mc,0),r.point(Mc,-i),r.point(0,-i),r.point(-Mc,-i),r.point(-Mc,0),r.point(-Mc,i);else if(Ic(t[0]-e[0])>Sc){var a=t[0]0,i=Ic(e)>Sc;function a(t,n){return Pc(t)*Pc(n)>e}function o(t,n,r){var i=[1,0,0],a=bu(mu(t),mu(n)),o=vu(a,a),s=a[0],c=o-s*s;if(!c)return!r&&t;var u=e*o/c,l=-e*s/c,h=bu(i,a),f=xu(i,u);_u(f,xu(a,l));var d=h,p=vu(f,d),g=vu(d,d),y=p*p-g*(vu(f,f)-1);if(!(y<0)){var m=Hc(y),v=xu(d,(-p-m)/g);if(_u(v,f),v=yu(v),!r)return v;var b,_=t[0],x=n[0],w=t[1],k=n[1];x<_&&(b=_,_=x,x=b);var T=x-_,E=Ic(T-Mc)0^v[1]<(Ic(v[0]-_)Mc^(_<=v[0]&&v[0]<=x)){var C=xu(d,(-p+m)/g);return _u(C,f),[v,yu(C)]}}}function s(e,n){var i=r?t:Mc-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}return Yl(a,(function(t){var e,n,c,u,l;return{lineStart:function(){u=c=!1,l=1},point:function(h,f){var d,p=[h,f],g=a(h,f),y=r?g?0:s(h,f):g?s(h+(h<0?Mc:-Mc),f):0;if(!e&&(u=c=g)&&t.lineStart(),g!==c&&(!(d=o(e,p))||Ll(e,d)||Ll(p,d))&&(p[2]=1),g!==c)l=0,g?(t.lineStart(),d=o(p,e),t.point(d[0],d[1])):(d=o(e,p),t.point(d[0],d[1],2),t.lineEnd()),e=d;else if(i&&e&&r^g){var m;y&n||!(m=o(p,e,!0))||(l=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1],3)))}!g||e&&Ll(e,p)||t.point(p[0],p[1]),e=p,c=g,n=y},lineEnd:function(){c&&t.lineEnd(),e=null},clean:function(){return l|(u&&c)<<1}}}),(function(e,r,i,a){Al(a,t,n,i,e,r)}),r?[0,-t]:[-Mc,t-Mc])}var ql=1e9,Hl=-ql;function Wl(t,e,n,r){function i(i,a){return t<=i&&i<=n&&e<=a&&a<=r}function a(i,a,s,u){var l=0,h=0;if(null==i||(l=o(i,s))!==(h=o(a,s))||c(i,a)<0^s>0)do{u.point(0===l||3===l?t:n,l>1?r:e)}while((l=(l+s+4)%4)!==h);else u.point(a[0],a[1])}function o(r,i){return Ic(r[0]-t)0?0:3:Ic(r[0]-n)0?2:1:Ic(r[1]-e)0?1:0:i>0?3:2}function s(t,e){return c(t.x,e.x)}function c(t,e){var n=o(t,1),r=o(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(o){var c,u,l,h,f,d,p,g,y,m,v,b=o,_=Dl(),x={point:w,lineStart:function(){x.point=k,u&&u.push(l=[]),m=!0,y=!1,p=g=NaN},lineEnd:function(){c&&(k(h,f),d&&y&&_.rejoin(),c.push(_.result())),x.point=w,y&&b.lineEnd()},polygonStart:function(){b=_,c=[],u=[],v=!0},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=u.length;nr&&(f-a)*(r-o)>(d-o)*(t-a)&&++e:d<=r&&(f-a)*(r-o)<(d-o)*(t-a)&&--e;return e}(),n=v&&e,i=(c=P(c)).length;(n||i)&&(o.polygonStart(),n&&(o.lineStart(),a(null,null,1,o),o.lineEnd()),i&&Ol(c,s,e,a,o),o.polygonEnd()),b=o,c=u=l=null}};function w(t,e){i(t,e)&&b.point(t,e)}function k(a,o){var s=i(a,o);if(u&&l.push([a,o]),m)h=a,f=o,d=s,m=!1,s&&(b.lineStart(),b.point(a,o));else if(s&&y)b.point(a,o);else{var c=[p=Math.max(Hl,Math.min(ql,p)),g=Math.max(Hl,Math.min(ql,g))],_=[a=Math.max(Hl,Math.min(ql,a)),o=Math.max(Hl,Math.min(ql,o))];!function(t,e,n,r,i,a){var o,s=t[0],c=t[1],u=0,l=1,h=e[0]-s,f=e[1]-c;if(o=n-s,h||!(o>0)){if(o/=h,h<0){if(o0){if(o>l)return;o>u&&(u=o)}if(o=i-s,h||!(o<0)){if(o/=h,h<0){if(o>l)return;o>u&&(u=o)}else if(h>0){if(o0)){if(o/=f,f<0){if(o0){if(o>l)return;o>u&&(u=o)}if(o=a-c,f||!(o<0)){if(o/=f,f<0){if(o>l)return;o>u&&(u=o)}else if(f>0){if(o0&&(t[0]=s+u*h,t[1]=c+u*f),l<1&&(e[0]=s+l*h,e[1]=c+l*f),!0}}}}}(c,_,t,e,n,r)?s&&(b.lineStart(),b.point(a,o),v=!1):(y||(b.lineStart(),b.point(c[0],c[1])),b.point(_[0],_[1]),s||b.lineEnd(),v=!1)}p=a,g=o,y=s}return x}}function Vl(){var t,e,n,r=0,i=0,a=960,o=500;return n={stream:function(n){return t&&e===n?t:t=Wl(r,i,a,o)(e=n)},extent:function(s){return arguments.length?(r=+s[0][0],i=+s[0][1],a=+s[1][0],o=+s[1][1],t=e=null,n):[[r,i],[a,o]]}}}var Gl,Xl,Zl,Kl=kc(),Ql={sphere:Zc,point:Zc,lineStart:function(){Ql.point=th,Ql.lineEnd=Jl},lineEnd:Zc,polygonStart:Zc,polygonEnd:Zc};function Jl(){Ql.point=Ql.lineEnd=Zc}function th(t,e){Gl=t*=Oc,Xl=$c(e*=Oc),Zl=Pc(e),Ql.point=eh}function eh(t,e){t*=Oc;var n=$c(e*=Oc),r=Pc(e),i=Ic(t-Gl),a=Pc(i),o=r*$c(i),s=Zl*n-Xl*r*a,c=Xl*n+Zl*r*a;Kl.add(Fc(Hc(o*o+s*s),c)),Gl=t,Xl=n,Zl=r}function nh(t){return Kl.reset(),nu(t,Ql),+Kl}var rh=[null,null],ih={type:"LineString",coordinates:rh};function ah(t,e){return rh[0]=t,rh[1]=e,nh(ih)}var oh={Feature:function(t,e){return ch(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r0&&(i=ah(t[a],t[a-1]))>0&&n<=i&&r<=i&&(n+r-i)*(1-Math.pow((n-r)/i,2))Sc})).map(c)).concat(k(Yc(a/d)*d,i,d).filter((function(t){return Ic(t%g)>Sc})).map(u))}return m.lines=function(){return v().map((function(t){return{type:"LineString",coordinates:t}}))},m.outline=function(){return{type:"Polygon",coordinates:[l(r).concat(h(o).slice(1),l(n).reverse().slice(1),h(s).reverse().slice(1))]}},m.extent=function(t){return arguments.length?m.extentMajor(t).extentMinor(t):m.extentMinor()},m.extentMajor=function(t){return arguments.length?(r=+t[0][0],n=+t[1][0],s=+t[0][1],o=+t[1][1],r>n&&(t=r,r=n,n=t),s>o&&(t=s,s=o,o=t),m.precision(y)):[[r,s],[n,o]]},m.extentMinor=function(n){return arguments.length?(e=+n[0][0],t=+n[1][0],a=+n[0][1],i=+n[1][1],e>t&&(n=e,e=t,t=n),a>i&&(n=a,a=i,i=n),m.precision(y)):[[e,a],[t,i]]},m.step=function(t){return arguments.length?m.stepMajor(t).stepMinor(t):m.stepMinor()},m.stepMajor=function(t){return arguments.length?(p=+t[0],g=+t[1],m):[p,g]},m.stepMinor=function(t){return arguments.length?(f=+t[0],d=+t[1],m):[f,d]},m.precision=function(f){return arguments.length?(y=+f,c=gh(a,i,90),u=yh(e,t,y),l=gh(s,o,90),h=yh(r,n,y),m):y},m.extentMajor([[-180,-89.999999],[180,89.999999]]).extentMinor([[-180,-80.000001],[180,80.000001]])}function vh(){return mh()()}function bh(t,e){var n=t[0]*Oc,r=t[1]*Oc,i=e[0]*Oc,a=e[1]*Oc,o=Pc(r),s=$c(r),c=Pc(a),u=$c(a),l=o*Pc(n),h=o*$c(n),f=c*Pc(i),d=c*$c(i),p=2*Gc(Hc(Xc(a-r)+o*c*Xc(i-n))),g=$c(p),y=p?function(t){var e=$c(t*=p)/g,n=$c(p-t)/g,r=n*l+e*f,i=n*h+e*d,a=n*s+e*u;return[Fc(i,r)*Bc,Fc(a,Hc(r*r+i*i))*Bc]}:function(){return[n*Bc,r*Bc]};return y.distance=p,y}function _h(t){return t}var xh,wh,kh,Th,Eh=kc(),Ch=kc(),Sh={point:Zc,lineStart:Zc,lineEnd:Zc,polygonStart:function(){Sh.lineStart=Ah,Sh.lineEnd=Dh},polygonEnd:function(){Sh.lineStart=Sh.lineEnd=Sh.point=Zc,Eh.add(Ic(Ch)),Ch.reset()},result:function(){var t=Eh/2;return Eh.reset(),t}};function Ah(){Sh.point=Mh}function Mh(t,e){Sh.point=Nh,xh=kh=t,wh=Th=e}function Nh(t,e){Ch.add(Th*t-kh*e),kh=t,Th=e}function Dh(){Nh(xh,wh)}const Lh=Sh;var Bh=1/0,Oh=Bh,Ih=-Bh,Rh=Ih,Fh={point:function(t,e){tIh&&(Ih=t),eRh&&(Rh=e)},lineStart:Zc,lineEnd:Zc,polygonStart:Zc,polygonEnd:Zc,result:function(){var t=[[Bh,Oh],[Ih,Rh]];return Ih=Rh=-(Oh=Bh=1/0),t}};const Ph=Fh;var Yh,jh,Uh,zh,$h=0,qh=0,Hh=0,Wh=0,Vh=0,Gh=0,Xh=0,Zh=0,Kh=0,Qh={point:Jh,lineStart:tf,lineEnd:rf,polygonStart:function(){Qh.lineStart=af,Qh.lineEnd=of},polygonEnd:function(){Qh.point=Jh,Qh.lineStart=tf,Qh.lineEnd=rf},result:function(){var t=Kh?[Xh/Kh,Zh/Kh]:Gh?[Wh/Gh,Vh/Gh]:Hh?[$h/Hh,qh/Hh]:[NaN,NaN];return $h=qh=Hh=Wh=Vh=Gh=Xh=Zh=Kh=0,t}};function Jh(t,e){$h+=t,qh+=e,++Hh}function tf(){Qh.point=ef}function ef(t,e){Qh.point=nf,Jh(Uh=t,zh=e)}function nf(t,e){var n=t-Uh,r=e-zh,i=Hc(n*n+r*r);Wh+=i*(Uh+t)/2,Vh+=i*(zh+e)/2,Gh+=i,Jh(Uh=t,zh=e)}function rf(){Qh.point=Jh}function af(){Qh.point=sf}function of(){cf(Yh,jh)}function sf(t,e){Qh.point=cf,Jh(Yh=Uh=t,jh=zh=e)}function cf(t,e){var n=t-Uh,r=e-zh,i=Hc(n*n+r*r);Wh+=i*(Uh+t)/2,Vh+=i*(zh+e)/2,Gh+=i,Xh+=(i=zh*t-Uh*e)*(Uh+t),Zh+=i*(zh+e),Kh+=3*i,Jh(Uh=t,zh=e)}const uf=Qh;function lf(t){this._context=t}lf.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._context.moveTo(t,e),this._point=1;break;case 1:this._context.lineTo(t,e);break;default:this._context.moveTo(t+this._radius,e),this._context.arc(t,e,this._radius,0,Lc)}},result:Zc};var hf,ff,df,pf,gf,yf=kc(),mf={point:Zc,lineStart:function(){mf.point=vf},lineEnd:function(){hf&&bf(ff,df),mf.point=Zc},polygonStart:function(){hf=!0},polygonEnd:function(){hf=null},result:function(){var t=+yf;return yf.reset(),t}};function vf(t,e){mf.point=bf,ff=pf=t,df=gf=e}function bf(t,e){pf-=t,gf-=e,yf.add(Hc(pf*pf+gf*gf)),pf=t,gf=e}const _f=mf;function xf(){this._string=[]}function wf(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function kf(t,e){var n,r,i=4.5;function a(t){return t&&("function"==typeof i&&r.pointRadius(+i.apply(this,arguments)),nu(t,n(r))),r.result()}return a.area=function(t){return nu(t,n(Lh)),Lh.result()},a.measure=function(t){return nu(t,n(_f)),_f.result()},a.bounds=function(t){return nu(t,n(Ph)),Ph.result()},a.centroid=function(t){return nu(t,n(uf)),uf.result()},a.projection=function(e){return arguments.length?(n=null==e?(t=null,_h):(t=e).stream,a):t},a.context=function(t){return arguments.length?(r=null==t?(e=null,new xf):new lf(e=t),"function"!=typeof i&&r.pointRadius(i),a):e},a.pointRadius=function(t){return arguments.length?(i="function"==typeof t?t:(r.pointRadius(+t),+t),a):i},a.projection(t).context(e)}function Tf(t){return{stream:Ef(t)}}function Ef(t){return function(e){var n=new Cf;for(var r in t)n[r]=t[r];return n.stream=e,n}}function Cf(){}function Sf(t,e,n){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),nu(n,t.stream(Ph)),e(Ph.result()),null!=r&&t.clipExtent(r),t}function Af(t,e,n){return Sf(t,(function(n){var r=e[1][0]-e[0][0],i=e[1][1]-e[0][1],a=Math.min(r/(n[1][0]-n[0][0]),i/(n[1][1]-n[0][1])),o=+e[0][0]+(r-a*(n[1][0]+n[0][0]))/2,s=+e[0][1]+(i-a*(n[1][1]+n[0][1]))/2;t.scale(150*a).translate([o,s])}),n)}function Mf(t,e,n){return Af(t,[[0,0],e],n)}function Nf(t,e,n){return Sf(t,(function(n){var r=+e,i=r/(n[1][0]-n[0][0]),a=(r-i*(n[1][0]+n[0][0]))/2,o=-i*n[0][1];t.scale(150*i).translate([a,o])}),n)}function Df(t,e,n){return Sf(t,(function(n){var r=+e,i=r/(n[1][1]-n[0][1]),a=-i*n[0][0],o=(r-i*(n[1][1]+n[0][1]))/2;t.scale(150*i).translate([a,o])}),n)}xf.prototype={_radius:4.5,_circle:wf(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,e){switch(this._point){case 0:this._string.push("M",t,",",e),this._point=1;break;case 1:this._string.push("L",t,",",e);break;default:null==this._circle&&(this._circle=wf(this._radius)),this._string.push("M",t,",",e,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},Cf.prototype={constructor:Cf,point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var Lf=Pc(30*Oc);function Bf(t,e){return+e?function(t,e){function n(r,i,a,o,s,c,u,l,h,f,d,p,g,y){var m=u-r,v=l-i,b=m*m+v*v;if(b>4*e&&g--){var _=o+f,x=s+d,w=c+p,k=Hc(_*_+x*x+w*w),T=Gc(w/=k),E=Ic(Ic(w)-1)e||Ic((m*M+v*N)/b-.5)>.3||o*f+s*d+c*p2?t[2]%360*Oc:0,M()):[y*Bc,m*Bc,v*Bc]},S.angle=function(t){return arguments.length?(b=t%360*Oc,M()):b*Bc},S.reflectX=function(t){return arguments.length?(_=t?-1:1,M()):_<0},S.reflectY=function(t){return arguments.length?(x=t?-1:1,M()):x<0},S.precision=function(t){return arguments.length?(o=Bf(s,C=t*t),N()):Hc(C)},S.fitExtent=function(t,e){return Af(S,t,e)},S.fitSize=function(t,e){return Mf(S,t,e)},S.fitWidth=function(t,e){return Nf(S,t,e)},S.fitHeight=function(t,e){return Df(S,t,e)},function(){return e=t.apply(this,arguments),S.invert=e.invert&&A,M()}}function Yf(t){var e=0,n=Mc/3,r=Pf(t),i=r(e,n);return i.parallels=function(t){return arguments.length?r(e=t[0]*Oc,n=t[1]*Oc):[e*Bc,n*Bc]},i}function jf(t,e){var n=$c(t),r=(n+$c(e))/2;if(Ic(r)=.12&&i<.234&&r>=-.425&&r<-.214?s:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:o).invert(t)},l.stream=function(n){return t&&e===n?t:(r=[o.stream(e=n),s.stream(n),c.stream(n)],i=r.length,t={point:function(t,e){for(var n=-1;++n0?e<-Nc+Sc&&(e=-Nc+Sc):e>Nc-Sc&&(e=Nc-Sc);var n=i/zc(Jf(e),r);return[n*$c(r*t),i-n*Pc(r*t)]}return a.invert=function(t,e){var n=i-e,a=qc(r)*Hc(t*t+n*n),o=Fc(t,Ic(n))*qc(n);return n*r<0&&(o-=Mc*qc(t)*qc(n)),[o/r,2*Rc(zc(i/a,1/r))-Nc]},a}function ed(){return Yf(td).scale(109.5).parallels([30,30])}function nd(t,e){return[t,e]}function rd(){return Ff(nd).scale(152.63)}function id(t,e){var n=Pc(t),r=t===e?$c(t):(n-Pc(e))/(e-t),i=n/r+t;if(Ic(r)2?t[2]+90:90]):[(t=n())[0],t[1],t[2]-90]},n([0,0,90]).scale(159.155)}function Td(t,e){return t.parent===e.parent?1:2}function Ed(t,e){return t+e.x}function Cd(t,e){return Math.max(t,e.y)}function Sd(){var t=Td,e=1,n=1,r=!1;function i(i){var a,o=0;i.eachAfter((function(e){var n=e.children;n?(e.x=function(t){return t.reduce(Ed,0)/t.length}(n),e.y=function(t){return 1+t.reduce(Cd,0)}(n)):(e.x=a?o+=t(e,a):0,e.y=0,a=e)}));var s=function(t){for(var e;e=t.children;)t=e[0];return t}(i),c=function(t){for(var e;e=t.children;)t=e[e.length-1];return t}(i),u=s.x-t(s,c)/2,l=c.x+t(c,s)/2;return i.eachAfter(r?function(t){t.x=(t.x-i.x)*e,t.y=(i.y-t.y)*n}:function(t){t.x=(t.x-u)/(l-u)*e,t.y=(1-(i.y?t.y/i.y:1))*n})}return i.separation=function(e){return arguments.length?(t=e,i):t},i.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],i):r?null:[e,n]},i.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],i):r?[e,n]:null},i}function Ad(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e}function Md(t,e){var n,r,i,a,o,s=new Bd(t),c=+t.value&&(s.value=t.value),u=[s];for(null==e&&(e=Nd);n=u.pop();)if(c&&(n.value=+n.data.value),(i=e(n.data))&&(o=i.length))for(n.children=new Array(o),a=o-1;a>=0;--a)u.push(r=n.children[a]=new Bd(i[a])),r.parent=n,r.depth=n.depth+1;return s.eachBefore(Ld)}function Nd(t){return t.children}function Dd(t){t.data=t.data.data}function Ld(t){var e=0;do{t.height=e}while((t=t.parent)&&t.height<++e)}function Bd(t){this.data=t,this.depth=this.height=0,this.parent=null}hd.invert=function(t,e){for(var n,r=e,i=r*r,a=i*i*i,o=0;o<12&&(a=(i=(r-=n=(r*(od+sd*i+a*(cd+ud*i))-e)/(od+3*sd*i+a*(7*cd+9*ud*i)))*r)*i*i,!(Ic(n)Sc&&--i>0);return[t/(.8707+(a=r*r)*(a*(a*a*a*(.003971-.001529*a)-.013791)-.131979)),r]},vd.invert=Hf(Gc),_d.invert=Hf((function(t){return 2*Rc(t)})),wd.invert=function(t,e){return[-e,2*Rc(jc(t))-Nc]},Bd.prototype=Md.prototype={constructor:Bd,count:function(){return this.eachAfter(Ad)},each:function(t){var e,n,r,i,a=this,o=[a];do{for(e=o.reverse(),o=[];a=e.pop();)if(t(a),n=a.children)for(r=0,i=n.length;r=0;--n)i.push(e[n]);return this},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,i=r&&r.length;--i>=0;)n+=r[i].value;e.value=n}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t)}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),i=null;for(t=n.pop(),e=r.pop();t===e;)i=t,t=n.pop(),e=r.pop();return i}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var i=r.length;t!==n;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){var t=[];return this.each((function(e){t.push(e)})),t},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e)})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n})})),e},copy:function(){return Md(this).eachBefore(Dd)}};var Od=Array.prototype.slice;function Id(t){for(var e,n,r=0,i=(t=function(t){for(var e,n,r=t.length;r;)n=Math.random()*r--|0,e=t[r],t[r]=t[n],t[n]=e;return t}(Od.call(t))).length,a=[];r0&&n*n>r*r+i*i}function Yd(t,e){for(var n=0;n(o*=o)?(r=(u+o-i)/(2*u),a=Math.sqrt(Math.max(0,o/u-r*r)),n.x=t.x-r*s-a*c,n.y=t.y-r*c+a*s):(r=(u+i-o)/(2*u),a=Math.sqrt(Math.max(0,i/u-r*r)),n.x=e.x+r*s-a*c,n.y=e.y+r*c+a*s)):(n.x=e.x+n.r,n.y=e.y)}function qd(t,e){var n=t.r+e.r-1e-6,r=e.x-t.x,i=e.y-t.y;return n>0&&n*n>r*r+i*i}function Hd(t){var e=t._,n=t.next._,r=e.r+n.r,i=(e.x*n.r+n.x*e.r)/r,a=(e.y*n.r+n.y*e.r)/r;return i*i+a*a}function Wd(t){this._=t,this.next=null,this.previous=null}function Vd(t){if(!(i=t.length))return 0;var e,n,r,i,a,o,s,c,u,l,h;if((e=t[0]).x=0,e.y=0,!(i>1))return e.r;if(n=t[1],e.x=-n.r,n.x=e.r,n.y=0,!(i>2))return e.r+n.r;$d(n,e,r=t[2]),e=new Wd(e),n=new Wd(n),r=new Wd(r),e.next=r.previous=n,n.next=e.previous=r,r.next=n.previous=e;t:for(s=3;s0)throw new Error("cycle");return a}return n.id=function(e){return arguments.length?(t=Zd(e),n):t},n.parentId=function(t){return arguments.length?(e=Zd(t),n):e},n}function fp(t,e){return t.parent===e.parent?1:2}function dp(t){var e=t.children;return e?e[0]:t.t}function pp(t){var e=t.children;return e?e[e.length-1]:t.t}function gp(t,e,n){var r=n/(e.i-t.i);e.c-=r,e.s+=n,t.c+=r,e.z+=n,e.m+=n}function yp(t,e,n){return t.a.parent===e.parent?t.a:n}function mp(t,e){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=e}function vp(){var t=fp,e=1,n=1,r=null;function i(i){var c=function(t){for(var e,n,r,i,a,o=new mp(t,0),s=[o];e=s.pop();)if(r=e._.children)for(e.children=new Array(a=r.length),i=a-1;i>=0;--i)s.push(n=e.children[i]=new mp(r[i],i)),n.parent=e;return(o.parent=new mp(null,0)).children=[o],o}(i);if(c.eachAfter(a),c.parent.m=-c.z,c.eachBefore(o),r)i.eachBefore(s);else{var u=i,l=i,h=i;i.eachBefore((function(t){t.xl.x&&(l=t),t.depth>h.depth&&(h=t)}));var f=u===l?1:t(u,l)/2,d=f-u.x,p=e/(l.x+f+d),g=n/(h.depth||1);i.eachBefore((function(t){t.x=(t.x+d)*p,t.y=t.depth*g}))}return i}function a(e){var n=e.children,r=e.parent.children,i=e.i?r[e.i-1]:null;if(n){!function(t){for(var e,n=0,r=0,i=t.children,a=i.length;--a>=0;)(e=i[a]).z+=n,e.m+=n,n+=e.s+(r+=e.c)}(e);var a=(n[0].z+n[n.length-1].z)/2;i?(e.z=i.z+t(e._,i._),e.m=e.z-a):e.z=a}else i&&(e.z=i.z+t(e._,i._));e.parent.A=function(e,n,r){if(n){for(var i,a=e,o=e,s=n,c=a.parent.children[0],u=a.m,l=o.m,h=s.m,f=c.m;s=pp(s),a=dp(a),s&&a;)c=dp(c),(o=pp(o)).a=e,(i=s.z+h-a.z-u+t(s._,a._))>0&&(gp(yp(s,e,r),e,i),u+=i,l+=i),h+=s.m,u+=a.m,f+=c.m,l+=o.m;s&&!pp(o)&&(o.t=s,o.m+=h-l),a&&!dp(c)&&(c.t=a,c.m+=u-f,r=e)}return r}(e,i,e.parent.A||r[0])}function o(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function s(t){t.x*=e,t.y=t.depth*n}return i.separation=function(e){return arguments.length?(t=e,i):t},i.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],i):r?null:[e,n]},i.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],i):r?[e,n]:null},i}function bp(t,e,n,r,i){for(var a,o=t.children,s=-1,c=o.length,u=t.value&&(i-n)/t.value;++sf&&(f=s),y=l*l*g,(d=Math.max(f/y,y/h))>p){l-=s;break}p=d}m.push(o={value:l,dice:c1?e:1)},n}(_p);function kp(){var t=wp,e=!1,n=1,r=1,i=[0],a=Kd,o=Kd,s=Kd,c=Kd,u=Kd;function l(t){return t.x0=t.y0=0,t.x1=n,t.y1=r,t.eachBefore(h),i=[0],e&&t.eachBefore(ip),t}function h(e){var n=i[e.depth],r=e.x0+n,l=e.y0+n,h=e.x1-n,f=e.y1-n;h=n-1){var l=s[e];return l.x0=i,l.y0=a,l.x1=o,void(l.y1=c)}for(var h=u[e],f=r/2+h,d=e+1,p=n-1;d>>1;u[g]c-a){var v=(i*m+o*y)/r;t(e,d,y,i,a,v,c),t(d,n,m,v,a,o,c)}else{var b=(a*m+c*y)/r;t(e,d,y,i,a,o,b),t(d,n,m,i,b,o,c)}}(0,c,t.value,e,n,r,i)}function Ep(t,e,n,r,i){(1&t.depth?bp:ap)(t,e,n,r,i)}const Cp=function t(e){function n(t,n,r,i,a){if((o=t._squarify)&&o.ratio===e)for(var o,s,c,u,l,h=-1,f=o.length,d=t.value;++h1?e:1)},n}(_p);function Sp(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}function Ap(t,e){var n=dn(+t,+e);return function(t){var e=n(t);return e-360*Math.floor(e/360)}}function Mp(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}var Np=Math.SQRT2;function Dp(t){return((t=Math.exp(t))+1/t)/2}function Lp(t,e){var n,r,i=t[0],a=t[1],o=t[2],s=e[0],c=e[1],u=e[2],l=s-i,h=c-a,f=l*l+h*h;if(f<1e-12)r=Math.log(u/o)/Np,n=function(t){return[i+t*l,a+t*h,o*Math.exp(Np*t*r)]};else{var d=Math.sqrt(f),p=(u*u-o*o+4*f)/(2*o*2*d),g=(u*u-o*o-4*f)/(2*u*2*d),y=Math.log(Math.sqrt(p*p+1)-p),m=Math.log(Math.sqrt(g*g+1)-g);r=(m-y)/Np,n=function(t){var e,n=t*r,s=Dp(y),c=o/(2*d)*(s*(e=Np*n+y,((e=Math.exp(2*e))-1)/(e+1))-function(t){return((t=Math.exp(t))-1/t)/2}(y));return[i+c*l,a+c*h,o*s/Dp(Np*n+y)]}}return n.duration=1e3*r,n}function Bp(t){return function(e,n){var r=t((e=an(e)).h,(n=an(n)).h),i=pn(e.s,n.s),a=pn(e.l,n.l),o=pn(e.opacity,n.opacity);return function(t){return e.h=r(t),e.s=i(t),e.l=a(t),e.opacity=o(t),e+""}}}const Op=Bp(dn);var Ip=Bp(pn);function Rp(t,e){var n=pn((t=Ta(t)).l,(e=Ta(e)).l),r=pn(t.a,e.a),i=pn(t.b,e.b),a=pn(t.opacity,e.opacity);return function(e){return t.l=n(e),t.a=r(e),t.b=i(e),t.opacity=a(e),t+""}}function Fp(t){return function(e,n){var r=t((e=La(e)).h,(n=La(n)).h),i=pn(e.c,n.c),a=pn(e.l,n.l),o=pn(e.opacity,n.opacity);return function(t){return e.h=r(t),e.c=i(t),e.l=a(t),e.opacity=o(t),e+""}}}const Pp=Fp(dn);var Yp=Fp(pn);function jp(t){return function e(n){function r(e,r){var i=t((e=qa(e)).h,(r=qa(r)).h),a=pn(e.s,r.s),o=pn(e.l,r.l),s=pn(e.opacity,r.opacity);return function(t){return e.h=i(t),e.s=a(t),e.l=o(Math.pow(t,n)),e.opacity=s(t),e+""}}return n=+n,r.gamma=e,r}(1)}const Up=jp(dn);var zp=jp(pn);function $p(t,e){for(var n=0,r=e.length-1,i=e[0],a=new Array(r<0?0:r);n1&&Vp(t[n[r-2]],t[n[r-1]],t[i])<=0;)--r;n[r++]=i}return n.slice(0,r)}function Zp(t){if((n=t.length)<3)return null;var e,n,r=new Array(n),i=new Array(n);for(e=0;e=0;--e)u.push(t[r[a[e]][2]]);for(e=+s;es!=u>s&&o<(c-n)*(s-r)/(u-r)+n&&(l=!l),c=n,u=r;return l}function Qp(t){for(var e,n,r=-1,i=t.length,a=t[i-1],o=a[0],s=a[1],c=0;++r1);return t+n*a*Math.sqrt(-2*Math.log(i)/i)}}return n.source=t,n}(Jp),ng=function t(e){function n(){var t=eg.source(e).apply(this,arguments);return function(){return Math.exp(t())}}return n.source=t,n}(Jp),rg=function t(e){function n(t){return function(){for(var n=0,r=0;rr&&(e=n,n=r,r=e),function(t){return Math.max(n,Math.min(r,t))}}function xg(t,e,n){var r=t[0],i=t[1],a=e[0],o=e[1];return i2?wg:xg,i=a=null,h}function h(e){return isNaN(e=+e)?n:(i||(i=r(o.map(t),s,c)))(t(u(e)))}return h.invert=function(n){return u(e((a||(a=r(s,o.map(t),Tn)))(n)))},h.domain=function(t){return arguments.length?(o=ug.call(t,yg),u===vg||(u=_g(o)),l()):o.slice()},h.range=function(t){return arguments.length?(s=lg.call(t),l()):s.slice()},h.rangeRound=function(t){return s=lg.call(t),c=Mp,l()},h.clamp=function(t){return arguments.length?(u=t?_g(o):vg,h):u!==vg},h.interpolate=function(t){return arguments.length?(c=t,l()):c},h.unknown=function(t){return arguments.length?(n=t,h):n},function(n,r){return t=n,e=r,l()}}function Eg(t,e){return Tg()(t,e)}function Cg(t,e,n,r){var i,a=M(t,e,n);switch((r=cc(null==r?",f":r)).type){case"s":var o=Math.max(Math.abs(t),Math.abs(e));return null!=r.precision||isNaN(i=xc(a,o))||(r.precision=i),gc(r,o);case"":case"e":case"g":case"p":case"r":null!=r.precision||isNaN(i=wc(a,Math.max(Math.abs(t),Math.abs(e))))||(r.precision=i-("e"===r.type));break;case"f":case"%":null!=r.precision||isNaN(i=_c(a))||(r.precision=i-2*("%"===r.type))}return pc(r)}function Sg(t){var e=t.domain;return t.ticks=function(t){var n=e();return S(n[0],n[n.length-1],null==t?10:t)},t.tickFormat=function(t,n){var r=e();return Cg(r[0],r[r.length-1],null==t?10:t,n)},t.nice=function(n){null==n&&(n=10);var r,i=e(),a=0,o=i.length-1,s=i[a],c=i[o];return c0?r=A(s=Math.floor(s/r)*r,c=Math.ceil(c/r)*r,n):r<0&&(r=A(s=Math.ceil(s*r)/r,c=Math.floor(c*r)/r,n)),r>0?(i[a]=Math.floor(s/r)*r,i[o]=Math.ceil(c/r)*r,e(i)):r<0&&(i[a]=Math.ceil(s*r)/r,i[o]=Math.floor(c*r)/r,e(i)),t},t}function Ag(){var t=Eg(vg,vg);return t.copy=function(){return kg(t,Ag())},og.apply(t,arguments),Sg(t)}function Mg(t){var e;function n(t){return isNaN(t=+t)?e:t}return n.invert=n,n.domain=n.range=function(e){return arguments.length?(t=ug.call(e,yg),n):t.slice()},n.unknown=function(t){return arguments.length?(e=t,n):e},n.copy=function(){return Mg(t).unknown(e)},t=arguments.length?ug.call(t,yg):[0,1],Sg(n)}function Ng(t,e){var n,r=0,i=(t=t.slice()).length-1,a=t[r],o=t[i];return o0){for(;fc)break;g.push(h)}}else for(;f=1;--l)if(!((h=u*l)c)break;g.push(h)}}else g=S(f,d,Math.min(d-f,p)).map(n);return r?g.reverse():g},r.tickFormat=function(t,i){if(null==i&&(i=10===a?".0e":","),"function"!=typeof i&&(i=pc(i)),t===1/0)return i;null==t&&(t=10);var o=Math.max(1,a*t/r.ticks().length);return function(t){var r=t/n(Math.round(e(t)));return r*a0?r[i-1]:e[0],i=r?[i[r-1],n]:[i[o-1],i[o]]},o.unknown=function(e){return arguments.length?(t=e,o):o},o.thresholds=function(){return i.slice()},o.copy=function(){return Zg().domain([e,n]).range(a).unknown(t)},og.apply(Sg(o),arguments)}function Kg(){var t,e=[.5],n=[0,1],r=1;function i(i){return i<=i?n[u(e,i,0,r)]:t}return i.domain=function(t){return arguments.length?(e=lg.call(t),r=Math.min(e.length,n.length-1),i):e.slice()},i.range=function(t){return arguments.length?(n=lg.call(t),r=Math.min(e.length,n.length-1),i):n.slice()},i.invertExtent=function(t){var r=n.indexOf(t);return[e[r-1],e[r]]},i.unknown=function(e){return arguments.length?(t=e,i):t},i.copy=function(){return Kg().domain(e).range(n).unknown(t)},og.apply(i,arguments)}var Qg=new Date,Jg=new Date;function ty(t,e,n,r){function i(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return i.floor=function(e){return t(e=new Date(+e)),e},i.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},i.round=function(t){var e=i(t),n=i.ceil(t);return t-e0))return s;do{s.push(o=new Date(+n)),e(n,a),t(n)}while(o=e)for(;t(e),!n(e);)e.setTime(e-1)}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(i.count=function(e,r){return Qg.setTime(+e),Jg.setTime(+r),t(Qg),t(Jg),Math.floor(n(Qg,Jg))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(e){return r(e)%t==0}:function(e){return i.count(0,e)%t==0}):i:null}),i}var ey=ty((function(t){t.setMonth(0,1),t.setHours(0,0,0,0)}),(function(t,e){t.setFullYear(t.getFullYear()+e)}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));ey.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ty((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)}),(function(e,n){e.setFullYear(e.getFullYear()+n*t)})):null};const ny=ey;var ry=ey.range,iy=ty((function(t){t.setDate(1),t.setHours(0,0,0,0)}),(function(t,e){t.setMonth(t.getMonth()+e)}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()}));const ay=iy;var oy=iy.range,sy=1e3,cy=6e4,uy=36e5,ly=864e5,hy=6048e5;function fy(t){return ty((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+7*e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*cy)/hy}))}var dy=fy(0),py=fy(1),gy=fy(2),yy=fy(3),my=fy(4),vy=fy(5),by=fy(6),_y=dy.range,xy=py.range,wy=gy.range,ky=yy.range,Ty=my.range,Ey=vy.range,Cy=by.range,Sy=ty((function(t){t.setHours(0,0,0,0)}),(function(t,e){t.setDate(t.getDate()+e)}),(function(t,e){return(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*cy)/ly}),(function(t){return t.getDate()-1}));const Ay=Sy;var My=Sy.range,Ny=ty((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*sy-t.getMinutes()*cy)}),(function(t,e){t.setTime(+t+e*uy)}),(function(t,e){return(e-t)/uy}),(function(t){return t.getHours()}));const Dy=Ny;var Ly=Ny.range,By=ty((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*sy)}),(function(t,e){t.setTime(+t+e*cy)}),(function(t,e){return(e-t)/cy}),(function(t){return t.getMinutes()}));const Oy=By;var Iy=By.range,Ry=ty((function(t){t.setTime(t-t.getMilliseconds())}),(function(t,e){t.setTime(+t+e*sy)}),(function(t,e){return(e-t)/sy}),(function(t){return t.getUTCSeconds()}));const Fy=Ry;var Py=Ry.range,Yy=ty((function(){}),(function(t,e){t.setTime(+t+e)}),(function(t,e){return e-t}));Yy.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?ty((function(e){e.setTime(Math.floor(e/t)*t)}),(function(e,n){e.setTime(+e+n*t)}),(function(e,n){return(n-e)/t})):Yy:null};const jy=Yy;var Uy=Yy.range;function zy(t){return ty((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e)}),(function(t,e){return(e-t)/hy}))}var $y=zy(0),qy=zy(1),Hy=zy(2),Wy=zy(3),Vy=zy(4),Gy=zy(5),Xy=zy(6),Zy=$y.range,Ky=qy.range,Qy=Hy.range,Jy=Wy.range,tm=Vy.range,em=Gy.range,nm=Xy.range,rm=ty((function(t){t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCDate(t.getUTCDate()+e)}),(function(t,e){return(e-t)/ly}),(function(t){return t.getUTCDate()-1}));const im=rm;var am=rm.range,om=ty((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e)}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));om.every=function(t){return isFinite(t=Math.floor(t))&&t>0?ty((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t)})):null};const sm=om;var cm=om.range;function um(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function lm(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function hm(t,e,n){return{y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function fm(t){var e=t.dateTime,n=t.date,r=t.time,i=t.periods,a=t.days,o=t.shortDays,s=t.months,c=t.shortMonths,u=Tm(i),l=Em(i),h=Tm(a),f=Em(a),d=Tm(o),p=Em(o),g=Tm(s),y=Em(s),m=Tm(c),v=Em(c),b={a:function(t){return o[t.getDay()]},A:function(t){return a[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return s[t.getMonth()]},c:null,d:Wm,e:Wm,f:Km,g:cv,G:lv,H:Vm,I:Gm,j:Xm,L:Zm,m:Qm,M:Jm,p:function(t){return i[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:Bv,s:Ov,S:tv,u:ev,U:nv,V:iv,w:av,W:ov,x:null,X:null,y:sv,Y:uv,Z:hv,"%":Lv},_={a:function(t){return o[t.getUTCDay()]},A:function(t){return a[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return s[t.getUTCMonth()]},c:null,d:fv,e:fv,f:mv,g:Av,G:Nv,H:dv,I:pv,j:gv,L:yv,m:vv,M:bv,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:Bv,s:Ov,S:_v,u:xv,U:wv,V:Tv,w:Ev,W:Cv,x:null,X:null,y:Sv,Y:Mv,Z:Dv,"%":Lv},x={a:function(t,e,n){var r=d.exec(e.slice(n));return r?(t.w=p[r[0].toLowerCase()],n+r[0].length):-1},A:function(t,e,n){var r=h.exec(e.slice(n));return r?(t.w=f[r[0].toLowerCase()],n+r[0].length):-1},b:function(t,e,n){var r=m.exec(e.slice(n));return r?(t.m=v[r[0].toLowerCase()],n+r[0].length):-1},B:function(t,e,n){var r=g.exec(e.slice(n));return r?(t.m=y[r[0].toLowerCase()],n+r[0].length):-1},c:function(t,n,r){return T(t,e,n,r)},d:Rm,e:Rm,f:zm,g:Lm,G:Dm,H:Pm,I:Pm,j:Fm,L:Um,m:Im,M:Ym,p:function(t,e,n){var r=u.exec(e.slice(n));return r?(t.p=l[r[0].toLowerCase()],n+r[0].length):-1},q:Om,Q:qm,s:Hm,S:jm,u:Sm,U:Am,V:Mm,w:Cm,W:Nm,x:function(t,e,r){return T(t,n,e,r)},X:function(t,e,n){return T(t,r,e,n)},y:Lm,Y:Dm,Z:Bm,"%":$m};function w(t,e){return function(n){var r,i,a,o=[],s=-1,c=0,u=t.length;for(n instanceof Date||(n=new Date(+n));++s53)return null;"w"in a||(a.w=1),"Z"in a?(i=(r=lm(hm(a.y,0,1))).getUTCDay(),r=i>4||0===i?qy.ceil(r):qy(r),r=im.offset(r,7*(a.V-1)),a.y=r.getUTCFullYear(),a.m=r.getUTCMonth(),a.d=r.getUTCDate()+(a.w+6)%7):(i=(r=um(hm(a.y,0,1))).getDay(),r=i>4||0===i?py.ceil(r):py(r),r=Ay.offset(r,7*(a.V-1)),a.y=r.getFullYear(),a.m=r.getMonth(),a.d=r.getDate()+(a.w+6)%7)}else("W"in a||"U"in a)&&("w"in a||(a.w="u"in a?a.u%7:"W"in a?1:0),i="Z"in a?lm(hm(a.y,0,1)).getUTCDay():um(hm(a.y,0,1)).getDay(),a.m=0,a.d="W"in a?(a.w+6)%7+7*a.W-(i+5)%7:a.w+7*a.U-(i+6)%7);return"Z"in a?(a.H+=a.Z/100|0,a.M+=a.Z%100,lm(a)):um(a)}}function T(t,e,n,r){for(var i,a,o=0,s=e.length,c=n.length;o=c)return-1;if(37===(i=e.charCodeAt(o++))){if(i=e.charAt(o++),!(a=x[i in vm?e.charAt(o++):i])||(r=a(t,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}return b.x=w(n,b),b.X=w(r,b),b.c=w(e,b),_.x=w(n,_),_.X=w(r,_),_.c=w(e,_),{format:function(t){var e=w(t+="",b);return e.toString=function(){return t},e},parse:function(t){var e=k(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=w(t+="",_);return e.toString=function(){return t},e},utcParse:function(t){var e=k(t+="",!0);return e.toString=function(){return t},e}}}var dm,pm,gm,ym,mm,vm={"-":"",_:" ",0:"0"},bm=/^\s*\d+/,_m=/^%/,xm=/[\\^$*+?|[\]().{}]/g;function wm(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",a=i.length;return r+(a68?1900:2e3),n+r[0].length):-1}function Bm(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function Om(t,e,n){var r=bm.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function Im(t,e,n){var r=bm.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function Rm(t,e,n){var r=bm.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function Fm(t,e,n){var r=bm.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function Pm(t,e,n){var r=bm.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function Ym(t,e,n){var r=bm.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function jm(t,e,n){var r=bm.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function Um(t,e,n){var r=bm.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function zm(t,e,n){var r=bm.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function $m(t,e,n){var r=_m.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function qm(t,e,n){var r=bm.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function Hm(t,e,n){var r=bm.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function Wm(t,e){return wm(t.getDate(),e,2)}function Vm(t,e){return wm(t.getHours(),e,2)}function Gm(t,e){return wm(t.getHours()%12||12,e,2)}function Xm(t,e){return wm(1+Ay.count(ny(t),t),e,3)}function Zm(t,e){return wm(t.getMilliseconds(),e,3)}function Km(t,e){return Zm(t,e)+"000"}function Qm(t,e){return wm(t.getMonth()+1,e,2)}function Jm(t,e){return wm(t.getMinutes(),e,2)}function tv(t,e){return wm(t.getSeconds(),e,2)}function ev(t){var e=t.getDay();return 0===e?7:e}function nv(t,e){return wm(dy.count(ny(t)-1,t),e,2)}function rv(t){var e=t.getDay();return e>=4||0===e?my(t):my.ceil(t)}function iv(t,e){return t=rv(t),wm(my.count(ny(t),t)+(4===ny(t).getDay()),e,2)}function av(t){return t.getDay()}function ov(t,e){return wm(py.count(ny(t)-1,t),e,2)}function sv(t,e){return wm(t.getFullYear()%100,e,2)}function cv(t,e){return wm((t=rv(t)).getFullYear()%100,e,2)}function uv(t,e){return wm(t.getFullYear()%1e4,e,4)}function lv(t,e){var n=t.getDay();return wm((t=n>=4||0===n?my(t):my.ceil(t)).getFullYear()%1e4,e,4)}function hv(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+wm(e/60|0,"0",2)+wm(e%60,"0",2)}function fv(t,e){return wm(t.getUTCDate(),e,2)}function dv(t,e){return wm(t.getUTCHours(),e,2)}function pv(t,e){return wm(t.getUTCHours()%12||12,e,2)}function gv(t,e){return wm(1+im.count(sm(t),t),e,3)}function yv(t,e){return wm(t.getUTCMilliseconds(),e,3)}function mv(t,e){return yv(t,e)+"000"}function vv(t,e){return wm(t.getUTCMonth()+1,e,2)}function bv(t,e){return wm(t.getUTCMinutes(),e,2)}function _v(t,e){return wm(t.getUTCSeconds(),e,2)}function xv(t){var e=t.getUTCDay();return 0===e?7:e}function wv(t,e){return wm($y.count(sm(t)-1,t),e,2)}function kv(t){var e=t.getUTCDay();return e>=4||0===e?Vy(t):Vy.ceil(t)}function Tv(t,e){return t=kv(t),wm(Vy.count(sm(t),t)+(4===sm(t).getUTCDay()),e,2)}function Ev(t){return t.getUTCDay()}function Cv(t,e){return wm(qy.count(sm(t)-1,t),e,2)}function Sv(t,e){return wm(t.getUTCFullYear()%100,e,2)}function Av(t,e){return wm((t=kv(t)).getUTCFullYear()%100,e,2)}function Mv(t,e){return wm(t.getUTCFullYear()%1e4,e,4)}function Nv(t,e){var n=t.getUTCDay();return wm((t=n>=4||0===n?Vy(t):Vy.ceil(t)).getUTCFullYear()%1e4,e,4)}function Dv(){return"+0000"}function Lv(){return"%"}function Bv(t){return+t}function Ov(t){return Math.floor(+t/1e3)}function Iv(t){return dm=fm(t),pm=dm.format,gm=dm.parse,ym=dm.utcFormat,mm=dm.utcParse,dm}Iv({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var Rv=31536e6;function Fv(t){return new Date(t)}function Pv(t){return t instanceof Date?+t:+new Date(+t)}function Yv(t,e,n,r,i,o,s,c,u){var l=Eg(vg,vg),h=l.invert,f=l.domain,d=u(".%L"),p=u(":%S"),g=u("%I:%M"),y=u("%I %p"),m=u("%a %d"),v=u("%b %d"),b=u("%B"),_=u("%Y"),x=[[s,1,1e3],[s,5,5e3],[s,15,15e3],[s,30,3e4],[o,1,6e4],[o,5,3e5],[o,15,9e5],[o,30,18e5],[i,1,36e5],[i,3,108e5],[i,6,216e5],[i,12,432e5],[r,1,864e5],[r,2,1728e5],[n,1,6048e5],[e,1,2592e6],[e,3,7776e6],[t,1,Rv]];function w(a){return(s(a)1)&&(t-=Math.floor(t));var e=Math.abs(t-.5);return S_.h=360*t-100,S_.s=1.5-1.5*e,S_.l=.8-.9*e,S_+""}var M_=Ke(),N_=Math.PI/3,D_=2*Math.PI/3;function L_(t){var e;return t=(.5-t)*Math.PI,M_.r=255*(e=Math.sin(t))*e,M_.g=255*(e=Math.sin(t+N_))*e,M_.b=255*(e=Math.sin(t+D_))*e,M_+""}function B_(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"}function O_(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}const I_=O_(hb("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var R_=O_(hb("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),F_=O_(hb("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),P_=O_(hb("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Y_(t){return Te(ie(t).call(document.documentElement))}var j_=0;function U_(){return new z_}function z_(){this._="@"+(++j_).toString(36)}function $_(t){return"string"==typeof t?new xe([document.querySelectorAll(t)],[document.documentElement]):new xe([null==t?[]:t],_e)}function q_(t,e){null==e&&(e=Nn().touches);for(var n=0,r=e?e.length:0,i=new Array(r);n1?0:t<-1?tx:Math.acos(t)}function ix(t){return t>=1?ex:t<=-1?-ex:Math.asin(t)}function ax(t){return t.innerRadius}function ox(t){return t.outerRadius}function sx(t){return t.startAngle}function cx(t){return t.endAngle}function ux(t){return t&&t.padAngle}function lx(t,e,n,r,i,a,o,s){var c=n-t,u=r-e,l=o-i,h=s-a,f=h*c-l*u;if(!(f*fN*N+D*D&&(T=C,E=S),{cx:T,cy:E,x01:-l,y01:-h,x11:T*(i/x-1),y11:E*(i/x-1)}}function fx(){var t=ax,e=ox,n=H_(0),r=null,i=sx,a=cx,o=ux,s=null;function c(){var c,u,l=+t.apply(this,arguments),h=+e.apply(this,arguments),f=i.apply(this,arguments)-ex,d=a.apply(this,arguments)-ex,p=W_(d-f),g=d>f;if(s||(s=c=Wi()),hJ_)if(p>nx-J_)s.moveTo(h*G_(f),h*K_(f)),s.arc(0,0,h,f,d,!g),l>J_&&(s.moveTo(l*G_(d),l*K_(d)),s.arc(0,0,l,d,f,g));else{var y,m,v=f,b=d,_=f,x=d,w=p,k=p,T=o.apply(this,arguments)/2,E=T>J_&&(r?+r.apply(this,arguments):Q_(l*l+h*h)),C=Z_(W_(h-l)/2,+n.apply(this,arguments)),S=C,A=C;if(E>J_){var M=ix(E/l*K_(T)),N=ix(E/h*K_(T));(w-=2*M)>J_?(_+=M*=g?1:-1,x-=M):(w=0,_=x=(f+d)/2),(k-=2*N)>J_?(v+=N*=g?1:-1,b-=N):(k=0,v=b=(f+d)/2)}var D=h*G_(v),L=h*K_(v),B=l*G_(x),O=l*K_(x);if(C>J_){var I,R=h*G_(b),F=h*K_(b),P=l*G_(_),Y=l*K_(_);if(pJ_?A>J_?(y=hx(P,Y,D,L,h,A,g),m=hx(R,F,B,O,h,A,g),s.moveTo(y.cx+y.x01,y.cy+y.y01),AJ_&&w>J_?S>J_?(y=hx(B,O,R,F,l,-S,g),m=hx(D,L,P,Y,l,-S,g),s.lineTo(y.cx+y.x01,y.cy+y.y01),S=l;--h)s.point(y[h],m[h]);s.lineEnd(),s.areaEnd()}g&&(y[u]=+t(f,u,c),m[u]=+n(f,u,c),s.point(e?+e(f,u,c):y[u],r?+r(f,u,c):m[u]))}if(d)return s=null,d+""||null}function u(){return mx().defined(i).curve(o).context(a)}return c.x=function(n){return arguments.length?(t="function"==typeof n?n:H_(+n),e=null,c):t},c.x0=function(e){return arguments.length?(t="function"==typeof e?e:H_(+e),c):t},c.x1=function(t){return arguments.length?(e=null==t?null:"function"==typeof t?t:H_(+t),c):e},c.y=function(t){return arguments.length?(n="function"==typeof t?t:H_(+t),r=null,c):n},c.y0=function(t){return arguments.length?(n="function"==typeof t?t:H_(+t),c):n},c.y1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:H_(+t),c):r},c.lineX0=c.lineY0=function(){return u().x(t).y(n)},c.lineY1=function(){return u().x(t).y(r)},c.lineX1=function(){return u().x(e).y(n)},c.defined=function(t){return arguments.length?(i="function"==typeof t?t:H_(!!t),c):i},c.curve=function(t){return arguments.length?(o=t,null!=a&&(s=o(a)),c):o},c.context=function(t){return arguments.length?(null==t?a=s=null:s=o(a=t),c):a},c}function bx(t,e){return et?1:e>=t?0:NaN}function _x(t){return t}function xx(){var t=_x,e=bx,n=null,r=H_(0),i=H_(nx),a=H_(0);function o(o){var s,c,u,l,h,f=o.length,d=0,p=new Array(f),g=new Array(f),y=+r.apply(this,arguments),m=Math.min(nx,Math.max(-nx,i.apply(this,arguments)-y)),v=Math.min(Math.abs(m)/f,a.apply(this,arguments)),b=v*(m<0?-1:1);for(s=0;s0&&(d+=h);for(null!=e?p.sort((function(t,n){return e(g[t],g[n])})):null!=n&&p.sort((function(t,e){return n(o[t],o[e])})),s=0,u=d?(m-f*b)/d:0;s0?h*u:0)+b,g[c]={data:o[c],index:s,value:h,startAngle:y,endAngle:l,padAngle:v};return g}return o.value=function(e){return arguments.length?(t="function"==typeof e?e:H_(+e),o):t},o.sortValues=function(t){return arguments.length?(e=t,n=null,o):e},o.sort=function(t){return arguments.length?(n=t,e=null,o):n},o.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:H_(+t),o):r},o.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:H_(+t),o):i},o.padAngle=function(t){return arguments.length?(a="function"==typeof t?t:H_(+t),o):a},o}dx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e)}}};var wx=Tx(px);function kx(t){this._curve=t}function Tx(t){function e(e){return new kx(t(e))}return e._curve=t,e}function Ex(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e(Tx(t)):e()._curve},t}function Cx(){return Ex(mx().curve(wx))}function Sx(){var t=vx().curve(wx),e=t.curve,n=t.lineX0,r=t.lineX1,i=t.lineY0,a=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Ex(n())},delete t.lineX0,t.lineEndAngle=function(){return Ex(r())},delete t.lineX1,t.lineInnerRadius=function(){return Ex(i())},delete t.lineY0,t.lineOuterRadius=function(){return Ex(a())},delete t.lineY1,t.curve=function(t){return arguments.length?e(Tx(t)):e()._curve},t}function Ax(t,e){return[(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}kx.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t))}};var Mx=Array.prototype.slice;function Nx(t){return t.source}function Dx(t){return t.target}function Lx(t){var e=Nx,n=Dx,r=gx,i=yx,a=null;function o(){var o,s=Mx.call(arguments),c=e.apply(this,s),u=n.apply(this,s);if(a||(a=o=Wi()),t(a,+r.apply(this,(s[0]=c,s)),+i.apply(this,s),+r.apply(this,(s[0]=u,s)),+i.apply(this,s)),o)return a=null,o+""||null}return o.source=function(t){return arguments.length?(e=t,o):e},o.target=function(t){return arguments.length?(n=t,o):n},o.x=function(t){return arguments.length?(r="function"==typeof t?t:H_(+t),o):r},o.y=function(t){return arguments.length?(i="function"==typeof t?t:H_(+t),o):i},o.context=function(t){return arguments.length?(a=null==t?null:t,o):a},o}function Bx(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e=(e+r)/2,n,e,i,r,i)}function Ox(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e,n=(n+i)/2,r,n,r,i)}function Ix(t,e,n,r,i){var a=Ax(e,n),o=Ax(e,n=(n+i)/2),s=Ax(r,n),c=Ax(r,i);t.moveTo(a[0],a[1]),t.bezierCurveTo(o[0],o[1],s[0],s[1],c[0],c[1])}function Rx(){return Lx(Bx)}function Fx(){return Lx(Ox)}function Px(){var t=Lx(Ix);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t}const Yx={draw:function(t,e){var n=Math.sqrt(e/tx);t.moveTo(n,0),t.arc(0,0,n,0,nx)}},jx={draw:function(t,e){var n=Math.sqrt(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath()}};var Ux=Math.sqrt(1/3),zx=2*Ux;const $x={draw:function(t,e){var n=Math.sqrt(e/zx),r=n*Ux;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath()}};var qx=Math.sin(tx/10)/Math.sin(7*tx/10),Hx=Math.sin(nx/10)*qx,Wx=-Math.cos(nx/10)*qx;const Vx={draw:function(t,e){var n=Math.sqrt(.8908130915292852*e),r=Hx*n,i=Wx*n;t.moveTo(0,-n),t.lineTo(r,i);for(var a=1;a<5;++a){var o=nx*a/5,s=Math.cos(o),c=Math.sin(o);t.lineTo(c*n,-s*n),t.lineTo(s*r-c*i,c*r+s*i)}t.closePath()}},Gx={draw:function(t,e){var n=Math.sqrt(e),r=-n/2;t.rect(r,r,n,n)}};var Xx=Math.sqrt(3);const Zx={draw:function(t,e){var n=-Math.sqrt(e/(3*Xx));t.moveTo(0,2*n),t.lineTo(-Xx*n,-n),t.lineTo(Xx*n,-n),t.closePath()}};var Kx=-.5,Qx=Math.sqrt(3)/2,Jx=1/Math.sqrt(12),tw=3*(Jx/2+1);const ew={draw:function(t,e){var n=Math.sqrt(e/tw),r=n/2,i=n*Jx,a=r,o=n*Jx+n,s=-a,c=o;t.moveTo(r,i),t.lineTo(a,o),t.lineTo(s,c),t.lineTo(Kx*r-Qx*i,Qx*r+Kx*i),t.lineTo(Kx*a-Qx*o,Qx*a+Kx*o),t.lineTo(Kx*s-Qx*c,Qx*s+Kx*c),t.lineTo(Kx*r+Qx*i,Kx*i-Qx*r),t.lineTo(Kx*a+Qx*o,Kx*o-Qx*a),t.lineTo(Kx*s+Qx*c,Kx*c-Qx*s),t.closePath()}};var nw=[Yx,jx,$x,Gx,Vx,Zx,ew];function rw(){var t=H_(Yx),e=H_(64),n=null;function r(){var r;if(n||(n=r=Wi()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),r)return n=null,r+""||null}return r.type=function(e){return arguments.length?(t="function"==typeof e?e:H_(e),r):t},r.size=function(t){return arguments.length?(e="function"==typeof t?t:H_(+t),r):e},r.context=function(t){return arguments.length?(n=null==t?null:t,r):n},r}function iw(){}function aw(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6)}function ow(t){this._context=t}function sw(t){return new ow(t)}function cw(t){this._context=t}function uw(t){return new cw(t)}function lw(t){this._context=t}function hw(t){return new lw(t)}function fw(t,e){this._basis=new ow(t),this._beta=e}ow.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:aw(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:aw(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},cw.prototype={areaStart:iw,areaEnd:iw,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:aw(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},lw.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:aw(this,t,e)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}},fw.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r,i=t[0],a=e[0],o=t[n]-i,s=e[n]-a,c=-1;++c<=n;)r=c/n,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*o),this._beta*e[c]+(1-this._beta)*(a+r*s));this._x=this._y=null,this._basis.lineEnd()},point:function(t,e){this._x.push(+t),this._y.push(+e)}};const dw=function t(e){function n(t){return 1===e?new ow(t):new fw(t,e)}return n.beta=function(e){return t(+e)},n}(.85);function pw(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2)}function gw(t,e){this._context=t,this._k=(1-e)/6}gw.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:pw(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:pw(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const yw=function t(e){function n(t){return new gw(t,e)}return n.tension=function(e){return t(+e)},n}(0);function mw(t,e){this._context=t,this._k=(1-e)/6}mw.prototype={areaStart:iw,areaEnd:iw,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:pw(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const vw=function t(e){function n(t){return new mw(t,e)}return n.tension=function(e){return t(+e)},n}(0);function bw(t,e){this._context=t,this._k=(1-e)/6}bw.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:pw(this,t,e)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const _w=function t(e){function n(t){return new bw(t,e)}return n.tension=function(e){return t(+e)},n}(0);function xw(t,e,n){var r=t._x1,i=t._y1,a=t._x2,o=t._y2;if(t._l01_a>J_){var s=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*s-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*s-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>J_){var u=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,l=3*t._l23_a*(t._l23_a+t._l12_a);a=(a*u+t._x1*t._l23_2a-e*t._l12_2a)/l,o=(o*u+t._y1*t._l23_2a-n*t._l12_2a)/l}t._context.bezierCurveTo(r,i,a,o,t._x2,t._y2)}function ww(t,e){this._context=t,this._alpha=e}ww.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:xw(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const kw=function t(e){function n(t){return e?new ww(t,e):new gw(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Tw(t,e){this._context=t,this._alpha=e}Tw.prototype={areaStart:iw,areaEnd:iw,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:xw(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const Ew=function t(e){function n(t){return e?new Tw(t,e):new mw(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Cw(t,e){this._context=t,this._alpha=e}Cw.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:xw(this,t,e)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e}};const Sw=function t(e){function n(t){return e?new Cw(t,e):new bw(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function Aw(t){this._context=t}function Mw(t){return new Aw(t)}function Nw(t){return t<0?-1:1}function Dw(t,e,n){var r=t._x1-t._x0,i=e-t._x1,a=(t._y1-t._y0)/(r||i<0&&-0),o=(n-t._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(Nw(a)+Nw(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function Lw(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function Bw(t,e,n){var r=t._x0,i=t._y0,a=t._x1,o=t._y1,s=(a-r)/3;t._context.bezierCurveTo(r+s,i+s*e,a-s,o-s*n,a,o)}function Ow(t){this._context=t}function Iw(t){this._context=new Rw(t)}function Rw(t){this._context=t}function Fw(t){return new Ow(t)}function Pw(t){return new Iw(t)}function Yw(t){this._context=t}function jw(t){var e,n,r=t.length-1,i=new Array(r),a=new Array(r),o=new Array(r);for(i[0]=0,a[0]=2,o[0]=t[0]+2*t[1],e=1;e=0;--e)i[e]=(o[e]-i[e+1])/a[e];for(a[r-1]=(t[r]+i[r-1])/2,e=0;e1)for(var n,r,i,a=1,o=t[e[0]],s=o.length;a=0;)n[e]=e;return n}function Gw(t,e){return t[e]}function Xw(){var t=H_([]),e=Vw,n=Ww,r=Gw;function i(i){var a,o,s=t.apply(this,arguments),c=i.length,u=s.length,l=new Array(u);for(a=0;a0){for(var n,r,i,a=0,o=t[0].length;a0)for(var n,r,i,a,o,s,c=0,u=t[e[0]].length;c0?(r[0]=a,r[1]=a+=i):i<0?(r[1]=o,r[0]=o+=i):(r[0]=0,r[1]=i)}function Qw(t,e){if((n=t.length)>0){for(var n,r=0,i=t[e[0]],a=i.length;r0&&(r=(n=t[e[0]]).length)>0){for(var n,r,i,a=0,o=1;oa&&(a=e,r=n);return r}function nk(t){var e=t.map(rk);return Vw(t).sort((function(t,n){return e[t]-e[n]}))}function rk(t){for(var e,n=0,r=-1,i=t.length;++r=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e)}}this._x=t,this._y=e}};var sk="%Y-%m-%dT%H:%M:%S.%LZ",ck=Date.prototype.toISOString?function(t){return t.toISOString()}:ym(sk);const uk=ck;var lk=+new Date("2000-01-01T00:00:00.000Z")?function(t){var e=new Date(t);return isNaN(e)?null:e}:mm(sk);const hk=lk;function fk(t,e,n){var r=new Wn,i=e;return null==e?(r.restart(t,e,n),r):(e=+e,n=null==n?qn():+n,r.restart((function a(o){o+=i,r.restart(a,i+=e,n),t(o)}),e,n),r)}function dk(t){return function(){return t}}function pk(t){return t[0]}function gk(t){return t[1]}function yk(){this._=null}function mk(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function vk(t,e){var n=e,r=e.R,i=n.U;i?i.L===n?i.L=r:i.R=r:t._=r,r.U=i,n.U=r,n.R=r.L,n.R&&(n.R.U=n),r.L=n}function bk(t,e){var n=e,r=e.L,i=n.U;i?i.L===n?i.L=r:i.R=r:t._=r,r.U=i,n.U=r,n.L=r.R,n.L&&(n.L.U=n),r.R=n}function _k(t){for(;t.L;)t=t.L;return t}yk.prototype={constructor:yk,insert:function(t,e){var n,r,i;if(t){if(e.P=t,e.N=t.N,t.N&&(t.N.P=e),t.N=e,t.R){for(t=t.R;t.L;)t=t.L;t.L=e}else t.R=e;n=t}else this._?(t=_k(this._),e.P=null,e.N=t,t.P=t.L=e,n=t):(e.P=e.N=null,this._=e,n=null);for(e.L=e.R=null,e.U=n,e.C=!0,t=e;n&&n.C;)n===(r=n.U).L?(i=r.R)&&i.C?(n.C=i.C=!1,r.C=!0,t=r):(t===n.R&&(vk(this,n),n=(t=n).U),n.C=!1,r.C=!0,bk(this,r)):(i=r.L)&&i.C?(n.C=i.C=!1,r.C=!0,t=r):(t===n.L&&(bk(this,n),n=(t=n).U),n.C=!1,r.C=!0,vk(this,r)),n=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var e,n,r,i=t.U,a=t.L,o=t.R;if(n=a?o?_k(o):a:o,i?i.L===t?i.L=n:i.R=n:this._=n,a&&o?(r=n.C,n.C=t.C,n.L=a,a.U=n,n!==o?(i=n.U,n.U=t.U,t=n.R,i.L=t,n.R=o,o.U=n):(n.U=i,i=n,t=n.R)):(r=t.C,t=n),t&&(t.U=i),!r)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===i.L){if((e=i.R).C&&(e.C=!1,i.C=!0,vk(this,i),e=i.R),e.L&&e.L.C||e.R&&e.R.C){e.R&&e.R.C||(e.L.C=!1,e.C=!0,bk(this,e),e=i.R),e.C=i.C,i.C=e.R.C=!1,vk(this,i),t=this._;break}}else if((e=i.L).C&&(e.C=!1,i.C=!0,bk(this,i),e=i.L),e.L&&e.L.C||e.R&&e.R.C){e.L&&e.L.C||(e.R.C=!1,e.C=!0,vk(this,e),e=i.L),e.C=i.C,i.C=e.L.C=!1,bk(this,i),t=this._;break}e.C=!0,t=i,i=i.U}while(!t.C);t&&(t.C=!1)}}};const xk=yk;function wk(t,e,n,r){var i=[null,null],a=Wk.push(i)-1;return i.left=t,i.right=e,n&&Tk(i,t,e,n),r&&Tk(i,e,t,r),qk[t.index].halfedges.push(a),qk[e.index].halfedges.push(a),i}function kk(t,e,n){var r=[e,n];return r.left=t,r}function Tk(t,e,n,r){t[0]||t[1]?t.left===n?t[1]=r:t[0]=r:(t[0]=r,t.left=e,t.right=n)}function Ek(t,e,n,r,i){var a,o=t[0],s=t[1],c=o[0],u=o[1],l=0,h=1,f=s[0]-c,d=s[1]-u;if(a=e-c,f||!(a>0)){if(a/=f,f<0){if(a0){if(a>h)return;a>l&&(l=a)}if(a=r-c,f||!(a<0)){if(a/=f,f<0){if(a>h)return;a>l&&(l=a)}else if(f>0){if(a0)){if(a/=d,d<0){if(a0){if(a>h)return;a>l&&(l=a)}if(a=i-u,d||!(a<0)){if(a/=d,d<0){if(a>h)return;a>l&&(l=a)}else if(d>0){if(a0||h<1)||(l>0&&(t[0]=[c+l*f,u+l*d]),h<1&&(t[1]=[c+h*f,u+h*d]),!0)}}}}}function Ck(t,e,n,r,i){var a=t[1];if(a)return!0;var o,s,c=t[0],u=t.left,l=t.right,h=u[0],f=u[1],d=l[0],p=l[1],g=(h+d)/2,y=(f+p)/2;if(p===f){if(g=r)return;if(h>d){if(c){if(c[1]>=i)return}else c=[g,n];a=[g,i]}else{if(c){if(c[1]1)if(h>d){if(c){if(c[1]>=i)return}else c=[(n-s)/o,n];a=[(i-s)/o,i]}else{if(c){if(c[1]=r)return}else c=[e,o*e+s];a=[r,o*r+s]}else{if(c){if(c[0]=-Gk)){var d=c*c+u*u,p=l*l+h*h,g=(h*d-u*p)/f,y=(c*p-l*d)/f,m=Dk.pop()||new Lk;m.arc=t,m.site=i,m.x=g+o,m.y=(m.cy=y+s)+Math.sqrt(g*g+y*y),t.circle=m;for(var v=null,b=Hk._;b;)if(m.yVk)s=s.L;else{if(!((i=a-zk(s,o))>Vk)){r>-Vk?(e=s.P,n=s):i>-Vk?(e=s,n=s.N):e=n=s;break}if(!s.R){e=s;break}s=s.R}!function(t){qk[t.index]={site:t,halfedges:[]}}(t);var c=Fk(t);if($k.insert(e,c),e||n){if(e===n)return Ok(e),n=Fk(e.site),$k.insert(c,n),c.edge=n.edge=wk(e.site,c.site),Bk(e),void Bk(n);if(n){Ok(e),Ok(n);var u=e.site,l=u[0],h=u[1],f=t[0]-l,d=t[1]-h,p=n.site,g=p[0]-l,y=p[1]-h,m=2*(f*y-d*g),v=f*f+d*d,b=g*g+y*y,_=[(y*v-d*b)/m+l,(f*b-g*v)/m+h];Tk(n.edge,u,p,_),c.edge=wk(u,t,null,_),n.edge=wk(t,p,null,_),Bk(e),Bk(n)}else c.edge=wk(e.site,c.site)}}function Uk(t,e){var n=t.site,r=n[0],i=n[1],a=i-e;if(!a)return r;var o=t.P;if(!o)return-1/0;var s=(n=o.site)[0],c=n[1],u=c-e;if(!u)return s;var l=s-r,h=1/a-1/u,f=l/u;return h?(-f+Math.sqrt(f*f-2*h*(l*l/(-2*u)-c+u/2+i-a/2)))/h+r:(r+s)/2}function zk(t,e){var n=t.N;if(n)return Uk(n,e);var r=t.site;return r[1]===e?r[0]:1/0}var $k,qk,Hk,Wk,Vk=1e-6,Gk=1e-12;function Xk(t,e,n){return(t[0]-n[0])*(e[1]-t[1])-(t[0]-e[0])*(n[1]-t[1])}function Zk(t,e){return e[1]-t[1]||e[0]-t[0]}function Kk(t,e){var n,r,i,a=t.sort(Zk).pop();for(Wk=[],qk=new Array(t.length),$k=new xk,Hk=new xk;;)if(i=Nk,a&&(!i||a[1]Vk||Math.abs(i[0][1]-i[1][1])>Vk)||delete Wk[a]}(o,s,c,u),function(t,e,n,r){var i,a,o,s,c,u,l,h,f,d,p,g,y=qk.length,m=!0;for(i=0;iVk||Math.abs(g-f)>Vk)&&(c.splice(s,0,Wk.push(kk(o,d,Math.abs(p-t)Vk?[t,Math.abs(h-t)Vk?[Math.abs(f-r)Vk?[n,Math.abs(h-n)Vk?[Math.abs(f-e)=s)return null;var c=t-i.site[0],u=e-i.site[1],l=c*c+u*u;do{i=a.cells[r=o],o=null,i.halfedges.forEach((function(n){var r=a.edges[n],s=r.left;if(s!==i.site&&s||(s=r.right)){var c=t-s[0],u=e-s[1],h=c*c+u*u;hr?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function fT(){var t,e,n=oT,r=sT,i=hT,a=uT,o=lT,s=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],u=250,l=Lp,h=ft("start","zoom","end"),f=500,d=0;function p(t){t.property("__zoom",cT).on("wheel.zoom",x).on("mousedown.zoom",w).on("dblclick.zoom",k).filter(o).on("touchstart.zoom",T).on("touchmove.zoom",E).on("touchend.zoom touchcancel.zoom",C).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function g(t,e){return(e=Math.max(s[0],Math.min(s[1],e)))===t.k?t:new eT(e,t.x,t.y)}function y(t,e,n){var r=e[0]-n[0]*t.k,i=e[1]-n[1]*t.k;return r===t.x&&i===t.y?t:new eT(t.k,r,i)}function m(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function v(t,e,n){t.on("start.zoom",(function(){b(this,arguments).start()})).on("interrupt.zoom end.zoom",(function(){b(this,arguments).end()})).tween("zoom",(function(){var t=this,i=arguments,a=b(t,i),o=r.apply(t,i),s=null==n?m(o):"function"==typeof n?n.apply(t,i):n,c=Math.max(o[1][0]-o[0][0],o[1][1]-o[0][1]),u=t.__zoom,h="function"==typeof e?e.apply(t,i):e,f=l(u.invert(s).concat(c/u.k),h.invert(s).concat(c/h.k));return function(t){if(1===t)t=h;else{var e=f(t),n=c/e[2];t=new eT(n,s[0]-e[0]*n,s[1]-e[1]*n)}a.zoom(null,t)}}))}function b(t,e,n){return!n&&t.__zooming||new _(t,e)}function _(t,e){this.that=t,this.args=e,this.active=0,this.extent=r.apply(t,e),this.taps=0}function x(){if(n.apply(this,arguments)){var t=b(this,arguments),e=this.__zoom,r=Math.max(s[0],Math.min(s[1],e.k*Math.pow(2,a.apply(this,arguments)))),o=Bn(this);if(t.wheel)t.mouse[0][0]===o[0]&&t.mouse[0][1]===o[1]||(t.mouse[1]=e.invert(t.mouse[0]=o)),clearTimeout(t.wheel);else{if(e.k===r)return;t.mouse=[o,e.invert(o)],ar(this),t.start()}aT(),t.wheel=setTimeout(u,150),t.zoom("mouse",i(y(g(e,r),t.mouse[0],t.mouse[1]),t.extent,c))}function u(){t.wheel=null,t.end()}}function w(){if(!e&&n.apply(this,arguments)){var t=b(this,arguments,!0),r=Te(le.view).on("mousemove.zoom",u,!0).on("mouseup.zoom",l,!0),a=Bn(this),o=le.clientX,s=le.clientY;Se(le.view),iT(),t.mouse=[a,this.__zoom.invert(a)],ar(this),t.start()}function u(){if(aT(),!t.moved){var e=le.clientX-o,n=le.clientY-s;t.moved=e*e+n*n>d}t.zoom("mouse",i(y(t.that.__zoom,t.mouse[0]=Bn(t.that),t.mouse[1]),t.extent,c))}function l(){r.on("mousemove.zoom mouseup.zoom",null),Ae(le.view,t.moved),aT(),t.end()}}function k(){if(n.apply(this,arguments)){var t=this.__zoom,e=Bn(this),a=t.invert(e),o=t.k*(le.shiftKey?.5:2),s=i(y(g(t,o),e,a),r.apply(this,arguments),c);aT(),u>0?Te(this).transition().duration(u).call(v,s,e):Te(this).call(p.transform,s)}}function T(){if(n.apply(this,arguments)){var e,r,i,a,o=le.touches,s=o.length,c=b(this,arguments,le.changedTouches.length===s);for(iT(),r=0;r{t.exports={graphlib:n(574),layout:n(8123),debug:n(7570),util:{time:n(1138).time,notime:n(1138).notime},version:n(8177)}},2188:(t,e,n)=>{"use strict";var r=n(8436),i=n(4079);t.exports={run:function(t){var e="greedy"===t.graph().acyclicer?i(t,function(t){return function(e){return t.edge(e).weight}}(t)):function(t){var e=[],n={},i={};return r.forEach(t.nodes(),(function a(o){r.has(i,o)||(i[o]=!0,n[o]=!0,r.forEach(t.outEdges(o),(function(t){r.has(n,t.w)?e.push(t):a(t.w)})),delete n[o])})),e}(t);r.forEach(e,(function(e){var n=t.edge(e);t.removeEdge(e),n.forwardName=e.name,n.reversed=!0,t.setEdge(e.w,e.v,n,r.uniqueId("rev"))}))},undo:function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.reversed){t.removeEdge(e);var r=n.forwardName;delete n.reversed,delete n.forwardName,t.setEdge(e.w,e.v,n,r)}}))}}},1133:(t,e,n)=>{var r=n(8436),i=n(1138);function a(t,e,n,r,a,o){var s={width:0,height:0,rank:o,borderType:e},c=a[e][o-1],u=i.addDummyNode(t,"border",s,n);a[e][o]=u,t.setParent(u,r),c&&t.setEdge(c,u,{weight:1})}t.exports=function(t){r.forEach(t.children(),(function e(n){var i=t.children(n),o=t.node(n);if(i.length&&r.forEach(i,e),r.has(o,"minRank")){o.borderLeft=[],o.borderRight=[];for(var s=o.minRank,c=o.maxRank+1;s{"use strict";var r=n(8436);function i(t){r.forEach(t.nodes(),(function(e){a(t.node(e))})),r.forEach(t.edges(),(function(e){a(t.edge(e))}))}function a(t){var e=t.width;t.width=t.height,t.height=e}function o(t){t.y=-t.y}function s(t){var e=t.x;t.x=t.y,t.y=e}t.exports={adjust:function(t){var e=t.graph().rankdir.toLowerCase();"lr"!==e&&"rl"!==e||i(t)},undo:function(t){var e=t.graph().rankdir.toLowerCase();"bt"!==e&&"rl"!==e||function(t){r.forEach(t.nodes(),(function(e){o(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,o),r.has(n,"y")&&o(n)}))}(t),"lr"!==e&&"rl"!==e||(function(t){r.forEach(t.nodes(),(function(e){s(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,s),r.has(n,"x")&&s(n)}))}(t),i(t))}}},7822:t=>{function e(){var t={};t._next=t._prev=t,this._sentinel=t}function n(t){t._prev._next=t._next,t._next._prev=t._prev,delete t._next,delete t._prev}function r(t,e){if("_next"!==t&&"_prev"!==t)return e}t.exports=e,e.prototype.dequeue=function(){var t=this._sentinel,e=t._prev;if(e!==t)return n(e),e},e.prototype.enqueue=function(t){var e=this._sentinel;t._prev&&t._next&&n(t),t._next=e._next,e._next._prev=t,e._next=t,t._prev=e},e.prototype.toString=function(){for(var t=[],e=this._sentinel,n=e._prev;n!==e;)t.push(JSON.stringify(n,r)),n=n._prev;return"["+t.join(", ")+"]"}},7570:(t,e,n)=>{var r=n(8436),i=n(1138),a=n(574).Graph;t.exports={debugOrdering:function(t){var e=i.buildLayerMatrix(t),n=new a({compound:!0,multigraph:!0}).setGraph({});return r.forEach(t.nodes(),(function(e){n.setNode(e,{label:e}),n.setParent(e,"layer"+t.node(e).rank)})),r.forEach(t.edges(),(function(t){n.setEdge(t.v,t.w,{},t.name)})),r.forEach(e,(function(t,e){var i="layer"+e;n.setNode(i,{rank:"same"}),r.reduce(t,(function(t,e){return n.setEdge(t,e,{style:"invis"}),e}))})),n}}},574:(t,e,n)=>{var r;try{r=n(8282)}catch(t){}r||(r=window.graphlib),t.exports=r},4079:(t,e,n)=>{var r=n(8436),i=n(574).Graph,a=n(7822);t.exports=function(t,e){if(t.nodeCount()<=1)return[];var n=function(t,e){var n=new i,o=0,s=0;r.forEach(t.nodes(),(function(t){n.setNode(t,{v:t,in:0,out:0})})),r.forEach(t.edges(),(function(t){var r=n.edge(t.v,t.w)||0,i=e(t),a=r+i;n.setEdge(t.v,t.w,a),s=Math.max(s,n.node(t.v).out+=i),o=Math.max(o,n.node(t.w).in+=i)}));var u=r.range(s+o+3).map((function(){return new a})),l=o+1;return r.forEach(n.nodes(),(function(t){c(u,l,n.node(t))})),{graph:n,buckets:u,zeroIdx:l}}(t,e||o),u=function(t,e,n){for(var r,i=[],a=e[e.length-1],o=e[0];t.nodeCount();){for(;r=o.dequeue();)s(t,e,n,r);for(;r=a.dequeue();)s(t,e,n,r);if(t.nodeCount())for(var c=e.length-2;c>0;--c)if(r=e[c].dequeue()){i=i.concat(s(t,e,n,r,!0));break}}return i}(n.graph,n.buckets,n.zeroIdx);return r.flatten(r.map(u,(function(e){return t.outEdges(e.v,e.w)})),!0)};var o=r.constant(1);function s(t,e,n,i,a){var o=a?[]:void 0;return r.forEach(t.inEdges(i.v),(function(r){var i=t.edge(r),s=t.node(r.v);a&&o.push({v:r.v,w:r.w}),s.out-=i,c(e,n,s)})),r.forEach(t.outEdges(i.v),(function(r){var i=t.edge(r),a=r.w,o=t.node(a);o.in-=i,c(e,n,o)})),t.removeNode(i.v),o}function c(t,e,n){n.out?n.in?t[n.out-n.in+e].enqueue(n):t[t.length-1].enqueue(n):t[0].enqueue(n)}},8123:(t,e,n)=>{"use strict";var r=n(8436),i=n(2188),a=n(5995),o=n(8093),s=n(1138).normalizeRanks,c=n(4219),u=n(1138).removeEmptyRanks,l=n(2981),h=n(1133),f=n(3258),d=n(3408),p=n(7873),g=n(1138),y=n(574).Graph;t.exports=function(t,e){var n=e&&e.debugTiming?g.time:g.notime;n("layout",(function(){var e=n(" buildLayoutGraph",(function(){return function(t){var e=new y({multigraph:!0,compound:!0}),n=C(t.graph());return e.setGraph(r.merge({},v,E(n,m),r.pick(n,b))),r.forEach(t.nodes(),(function(n){var i=C(t.node(n));e.setNode(n,r.defaults(E(i,_),x)),e.setParent(n,t.parent(n))})),r.forEach(t.edges(),(function(n){var i=C(t.edge(n));e.setEdge(n,r.merge({},k,E(i,w),r.pick(i,T)))})),e}(t)}));n(" runLayout",(function(){!function(t,e){e(" makeSpaceForEdgeLabels",(function(){!function(t){var e=t.graph();e.ranksep/=2,r.forEach(t.edges(),(function(n){var r=t.edge(n);r.minlen*=2,"c"!==r.labelpos.toLowerCase()&&("TB"===e.rankdir||"BT"===e.rankdir?r.width+=r.labeloffset:r.height+=r.labeloffset)}))}(t)})),e(" removeSelfEdges",(function(){!function(t){r.forEach(t.edges(),(function(e){if(e.v===e.w){var n=t.node(e.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e,label:t.edge(e)}),t.removeEdge(e)}}))}(t)})),e(" acyclic",(function(){i.run(t)})),e(" nestingGraph.run",(function(){l.run(t)})),e(" rank",(function(){o(g.asNonCompoundGraph(t))})),e(" injectEdgeLabelProxies",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.width&&n.height){var r=t.node(e.v),i={rank:(t.node(e.w).rank-r.rank)/2+r.rank,e};g.addDummyNode(t,"edge-proxy",i,"_ep")}}))}(t)})),e(" removeEmptyRanks",(function(){u(t)})),e(" nestingGraph.cleanup",(function(){l.cleanup(t)})),e(" normalizeRanks",(function(){s(t)})),e(" assignRankMinMax",(function(){!function(t){var e=0;r.forEach(t.nodes(),(function(n){var i=t.node(n);i.borderTop&&(i.minRank=t.node(i.borderTop).rank,i.maxRank=t.node(i.borderBottom).rank,e=r.max(e,i.maxRank))})),t.graph().maxRank=e}(t)})),e(" removeEdgeLabelProxies",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);"edge-proxy"===n.dummy&&(t.edge(n.e).labelRank=n.rank,t.removeNode(e))}))}(t)})),e(" normalize.run",(function(){a.run(t)})),e(" parentDummyChains",(function(){c(t)})),e(" addBorderSegments",(function(){h(t)})),e(" order",(function(){d(t)})),e(" insertSelfEdges",(function(){!function(t){var e=g.buildLayerMatrix(t);r.forEach(e,(function(e){var n=0;r.forEach(e,(function(e,i){var a=t.node(e);a.order=i+n,r.forEach(a.selfEdges,(function(e){g.addDummyNode(t,"selfedge",{width:e.label.width,height:e.label.height,rank:a.rank,order:i+ ++n,e:e.e,label:e.label},"_se")})),delete a.selfEdges}))}))}(t)})),e(" adjustCoordinateSystem",(function(){f.adjust(t)})),e(" position",(function(){p(t)})),e(" positionSelfEdges",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);if("selfedge"===n.dummy){var r=t.node(n.e.v),i=r.x+r.width/2,a=r.y,o=n.x-i,s=r.height/2;t.setEdge(n.e,n.label),t.removeNode(e),n.label.points=[{x:i+2*o/3,y:a-s},{x:i+5*o/6,y:a-s},{x:i+o,y:a},{x:i+5*o/6,y:a+s},{x:i+2*o/3,y:a+s}],n.label.x=n.x,n.label.y=n.y}}))}(t)})),e(" removeBorderNodes",(function(){!function(t){r.forEach(t.nodes(),(function(e){if(t.children(e).length){var n=t.node(e),i=t.node(n.borderTop),a=t.node(n.borderBottom),o=t.node(r.last(n.borderLeft)),s=t.node(r.last(n.borderRight));n.width=Math.abs(s.x-o.x),n.height=Math.abs(a.y-i.y),n.x=o.x+n.width/2,n.y=i.y+n.height/2}})),r.forEach(t.nodes(),(function(e){"border"===t.node(e).dummy&&t.removeNode(e)}))}(t)})),e(" normalize.undo",(function(){a.undo(t)})),e(" fixupEdgeLabelCoords",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(r.has(n,"x"))switch("l"!==n.labelpos&&"r"!==n.labelpos||(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset}}))}(t)})),e(" undoCoordinateSystem",(function(){f.undo(t)})),e(" translateGraph",(function(){!function(t){var e=Number.POSITIVE_INFINITY,n=0,i=Number.POSITIVE_INFINITY,a=0,o=t.graph(),s=o.marginx||0,c=o.marginy||0;function u(t){var r=t.x,o=t.y,s=t.width,c=t.height;e=Math.min(e,r-s/2),n=Math.max(n,r+s/2),i=Math.min(i,o-c/2),a=Math.max(a,o+c/2)}r.forEach(t.nodes(),(function(e){u(t.node(e))})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.has(n,"x")&&u(n)})),e-=s,i-=c,r.forEach(t.nodes(),(function(n){var r=t.node(n);r.x-=e,r.y-=i})),r.forEach(t.edges(),(function(n){var a=t.edge(n);r.forEach(a.points,(function(t){t.x-=e,t.y-=i})),r.has(a,"x")&&(a.x-=e),r.has(a,"y")&&(a.y-=i)})),o.width=n-e+s,o.height=a-i+c}(t)})),e(" assignNodeIntersects",(function(){!function(t){r.forEach(t.edges(),(function(e){var n,r,i=t.edge(e),a=t.node(e.v),o=t.node(e.w);i.points?(n=i.points[0],r=i.points[i.points.length-1]):(i.points=[],n=o,r=a),i.points.unshift(g.intersectRect(a,n)),i.points.push(g.intersectRect(o,r))}))}(t)})),e(" reversePoints",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);n.reversed&&n.points.reverse()}))}(t)})),e(" acyclic.undo",(function(){i.undo(t)}))}(e,n)})),n(" updateInputGraph",(function(){!function(t,e){r.forEach(t.nodes(),(function(n){var r=t.node(n),i=e.node(n);r&&(r.x=i.x,r.y=i.y,e.children(n).length&&(r.width=i.width,r.height=i.height))})),r.forEach(t.edges(),(function(n){var i=t.edge(n),a=e.edge(n);i.points=a.points,r.has(a,"x")&&(i.x=a.x,i.y=a.y)})),t.graph().width=e.graph().width,t.graph().height=e.graph().height}(t,e)}))}))};var m=["nodesep","edgesep","ranksep","marginx","marginy"],v={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},b=["acyclicer","ranker","rankdir","align"],_=["width","height"],x={width:0,height:0},w=["minlen","weight","width","height","labeloffset"],k={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(t,e){return r.mapValues(r.pick(t,e),Number)}function C(t){var e={};return r.forEach(t,(function(t,n){e[n.toLowerCase()]=t})),e}},8436:(t,e,n)=>{var r;try{r={cloneDeep:n(361),constant:n(5703),defaults:n(1747),each:n(6073),filter:n(3105),find:n(3311),flatten:n(5564),forEach:n(4486),forIn:n(2620),has:n(8721),isUndefined:n(2353),last:n(928),map:n(5161),mapValues:n(6604),max:n(6162),merge:n(3857),min:n(3632),minBy:n(2762),now:n(7771),pick:n(9722),range:n(6026),reduce:n(4061),sortBy:n(9734),uniqueId:n(3955),values:n(2628),zipObject:n(7287)}}catch(t){}r||(r=window._),t.exports=r},2981:(t,e,n)=>{var r=n(8436),i=n(1138);function a(t,e,n,o,s,c,u){var l=t.children(u);if(l.length){var h=i.addBorderNode(t,"_bt"),f=i.addBorderNode(t,"_bb"),d=t.node(u);t.setParent(h,u),d.borderTop=h,t.setParent(f,u),d.borderBottom=f,r.forEach(l,(function(r){a(t,e,n,o,s,c,r);var i=t.node(r),l=i.borderTop?i.borderTop:r,d=i.borderBottom?i.borderBottom:r,p=i.borderTop?o:2*o,g=l!==d?1:s-c[u]+1;t.setEdge(h,l,{weight:p,minlen:g,nestingEdge:!0}),t.setEdge(d,f,{weight:p,minlen:g,nestingEdge:!0})})),t.parent(u)||t.setEdge(e,h,{weight:0,minlen:s+c[u]})}else u!==e&&t.setEdge(e,u,{weight:0,minlen:n})}t.exports={run:function(t){var e=i.addDummyNode(t,"root",{},"_root"),n=function(t){var e={};function n(i,a){var o=t.children(i);o&&o.length&&r.forEach(o,(function(t){n(t,a+1)})),e[i]=a}return r.forEach(t.children(),(function(t){n(t,1)})),e}(t),o=r.max(r.values(n))-1,s=2*o+1;t.graph().nestingRoot=e,r.forEach(t.edges(),(function(e){t.edge(e).minlen*=s}));var c=function(t){return r.reduce(t.edges(),(function(e,n){return e+t.edge(n).weight}),0)}(t)+1;r.forEach(t.children(),(function(r){a(t,e,s,c,o,n,r)})),t.graph().nodeRankFactor=s},cleanup:function(t){var e=t.graph();t.removeNode(e.nestingRoot),delete e.nestingRoot,r.forEach(t.edges(),(function(e){t.edge(e).nestingEdge&&t.removeEdge(e)}))}}},5995:(t,e,n)=>{"use strict";var r=n(8436),i=n(1138);t.exports={run:function(t){t.graph().dummyChains=[],r.forEach(t.edges(),(function(e){!function(t,e){var n,r,a,o=e.v,s=t.node(o).rank,c=e.w,u=t.node(c).rank,l=e.name,h=t.edge(e),f=h.labelRank;if(u!==s+1){for(t.removeEdge(e),a=0,++s;s{var r=n(8436);t.exports=function(t,e,n){var i,a={};r.forEach(n,(function(n){for(var r,o,s=t.parent(n);s;){if((r=t.parent(s))?(o=a[r],a[r]=s):(o=i,i=s),o&&o!==s)return void e.setEdge(o,s);s=r}}))}},5439:(t,e,n)=>{var r=n(8436);t.exports=function(t,e){return r.map(e,(function(e){var n=t.inEdges(e);if(n.length){var i=r.reduce(n,(function(e,n){var r=t.edge(n),i=t.node(n.v);return{sum:e.sum+r.weight*i.order,weight:e.weight+r.weight}}),{sum:0,weight:0});return{v:e,barycenter:i.sum/i.weight,weight:i.weight}}return{v:e}}))}},3128:(t,e,n)=>{var r=n(8436),i=n(574).Graph;t.exports=function(t,e,n){var a=function(t){for(var e;t.hasNode(e=r.uniqueId("_root")););return e}(t),o=new i({compound:!0}).setGraph({root:a}).setDefaultNodeLabel((function(e){return t.node(e)}));return r.forEach(t.nodes(),(function(i){var s=t.node(i),c=t.parent(i);(s.rank===e||s.minRank<=e&&e<=s.maxRank)&&(o.setNode(i),o.setParent(i,c||a),r.forEach(t[n](i),(function(e){var n=e.v===i?e.w:e.v,a=o.edge(n,i),s=r.isUndefined(a)?0:a.weight;o.setEdge(n,i,{weight:t.edge(e).weight+s})})),r.has(s,"minRank")&&o.setNode(i,{borderLeft:s.borderLeft[e],borderRight:s.borderRight[e]}))})),o}},6630:(t,e,n)=>{"use strict";var r=n(8436);function i(t,e,n){for(var i=r.zipObject(n,r.map(n,(function(t,e){return e}))),a=r.flatten(r.map(e,(function(e){return r.sortBy(r.map(t.outEdges(e),(function(e){return{pos:i[e.w],weight:t.edge(e).weight}})),"pos")})),!0),o=1;o0;)e%2&&(n+=c[e+1]),c[e=e-1>>1]+=t.weight;u+=t.weight*n}))),u}t.exports=function(t,e){for(var n=0,r=1;r{"use strict";var r=n(8436),i=n(2588),a=n(6630),o=n(1026),s=n(3128),c=n(5093),u=n(574).Graph,l=n(1138);function h(t,e,n){return r.map(e,(function(e){return s(t,e,n)}))}function f(t,e){var n=new u;r.forEach(t,(function(t){var i=t.graph().root,a=o(t,i,n,e);r.forEach(a.vs,(function(e,n){t.node(e).order=n})),c(t,n,a.vs)}))}function d(t,e){r.forEach(e,(function(e){r.forEach(e,(function(e,n){t.node(e).order=n}))}))}t.exports=function(t){var e=l.maxRank(t),n=h(t,r.range(1,e+1),"inEdges"),o=h(t,r.range(e-1,-1,-1),"outEdges"),s=i(t);d(t,s);for(var c,u=Number.POSITIVE_INFINITY,p=0,g=0;g<4;++p,++g){f(p%2?n:o,p%4>=2),s=l.buildLayerMatrix(t);var y=a(t,s);y{"use strict";var r=n(8436);t.exports=function(t){var e={},n=r.filter(t.nodes(),(function(e){return!t.children(e).length})),i=r.max(r.map(n,(function(e){return t.node(e).rank}))),a=r.map(r.range(i+1),(function(){return[]})),o=r.sortBy(n,(function(e){return t.node(e).rank}));return r.forEach(o,(function n(i){if(!r.has(e,i)){e[i]=!0;var o=t.node(i);a[o.rank].push(i),r.forEach(t.successors(i),n)}})),a}},9567:(t,e,n)=>{"use strict";var r=n(8436);t.exports=function(t,e){var n={};return r.forEach(t,(function(t,e){var i=n[t.v]={indegree:0,in:[],out:[],vs:[t.v],i:e};r.isUndefined(t.barycenter)||(i.barycenter=t.barycenter,i.weight=t.weight)})),r.forEach(e.edges(),(function(t){var e=n[t.v],i=n[t.w];r.isUndefined(e)||r.isUndefined(i)||(i.indegree++,e.out.push(n[t.w]))})),function(t){var e=[];function n(t){return function(e){var n,i,a,o;e.merged||(r.isUndefined(e.barycenter)||r.isUndefined(t.barycenter)||e.barycenter>=t.barycenter)&&(i=e,a=0,o=0,(n=t).weight&&(a+=n.barycenter*n.weight,o+=n.weight),i.weight&&(a+=i.barycenter*i.weight,o+=i.weight),n.vs=i.vs.concat(n.vs),n.barycenter=a/o,n.weight=o,n.i=Math.min(i.i,n.i),i.merged=!0)}}function i(e){return function(n){n.in.push(e),0==--n.indegree&&t.push(n)}}for(;t.length;){var a=t.pop();e.push(a),r.forEach(a.in.reverse(),n(a)),r.forEach(a.out,i(a))}return r.map(r.filter(e,(function(t){return!t.merged})),(function(t){return r.pick(t,["vs","i","barycenter","weight"])}))}(r.filter(n,(function(t){return!t.indegree})))}},1026:(t,e,n)=>{var r=n(8436),i=n(5439),a=n(9567),o=n(7304);t.exports=function t(e,n,s,c){var u=e.children(n),l=e.node(n),h=l?l.borderLeft:void 0,f=l?l.borderRight:void 0,d={};h&&(u=r.filter(u,(function(t){return t!==h&&t!==f})));var p=i(e,u);r.forEach(p,(function(n){if(e.children(n.v).length){var i=t(e,n.v,s,c);d[n.v]=i,r.has(i,"barycenter")&&(a=n,o=i,r.isUndefined(a.barycenter)?(a.barycenter=o.barycenter,a.weight=o.weight):(a.barycenter=(a.barycenter*a.weight+o.barycenter*o.weight)/(a.weight+o.weight),a.weight+=o.weight))}var a,o}));var g=a(p,s);!function(t,e){r.forEach(t,(function(t){t.vs=r.flatten(t.vs.map((function(t){return e[t]?e[t].vs:t})),!0)}))}(g,d);var y=o(g,c);if(h&&(y.vs=r.flatten([h,y.vs,f],!0),e.predecessors(h).length)){var m=e.node(e.predecessors(h)[0]),v=e.node(e.predecessors(f)[0]);r.has(y,"barycenter")||(y.barycenter=0,y.weight=0),y.barycenter=(y.barycenter*y.weight+m.order+v.order)/(y.weight+2),y.weight+=2}return y}},7304:(t,e,n)=>{var r=n(8436),i=n(1138);function a(t,e,n){for(var i;e.length&&(i=r.last(e)).i<=n;)e.pop(),t.push(i.vs),n++;return n}t.exports=function(t,e){var n,o=i.partition(t,(function(t){return r.has(t,"barycenter")})),s=o.lhs,c=r.sortBy(o.rhs,(function(t){return-t.i})),u=[],l=0,h=0,f=0;s.sort((n=!!e,function(t,e){return t.barycentere.barycenter?1:n?e.i-t.i:t.i-e.i})),f=a(u,c,f),r.forEach(s,(function(t){f+=t.vs.length,u.push(t.vs),l+=t.barycenter*t.weight,h+=t.weight,f=a(u,c,f)}));var d={vs:r.flatten(u,!0)};return h&&(d.barycenter=l/h,d.weight=h),d}},4219:(t,e,n)=>{var r=n(8436);t.exports=function(t){var e=function(t){var e={},n=0;return r.forEach(t.children(),(function i(a){var o=n;r.forEach(t.children(a),i),e[a]={low:o,lim:n++}})),e}(t);r.forEach(t.graph().dummyChains,(function(n){for(var r=t.node(n),i=r.edgeObj,a=function(t,e,n,r){var i,a,o=[],s=[],c=Math.min(e[n].low,e[r].low),u=Math.max(e[n].lim,e[r].lim);i=n;do{i=t.parent(i),o.push(i)}while(i&&(e[i].low>c||u>e[i].lim));for(a=i,i=r;(i=t.parent(i))!==a;)s.push(i);return{path:o.concat(s.reverse()),lca:a}}(t,e,i.v,i.w),o=a.path,s=a.lca,c=0,u=o[c],l=!0;n!==i.w;){if(r=t.node(n),l){for(;(u=o[c])!==s&&t.node(u).maxRank{"use strict";var r=n(8436),i=n(574).Graph,a=n(1138);function o(t,e){var n={};return r.reduce(e,(function(e,i){var a=0,o=0,s=e.length,u=r.last(i);return r.forEach(i,(function(e,l){var h=function(t,e){if(t.node(e).dummy)return r.find(t.predecessors(e),(function(e){return t.node(e).dummy}))}(t,e),f=h?t.node(h).order:s;(h||e===u)&&(r.forEach(i.slice(o,l+1),(function(e){r.forEach(t.predecessors(e),(function(r){var i=t.node(r),o=i.order;!(os)&&c(n,e,u)}))}))}return r.reduce(e,(function(e,n){var a,o=-1,s=0;return r.forEach(n,(function(r,c){if("border"===t.node(r).dummy){var u=t.predecessors(r);u.length&&(a=t.node(u[0]).order,i(n,s,c,o,a),s=c,o=a)}i(n,s,n.length,a,e.length)})),n})),n}function c(t,e,n){if(e>n){var r=e;e=n,n=r}var i=t[e];i||(t[e]=i={}),i[n]=!0}function u(t,e,n){if(e>n){var i=e;e=n,n=i}return r.has(t[e],n)}function l(t,e,n,i){var a={},o={},s={};return r.forEach(e,(function(t){r.forEach(t,(function(t,e){a[t]=t,o[t]=t,s[t]=e}))})),r.forEach(e,(function(t){var e=-1;r.forEach(t,(function(t){var c=i(t);if(c.length){c=r.sortBy(c,(function(t){return s[t]}));for(var l=(c.length-1)/2,h=Math.floor(l),f=Math.ceil(l);h<=f;++h){var d=c[h];o[t]===t&&e{"use strict";var r=n(8436),i=n(1138),a=n(3573).positionX;t.exports=function(t){(function(t){var e=i.buildLayerMatrix(t),n=t.graph().ranksep,a=0;r.forEach(e,(function(e){var i=r.max(r.map(e,(function(e){return t.node(e).height})));r.forEach(e,(function(e){t.node(e).y=a+i/2})),a+=i+n}))})(t=i.asNonCompoundGraph(t)),r.forEach(a(t),(function(e,n){t.node(n).x=e}))}},300:(t,e,n)=>{"use strict";var r=n(8436),i=n(574).Graph,a=n(6681).slack;function o(t,e){return r.forEach(t.nodes(),(function n(i){r.forEach(e.nodeEdges(i),(function(r){var o=r.v,s=i===o?r.w:o;t.hasNode(s)||a(e,r)||(t.setNode(s,{}),t.setEdge(i,s,{}),n(s))}))})),t.nodeCount()}function s(t,e){return r.minBy(e.edges(),(function(n){if(t.hasNode(n.v)!==t.hasNode(n.w))return a(e,n)}))}function c(t,e,n){r.forEach(t.nodes(),(function(t){e.node(t).rank+=n}))}t.exports=function(t){var e,n,r=new i({directed:!1}),u=t.nodes()[0],l=t.nodeCount();for(r.setNode(u,{});o(r,t){"use strict";var r=n(6681).longestPath,i=n(300),a=n(2472);t.exports=function(t){switch(t.graph().ranker){case"network-simplex":default:!function(t){a(t)}(t);break;case"tight-tree":!function(t){r(t),i(t)}(t);break;case"longest-path":o(t)}};var o=r},2472:(t,e,n)=>{"use strict";var r=n(8436),i=n(300),a=n(6681).slack,o=n(6681).longestPath,s=n(574).alg.preorder,c=n(574).alg.postorder,u=n(1138).simplify;function l(t){t=u(t),o(t);var e,n=i(t);for(d(n),h(n,t);e=g(n);)m(n,t,e,y(n,t,e))}function h(t,e){var n=c(t,t.nodes());n=n.slice(0,n.length-1),r.forEach(n,(function(n){!function(t,e,n){var r=t.node(n).parent;t.edge(n,r).cutvalue=f(t,e,n)}(t,e,n)}))}function f(t,e,n){var i=t.node(n).parent,a=!0,o=e.edge(n,i),s=0;return o||(a=!1,o=e.edge(i,n)),s=o.weight,r.forEach(e.nodeEdges(n),(function(r){var o,c,u=r.v===n,l=u?r.w:r.v;if(l!==i){var h=u===a,f=e.edge(r).weight;if(s+=h?f:-f,o=n,c=l,t.hasEdge(o,c)){var d=t.edge(n,l).cutvalue;s+=h?-d:d}}})),s}function d(t,e){arguments.length<2&&(e=t.nodes()[0]),p(t,{},1,e)}function p(t,e,n,i,a){var o=n,s=t.node(i);return e[i]=!0,r.forEach(t.neighbors(i),(function(a){r.has(e,a)||(n=p(t,e,n,a,i))})),s.low=o,s.lim=n++,a?s.parent=a:delete s.parent,n}function g(t){return r.find(t.edges(),(function(e){return t.edge(e).cutvalue<0}))}function y(t,e,n){var i=n.v,o=n.w;e.hasEdge(i,o)||(i=n.w,o=n.v);var s=t.node(i),c=t.node(o),u=s,l=!1;s.lim>c.lim&&(u=c,l=!0);var h=r.filter(e.edges(),(function(e){return l===v(0,t.node(e.v),u)&&l!==v(0,t.node(e.w),u)}));return r.minBy(h,(function(t){return a(e,t)}))}function m(t,e,n,i){var a=n.v,o=n.w;t.removeEdge(a,o),t.setEdge(i.v,i.w,{}),d(t),h(t,e),function(t,e){var n=r.find(t.nodes(),(function(t){return!e.node(t).parent})),i=s(t,n);i=i.slice(1),r.forEach(i,(function(n){var r=t.node(n).parent,i=e.edge(n,r),a=!1;i||(i=e.edge(r,n),a=!0),e.node(n).rank=e.node(r).rank+(a?i.minlen:-i.minlen)}))}(t,e)}function v(t,e,n){return n.low<=e.lim&&e.lim<=n.lim}t.exports=l,l.initLowLimValues=d,l.initCutValues=h,l.calcCutValue=f,l.leaveEdge=g,l.enterEdge=y,l.exchangeEdges=m},6681:(t,e,n)=>{"use strict";var r=n(8436);t.exports={longestPath:function(t){var e={};r.forEach(t.sources(),(function n(i){var a=t.node(i);if(r.has(e,i))return a.rank;e[i]=!0;var o=r.min(r.map(t.outEdges(i),(function(e){return n(e.w)-t.edge(e).minlen})));return o!==Number.POSITIVE_INFINITY&&null!=o||(o=0),a.rank=o}))},slack:function(t,e){return t.node(e.w).rank-t.node(e.v).rank-t.edge(e).minlen}}},1138:(t,e,n)=>{"use strict";var r=n(8436),i=n(574).Graph;function a(t,e,n,i){var a;do{a=r.uniqueId(i)}while(t.hasNode(a));return n.dummy=e,t.setNode(a,n),a}function o(t){return r.max(r.map(t.nodes(),(function(e){var n=t.node(e).rank;if(!r.isUndefined(n))return n})))}t.exports={addDummyNode:a,simplify:function(t){var e=(new i).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){e.setNode(n,t.node(n))})),r.forEach(t.edges(),(function(n){var r=e.edge(n.v,n.w)||{weight:0,minlen:1},i=t.edge(n);e.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)})})),e},asNonCompoundGraph:function(t){var e=new i({multigraph:t.isMultigraph()}).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){t.children(n).length||e.setNode(n,t.node(n))})),r.forEach(t.edges(),(function(n){e.setEdge(n,t.edge(n))})),e},successorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.outEdges(e),(function(e){n[e.w]=(n[e.w]||0)+t.edge(e).weight})),n}));return r.zipObject(t.nodes(),e)},predecessorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.inEdges(e),(function(e){n[e.v]=(n[e.v]||0)+t.edge(e).weight})),n}));return r.zipObject(t.nodes(),e)},intersectRect:function(t,e){var n,r,i=t.x,a=t.y,o=e.x-i,s=e.y-a,c=t.width/2,u=t.height/2;if(!o&&!s)throw new Error("Not possible to find intersection inside of the rectangle");return Math.abs(s)*c>Math.abs(o)*u?(s<0&&(u=-u),n=u*o/s,r=u):(o<0&&(c=-c),n=c,r=c*s/o),{x:i+n,y:a+r}},buildLayerMatrix:function(t){var e=r.map(r.range(o(t)+1),(function(){return[]}));return r.forEach(t.nodes(),(function(n){var i=t.node(n),a=i.rank;r.isUndefined(a)||(e[a][i.order]=n)})),e},normalizeRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank})));r.forEach(t.nodes(),(function(n){var i=t.node(n);r.has(i,"rank")&&(i.rank-=e)}))},removeEmptyRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank}))),n=[];r.forEach(t.nodes(),(function(r){var i=t.node(r).rank-e;n[i]||(n[i]=[]),n[i].push(r)}));var i=0,a=t.graph().nodeRankFactor;r.forEach(n,(function(e,n){r.isUndefined(e)&&n%a!=0?--i:i&&r.forEach(e,(function(e){t.node(e).rank+=i}))}))},addBorderNode:function(t,e,n,r){var i={width:0,height:0};return arguments.length>=4&&(i.rank=n,i.order=r),a(t,"border",i,e)},maxRank:o,partition:function(t,e){var n={lhs:[],rhs:[]};return r.forEach(t,(function(t){e(t)?n.lhs.push(t):n.rhs.push(t)})),n},time:function(t,e){var n=r.now();try{return e()}finally{console.log(t+" time: "+(r.now()-n)+"ms")}},notime:function(t,e){return e()}}},8177:t=>{t.exports="0.8.5"},7856:function(t){t.exports=function(){"use strict";function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(t,n){return e=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},e(t,n)}function n(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function r(t,i,a){return r=n()?Reflect.construct:function(t,n,r){var i=[null];i.push.apply(i,n);var a=new(Function.bind.apply(t,i));return r&&e(a,r.prototype),a},r.apply(null,arguments)}function i(t){return function(t){if(Array.isArray(t))return a(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n1?n-1:0),i=1;i/gm),H=f(/^data-[\-\w.\u00B7-\uFFFF]/),W=f(/^aria-[\-\w]+$/),V=f(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),G=f(/^(?:\w+script|data):/i),X=f(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Z=f(/^html$/i),K=function(){return"undefined"==typeof window?null:window},Q=function(e,n){if("object"!==t(e)||"function"!=typeof e.createPolicy)return null;var r=null,i="data-tt-policy-suffix";n.currentScript&&n.currentScript.hasAttribute(i)&&(r=n.currentScript.getAttribute(i));var a="dompurify"+(r?"#"+r:"");try{return e.createPolicy(a,{createHTML:function(t){return t}})}catch(t){return console.warn("TrustedTypes policy "+a+" could not be created."),null}};return function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:K(),r=function(t){return e(t)};if(r.version="2.3.8",r.removed=[],!n||!n.document||9!==n.document.nodeType)return r.isSupported=!1,r;var a=n.document,o=n.document,s=n.DocumentFragment,c=n.HTMLTemplateElement,u=n.Node,l=n.Element,f=n.NodeFilter,d=n.NamedNodeMap,p=void 0===d?n.NamedNodeMap||n.MozNamedAttrMap:d,g=n.HTMLFormElement,y=n.DOMParser,m=n.trustedTypes,A=l.prototype,J=D(A,"cloneNode"),tt=D(A,"nextSibling"),et=D(A,"childNodes"),nt=D(A,"parentNode");if("function"==typeof c){var rt=o.createElement("template");rt.content&&rt.content.ownerDocument&&(o=rt.content.ownerDocument)}var it=Q(m,a),at=it?it.createHTML(""):"",ot=o,st=ot.implementation,ct=ot.createNodeIterator,ut=ot.createDocumentFragment,lt=ot.getElementsByTagName,ht=a.importNode,ft={};try{ft=N(o).documentMode?o.documentMode:{}}catch(t){}var dt={};r.isSupported="function"==typeof nt&&st&&void 0!==st.createHTMLDocument&&9!==ft;var pt,gt,yt=$,mt=q,vt=H,bt=W,_t=G,xt=X,wt=V,kt=null,Tt=M({},[].concat(i(L),i(B),i(O),i(R),i(P))),Et=null,Ct=M({},[].concat(i(Y),i(j),i(U),i(z))),St=Object.seal(Object.create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),At=null,Mt=null,Nt=!0,Dt=!0,Lt=!1,Bt=!1,Ot=!1,It=!1,Rt=!1,Ft=!1,Pt=!1,Yt=!1,jt=!0,Ut=!0,zt=!1,$t={},qt=null,Ht=M({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Wt=null,Vt=M({},["audio","video","img","source","image","track"]),Gt=null,Xt=M({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Zt="http://www.w3.org/1998/Math/MathML",Kt="http://www.w3.org/2000/svg",Qt="http://www.w3.org/1999/xhtml",Jt=Qt,te=!1,ee=["application/xhtml+xml","text/html"],ne="text/html",re=null,ie=o.createElement("form"),ae=function(t){return t instanceof RegExp||t instanceof Function},oe=function(e){re&&re===e||(e&&"object"===t(e)||(e={}),e=N(e),kt="ALLOWED_TAGS"in e?M({},e.ALLOWED_TAGS):Tt,Et="ALLOWED_ATTR"in e?M({},e.ALLOWED_ATTR):Ct,Gt="ADD_URI_SAFE_ATTR"in e?M(N(Xt),e.ADD_URI_SAFE_ATTR):Xt,Wt="ADD_DATA_URI_TAGS"in e?M(N(Vt),e.ADD_DATA_URI_TAGS):Vt,qt="FORBID_CONTENTS"in e?M({},e.FORBID_CONTENTS):Ht,At="FORBID_TAGS"in e?M({},e.FORBID_TAGS):{},Mt="FORBID_ATTR"in e?M({},e.FORBID_ATTR):{},$t="USE_PROFILES"in e&&e.USE_PROFILES,Nt=!1!==e.ALLOW_ARIA_ATTR,Dt=!1!==e.ALLOW_DATA_ATTR,Lt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Bt=e.SAFE_FOR_TEMPLATES||!1,Ot=e.WHOLE_DOCUMENT||!1,Ft=e.RETURN_DOM||!1,Pt=e.RETURN_DOM_FRAGMENT||!1,Yt=e.RETURN_TRUSTED_TYPE||!1,Rt=e.FORCE_BODY||!1,jt=!1!==e.SANITIZE_DOM,Ut=!1!==e.KEEP_CONTENT,zt=e.IN_PLACE||!1,wt=e.ALLOWED_URI_REGEXP||wt,Jt=e.NAMESPACE||Qt,e.CUSTOM_ELEMENT_HANDLING&&ae(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(St.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ae(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(St.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(St.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),pt=pt=-1===ee.indexOf(e.PARSER_MEDIA_TYPE)?ne:e.PARSER_MEDIA_TYPE,gt="application/xhtml+xml"===pt?function(t){return t}:x,Bt&&(Dt=!1),Pt&&(Ft=!0),$t&&(kt=M({},i(P)),Et=[],!0===$t.html&&(M(kt,L),M(Et,Y)),!0===$t.svg&&(M(kt,B),M(Et,j),M(Et,z)),!0===$t.svgFilters&&(M(kt,O),M(Et,j),M(Et,z)),!0===$t.mathMl&&(M(kt,R),M(Et,U),M(Et,z))),e.ADD_TAGS&&(kt===Tt&&(kt=N(kt)),M(kt,e.ADD_TAGS)),e.ADD_ATTR&&(Et===Ct&&(Et=N(Et)),M(Et,e.ADD_ATTR)),e.ADD_URI_SAFE_ATTR&&M(Gt,e.ADD_URI_SAFE_ATTR),e.FORBID_CONTENTS&&(qt===Ht&&(qt=N(qt)),M(qt,e.FORBID_CONTENTS)),Ut&&(kt["#text"]=!0),Ot&&M(kt,["html","head","body"]),kt.table&&(M(kt,["tbody"]),delete At.tbody),h&&h(e),re=e)},se=M({},["mi","mo","mn","ms","mtext"]),ce=M({},["foreignobject","desc","title","annotation-xml"]),ue=M({},["title","style","font","a","script"]),le=M({},B);M(le,O),M(le,I);var he=M({},R);M(he,F);var fe=function(t){var e=nt(t);e&&e.tagName||(e={namespaceURI:Qt,tagName:"template"});var n=x(t.tagName),r=x(e.tagName);return t.namespaceURI===Kt?e.namespaceURI===Qt?"svg"===n:e.namespaceURI===Zt?"svg"===n&&("annotation-xml"===r||se[r]):Boolean(le[n]):t.namespaceURI===Zt?e.namespaceURI===Qt?"math"===n:e.namespaceURI===Kt?"math"===n&&ce[r]:Boolean(he[n]):t.namespaceURI===Qt&&!(e.namespaceURI===Kt&&!ce[r])&&!(e.namespaceURI===Zt&&!se[r])&&!he[n]&&(ue[n]||!le[n])},de=function(t){_(r.removed,{element:t});try{t.parentNode.removeChild(t)}catch(e){try{t.outerHTML=at}catch(e){t.remove()}}},pe=function(t,e){try{_(r.removed,{attribute:e.getAttributeNode(t),from:e})}catch(t){_(r.removed,{attribute:null,from:e})}if(e.removeAttribute(t),"is"===t&&!Et[t])if(Ft||Pt)try{de(e)}catch(t){}else try{e.setAttribute(t,"")}catch(t){}},ge=function(t){var e,n;if(Rt)t=""+t;else{var r=w(t,/^[\r\n\t ]+/);n=r&&r[0]}"application/xhtml+xml"===pt&&(t=''+t+"");var i=it?it.createHTML(t):t;if(Jt===Qt)try{e=(new y).parseFromString(i,pt)}catch(t){}if(!e||!e.documentElement){e=st.createDocument(Jt,"template",null);try{e.documentElement.innerHTML=te?"":i}catch(t){}}var a=e.body||e.documentElement;return t&&n&&a.insertBefore(o.createTextNode(n),a.childNodes[0]||null),Jt===Qt?lt.call(e,Ot?"html":"body")[0]:Ot?e.documentElement:a},ye=function(t){return ct.call(t.ownerDocument||t,t,f.SHOW_ELEMENT|f.SHOW_COMMENT|f.SHOW_TEXT,null,!1)},me=function(t){return t instanceof g&&("string"!=typeof t.nodeName||"string"!=typeof t.textContent||"function"!=typeof t.removeChild||!(t.attributes instanceof p)||"function"!=typeof t.removeAttribute||"function"!=typeof t.setAttribute||"string"!=typeof t.namespaceURI||"function"!=typeof t.insertBefore)},ve=function(e){return"object"===t(u)?e instanceof u:e&&"object"===t(e)&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},be=function(t,e,n){dt[t]&&v(dt[t],(function(t){t.call(r,e,n,re)}))},_e=function(t){var e;if(be("beforeSanitizeElements",t,null),me(t))return de(t),!0;if(C(/[\u0080-\uFFFF]/,t.nodeName))return de(t),!0;var n=gt(t.nodeName);if(be("uponSanitizeElement",t,{tagName:n,allowedTags:kt}),t.hasChildNodes()&&!ve(t.firstElementChild)&&(!ve(t.content)||!ve(t.content.firstElementChild))&&C(/<[/\w]/g,t.innerHTML)&&C(/<[/\w]/g,t.textContent))return de(t),!0;if("select"===n&&C(/