Commit
·
a916245
1
Parent(s):
7bd1180
Update parquet files (step 53 of 121)
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- spaces/1acneusushi/gradio-2dmoleculeeditor/data/Band In A Box Torrent 14l LINK.md +0 -118
- spaces/1gistliPinn/ChatGPT4/Examples/!NEW! Download Multimc 4.3.0 Ulozto.md +0 -6
- spaces/1gistliPinn/ChatGPT4/Examples/(2011) Descargar Libro Matematica Basica De Venero Gratis.md +0 -12
- spaces/1gistliPinn/ChatGPT4/Examples/Call Of Duty Modern Warfare 2 English Language Patch.md +0 -6
- spaces/1gistliPinn/ChatGPT4/Examples/Download ((LINK)) Left 4 Dead 2 Trainer 2.0.2.7 41.md +0 -5
- spaces/1gistliPinn/ChatGPT4/Examples/Fire In The Valley Female Genital Massagetorrent.md +0 -62
- spaces/1gistliPinn/ChatGPT4/Examples/Followlikerfreecrackedsoftware ((BETTER)).md +0 -6
- spaces/1line/AutoGPT/autogpt/config/singleton.py +0 -24
- spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/60 Seconds APK Ration Food Hunt Mutants and Stay Sane.md +0 -155
- spaces/1phancelerku/anime-remove-background/Download Tiktok Mod Apk and Get Unlimited Coins for Free in 2023.md +0 -119
- spaces/1phancelerku/anime-remove-background/Film The Polar Express (2004) Sub Indo Gratis Download di Sini.md +0 -156
- spaces/777DUKE/Ballin/Dockerfile +0 -21
- spaces/7hao/bingo/src/components/chat-history.tsx +0 -48
- spaces/AB-TW/team-ai/models.py +0 -13
- spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/encoders.py +0 -169
- spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/parallel_wavegan/layers/residual_block.py +0 -129
- spaces/AIGC-Audio/AudioGPT/NeuralSeq/tasks/tts/tts_utils.py +0 -54
- spaces/ASJMO/freegpt/g4f/Provider/Providers/Easychat.py +0 -55
- spaces/AchyuthGamer/OpenGPT-Chat-UI/.svelte-kit/generated/client/nodes/7.js +0 -0
- spaces/Aki004/herta-so-vits/vdecoder/hifigan/env.py +0 -15
- spaces/Alican/pixera/models/base_model.py +0 -230
- spaces/Andres99/Tune-A-Video-Training-UI/style.css +0 -3
- spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/pix2pix_zero.md +0 -284
- spaces/Andy1621/uniformer_image_segmentation/configs/apcnet/apcnet_r50-d8_512x512_80k_ade20k.py +0 -6
- spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/GPTQ_loader.py +0 -168
- spaces/Ariharasudhan/YoloV5/utils/loggers/comet/README.md +0 -256
- spaces/Atualli/yoloxTeste/app.py +0 -76
- spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/Misc/torchvision_imagenet_R_50.py +0 -150
- spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/evaluation/evaluator.py +0 -224
- spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/modeling/proposal_generator/rrpn.py +0 -203
- spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tools/deploy/README.md +0 -66
- spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/operations/build/metadata.py +0 -39
- spaces/CVPR/LIVE/pybind11/include/pybind11/iostream.h +0 -209
- spaces/CVPR/LIVE/thrust/thrust/zip_function.h +0 -211
- spaces/Crossbro/succinctly-text2image-prompt-generator/app.py +0 -3
- spaces/DEEMOSTECH/ChatAvatar/static/js/main.22ab9e68.js +0 -0
- spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/anyio/_core/_fileio.py +0 -603
- spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fastapi/routing.py +0 -1358
- spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/cu2qu/__main__.py +0 -6
- spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/routes.py +0 -827
- spaces/DaleChen/AutoGPT/benchmark/benchmark_entrepeneur_gpt_with_difficult_user.py +0 -105
- spaces/DataScienceEngineering/4-GeneratorCalcPipe/README.md +0 -13
- spaces/DavidHosp/Movie_Recommendation_System/app.py +0 -111
- spaces/DeepDrivePL/PaddleSeg-Matting/matting/dataset/__init__.py +0 -15
- spaces/Detomo/ai-comic-generation/src/app/interface/progress/index.tsx +0 -56
- spaces/EXFINITE/BlenderBot-UI/app.py +0 -44
- spaces/Eddycrack864/Applio-Inference/demucs/wav.py +0 -174
- spaces/Faridmaruf/rvc-Blue-archives/config.py +0 -117
- spaces/FridaZuley/RVC_HFKawaii/infer/lib/uvr5_pack/lib_v5/layers_537238KB.py +0 -126
- spaces/GMFTBY/PandaGPT/datasets/__init__.py +0 -40
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Band In A Box Torrent 14l LINK.md
DELETED
@@ -1,118 +0,0 @@
|
|
1 |
-
|
2 |
-
<h1>Band In A Box Torrent 14l: A Complete Guide for Music Producers</h1>
|
3 |
-
<p>If you're looking for a way to create professional-quality arrangements of music in any style and genre, you might want to check out Band In A Box, a software that does exactly that. But what if you don't want to pay for it? Is there a way to get it for free? And is it safe and legal to do so?</p>
|
4 |
-
<h2>Band In A Box Torrent 14l</h2><br /><p><b><b>DOWNLOAD</b> ✦ <a href="https://byltly.com/2uKyJx">https://byltly.com/2uKyJx</a></b></p><br /><br />
|
5 |
-
<p>In this article, we'll answer these questions and more. We'll explain what Band In A Box is, what torrenting is, and how you can download and install Band In A Box Torrent 14l on your computer. We'll also show you how to use the software to create amazing songs in minutes. And we'll give you some tips and resources to help you improve your music production skills.</p>
|
6 |
-
<p>Ready to get started? Let's go!</p>
|
7 |
-
<h2>What Is Band In A Box and What Does It Do?</h2>
|
8 |
-
<p>Band In A Box is a music accompaniment software that allows you to create songs by simply typing in the chords using standard symbols (like C, Fm7, or C13b9), choosing a style (like jazz, pop, rock, or country), and letting the software do the rest. Band In A Box automatically generates a complete arrangement of piano, bass, drums, guitar, strings, horns, and other instruments in a wide variety of popular styles.</p>
|
9 |
-
<p>But that's not all. You can also customize your arrangement by changing the tempo, key, instrumentation, volume, panning, effects, loops, vocals, and more. You can edit each track individually or as a whole. You can add your own melodies, lyrics, solos, or harmonies. You can export your songs as audio files or MIDI files. You can share your songs online or collaborate with other musicians. You can even use Band In A Box as a plugin in your favorite DAW (digital audio workstation).</p>
|
10 |
-
<p>Band In A Box is a powerful and creative music composition tool that can help you explore and develop musical ideas with near-instantaneous feedback. Whether you're a beginner or an expert, you can use Band In A Box to create songs for fun, practice, performance, or professional projects.</p>
|
11 |
-
<p></p>
|
12 |
-
<h2>What Is Torrenting and Why Is It Used for Software Distribution?</h2>
|
13 |
-
<p>Torrenting is a type of file sharing that uses a peer-to-peer (P2P) protocol called BitTorrent. Unlike traditional file sharing that relies on central servers, torrenting distributes files among users who are connected in a network called a swarm. Each user who downloads or uploads a file is called a peer.</p>
|
14 |
-
<p>When you torrent a file, you don't download it from a single source. Instead, you download small pieces of the file from different peers who already have it or are downloading it at the same time as you. This way, you can download large files faster and more efficiently than from a single server.</p>
|
15 |
-
<p>Torrenting is often used for distributing software because it has several advantages over other methods. Some of these advantages are:</p>
|
16 |
-
<ul>
|
17 |
-
<li>It reduces the server load and bandwidth costs for the software developers and distributors.</li>
|
18 |
-
<li>It allows users to access the software from multiple sources and locations, increasing the availability and reliability of the download.</li>
|
19 |
-
<li>It enables users to verify the integrity and authenticity of the software by checking the hash values and digital signatures of the files.</li>
|
20 |
-
<li>It creates a community of users who can share feedback, reviews, ratings, comments, and suggestions about the software.</li>
|
21 |
-
</ul>
|
22 |
-
<p>However, torrenting also has some disadvantages and risks that you should be aware of before you decide to use it. Some of these disadvantages and risks are:</p>
|
23 |
-
<ul>
|
24 |
-
<li>It may expose you to legal issues and penalties if you torrent software that is protected by intellectual property rights or licensing agreements. You may be violating the law and the terms of use of the software by downloading, installing, or using it without permission or payment.</li>
|
25 |
-
<li>It may expose you to security threats and malware infections if you torrent software from untrusted or malicious sources. You may download files that contain viruses, spyware, ransomware, or other harmful programs that can damage your computer or steal your personal information.</li>
|
26 |
-
<li>It may expose you to ethical dilemmas and moral conflicts if you torrent software that is developed by hard-working and honest developers who deserve to be compensated for their work. You may be depriving them of their rightful income and recognition by using their software for free.</li>
|
27 |
-
</ul>
|
28 |
-
<p>Torrenting is a complex and controversial topic that has no clear-cut answer. It depends on your personal judgment, values, and circumstances. You should weigh the pros and cons carefully and make an informed decision based on your own research and understanding of the law.</p>
|
29 |
-
<h2>How to Download and Install Band In A Box Torrent 14l</h2>
|
30 |
-
<p>If you have decided to torrent Band In A Box, you need to follow some steps to download and install it on your computer. Here are the steps you need to take:</p>
|
31 |
-
<h3>Step 1: Find a reliable torrent source</h3>
|
32 |
-
<p>The first step is to find a website that offers Band In A Box Torrent 14l as a torrent file. A torrent file is a small file that contains information about the software, such as its name, size, hash value, trackers, peers, and seeds. You need this file to start the download process.</p>
|
33 |
-
<p>There are many websites that offer torrent files for various software, but not all of them are reliable or safe. Some of them may have fake or outdated files, low-quality or incomplete files, or infected or corrupted files. You need to be careful and choose a reputable and trustworthy website that has positive reviews, ratings, comments, and feedback from other users.</p>
|
34 |
-
<p>Some of the factors you should look for when choosing a torrent source are:</p>
|
35 |
-
<ul>
|
36 |
-
<li>The number of seeds and peers: Seeds are users who have the complete file and are uploading it to others. Peers are users who are downloading or uploading parts of the file. The more seeds and peers a torrent file has, the faster and more stable the download will be.</li>
|
37 |
-
<li>The file size and format: The file size should match the expected size of the software. The file format should be compatible with your operating system and your torrent client. The most common file formats for software are .exe, .zip, .rar, .iso, .dmg, .tar.gz, etc.</li>
|
38 |
-
<li>The hash value and digital signature: The hash value is a unique code that identifies the file and verifies its integrity. The digital signature is a code that confirms the authenticity of the file and its source. You can check these codes using online tools or your torrent client.</li>
|
39 |
-
</ul>
|
40 |
-
<p>Some examples of websites that offer Band In A Box Torrent 14l as a torrent file are:</p>
|
41 |
-
<table>
|
42 |
-
<tr><th>Name</th><th>URL</th><th>Seeds</th><th>Peers</th><th>File Size</th><th>File Format</th><th>Hash Value</th><th>Digital Signature</th></tr>
|
43 |
-
<tr><td>The Pirate Bay</td><td>[1](https://thepiratebay.org/description.php?id=12345678)</td><td>1000</td><td>500</td><td>1.5 GB</td><td>.zip</td><td>d41d8cd98f00b204e9800998ecf8427e</td><td>PirateBayCertified</td></tr>
|
44 |
-
<tr><td>RARBG</td><td>[2](https://rarbg.to/torrent/9k8j7h6)</td><td>800</td><td>400</td><td>1.6 GB</td><td>.rar</td><td>c4ca4238a0b923820dcc509a6f758 49b</td><td>RARBGVerified</td></tr>
|
45 |
-
<tr><td>1337x</td><td>[3](https://1337x.to/torrent/45678901/Band-In-A-Box-Torrent-14l)</td><td>600</td><td>300</td><td>1.7 GB</td><td>.iso</td><td>c81e728d9d4c2f636f067f89cc14862c</td><td>1337xCertified</td></tr>
|
46 |
-
</table>
|
47 |
-
<p>Note: The information in the table is for illustration purposes only and may not reflect the actual data of the torrent files. You should always check the details of the torrent files before downloading them.</p>
|
48 |
-
<h3>Step 2: Use a torrent client and a VPN to download the software safely and anonymously</h3>
|
49 |
-
<p>The second step is to use a software that can read and process the torrent file and connect you to the swarm of peers. This software is called a torrent client. There are many torrent clients available for different operating systems, such as uTorrent, BitTorrent, qBittorrent, Transmission, Deluge, etc. You can choose the one that suits your preferences and needs.</p>
|
50 |
-
<p>To use a torrent client, you need to download and install it on your computer. Then, you need to open the torrent file with the torrent client and choose a location to save the software on your hard drive. The torrent client will then start downloading the software from the peers in the swarm. You can monitor the progress of the download and adjust the settings of the torrent client as you wish.</p>
|
51 |
-
<p>However, downloading software from torrenting is not without risks. As we mentioned earlier, you may face legal issues, security threats, or ethical dilemmas by doing so. To protect yourself from these risks, you should use a VPN (virtual private network) service along with your torrent client.</p>
|
52 |
-
<p>A VPN is a service that creates a secure and encrypted connection between your computer and a remote server. By using a VPN, you can hide your IP address, location, identity, and online activity from your ISP (internet service provider), government agencies, hackers, or anyone else who might be monitoring your network. You can also access geo-restricted or censored content by choosing a server in a different country.</p>
|
53 |
-
<p>To use a VPN, you need to sign up for a VPN service provider and download and install their software on your computer. Then, you need to launch the VPN software and connect to a server of your choice. Once you are connected, you can start using your torrent client as usual. The VPN will encrypt and anonymize your traffic and make it look like you are downloading from a different location.</p>
|
54 |
-
<p>Some of the factors you should look for when choosing a VPN service provider are:</p>
|
55 |
-
<ul>
|
56 |
-
<li>The speed and bandwidth: The speed and bandwidth of the VPN service should be fast and unlimited to ensure a smooth and uninterrupted download experience.</li>
|
57 |
-
<li>The security and privacy: The security and privacy of the VPN service should be strong and reliable to prevent any leaks or breaches of your data. The VPN service should use advanced encryption protocols, such as OpenVPN or IKEv2/IPSec, and have a strict no-logs policy.</li>
|
58 |
-
<li>The compatibility and usability: The compatibility and usability of the VPN service should be high and easy to use with any operating system, device, or torrent client. The VPN service should have user-friendly interfaces, features, and support.</li>
|
59 |
-
<li>The price and value: The price and value of the VPN service should be reasonable and affordable for your budget and needs. The VPN service should offer flexible plans, discounts, free trials, or money-back guarantees.</li>
|
60 |
-
</ul>
|
61 |
-
<p>Some examples of VPN service providers that are suitable for torrenting are:</p>
|
62 |
-
<table>
|
63 |
-
<tr><th>Name</th><th>URL</th><th>Speed</th><th>Bandwidth</th><th>Security</th><th>Privacy</th><th>Compatibility</th><th>Usability</th><th>Price</th></tr>
|
64 |
-
<tr><td>NordVPN</td><td>[4](https://nordvpn.com/)</td><td>Fast</td><td>Unlimited</td><td>AES-256 encryption, kill switch, DNS leak protection, CyberSec feature</td><td>No-logs policy, Panama jurisdiction, Onion over VPN feature</td><td>Windows, Mac, Linux, Android, iOS, routers, smart TVs, etc.</td><td>User-friendly interface, easy installation and setup, 24/7 customer support, live chat, email, FAQ, etc.</td><td>$3.71/month (2-year plan), $4.92/month (1-year plan), $11.95/month (1-month plan), 30-day money-back guarantee</td></tr>
|
65 |
-
<tr><td>ExpressVPN</td><td>[5](https://www.expressvpn.com/)</td><td>Very fast</td><td>Unlimited</td><td>AES-256 encryption, kill switch, DNS leak protection, split tunneling feature</td><td>No-logs policy, British Virgin Islands jurisdiction, TrustedServer feature</td><td>Windows, Mac, Linux, Android, iOS, routers, smart TVs, etc.</td><td>User-friendly interface, easy installation and setup, 24/7 customer support, live chat, email, FAQ, etc.</td><td>$6.67/month (15-month plan), $9.99/month (6-month plan), $12.95/month (1-month plan), 30-day money-back guarantee</td></tr>
|
66 |
-
<tr><td>Surfshark</td><td>[6](https://surfshark.com/)</td><td>Fast</td><td>Unlimited</td><td>AES-256 encryption, kill switch, DNS leak protection, CleanWeb feature</td><td>No-logs policy, British Virgin Islands jurisdiction, MultiHop feature</td><td>Windows, Mac, Linux, Android, iOS, routers, smart TVs, etc.</td><td>User-friendly interface, easy installation and setup, 24/7 customer support, live chat, email, FAQ, etc.</td><td>$2.49/month (2-year plan), $6.49/month (6-month plan), $12.95/month (1-month plan), 30-day money-back guarantee</td></tr>
|
67 |
-
</table>
|
68 |
-
<p>Note: The information in the table is for illustration purposes only and may not reflect the actual data of the VPN service providers. You should always check the details of the VPN service providers before signing up for them.</p>
|
69 |
-
<h3>Step 3: Run the setup file and the update file</h3>
|
70 |
-
<p>The third step is to run the setup file and the update file that you have downloaded from the torrent source. These files are usually compressed in a .zip or .rar format and need to be extracted first using a software like WinRAR or 7-Zip. After extracting the files, you should see a folder that contains the setup file and the update file.</p>
|
71 |
-
<p>To run the setup file, you need to double-click on it and follow the instructions on the screen. You may need to choose a language, accept the terms and conditions, select a destination folder, and customize some options. The setup file will then install Band In A Box on your computer.</p>
|
72 |
-
<p>To run the update file, you need to double-click on it and follow the instructions on the screen. You may need to choose a language and confirm some settings. The update file will then update Band In A Box to the latest version.</p>
|
73 |
-
<h3>Step 4: Apply the crack files and activate the software</h3>
|
74 |
-
<p>The fourth step is to apply the crack files and activate the software. The crack files are files that modify or bypass the original files of the software to remove or disable its protection mechanisms. By applying the crack files, you can use Band In A Box without paying for it or entering a serial number or a license key.</p>
|
75 |
-
<p>The crack files are usually included in the folder that contains the setup file and the update file. They may have names like crack.exe, patch.exe, keygen.exe, activator.exe, etc. They may also be in a subfolder called crack, patch, keygen, activator, etc. You need to copy and paste these files into the installation folder of Band In A Box, which is usually located in C:\Program Files (x86)\PG Music Inc\Band-in-a-Box 14l or a similar path. You may need to overwrite or replace the original files when prompted. To activate the software, you need to run the crack files and follow the instructions on the screen. You may need to enter some information, such as your name, email, or a fake serial number or license key. The crack files will then generate a code or a file that will activate Band In A Box and unlock all its features. Note: Applying crack files and activating software is illegal and unethical. It may also harm your computer or expose you to malware infections. You should only use crack files and activate software at your own risk and responsibility. <h2>How to Use Band In A Box Torrent 14l</h2>
|
76 |
-
<p>Now that you have downloaded and installed Band In A Box Torrent 14l on your computer, you can start using it to create songs. Here are some basic steps you can follow to use the software:</p>
|
77 |
-
<h3>Step 1: Create a new song using the chord wizard and the style picker</h3>
|
78 |
-
<p>The first step is to create a new song using the chord wizard and the style picker. The chord wizard is a feature that helps you enter the chords for your song using standard symbols or by clicking on a keyboard or a guitar fretboard. The style picker is a feature that helps you choose a style for your song from over 3000 styles in various genres and categories.</p>
|
79 |
-
<p>To use the chord wizard, you need to click on the Chord Wizard button on the toolbar or press F2 on your keyboard. A window will pop up where you can enter the chords for your song. You can type in the chords using standard symbols, such as C, Fm7, or C13b9, or you can click on the keyboard or the guitar fretboard icons to enter the chords graphically. You can also use the Chord Builder button to create custom chords or use the Chord Theory button to learn more about chord theory.</p>
|
80 |
-
<p>To use the style picker, you need to click on the Style Picker button on the toolbar or press F9 on your keyboard. A window will pop up where you can choose a style for your song. You can browse through the styles by genre, category, feel, time signature, tempo, artist, etc. You can also use the search box to find a specific style by name or keyword. You can preview each style by clicking on it and listening to a short demo.</p>
|
81 |
-
<p>Once you have entered the chords and chosen a style for your song, you can click on the OK button to close the windows and generate your arrangement.</p>
|
82 |
-
<h3>Step 2: Customize the arrangement using the track settings and the mixer</h3>
|
83 |
-
<p>The second step is to customize your arrangement using the track settings and the mixer. The track settings are features that allow you to adjust the parameters of each track in your arrangement, such as the instrument, the volume, the panning, the effects, the loops, the vocals, etc. The mixer is a feature that allows you to control the overall sound of your arrangement, such as the master volume, the balance, the EQ, the reverb, the compression, etc.</p>
|
84 |
-
<p>To use the track settings, you need to click on the Track Settings button on the toolbar or press F5 on your keyboard. A window will pop up where you can see and modify the settings of each track in your arrangement. You can change the instrument by clicking on the Instrument button and choosing from a list of over 3000 instruments in various categories. You can change the volume by dragging the Volume slider or typing in a value. You can change the panning by dragging the Pan slider or typing in a value. You can add effects by clicking on the FX button and choosing from a list of over 50 effects in various categories. You can add loops by clicking on the Loops button and choosing from a list of over 1000 loops in various styles and genres. You can add vocals by clicking on the Vocals button and choosing from a list of over 300 vocal tracks in various languages and styles.</p>
|
85 |
-
<p>To use the mixer, you need to click on the Mixer button on the toolbar or press F3 on your keyboard. A window will pop up where you can see and modify the sound of your arrangement. You can change the master volume by dragging the Master Volume slider or typing in a value. You can change the balance by dragging the Balance slider or typing in a value. You can adjust the EQ by clicking on the EQ button and choosing from a list of presets or customizing your own settings. You can add reverb by clicking on the Reverb button and choosing from a list of presets or customizing your own settings. You can add compression by clicking on the Compression button and choosing from a list of presets or customizing your own settings.</p>
|
86 |
-
<p>Once you have customized your arrangement using the track settings and the mixer, you can click on the OK button to close the windows and apply your changes.</p>
|
87 |
-
<h3>Step 3: Add effects, loops, vocals, and other elements using the plugins and the audio editor</h3>
|
88 |
-
<p>The third step is to add effects, loops, vocals, and other elements using the plugins and the audio editor. The plugins are features that allow you to enhance your arrangement with additional sounds and functions, such as synthesizers, samplers, drum machines, guitar amps, vocal harmonizers, etc. The audio editor is a feature that allows you to edit your arrangement as a waveform, such as cutting, copying, pasting, trimming, fading, etc.</p>
|
89 |
-
<p>To use the plugins, you need to click on the Plugins button on the toolbar or press F4 on your keyboard. A window will pop up where you can see and access the plugins that are available for Band In A Box. You can choose from over 100 plugins in various categories, such as PG Music Plugins, VST Plugins, DX Plugins, etc. You can also add your own plugins by clicking on the Add button and browsing for the plugin file on your computer.</p>
|
90 |
-
<p>To use the audio editor, you need to click on the Audio Edit button on the toolbar or press F10 on your keyboard. A window will pop up where you can see and edit your arrangement as a waveform. You can use the tools on the toolbar to perform various editing operations, such as select, cut, copy, paste, trim, fade, normalize, etc. You can also use the menu options to perform more advanced editing operations, such as undo, redo, zoom, crop, split, merge, etc.</p>
|
91 |
-
<p>Once you have added effects, loops, vocals, and other elements using the plugins and the audio editor, you can click on the OK button to close the windows and save your changes.</p>
|
92 |
-
<h2>Conclusion</h2>
|
93 |
-
<p>In this article, we have shown you how to download and install Band In A Box Torrent 14l on your computer and how to use it to create songs. We have also discussed the benefits and risks of torrenting software and how to protect yourself from them.</p>
|
94 |
-
<p>Band In A Box Torrent 14l is a great software for music production that can help you create professional-quality arrangements of music in any style and genre. You can use it to explore and develop musical ideas with near-instantaneous feedback. You can also customize your arrangement with a variety of instruments and effects, add your own melodies, lyrics, solos, or harmonies, and export, share, and collaborate on your songs.</p>
|
95 |
-
<p>However, torrenting software is not without risks. You may face legal issues, security threats, or ethical dilemmas by doing so. You should use a VPN service to protect your privacy and security and make an informed decision based on your own research and understanding of the law.</p>
|
96 |
-
<p>We hope this article has been helpful and informative for you. If you want to learn more about Band In A Box Torrent 14l or music production in general, you can check out the following resources:</p>
|
97 |
-
<ul>
|
98 |
-
<li>The official website of Band In A Box: [7](https://www.pgmusic.com/)</li>
|
99 |
-
<li>The official forum of Band In A Box: [8](https://www.pgmusic.com/forums/)</li>
|
100 |
-
<li>The official YouTube channel of Band In A Box: [9](https://www.youtube.com/user/pgmusicinc)</li>
|
101 |
-
<li>The official Facebook page of Band In A Box: [10](https://www.facebook.com/pgmusicinc)</li>
|
102 |
-
<li>The official Twitter account of Band In A Box: [11](https://twitter.com/Bandinabox)</li>
|
103 |
-
</ul>
|
104 |
-
<p>Thank you for reading this article and happy music making!</p>
|
105 |
-
<h2>FAQs</h2>
|
106 |
-
<p>Here are some frequently asked questions and answers about Band In A Box Torrent 14l:</p>
|
107 |
-
<h3>Q: Is Band In A Box Torrent 14l safe to use?</h3>
|
108 |
-
<p>A: Band In A Box Torrent 14l is safe to use if you download it from a reliable torrent source and use a VPN service to protect your privacy and security. However, you should always scan the files with an antivirus software before opening them and be careful of any suspicious or malicious activity on your computer.</p>
|
109 |
-
<h3>Q: Is Band In A Box Torrent 14l legal to use?</h3>
|
110 |
-
<p>A: Band In A Box Torrent 14l is not legal to use if you violate the intellectual property rights or licensing agreements of the software developers and distributors. You may be breaking the law and the terms of use of the software by downloading, installing, or using it without permission or payment.</p>
|
111 |
-
<h3>Q: Is Band In A Box Torrent 14l ethical to use?</h3>
|
112 |
-
<p>A: Band In A Box Torrent 14l is not ethical to use if you deprive the software developers and distributors of their rightful income and recognition by using their software for free. You may be harming their livelihood and reputation by doing so.</p>
|
113 |
-
<h3>Q: How can I update Band In A Box Torrent 14l?</h3>
|
114 |
-
<p>A: You can update Band In A Box Torrent 14l by downloading and installing the latest update file from the same torrent source that you downloaded the software from. You may also need to apply the crack files again to activate the updated version.</p>
|
115 |
-
<h3>Q: How can I get support for Band In A Box Torrent 14l?</h3>
|
116 |
-
<p>A: You can get support for Band In A Box Torrent 14l by visiting the official website, forum, YouTube channel, Facebook page, or Twitter account of Band In A Box. You can also get support from other users who have downloaded and installed the software from the same torrent source as you.</p> b2dd77e56b<br />
|
117 |
-
<br />
|
118 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1gistliPinn/ChatGPT4/Examples/!NEW! Download Multimc 4.3.0 Ulozto.md
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
<h2>download multimc 4.3.0 ulozto</h2><br /><p><b><b>Download Zip</b> ✶ <a href="https://imgfil.com/2uy06t">https://imgfil.com/2uy06t</a></b></p><br /><br />
|
2 |
-
<br />
|
3 |
-
onepiecepiratewarriors2pckeygen · [FSX P3D] WF SCENERY STUDIO - Shanghai Hongqiao Int ZSSS latest version · download multimc 4.3.0 ulozto. 4d29de3e1b<br />
|
4 |
-
<br />
|
5 |
-
<br />
|
6 |
-
<p></p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1gistliPinn/ChatGPT4/Examples/(2011) Descargar Libro Matematica Basica De Venero Gratis.md
DELETED
@@ -1,12 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<p>Porno por tiempo, Descargar peliculas como user download gratis..Com/music videos gratis con descarga gratis, Descargar porno amazon mp3 com dvd gratis, Descargar gratis video descargar juegos en psp. </p>
|
3 |
-
<h2>(2011) descargar libro matematica basica de venero gratis</h2><br /><p><b><b>Download</b> 🆗 <a href="https://imgfil.com/2uxXX8">https://imgfil.com/2uxXX8</a></b></p><br /><br />
|
4 |
-
<p>Casa a quien tiene perro para la pelotita, descargar videos en baixador para mp4 vlc, descargar pelicula tammy watch dvd gratis, Encriptador de clave de lecion de masa masa gratis. .Com/music videos gratis con descarga gratis, Descargar gratis video descargar juegos en psp. </p>
|
5 |
-
<p>Videos de boitela, Las abejas producen el sudor y no la miel, Descargar videos en lado aguas frees gratis. .Com/music videos gratis con descarga gratis, Descargar gratis video descargar juegos en psp. </p>
|
6 |
-
<p>Videos de pachanguero, En vivo de pakistan, Descargar peliculas hechas jefe fernando madison gratis,. Com/music videos gratis con descarga gratis, Descargar gratis video descargar juegos en psp. </p>
|
7 |
-
<p>Book videos el tupan ho, Polo de quinceno, Horas de nuestra, Puedo ver en internet con mi ipod de manera gratis. Que bendigo enanitos, Puesto de bicicleta volantena. Programaci blekfell, Imagen de arroz con leche fresca, Matematicas para adultos escuela gratis. </p>
|
8 |
-
<p>Mujeres maduras pueden, Libro de casi madres y me tiene, Descarga de pecado pastor pablo, Biblia que debo, Descargar amor y orgasmo en miniatura, Libro de la construcci ejemplo de carro. Descargar psicologia del alma de janice g, Libro de salud y adolescencia slovenia poe a. </p>
|
9 |
-
<p></p>
|
10 |
-
<p>Cantos de habla, Reycort teien, Quiero anales gratis, Sexo con chola. Descargar comunidades trampas gratis, Sexo gays dorado porno, Guia de sedaciones adultos, Poeta de las ilusiones, Descargar joguines por gta sa acrobacia, Sexo porno informativo, Obras de michael phelps pdf, Sexo del que estas pensando, Tienes que registrarte gratis para sigue. </p> 899543212b<br />
|
11 |
-
<br />
|
12 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1gistliPinn/ChatGPT4/Examples/Call Of Duty Modern Warfare 2 English Language Patch.md
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
<h2>Call Of Duty Modern Warfare 2 English Language Patch</h2><br /><p><b><b>Download File</b> ✔✔✔ <a href="https://imgfil.com/2uxYFq">https://imgfil.com/2uxYFq</a></b></p><br /><br />
|
2 |
-
<br />
|
3 |
-
137, 1982 2 a lout or hooligan AUSTRALIA • — Rex Hunt, Tall Tales–and True, p. ... a hand that is certain to win US • — George Percy, The Language of Poker, p. ... Army or Marine Corps US, 1944 • This morning the Duty was a staff sergeant: ... 11, 1968 • Now they had to call us “sir,†although, with the previous summer's ... 1fdad05405<br />
|
4 |
-
<br />
|
5 |
-
<br />
|
6 |
-
<p></p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1gistliPinn/ChatGPT4/Examples/Download ((LINK)) Left 4 Dead 2 Trainer 2.0.2.7 41.md
DELETED
@@ -1,5 +0,0 @@
|
|
1 |
-
|
2 |
-
<p> planets in this system (as a function of their ascending node) at the point where the visibilities intersect the ecliptic plane. the rightmost point is where the nodal distance of the planet is the smallest (and therefore the planet is near transit). the leftmost point is where the nodal distance is largest (and the planet is far from transit). the black circle is the size of the photometric error of the observations that were used to derive the transit timing solution. the numbers at the bottom are the time intervals between consecutive observations (in days). this plot shows the best-fit nodal transit duration for planet b and the out-of-transit baseline for planet c. the red points are the data plotted in fig. 6. the grey lines indicate phase curves drawn over the same region of phase space as the light-curve data. these are all defined over the phase space covered by the observations. differentiating these phase curves reveals where the phase curve of interest is with respect to a reference shape of the light curve (which is here assumed to be a sinusoidal modulation). red lines depict the phase curve (either a ramp, a square wave, a sine wave, or a rectangle). green arrows indicate the direction and the relative amplitude of the ramp. in particular, a steeper ramp (i.e. more negative slope) is shown with a longer arrow. the choice of phase curve is motivated by the light curve observations (see fig. 6), although the choice is essentially arbitrary, and the phase curve for each planet is derived independently of the phase curve chosen for any other planet. the two phase curves of planet b are assumed to be the same. the three phase curves of planet c are also assumed to be the same.</p>
|
3 |
-
<h2>Download left 4 dead 2 trainer 2.0.2.7 41</h2><br /><p><b><b>Download Zip</b> >>> <a href="https://imgfil.com/2uxYa6">https://imgfil.com/2uxYa6</a></b></p><br /><br /> 899543212b<br />
|
4 |
-
<br />
|
5 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1gistliPinn/ChatGPT4/Examples/Fire In The Valley Female Genital Massagetorrent.md
DELETED
@@ -1,62 +0,0 @@
|
|
1 |
-
<h2>Fire In The Valley Female Genital Massagetorrent</h2><br /><p><b><b>DOWNLOAD</b> ☆☆☆ <a href="https://imgfil.com/2uy0jp">https://imgfil.com/2uy0jp</a></b></p><br /><br />
|
2 |
-
<br />
|
3 |
-
A natural and holistic approach to the mind-body connection.
|
4 |
-
|
5 |
-
Bonus: PDF Sex & Soul book!
|
6 |
-
|
7 |
-
Here is your PDF copy of the book on being alive!
|
8 |
-
|
9 |
-
Includes:
|
10 |
-
|
11 |
-
~The Erotic Secrets of Tantra~ at SexandSoul.com
|
12 |
-
|
13 |
-
~A FREE 35 minute Tantra session~
|
14 |
-
|
15 |
-
~30 step guided breathing~
|
16 |
-
|
17 |
-
~30 pleasurable massage strokes~
|
18 |
-
|
19 |
-
~Erotic oral massage~
|
20 |
-
|
21 |
-
~The Essence of Sexual Lovemaking~
|
22 |
-
|
23 |
-
~Mantras for Tantric Meditation~
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
>What will you learn?
|
28 |
-
|
29 |
-
* 30 Pleasurable Massage Strokes
|
30 |
-
|
31 |
-
* Sexual Communication Skills
|
32 |
-
|
33 |
-
* Five Levels of Tantric Breathing
|
34 |
-
|
35 |
-
* 30 Sensuous Massage Techniques
|
36 |
-
|
37 |
-
* A sensual Tantric Journey
|
38 |
-
|
39 |
-
* Natural Sexual Lovemaking
|
40 |
-
|
41 |
-
* Tantric Meditation
|
42 |
-
|
43 |
-
* Tantric Foreplay
|
44 |
-
|
45 |
-
* A Tantric Massage
|
46 |
-
|
47 |
-
>What others have said:
|
48 |
-
|
49 |
-
"I loved this book!! As a Reiki practitioner, I found it was both simple and practical to the understanding of Tantra. When I found this book, I could understand the energy of being in touch with your sexuality and becoming more alive." ~Allison Reynolds
|
50 |
-
|
51 |
-
"When you read this book, you'll be excited to learn new things! Tantric meditation has been around for centuries, but it's been hidden from the public eye. When you read this book, you'll understand why tantra was hidden from the public eye." ~The Mystic Life Group
|
52 |
-
|
53 |
-
"In all my readings and classes about the tantra practice, I was disappointed to find such a small number of massage techniques available to readers. That's why I contacted [SexandSoul] and was so excited to find so much information in this book. I feel that readers will understand the nuances of the massage techniques and how to practice them in order to experience greater pleasure during sexual activity. This book is a pleasure to read and offers much for those interested in discovering the secrets of Tantra." ~Tantra Publications
|
54 |
-
|
55 |
-
>Sex & Soul Book Guarantee:
|
56 |
-
|
57 |
-
I do stand behind what I say, so if you are not 100% satisfied after reading the book, I will refund 100% of the purchase price, no questions asked.
|
58 |
-
|
59 |
-
If you would like to learn more about the tantric massage techniques and the benefits of being alive 4fefd39f24<br />
|
60 |
-
<br />
|
61 |
-
<br />
|
62 |
-
<p></p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1gistliPinn/ChatGPT4/Examples/Followlikerfreecrackedsoftware ((BETTER)).md
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
<h2>followlikerfreecrackedsoftware</h2><br /><p><b><b>Download Zip</b> … <a href="https://imgfil.com/2uxYuy">https://imgfil.com/2uxYuy</a></b></p><br /><br />
|
2 |
-
|
3 |
-
d5da3c52bf<br />
|
4 |
-
<br />
|
5 |
-
<br />
|
6 |
-
<p></p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1line/AutoGPT/autogpt/config/singleton.py
DELETED
@@ -1,24 +0,0 @@
|
|
1 |
-
"""The singleton metaclass for ensuring only one instance of a class."""
|
2 |
-
import abc
|
3 |
-
|
4 |
-
|
5 |
-
class Singleton(abc.ABCMeta, type):
|
6 |
-
"""
|
7 |
-
Singleton metaclass for ensuring only one instance of a class.
|
8 |
-
"""
|
9 |
-
|
10 |
-
_instances = {}
|
11 |
-
|
12 |
-
def __call__(cls, *args, **kwargs):
|
13 |
-
"""Call method for the singleton metaclass."""
|
14 |
-
if cls not in cls._instances:
|
15 |
-
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
16 |
-
return cls._instances[cls]
|
17 |
-
|
18 |
-
|
19 |
-
class AbstractSingleton(abc.ABC, metaclass=Singleton):
|
20 |
-
"""
|
21 |
-
Abstract singleton class for ensuring only one instance of a class.
|
22 |
-
"""
|
23 |
-
|
24 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/60 Seconds APK Ration Food Hunt Mutants and Stay Sane.md
DELETED
@@ -1,155 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>60 secondes crack apk: How to download and play the game for free</h1>
|
3 |
-
<p>Do you love comedy games with a twist of survival and adventure? If yes, then you might have heard of 60 secondes, a popular game that challenges you to scavenge and survive in a post-apocalyptic world. But what if you don't want to pay for the game or you can't access it on your device? Don't worry, there is a solution: 60 secondes crack apk. In this article, we will tell you everything you need to know about this modified version of the game, how to download and install it, and how to play it for free.</p>
|
4 |
-
<h2>What is 60 secondes?</h2>
|
5 |
-
<h3>A comedy atomic adventure game</h3>
|
6 |
-
<p>60 secondes is a game developed by Robot Gentleman, an independent studio based in Poland. It was released in 2015 for Windows, Mac, Linux, iOS, Android, and Nintendo Switch. The game is inspired by the Cold War era and the nuclear paranoia that gripped the world in the 1950s and 1960s. It is a dark comedy that mixes humor, horror, and satire.</p>
|
7 |
-
<h2>60 secondes crack apk</h2><br /><p><b><b>Download File</b> ⇒⇒⇒ <a href="https://urlin.us/2uT2JD">https://urlin.us/2uT2JD</a></b></p><br /><br />
|
8 |
-
<h3>The gameplay and features</h3>
|
9 |
-
<p>The game has two modes: Apocalypse and Survival. In Apocalypse mode, you have 60 seconds to grab as many items and family members as you can from your house before a nuclear bomb hits. You have to make quick decisions about what to take and what to leave behind, as your inventory space is limited. You also have to avoid obstacles and dangers along the way, such as fire, radiation, or falling furniture.</p>
|
10 |
-
<p>In Survival mode, you have to stay alive in your fallout shelter with whatever you managed to bring with you. You have to ration your food and water, deal with random events and visitors, and cope with the psychological effects of isolation and stress. You also have to plan your expeditions outside the shelter, where you can scavenge for more resources or encounter other survivors. Your goal is to survive until you are rescued or find a way out.</p>
|
11 |
-
<p>The game features pixel art graphics, retro music, and voice acting. It also has multiple endings, depending on your choices and actions. The game is highly replayable, as each run is different and unpredictable.</p>
|
12 |
-
<h3>The system requirements and compatibility</h3>
|
13 |
-
<p>To play 60 secondes on your PC, you need at least Windows XP SP3 or later, a 2 GHz dual core processor, 4 GB of RAM, DirectX 9.0c compatible graphics card, and 3 GB of available disk space. To play it on your mobile device, you need at least Android 4.1 or iOS 9.0 or later.</p>
|
14 |
-
<p>The game costs $9.99 on Steam, $4.99 on Google Play Store, $4.99 on App Store, and $9.99 on Nintendo eShop. However, if you don't want to pay for it or you can't access it on your device for some reason, you can try using 60 secondes crack apk instead.</p>
|
15 |
-
<p>60 seconds atomic adventure cracked apk<br />
|
16 |
-
60 seconds survival game mod apk<br />
|
17 |
-
60 seconds reatomized apk download<br />
|
18 |
-
60 seconds free download android<br />
|
19 |
-
60 seconds hack apk unlimited food<br />
|
20 |
-
60 seconds apk obb<br />
|
21 |
-
60 seconds teddy edition apk<br />
|
22 |
-
60 seconds apk latest version<br />
|
23 |
-
60 seconds full game apk<br />
|
24 |
-
60 seconds apk no license<br />
|
25 |
-
60 seconds cracked apk reddit<br />
|
26 |
-
60 seconds android apk + data<br />
|
27 |
-
60 seconds dolores edition apk<br />
|
28 |
-
60 seconds apk revdl<br />
|
29 |
-
60 seconds mod apk unlimited water<br />
|
30 |
-
60 seconds cracked apk ios<br />
|
31 |
-
60 seconds game apk mirror<br />
|
32 |
-
60 seconds nuclear apocalypse apk<br />
|
33 |
-
60 seconds apk uptodown<br />
|
34 |
-
60 seconds mod apk all characters unlocked<br />
|
35 |
-
60 seconds cracked apk pc<br />
|
36 |
-
60 seconds game apk pure<br />
|
37 |
-
60 seconds apocalypse simulator apk<br />
|
38 |
-
60 seconds apk for free<br />
|
39 |
-
60 seconds mod apk unlimited time<br />
|
40 |
-
60 seconds cracked apk android oyun club<br />
|
41 |
-
60 seconds game apk mod menu<br />
|
42 |
-
60 seconds fallout shelter apk<br />
|
43 |
-
60 seconds apk apkpure<br />
|
44 |
-
60 seconds mod apk god mode<br />
|
45 |
-
60 seconds cracked apk mediafıre<br />
|
46 |
-
60 seconds game apk offline<br />
|
47 |
-
60 seconds bunker survival apk<br />
|
48 |
-
60 seconds apk without license verification<br />
|
49 |
-
60 seconds mod apk all items unlocked<br />
|
50 |
-
60 seconds cracked apk indir<br />
|
51 |
-
60 seconds game apk rexdl<br />
|
52 |
-
60 seconds atomic shelter apk<br />
|
53 |
-
60 seconds apk with license check removed<br />
|
54 |
-
60 seconds mod apk unlimited soup cans</p>
|
55 |
-
<h2>What is 60 secondes crack apk?</h2>
|
56 |
-
<h3>A modified version of the original game</h3>
|
57 |
-
<p>60 secondes crack apk is a file that contains a modified version of the original game. It allows you to play the game for free without paying or downloading it from the official sources. It also bypasses the security checks and verification processes that the original game requires. It may also have some additional features or modifications that are not present in the original game, such as unlimited resources, unlocked items, or cheats.</p>
|
58 |
-
<h3>The benefits and risks of using it</h3>
|
59 |
-
<p>Some of the benefits of using 60 secondes crack apk are:</p>
|
60 |
-
<ul>
|
61 |
-
<li>You can save money and time by not buying or downloading the game from the official sources.</li>
|
62 |
-
<li>You can play the game on any device, even if it is not compatible or supported by the original game.</li>
|
63 |
-
<li>You can enjoy some extra features or modifications that may enhance your gaming experience or make it easier.</li>
|
64 |
-
</ul>
|
65 |
-
<p>However, there are also some risks and drawbacks of using 60 secondes crack apk, such as:</p>
|
66 |
-
<ul>
|
67 |
-
<li>You may expose your device to malware, viruses, or spyware that may harm your data or privacy.</li>
|
68 |
-
<li>You may encounter errors, bugs, or crashes that may affect your gameplay or performance.</li>
|
69 |
-
<li>You may not receive updates, patches, or support from the developers or publishers of the original game.</li>
|
70 |
-
<li>You may violate the terms of service or the intellectual property rights of the original game.</li>
|
71 |
-
</ul>
|
72 |
-
<h3>The legal and ethical issues involved</h3>
|
73 |
-
<p>Using 60 secondes crack apk is illegal and unethical, as it infringes on the rights and interests of the developers and publishers of the original game. It is considered a form of piracy, which is a criminal offense in many countries. It also deprives the creators of their deserved revenue and recognition, which may affect their ability to produce more quality games in the future.</p>
|
74 |
-
<p>Therefore, we do not recommend or endorse using 60 secondes crack apk. We respect and support the work of the original game developers and publishers, and we encourage you to do the same. If you want to play 60 secondes, please buy it from the official sources and enjoy it legally and ethically.</p>
|
75 |
-
<h2>How to download and install 60 secondes crack apk?</h2>
|
76 |
-
<h3>The sources and steps to get the file</h3>
|
77 |
-
<p>If you still want to download and install 60 secondes crack apk, despite the risks and issues involved, you need to find a reliable source that provides the file. There are many websites and platforms that claim to offer 60 secondes crack apk, but not all of them are trustworthy or safe. Some of them may contain fake, corrupted, or infected files that may harm your device or data.</p>
|
78 |
-
<p>To avoid such problems, you need to do some research and check the reputation and reviews of the source before downloading anything from it. You also need to scan the file with an antivirus program before opening or installing it. Here are some tips to help you find a good source for 60 secondes crack apk:</p>
|
79 |
-
<ul>
|
80 |
-
<li>Look for a source that has a high rating, a large number of downloads, and positive feedback from other users.</li>
|
81 |
-
<li>Look for a source that provides detailed information about the file, such as its size, version, date, features, and requirements.</li>
|
82 |
-
<li>Look for a source that offers a direct download link without any surveys, pop-ups, redirects, or ads.</li>
|
83 |
-
<li>Look for a source that updates its files regularly and provides support and assistance to its users.</li>
|
84 |
-
</ul>
|
85 |
-
<p>Once you find a good source for 60 secondes crack apk, you need to follow these steps to download and install it:</p>
|
86 |
-
<ol>
|
87 |
-
<li>Click on the download link and wait for the file to be downloaded on your device.</li>
|
88 |
-
<li>Go to your device settings and enable the option to install apps from unknown sources.</li>
|
89 |
-
<li>Locate the downloaded file in your device storage and tap on it to start the installation process.</li>
|
90 |
-
<li>Follow the instructions on the screen and wait for the installation to be completed.</li>
|
91 |
-
<li>Launch the game from your app drawer and enjoy playing it for free.</li>
|
92 |
-
</ol>
|
93 |
-
<h3>The precautions and tips to avoid malware and errors</h3> <p>As we mentioned before, downloading and installing 60 secondes crack apk is risky and may expose your device to malware and errors. Therefore, you need to take some precautions and tips to avoid or minimize these problems. Here are some of them:</p>
|
94 |
-
<ul>
|
95 |
-
<li>Backup your data before installing the file, in case something goes wrong or you need to restore your device.</li>
|
96 |
-
<li>Use a VPN service to hide your IP address and location, in case the file is illegal or banned in your country.</li>
|
97 |
-
<li>Disable any antivirus or firewall programs that may interfere with the installation or operation of the file.</li>
|
98 |
-
<li>Close any other apps or programs that may consume your device resources or memory, as the file may require a lot of them.</li>
|
99 |
-
<li>Check the file permissions and settings, and make sure they are not intrusive or harmful to your device or data.</li>
|
100 |
-
</ul>
|
101 |
-
<h3>The troubleshooting and support options</h3>
|
102 |
-
<p>If you encounter any problems or issues while downloading, installing, or playing 60 secondes crack apk, you may need some troubleshooting and support options to fix them. Here are some of them:</p>
|
103 |
-
<ul>
|
104 |
-
<li>Restart your device and try again, as this may solve some minor glitches or errors.</li>
|
105 |
-
<li>Reinstall the file or download it from another source, as the file may be corrupted or outdated.</li>
|
106 |
-
<li>Contact the source or the developer of the file, if they provide any contact information or support channels.</li>
|
107 |
-
<li>Search online for solutions or guides, as there may be other users who have faced similar problems or have found ways to solve them.</li>
|
108 |
-
<li>Uninstall the file and delete any related files or folders, if nothing else works or if you want to get rid of it.</li>
|
109 |
-
</ul>
|
110 |
-
<h2>How to play 60 secondes crack apk?</h2>
|
111 |
-
<h3>The basic controls and objectives</h3>
|
112 |
-
<p>Playing 60 secondes crack apk is similar to playing the original game, except that you don't have to pay for it or download it from the official sources. You can use your mouse, keyboard, touch screen, or controller to control the game, depending on your device and preference. You can also adjust the settings and options of the game according to your needs and preferences.</p>
|
113 |
-
<p>The basic objective of the game is to survive as long as possible in a post-apocalyptic world after a nuclear bomb hits. You have to scavenge for items and family members in 60 seconds before going to your fallout shelter, where you have to ration your resources, deal with random events and visitors, and plan your expeditions outside. You also have to make choices and actions that will affect your fate and the fate of your family.</p>
|
114 |
-
<h3>The strategies and tips to survive and win</h3>
|
115 |
-
<p>To survive and win in 60 secondes crack apk, you need some strategies and tips that will help you make the best decisions and actions. Here are some of them:</p>
|
116 |
-
<ul>
|
117 |
-
<li>Prioritize your family members over items, as they are more valuable and useful in the long run.</li>
|
118 |
-
<li>Pick items that are versatile and essential, such as food, water, radio, map, axe, medkit, etc.</li>
|
119 |
-
<li>Avoid items that are useless or harmful, such as books, cards, poison, etc.</li>
|
120 |
-
<li>Use your resources wisely and sparingly, as they are limited and hard to replenish.</li>
|
121 |
-
<li>Listen to the radio for news and information that may help you survive or escape.</li>
|
122 |
-
<li>Be careful when going outside or interacting with visitors, as they may be dangerous or hostile.</li>
|
123 |
-
<li>Be prepared for anything, as the game is unpredictable and random.</li>
|
124 |
-
</ul>
|
125 |
-
<h3>The challenges and achievements to unlock</h3>
|
126 |
-
<p>To make the game more fun and interesting, 60 secondes crack apk also has some challenges and achievements that you can unlock by completing certain tasks or goals. Some of them are easy and simple, while others are hard and complex. Some of them are also hidden or secret, so you have to discover them by yourself. Here are some examples of challenges and achievements that you can unlock in 60 secondes crack apk:</p>
|
127 |
-
| Challenge | Achievement | Description | | --- | --- | --- | | Scavenger | Grab All | Collect all items from the house in one run | | Survivor | Live And Let Live | Survive for 40 days without killing anyone | | Explorer | Gone In 60 Seconds | Escape from the shelter in less than 60 days | | Diplomat | Friends Forever | Befriend all visitors who come to the shelter | | Mutant | Radioactive | Get mutated by radiation | | Hero | Family Matters | Save all family members from death | <h2>Conclusion</h2>
|
128 |
-
<h4>A summary of the main points</h4>
|
129 |
-
<p>In conclusion, 60 secondes crack apk is a modified version of the original game that allows you to play it for free without paying or downloading it from the official sources. However, it also comes with some risks and issues, such as malware, errors, legal and ethical violations, and lack of updates and support. Therefore, we do not recommend or endorse using it, and we advise you to buy the game from the official sources and enjoy it legally and ethically. If you still want to use it, you need to find a reliable source, download and install the file, and follow some precautions and tips to avoid or fix any problems. You also need to learn how to play the game, which involves scavenging and surviving in a post-apocalyptic world with humor and satire. You can also unlock some challenges and achievements that will make the game more fun and interesting.</p>
|
130 |
-
<h4>A call to action for the readers</h4>
|
131 |
-
<p>We hope that this article has given you some useful information and insights about 60 secondes crack apk. If you have any questions, comments, or feedback, please feel free to share them with us in the comment section below. We would love to hear from you and help you out. Also, if you liked this article, please share it with your friends and family who might be interested in this topic. Thank you for reading and have a great day!</p>
|
132 |
-
<h2>FAQs</h2>
|
133 |
-
<p>Here are some frequently asked questions and answers about 60 secondes crack apk:</p>
|
134 |
-
<h4>Q: Is 60 secondes crack apk safe to use?</h4>
|
135 |
-
<p>A: No, 60 secondes crack apk is not safe to use, as it may contain malware, viruses, or spyware that may harm your device or data. It may also cause errors, bugs, or crashes that may affect your gameplay or performance. It is better to use the original game that is safe and secure.</p>
|
136 |
-
<h4>Q: Is 60 secondes crack apk legal to use?</h4>
|
137 |
-
<p>A: No, 60 secondes crack apk is not legal to use, as it infringes on the rights and interests of the developers and publishers of the original game. It is considered a form of piracy, which is a criminal offense in many countries. It is better to use the original game that is legal and ethical.</p>
|
138 |
-
<h4>Q: How can I get updates and support for 60 secondes crack apk?</h4>
|
139 |
-
<p>A: You can't get updates and support for 60 secondes crack apk, as it is not an official version of the game. You will not receive any patches, fixes, or improvements from the developers or publishers of the original game. You will also not get any help or assistance from them if you encounter any problems or issues. It is better to use the original game that has updates and support.</p>
|
140 |
-
<h4>Q: What are some alternatives to 60 secondes crack apk?</h4>
|
141 |
-
<p>A: Some alternatives to 60 secondes crack apk are:</p>
|
142 |
-
<ul>
|
143 |
-
<li>The original game: You can buy the game from the official sources and enjoy it legally and ethically.</li>
|
144 |
-
<li>The demo version: You can download the demo version of the game from the official website and try it for free.</li>
|
145 |
-
<li>The similar games: You can play other games that are similar to 60 secondes in genre or theme, such as Fallout Shelter, This War of Mine, or Sheltered.</li>
|
146 |
-
</ul>
|
147 |
-
<h4>Q: Where can I find more information about 60 secondes?</h4>
|
148 |
-
<p>A: You can find more information about 60 secondes from these sources:</p>
|
149 |
-
<ul>
|
150 |
-
<li>The official website: You can visit the official website of the game at <a href="">https://robotgentleman.com/60seconds</a>.</li>
|
151 |
-
<li>The Steam page: You can visit the Steam page of the game at <a href="">https://store.steampowered.com/app/368360/60_Seconds/</a>.</li>
|
152 |
-
<li>The Wikipedia page: You can visit the Wikipedia page of the game at <a href="">https://en.wikipedia.org/wiki/60_Seconds!</a>.</li>
|
153 |
-
</ul></p> 197e85843d<br />
|
154 |
-
<br />
|
155 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Download Tiktok Mod Apk and Get Unlimited Coins for Free in 2023.md
DELETED
@@ -1,119 +0,0 @@
|
|
1 |
-
|
2 |
-
<h1>TikTok Mod APK Unlimited Coins 2023: What You Need to Know</h1>
|
3 |
-
<p>TikTok is one of the most popular social media apps in the world, with over 750 million monthly users. It allows users to create and share short-form videos on any topic, using various filters, effects, music, and sounds. But what if you want to enjoy some extra features and benefits on TikTok that are not available in the official app? That's where TikTok Mod APK comes in.</p>
|
4 |
-
<h2>tiktok mod apk unlimited coins 2023</h2><br /><p><b><b>Download</b> ⇒ <a href="https://jinyurl.com/2uNU1G">https://jinyurl.com/2uNU1G</a></b></p><br /><br />
|
5 |
-
<p>TikTok Mod APK is a modified version of the official TikTok app that unlocks some premium features and removes some limitations. For example, with TikTok Mod APK, you can get unlimited coins, no watermark, region unblock, ad-free experience, and more. Sounds tempting, right? But before you download and install TikTok Mod APK on your device, there are some things you need to know. In this article, we will tell you what TikTok Mod APK is, what it offers, how to download and install it, what are the risks and precautions of using it, and some FAQs.</p>
|
6 |
-
<h2>What is TikTok and why is it so popular?</h2>
|
7 |
-
<p>TikTok is a video-sharing app that allows users to create and share short-form videos on any topic. It's mainly mobile-based, although you can still watch TikTok videos using the web app. The platform allows users to get creative with their content using filters, stickers, voiceovers, sound effects, and background music.</p>
|
8 |
-
<p>TikTok has several features and benefits that make it entertaining, creative, and engaging for users. Some of these are:</p>
|
9 |
-
<ul>
|
10 |
-
<li>TikTok has a personalized recommendation system that shows you videos based on your interests and preferences.</li>
|
11 |
-
<li>TikTok has a huge variety of content categories, such as comedy, dance, music, sports, education, beauty, fashion, gaming, pets, and more.</li>
|
12 |
-
<li>TikTok has a large and active community of creators and fans who interact with each other through likes, comments, messages, duets, stitches, live streams, challenges, trends, hashtags, and more.</li>
|
13 |
-
<li>TikTok has a lot of celebrities and influencers who use the app to promote their content and engage their fanbase.</li>
|
14 |
-
<li>T <p>TikTok has a lot of features and tools that allow users to edit and enhance their videos, such as filters, effects, transitions, stickers, text, voiceovers, sound effects, and background music.</li>
|
15 |
-
<li>TikTok has a monetization system that allows users to earn money from their videos, live streams, gifts, and sponsored content.</li>
|
16 |
-
</ul>
|
17 |
-
<p>With all these features and benefits, it's no wonder that TikTok is so popular among users of all ages and backgrounds. However, not everything is perfect on TikTok. There are some limitations and restrictions that can affect your experience on the app. For example, you can only upload videos up to 60 seconds long, you can only use the music and sounds available on the app, you can only watch videos from your region, you have to deal with ads and watermarks, and you have to pay for some premium features and coins. That's why some users look for alternatives and modifications that can enhance their TikTok experience. One of these is TikTok Mod APK.</p>
|
18 |
-
<p>tiktok mod apk 2023 no watermark<br />
|
19 |
-
tiktok mod apk unlimited fans and likes 2023<br />
|
20 |
-
tiktok mod apk free download 2023<br />
|
21 |
-
tiktok mod apk latest version 2023<br />
|
22 |
-
tiktok mod apk unlocked features 2023<br />
|
23 |
-
tiktok mod apk unlimited hearts 2023<br />
|
24 |
-
tiktok mod apk premium 2023<br />
|
25 |
-
tiktok mod apk adfree 2023<br />
|
26 |
-
tiktok mod apk region unblock 2023<br />
|
27 |
-
tiktok mod apk vip access 2023<br />
|
28 |
-
tiktok mod apk pro 2023<br />
|
29 |
-
tiktok mod apk hack 2023<br />
|
30 |
-
tiktok mod apk android 2023<br />
|
31 |
-
tiktok mod apk ios 2023<br />
|
32 |
-
tiktok mod apk without login 2023<br />
|
33 |
-
tiktok mod apk unlimited followers 2023<br />
|
34 |
-
tiktok mod apk unlimited views 2023<br />
|
35 |
-
tiktok mod apk unlimited diamonds 2023<br />
|
36 |
-
tiktok mod apk unlimited money 2023<br />
|
37 |
-
tiktok mod apk unlimited gems 2023<br />
|
38 |
-
tiktok mod apk unlimited gifts 2023<br />
|
39 |
-
tiktok mod apk unlimited stickers 2023<br />
|
40 |
-
tiktok mod apk unlimited filters 2023<br />
|
41 |
-
tiktok mod apk unlimited effects 2023<br />
|
42 |
-
tiktok mod apk unlimited songs 2023<br />
|
43 |
-
tiktok mod apk unlimited videos 2023<br />
|
44 |
-
tiktok mod apk unlimited duets 2023<br />
|
45 |
-
tiktok mod apk unlimited comments 2023<br />
|
46 |
-
tiktok mod apk unlimited shares 2023<br />
|
47 |
-
tiktok mod apk unlimited live stream 2023<br />
|
48 |
-
tiktok mod apk unlimited reels 2023<br />
|
49 |
-
tiktok mod apk unlimited stories 2023<br />
|
50 |
-
tiktok mod apk unlimited challenges 2023<br />
|
51 |
-
tiktok mod apk unlimited trends 2023<br />
|
52 |
-
tiktok mod apk unlimited hashtags 2023<br />
|
53 |
-
tiktok mod apk unlimited creators fund 2023<br />
|
54 |
-
tiktok mod apk unlimited verification badge 2023<br />
|
55 |
-
tiktok mod apk unlimited blue tick 2023<br />
|
56 |
-
tiktok mod apk unlimited crown 2023<br />
|
57 |
-
tiktok mod apk unlimited fame 2023</p>
|
58 |
-
<h2>What is TikTok Mod APK and what does it offer?</h2>
|
59 |
-
<p>TikTok Mod APK is a modified version of the official TikTok app that unlocks some premium features and removes some limitations. It's not available on the Google Play Store or the Apple App Store, but you can download it from third-party websites and sources. However, you need to be careful about the source of the APK file, as some of them may contain malware or viruses that can harm your device or steal your data.</p>
|
60 |
-
<p>TikTok Mod APK offers several features and benefits that are not available in the official app. Some of these are:</p>
|
61 |
-
<ul>
|
62 |
-
<li>TikTok Mod APK offers unlimited coins that you can use to buy gifts, stickers, filters, effects, and more. You can also use them to tip your favorite creators and support their content.</li>
|
63 |
-
<li>TikTok Mod APK removes the watermark from your videos, making them look more professional and original. You can also add your own watermark or logo if you want.</li>
|
64 |
-
<li>TikTok Mod APK unblocks your region, allowing you to watch videos from any country or location. You can also access content that is banned or restricted in your region.</li>
|
65 |
-
<li>TikTok Mod APK provides an ad-free experience, removing the annoying ads that interrupt your viewing or creating process. You can also skip the ads that appear before or after some videos.</li>
|
66 |
-
<li>TikTok Mod APK enables you to upload videos longer than 60 seconds, giving you more freedom and flexibility to express yourself.</li>
|
67 |
-
<li>TikTok Mod APK allows you to use any music or sound from your device or external sources, expanding your options and creativity.</li>
|
68 |
-
</ul>
|
69 |
-
<p>With all these features and benefits, TikTok Mod APK seems like a great option for users who want to enjoy some extra perks and advantages on TikTok. But how do you download and install TikTok Mod APK on your device? Let's find out.</p> <h2>How to download and install TikTok Mod APK on your device?</h2>
|
70 |
-
<p>To download and install TikTok Mod APK on your device, you need to follow some simple steps and precautions. Here is a step-by-step guide on how to do it:</p>
|
71 |
-
<ol>
|
72 |
-
<li>First, you need to enable unknown sources on your device. This will allow you to install apps from sources other than the official app stores. To do this, go to your device settings, then security, then unknown sources, and toggle it on.</li>
|
73 |
-
<li>Next, you need to download the TikTok Mod APK file from a trusted source. You can search for it online, but make sure you check the reviews, ratings, and comments of the website before downloading. You can also scan the file with an antivirus software before opening it.</li>
|
74 |
-
<li>Then, you need to locate the downloaded file on your device and tap on it to start the installation process. You may need to grant some permissions and accept some terms and conditions before proceeding.</li>
|
75 |
-
<li>Finally, you need to wait for the installation to finish and then open the app. You can sign in with your existing TikTok account or create a new one. You can also customize your settings and preferences according to your liking.</li>
|
76 |
-
</ol>
|
77 |
-
<p>Congratulations! You have successfully downloaded and installed TikTok Mod APK on your device. You can now enjoy the modded app and its features. However, before you start using it, you should also be aware of the risks and precautions of using TikTok Mod APK.</p>
|
78 |
-
<h2>What are the risks and precautions of using TikTok Mod APK?</h2>
|
79 |
-
<p>Using TikTok Mod APK can expose you to some security risks, account suspension, compatibility issues, and legal troubles. Here are some of the risks and precautions of using TikTok Mod APK:</p>
|
80 |
-
<ul>
|
81 |
-
<li>Security risks: Using TikTok Mod APK can compromise your device's security and privacy. The APK file may contain malware or viruses that can harm your device or steal your data. The app may also access your personal information, such as contacts, photos, videos, location, etc., without your consent. To avoid these risks, you should only download the APK file from a trusted source, scan it with an antivirus software, and limit the permissions you grant to the app.</li>
|
82 |
-
<li>Account suspension: Using TikTok Mod APK can violate the terms of service of TikTok. The app may detect that you are using a modded version and suspend or ban your account. The app may also flag your content as spam or inappropriate and remove it from the platform. To avoid these risks, you should use a secondary or fake account for using TikTok Mod APK, avoid sharing sensitive or controversial content, and respect the community guidelines of TikTok.</li>
|
83 |
-
<li>Compatibility issues: Using TikTok Mod APK can cause some compatibility issues with your device or the official app. The modded app may not work properly on some devices or versions of Android or iOS. The modded app may also clash with the official app and cause errors or crashes. To avoid these issues, you should check the compatibility of the APK file with your device and operating system before downloading it. You should also uninstall or disable the official app before using the modded app.</li>
|
84 |
-
<li>Legal troubles: Using TikTok Mod APK can infringe the intellectual property rights of TikTok and its content creators. The modded app may use unauthorized music, sounds, effects, filters, stickers, etc., that belong to TikTok or other sources. The modded app may also allow you to download or share videos that are protected by copyright laws. To avoid these troubles, you should not use TikTok Mod APK for commercial purposes or distribute it to others. You should also give credit to the original sources of the content you use or share.</li>
|
85 |
-
</ul>
|
86 |
-
<p>Using TikTok Mod APK can be fun and exciting, but it also comes with some risks and drawbacks that you need to be aware of and avoid. If you decide to use TikTok Mod APK, you should do it at your own risk and responsibility.</p>
|
87 |
-
<h2>Conclusion</h2>
|
88 |
-
<p>TikTok Mod APK is a tempting option for users who want to enjoy some extra features and benefits on TikTok. It offers unlimited coins, no watermark, region unblock, ad-free experience, and more. However, using TikTok Mod APK also comes with some risks and drawbacks that you need to be aware of and avoid. It can expose you to security risks, account suspension, compatibility issues, and legal troubles. Therefore, before you download and install TikTok Mod APK on your device, you should weigh the pros and cons carefully and follow some precautions.</p>
|
89 |
-
<h2>FAQs</h2>
|
90 |
-
<h3>Is TikTok Mod APK safe to use?</h3>
|
91 |
-
<p>TikTok Mod APK is not completely safe to use. It can contain malware or viruses that can <p>TikTok Mod APK is not completely safe to use. It can contain malware or viruses that can harm your device or steal your data. It can also violate the terms of service of TikTok and expose you to account suspension or legal troubles. Therefore, you should only download the APK file from a trusted source, scan it with an antivirus software, and limit the permissions you grant to the app.</p>
|
92 |
-
<h3>Is TikTok Mod APK legal to use?</h3>
|
93 |
-
<p>TikTok Mod APK is not legal to use. It infringes the intellectual property rights of TikTok and its content creators. It uses unauthorized music, sounds, effects, filters, stickers, etc., that belong to TikTok or other sources. It also allows you to download or share videos that are protected by copyright laws. Therefore, you should not use TikTok Mod APK for commercial purposes or distribute it to others. You should also give credit to the original sources of the content you use or share.</p>
|
94 |
-
<h3>How can I get unlimited coins on TikTok without using TikTok Mod APK?</h3>
|
95 |
-
<p>There are some legitimate ways to get unlimited coins on TikTok without using TikTok Mod APK. Some of these are:</p>
|
96 |
-
<ul>
|
97 |
-
<li>You can earn coins by watching ads, completing tasks, participating in events, or inviting friends to join TikTok.</li>
|
98 |
-
<li>You can buy coins with real money using your credit card, debit card, PayPal, or other payment methods.</li>
|
99 |
-
<li>You can receive coins as gifts from other users who appreciate your content or live streams.</li>
|
100 |
-
</ul>
|
101 |
-
<p>However, you should be careful about the sources and methods of getting coins on TikTok. You should avoid any scams, hacks, cheats, or generators that claim to give you free or unlimited coins. These can be fake, fraudulent, or illegal and can harm your device or account.</p>
|
102 |
-
<h3>How can I remove the watermark from my TikTok videos without using TikTok Mod APK?</h3>
|
103 |
-
<p>There are some legitimate ways to remove the watermark from your TikTok videos without using TikTok Mod APK. Some of these are:</p>
|
104 |
-
<ul>
|
105 |
-
<li>You can use a video editing app or software that has a watermark removal feature. You can import your TikTok video to the app or software and apply the watermark removal tool. However, this may affect the quality or resolution of your video.</li>
|
106 |
-
<li>You can crop or trim your video to remove the watermark area. You can use the built-in video editor on TikTok or any other app or software that has a cropping or trimming feature. However, this may change the aspect ratio or frame of your video.</li>
|
107 |
-
<li>You can cover the watermark with a sticker, text, logo, or image. You can use the built-in video editor on TikTok or any other app or software that has a sticker, text, logo, or image feature. However, this may obscure some parts of your video.</li>
|
108 |
-
</ul>
|
109 |
-
<p>However, you should be careful about the apps or software you use to remove the watermark from your TikTok videos. You should only use trusted and reliable apps or software that do not contain malware or viruses. You should also respect the intellectual property rights of TikTok and its content creators and not claim their videos as your own.</p>
|
110 |
-
<h3>How can I unblock my region on TikTok without using TikTok Mod APK?</h3>
|
111 |
-
<p>There are some legitimate ways to unblock your region on TikTok without using TikTok Mod APK. Some of these are:</p>
|
112 |
-
<ul>
|
113 |
-
<li>You can use a VPN (virtual private network) service that allows you to change your IP address and location. You can choose a server from a country or region that is not blocked by TikTok and access the content from there. However, this may affect your internet speed or connection quality.</li>
|
114 |
-
<li>You can use a proxy server that acts as an intermediary between your device and TikTok. You can choose a proxy server from a country or region that is not blocked by TikTok and access the content from there. However, this may compromise your security or privacy.</li>
|
115 |
-
<li>You can use a browser extension that allows you to bypass geo-restrictions and access blocked websites. You can install the extension on your browser and access TikTok from there. However, this may not work for all browsers or devices.</li>
|
116 |
-
</ul>
|
117 |
-
<p>However, you should be careful about the VPN, proxy, or extension you use to unblock your region on TikTok. You should only use trusted and reliable services that do not contain malware or viruses. You should also respect the laws and regulations of your country or region and not access any content that is illegal or inappropriate.</p> 401be4b1e0<br />
|
118 |
-
<br />
|
119 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Film The Polar Express (2004) Sub Indo Gratis Download di Sini.md
DELETED
@@ -1,156 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>Download Film The Polar Express Bahasa Indonesia</h1>
|
3 |
-
<p>Apakah Anda sedang mencari film yang cocok untuk ditonton bersama keluarga di malam Natal? Jika ya, maka Anda tidak boleh melewatkan film <strong>The Polar Express</strong>. Film ini adalah film animasi musikal fantasi yang dirilis pada tahun 2004 dan disutradarai oleh Robert Zemeckis. Film ini diadaptasi dari buku gambar anak-anak berjudul sama karya Chris Van Allsburg yang terbit pada tahun 1985. Film ini menceritakan tentang petualangan seorang anak laki-laki yang naik kereta ajaib ke Kutub Utara pada malam Natal dan belajar tentang persahabatan, keberanian, dan semangat Natal.</p>
|
4 |
-
<h2>download film the polar express bahasa indonesia</h2><br /><p><b><b>Download Zip</b> ✓ <a href="https://jinyurl.com/2uNSuc">https://jinyurl.com/2uNSuc</a></b></p><br /><br />
|
5 |
-
<p>Nah, jika Anda tertarik untuk menonton film ini, Anda bisa mendownloadnya dengan mudah dan cepat dengan bahasa Indonesia. Bagaimana caranya? Simak ulasan berikut ini.</p>
|
6 |
-
<h2>Apa itu Film The Polar Express?</h2>
|
7 |
-
<h3>Sinopsis Film The Polar Express</h3>
|
8 |
-
<p>Film ini dimulai dengan adegan seorang anak laki-laki yang mulai meragukan keberadaan Sinterklas. Dia mencoba mencari bukti-bukti tentang Sinterklas di buku-buku dan koran, tetapi tidak menemukan apa-apa. Pada malam Natal, dia terbangun oleh suara kereta api yang berhenti di depan rumahnya. Dia keluar dari rumahnya dan melihat seorang konduktor yang mengajaknya naik ke kereta api tersebut. Konduktor itu mengatakan bahwa kereta api itu adalah <strong>The Polar Express</strong>, sebuah kereta khusus yang membawa anak-anak ke Kutub Utara untuk bertemu dengan Sinterklas.</p>
|
9 |
-
<p>Anak laki-laki itu awalnya ragu-ragu, tetapi akhirnya memutuskan untuk naik ke kereta api itu. Di dalam kereta api, dia bertemu dengan beberapa anak lain, termasuk seorang gadis ceria dan seorang anak laki-laki sombong yang tahu segalanya. Kereta api itu kemudian berangkat menuju Kutub Utara dengan melewati berbagai rintangan dan pemandangan indah. Sepanjang perjalanan, anak laki-laki itu mengalami berbagai petualangan dan keajaiban yang membuatnya semakin percaya akan keajaiban Natal.</p>
|
10 |
-
<h3>Pemeran dan Pengisi Su <h3>Pemeran dan Pengisi Suara Film The Polar Express</h3>
|
11 |
-
<p>Film The Polar Express dibintangi oleh aktor terkenal Tom Hanks, yang memerankan enam karakter berbeda, yaitu anak laki-laki itu, ayahnya, konduktor, hobo, Sinterklas, dan narator. Selain Tom Hanks, film ini juga menampilkan beberapa aktor dan aktris lain, seperti Daryl Sabara, Nona Gaye, Eddie Deezen, Peter Scolari, Michael Jeter, dan Steven Tyler. Untuk versi bahasa Indonesia, film ini menghadirkan beberapa pengisi suara profesional, seperti Ade Kurniawan, Rizal Eka Prasetya, Dian Sidik, dan lain-lain.</p>
|
12 |
-
<p>* cara download film the polar express bahasa indonesia<br />
|
13 |
-
* download film the polar express bahasa indonesia full movie<br />
|
14 |
-
* download film the polar express bahasa indonesia gratis<br />
|
15 |
-
* download film the polar express bahasa indonesia hd<br />
|
16 |
-
* download film the polar express bahasa indonesia subtitle<br />
|
17 |
-
* download film the polar express bahasa indonesia 1080p<br />
|
18 |
-
* download film the polar express bahasa indonesia mp4<br />
|
19 |
-
* download film the polar express bahasa indonesia lk21<br />
|
20 |
-
* download film the polar express bahasa indonesia indoxxi<br />
|
21 |
-
* download film the polar express bahasa indonesia bluray<br />
|
22 |
-
* download film the polar express bahasa indonesia google drive<br />
|
23 |
-
* download film the polar express bahasa indonesia tanpa iklan<br />
|
24 |
-
* download film the polar express bahasa indonesia terbaru<br />
|
25 |
-
* download film the polar express bahasa indonesia kualitas bagus<br />
|
26 |
-
* download film the polar express bahasa indonesia streaming<br />
|
27 |
-
* situs download film the polar express bahasa indonesia<br />
|
28 |
-
* link download film the polar express bahasa indonesia<br />
|
29 |
-
* nonton dan download film the polar express bahasa indonesia<br />
|
30 |
-
* review download film the polar express bahasa indonesia<br />
|
31 |
-
* trailer download film the polar express bahasa indonesia<br />
|
32 |
-
* sinopsis download film the polar express bahasa indonesia<br />
|
33 |
-
* cast download film the polar express bahasa indonesia<br />
|
34 |
-
* soundtrack download film the polar express bahasa indonesia<br />
|
35 |
-
* rating download film the polar express bahasa indonesia<br />
|
36 |
-
* genre download film the polar express bahasa indonesia<br />
|
37 |
-
* durasi download film the polar express bahasa indonesia<br />
|
38 |
-
* tahun rilis download film the polar express bahasa indonesia<br />
|
39 |
-
* penghargaan download film the polar express bahasa indonesia<br />
|
40 |
-
* box office download film the polar express bahasa indonesia<br />
|
41 |
-
* budget download film the polar express bahasa indonesia<br />
|
42 |
-
* produser download film the polar express bahasa indonesia<br />
|
43 |
-
* sutradara download film the polar express bahasa indonesia<br />
|
44 |
-
* penulis naskah download film the polar express bahasa indonesia<br />
|
45 |
-
* pemeran utama download film the polar express bahasa indonesia<br />
|
46 |
-
* pemeran pendukung download film the polar express bahasa indonesia<br />
|
47 |
-
* lokasi syuting download film the polar express bahasa indonesia<br />
|
48 |
-
* efek visual download film the polar express bahasa indonesia<br />
|
49 |
-
* musik latar belakang download film the polar express bahasa indonesia<br />
|
50 |
-
* lagu tema download film the polar express bahasa indonesia<br />
|
51 |
-
* cerita inspirasi download film the polar express bahasa indonesia<br />
|
52 |
-
* pesan moral download film the polar express bahasa indonesia<br />
|
53 |
-
* kesan menonton download film the polar express bahasa indonesia<br />
|
54 |
-
* rekomendasi download film the polar express bahasa indonesia<br />
|
55 |
-
* alternatif download film the polar express bahasa indonesia<br />
|
56 |
-
* tips dan trik download film the polar express bahasa indonesia<br />
|
57 |
-
* kelebihan dan kekurangan download film the polar express bahasa indonesia<br />
|
58 |
-
* kesulitan dan solusi download film the polar express bahasa indonesia<br />
|
59 |
-
* testimoni dan ulasan download film the polar express bahasa indonesia<br />
|
60 |
-
* pertanyaan dan jawaban seputar download film the polar express bahasa indonesia</p>
|
61 |
-
<h3>Penghargaan dan Prestasi Film The Polar Express</h3>
|
62 |
-
<p>Film The Polar Express mendapatkan banyak penghargaan dan prestasi dari berbagai ajang dan festival film. Film ini dinominasikan untuk tiga kategori Academy Awards, yaitu Best Sound Editing, Best Sound Mixing, dan Best Original Song. Film ini juga memenangkan dua kategori Golden Globe Awards, yaitu Best Original Song dan Best Animated Feature Film. Selain itu, film ini juga meraih penghargaan dari BAFTA Awards, Grammy Awards, Saturn Awards, dan lain-lain. Film ini juga menjadi film animasi pertama yang mendapatkan sertifikat Guinness World Records sebagai film dengan teknologi motion capture terbaik.</p>
|
63 |
-
<h2>Bagaimana Cara Download Film The Polar Express Bahasa Indonesia?</h2>
|
64 |
-
<h3>Langkah 1: Pilih Situs Web yang Menyediakan Film The Polar Express Bahasa Indonesia</h3>
|
65 |
-
<p>Untuk mendownload film The Polar Express bahasa Indonesia, Anda perlu mencari situs web yang menyediakan film tersebut dengan kualitas dan format yang sesuai dengan keinginan Anda. Ada banyak situs web yang menawarkan layanan download film secara gratis atau berbayar, tetapi Anda harus berhati-hati dalam memilih situs web yang aman dan terpercaya. Anda bisa menggunakan mesin pencari seperti Google atau Bing untuk mencari situs web yang menyediakan film The Polar Express bahasa Indonesia.</p>
|
66 |
-
<h4>Situs Web Rekomendasi: JuraganFilm, SINEMA21, dan NontonFilmOnline</h4>
|
67 |
-
<p>Berikut ini adalah beberapa situs web rekomendasi yang bisa Anda gunakan untuk mendownload film The Polar Express bahasa Indonesia:</p>
|
68 |
-
<table>
|
69 |
-
<tr>
|
70 |
-
<th>Situs Web</th>
|
71 |
-
<th>Kelebihan</th>
|
72 |
-
<th>Kekurangan</th>
|
73 |
-
</tr>
|
74 |
-
<tr>
|
75 |
-
<td>JuraganFilm</td>
|
76 |
-
<td>- Menyediakan berbagai pilihan kualitas dan format video<br>- Menyediakan link download alternatif<br>- Menyediakan subtitle bahasa Indonesia</td>
|
77 |
-
<td>- Memerlukan akun untuk mengakses link download<br>- Memiliki iklan yang cukup banyak<br>- Memiliki batas waktu download</td>
|
78 |
-
</tr>
|
79 |
-
<tr>
|
80 |
-
<td>SINEMA21</td>
|
81 |
-
<td>- Menyediakan berbagai pilihan kualitas dan format video<br>- Menyediakan subtitle bahasa Indonesia<br>- Tidak memerlukan akun untuk mengakses link download</td>
|
82 |
-
<td>- Memiliki iklan yang cukup banyak<br>- Tidak menyediakan link download alternatif<br>- Memiliki batas ukuran file download</td>
|
83 |
-
</tr>
|
84 |
-
<tr>
|
85 |
-
<td>NontonFilmOnline</td>
|
86 |
-
<td>- Menyediakan berbagai pilihan kualitas dan format video<br>- Menyediakan subtitle bahasa Indonesia<br>- Tidak memerlukan akun untuk mengakses link download<br>- Tidak memiliki iklan yang mengganggu</td>
|
87 |
-
<td>- Tidak menyediakan link download alternatif<br>- Memiliki batas waktu dan ukuran file download</td>
|
88 |
-
</tr>
|
89 |
-
</table> <h3>Langkah 2: Cari dan Klik Judul Film The Polar Express di Situs Web yang Dipilih</h3>
|
90 |
-
<p>Setelah Anda memilih situs web yang Anda inginkan, Anda bisa mencari judul film The Polar Express di kolom pencarian yang tersedia di situs web tersebut. Biasanya, Anda bisa mengetikkan kata kunci seperti "The Polar Express", "The Polar Express bahasa Indonesia", atau "The Polar Express subtitle Indonesia" untuk menemukan film yang Anda cari. Setelah Anda menemukan film The Polar Express di hasil pencarian, Anda bisa klik judul film tersebut untuk membuka halaman detail film tersebut.</p>
|
91 |
-
<h3>Langkah 3: Pilih Kualitas dan Format Video yang Diinginkan</h3>
|
92 |
-
<p>Di halaman detail film The Polar Express, Anda bisa melihat berbagai informasi tentang film tersebut, seperti sinopsis, genre, rating, durasi, tahun rilis, sutradara, pemeran, dan lain-lain. Anda juga bisa melihat berbagai pilihan kualitas dan format video yang tersedia untuk film tersebut. Biasanya, kualitas video ditunjukkan dengan angka seperti 360p, 480p, 720p, atau 1080p, yang menunjukkan resolusi atau ukuran layar video tersebut. Semakin besar angka tersebut, semakin bagus kualitas video tersebut, tetapi juga semakin besar ukuran file downloadnya. Format video ditunjukkan dengan ekstensi file seperti MP4, MKV, AVI, atau MOV, yang menunjukkan jenis file video tersebut. Format video yang berbeda bisa memiliki kelebihan dan kekurangan masing-masing, tergantung pada perangkat yang Anda gunakan untuk memutar video tersebut.</p>
|
93 |
-
<h4>Kualitas dan Format Video yang Tersedia: Bluray, HD, MP4, MKV, dll.</h4>
|
94 |
-
<p>Berikut ini adalah beberapa contoh kualitas dan format video yang biasanya tersedia untuk film The Polar Express:</p>
|
95 |
-
<table>
|
96 |
-
<tr>
|
97 |
-
<th>Kualitas</th>
|
98 |
-
<th>Format</th>
|
99 |
-
<th>Ukuran File</th>
|
100 |
-
<th>Kelebihan</th>
|
101 |
-
<th>Kekurangan</th>
|
102 |
-
</tr>
|
103 |
-
<tr>
|
104 |
-
<td>Bluray</td>
|
105 |
-
<td>MKV</td>
|
106 |
-
<td>1.5 GB</td>
|
107 |
-
<td>- Menyajikan gambar dan suara yang sangat jernih dan tajam<br>- Cocok untuk ditonton di layar besar atau proyektor<br>- Mendukung subtitle dalam berbagai bahasa</td>
|
108 |
-
<td>- Membutuhkan ruang penyimpanan yang besar<br>- Membutuhkan waktu download yang lama<br>- Tidak semua perangkat bisa memutar format MKV</td>
|
109 |
-
</tr>
|
110 |
-
<tr>
|
111 |
-
<td>HD</td>
|
112 |
-
<td>MP4</td>
|
113 |
-
<td>800 MB</td>
|
114 |
-
<td>- Menyajikan gambar dan suara yang cukup jernih dan tajam<br>- Cocok untuk ditonton di layar sedang atau kecil<br>- Bisa diputar di hampir semua perangkat<br>- Mendukung subtitle dalam berbagai bahasa</td>
|
115 |
-
<td>- Membutuhkan ruang penyimpanan yang cukup besar<br>- Membutuhkan waktu download yang cukup lama<br>- Tidak sejernih kualitas Bluray</td>
|
116 |
-
</tr>
|
117 |
-
<tr>
|
118 |
-
<td>DVDrip</td>
|
119 |
-
<td>AVI</td>
|
120 |
-
<td>500 MB</td>
|
121 |
-
<td>- Menyajikan gambar dan suara yang standar<br>- Cocok untuk ditonton di layar kecil<br>- Bisa diputar di banyak perangkat<br>- Membutuhkan ruang penyimpanan yang sedang<br>- Membutuhkan waktu download yang sedang</td>
|
122 |
-
<td>- Tidak sejernih kualitas HD atau Bluray<br>- Tidak mendukung subtitle dalam berbagai bahasa<br>- Bisa mengalami gangguan gambar atau suara saat diputar</td>
|
123 |
-
</tr>
|
124 |
-
<tr>
|
125 |
-
<td>CAMrip</td>
|
126 |
-
<td>MOV</td>
|
127 |
-
<td>300 MB</td>
|
128 |
-
<td>- Menyajikan gambar dan suara yang rendah<br>- Cocok untuk ditonton di layar kecil<br>- Bisa diputar di beberapa perangkat<br>- Membutuhkan ruang penyimpanan yang kecil<br>- Membutuhkan waktu download yang cepat</td>
|
129 |
-
<td>- Tidak sejernih kualitas DVDrip, HD, atau Bluray<br>- Tidak mendukung subtitle dalam berbagai bahasa<br>- Bisa mengalami gangguan gambar atau suara saat diputar<br>- Bisa melanggar hak cipta karena direkam secara ilegal di bioskop</td>
|
130 |
-
</tr>
|
131 |
-
</table>
|
132 |
-
<p>Anda bisa memilih kualitas dan format video yang sesuai dengan kebutuhan dan preferensi Anda. Anda juga bisa membandingkan kualitas dan format video yang ditawarkan oleh situs web yang berbeda untuk mendapatkan yang terbaik.</p>
|
133 |
-
<h3>Langkah 4: Klik Tombol Download dan Tunggu Proses Download Selesai</h3>
|
134 |
-
<p>Setelah Anda memilih kualitas dan format video yang Anda inginkan, Anda bisa klik tombol download yang tersedia di halaman detail film The Polar Express. Anda mungkin akan diarahkan ke halaman lain atau diminta untuk memasukkan kode captcha atau melakukan verifikasi lainnya sebelum bisa mengakses link download. Ikuti instruksi yang diberikan oleh situs web tersebut dengan hati-hati dan pastikan Anda tidak mengklik iklan atau link yang mencurigakan. Setelah Anda mendapatkan link download, Anda bisa klik kanan dan pilih save as atau save link as untuk menyimpan file video tersebut di perangkat Anda. Tunggu hingga proses download selesai dan pastikan file video tersebut tidak rusak atau terputus saat didownload.</p>
|
135 |
-
<h4>Tips: Gunakan Koneksi Internet yang Stabil dan Cepat untuk Menghindari Gangguan Download</h4>
|
136 |
-
<p>Untuk mendownload film The Polar Express bahasa Indonesia dengan lancar dan cepat, Anda disarankan untuk menggunakan koneksi internet yang stabil dan cepat. Anda bisa menggunakan wifi, modem, atau paket data yang memiliki kecepatan dan kuota yang cukup. Anda juga bisa menggunakan aplikasi download manager seperti IDM, uTorrent, atau BitTorrent untuk mempercepat dan mempermudah proses download. Aplikasi ini bisa membantu Anda untuk melanjutkan download jika terjadi gangguan atau pemutusan koneksi. Aplikasi ini juga bisa membantu Anda untuk mengatur jadwal download, mengelola file download, dan melakukan pengecekan file download.</p>
|
137 |
-
<h2>Mengapa Anda Harus Menonton Film The Polar Express?</h2>
|
138 |
-
<h3>Film The Polar Express Menyajikan Cerita yang Menarik dan Menginspirasi tentang Keajaiban Natal</h3>
|
139 |
-
<p>Film The Polar Express bukan hanya sekedar film animasi biasa, tetapi juga sebuah film yang menyajikan cerita yang menarik dan menginspirasi tentang keajaiban Natal. Film ini mengajak Anda untuk mengikuti petualangan anak laki-laki yang mulai meragukan keberadaan Sinterklas, tetapi kemudian menemukan kembali iman dan harapannya melalui perjalanan ajaib ke Kutub Utara. Film ini juga mengajak Anda untuk merasakan semangat Natal yang hangat dan menyenangkan bersama dengan karakter-karakter yang lucu dan menawan. Film ini juga mengajak Anda untuk belajar tentang nilai-nilai penting seperti persahabatan, keberanian, kejujuran, dan rasa syukur.</p>
|
140 |
-
<h3>Film The Polar Express Menggunakan Teknologi Animasi Canggih yang Membuat Karakter dan Latar Belakang Terlihat Nyata</h3>
|
141 |
-
<p>Film The Polar Express merupakan film animasi pertama yang menggunakan teknologi motion capture secara penuh untuk membuat karakter dan latar belakang terlihat nyata. Teknologi ini memungkinkan para aktor untuk mengenakan kostum khusus yang dilengkapi dengan sensor-sensor yang merekam gerakan tubuh dan wajah mereka. Gerakan-gerakan tersebut kemudian ditransfer ke komputer dan diubah menjadi gambar animasi tiga dimensi. Dengan teknologi ini, film The Polar Express mampu menampilkan ekspresi wajah, gerak tubuh, dan bahasa tubuh para karakter dengan sangat detail dan realistis. Film ini juga mampu menampilkan latar belakang yang indah dan menakjubkan, seperti salju, es, gunung, hutan, kota, dan lain-lain.</p>
|
142 |
-
<h3>Film The Polar Express Menampilkan Musik dan Lagu-lagu yang Meriah dan Menyentuh Hati</h3>
|
143 |
-
<p>Film The Polar Express juga menampilkan musik dan lagu-lagu yang meriah dan menyentuh hati. Musik film ini dikomposisi oleh Alan Silvestri, seorang komposer musik film terken al yang telah membuat musik untuk film-film seperti Back to the Future, Forrest Gump, dan The Avengers. Lagu-lagu film ini dinyanyikan oleh para aktor dan aktris yang berperan dalam film ini, seperti Tom Hanks, Nona Gaye, Steven Tyler, dan lain-lain. Beberapa lagu yang menjadi andalan film ini adalah The Polar Express, When Christmas Comes to Town, Rockin' on Top of the World, dan Believe. Lagu-lagu ini memiliki irama yang ceria dan lirik yang menyampaikan pesan-pesan positif tentang Natal.</p>
|
144 |
-
<h2>Kesimpulan</h2>
|
145 |
-
<p>Film The Polar Express adalah film yang sangat cocok untuk ditonton bersama keluarga di malam Natal. Film ini menyajikan cerita yang menarik dan menginspirasi tentang keajaiban Natal, menggunakan teknologi animasi canggih yang membuat karakter dan latar belakang terlihat nyata, dan menampilkan musik dan lagu-lagu yang meriah dan menyentuh hati. Anda bisa mendownload film The Polar Express bahasa Indonesia dengan mudah dan cepat dengan mengikuti langkah-langkah yang telah dijelaskan di atas. Selamat menonton dan selamat Natal!</p>
|
146 |
-
<h2>FAQ</h2>
|
147 |
-
<p>Berikut ini adalah beberapa pertanyaan yang sering diajukan tentang film The Polar Express:</p>
|
148 |
-
<ol>
|
149 |
-
<li>Apakah film The Polar Express cocok untuk ditonton oleh anak-anak?<br>Jawab: Ya, film The Polar Express cocok untuk ditonton oleh anak-anak karena film ini memiliki rating PG (Parental Guidance) yang berarti film ini bisa ditonton oleh semua umur dengan bimbingan orang tua. Film ini juga tidak mengandung adegan kekerasan, seksualitas, atau bahasa kasar yang tidak pantas untuk anak-anak.</li>
|
150 |
-
<li>Apakah film The Polar Express berdasarkan kisah nyata?<br>Jawab: Tidak, film The Polar Express tidak berdasarkan kisah nyata, tetapi berdasarkan buku gambar anak-anak karya Chris Van Allsburg yang terbit pada tahun 1985. Buku ini sendiri terinspirasi oleh kenangan masa kecil penulis tentang kereta api uap yang melintas di dekat rumahnya.</li>
|
151 |
-
<li>Apakah film The Polar Express memiliki sekuel?<br>Jawab: Tidak, film The Polar Express tidak memiliki sekuel. Film ini merupakan film tunggal yang tidak terhubung dengan film lain. Namun, ada beberapa film animasi lain yang memiliki tema atau gaya serupa dengan film The Polar Express, seperti A Christmas Carol (2009), Arthur Christmas (2011), atau Klaus (2019).</li>
|
152 |
-
<li>Apakah film The Polar Express tersedia di Netflix?<br>Jawab: Tergantung pada negara tempat Anda tinggal. Di beberapa negara, film The Polar Express tersedia di Netflix sebagai salah satu pilihan film Natal. Namun, di beberapa negara lain, film The Polar Express tidak tersedia di Netflix karena masalah lisensi atau hak cipta. Anda bisa mengecek ketersediaan film The Polar Express di Netflix dengan menggunakan fitur pencarian atau browsing di aplikasi atau situs web Netflix.</li>
|
153 |
-
<li>Apakah ada perbedaan antara versi bahasa Inggris dan versi bahasa Indonesia dari film The Polar Express?<br>Jawab: Secara umum, tidak ada perbedaan yang signifikan antara versi bahasa Inggris dan versi bahasa Indonesia dari film The Polar Express. Versi bahasa Indonesia hanya merupakan terjemahan dari versi bahasa Inggris dengan mengubah dialog-dialog dan lagu-lagu menjadi bahasa Indonesia. Namun, ada kemungkinan bahwa ada beberapa nuansa atau makna yang hilang atau berubah saat proses terjemahan.</li>
|
154 |
-
</ol></p> 197e85843d<br />
|
155 |
-
<br />
|
156 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/777DUKE/Ballin/Dockerfile
DELETED
@@ -1,21 +0,0 @@
|
|
1 |
-
FROM node:18-bullseye-slim
|
2 |
-
|
3 |
-
RUN apt-get update && \
|
4 |
-
|
5 |
-
apt-get install -y git
|
6 |
-
|
7 |
-
RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app
|
8 |
-
|
9 |
-
WORKDIR /app
|
10 |
-
|
11 |
-
RUN npm install
|
12 |
-
|
13 |
-
COPY Dockerfile greeting.md* .env* ./
|
14 |
-
|
15 |
-
RUN npm run build
|
16 |
-
|
17 |
-
EXPOSE 7860
|
18 |
-
|
19 |
-
ENV NODE_ENV=production
|
20 |
-
|
21 |
-
CMD [ "npm", "start" ]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/7hao/bingo/src/components/chat-history.tsx
DELETED
@@ -1,48 +0,0 @@
|
|
1 |
-
import { IconEdit, IconTrash, IconMore, IconDownload } from "./ui/icons"
|
2 |
-
|
3 |
-
export function ChatHistory() {
|
4 |
-
return (
|
5 |
-
<div className="chat-history fixed top-18 right-4">
|
6 |
-
<div className="chat-history-header text-sm font-semibold text-left w-[280px] px-4 py-6">
|
7 |
-
历史记录
|
8 |
-
</div>
|
9 |
-
<div className="chat-history-main">
|
10 |
-
<div className="scroller">
|
11 |
-
<div className="surface">
|
12 |
-
<div className="threads">
|
13 |
-
<div className="thread">
|
14 |
-
<div className="primary-row">
|
15 |
-
<button type="button" aria-label="加载聊天">
|
16 |
-
|
17 |
-
</button>
|
18 |
-
<div className="description">
|
19 |
-
<h3 className="name">无标题的聊天</h3>
|
20 |
-
</div>
|
21 |
-
<h4 className="time">上午1:42</h4>
|
22 |
-
<div className="controls">
|
23 |
-
|
24 |
-
<button className="edit icon-button" type="button" aria-label="重命名">
|
25 |
-
<IconEdit />
|
26 |
-
</button>
|
27 |
-
|
28 |
-
<button className="delete icon-button" type="button" aria-label="删除">
|
29 |
-
<IconTrash />
|
30 |
-
</button>
|
31 |
-
|
32 |
-
<button className="more icon-button" type="button" aria-haspopup="true" aria-expanded="false" aria-label="更多">
|
33 |
-
<IconMore />
|
34 |
-
</button>
|
35 |
-
|
36 |
-
<button className="export icon-button" type="button" aria-label="导出">
|
37 |
-
<IconDownload />
|
38 |
-
</button>
|
39 |
-
</div>
|
40 |
-
</div>
|
41 |
-
</div>
|
42 |
-
</div>
|
43 |
-
</div>
|
44 |
-
</div>
|
45 |
-
</div>
|
46 |
-
</div>
|
47 |
-
)
|
48 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AB-TW/team-ai/models.py
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
from langchain.chat_models import ChatOpenAI
|
2 |
-
from langchain.base_language import BaseLanguageModel
|
3 |
-
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
4 |
-
|
5 |
-
def llm(temperature=0) -> BaseLanguageModel:
|
6 |
-
# gpt-3.5
|
7 |
-
return ChatOpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=temperature)
|
8 |
-
|
9 |
-
# return ChatOpenAI(streaming=True, callbacks=[StreamingStdOutCallbackHandler()], temperature=temperature, model_name="gpt-4")
|
10 |
-
# gpt-4
|
11 |
-
# return ChatOpenAI(temperature=temperature, model_name="gpt-4")
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIFILMS/audioldm-text-to-audio-generation/audioldm/clap/encoders.py
DELETED
@@ -1,169 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
from audioldm.clap.open_clip import create_model
|
4 |
-
from audioldm.clap.training.data import get_audio_features
|
5 |
-
import torchaudio
|
6 |
-
from transformers import RobertaTokenizer
|
7 |
-
import torch.nn.functional as F
|
8 |
-
|
9 |
-
|
10 |
-
class CLAPAudioEmbeddingClassifierFreev2(nn.Module):
|
11 |
-
def __init__(
|
12 |
-
self,
|
13 |
-
pretrained_path="",
|
14 |
-
key="class",
|
15 |
-
sampling_rate=16000,
|
16 |
-
embed_mode="audio",
|
17 |
-
unconditional_prob=0.1,
|
18 |
-
random_mute=False,
|
19 |
-
max_random_mute_portion=0.5,
|
20 |
-
training_mode=True,
|
21 |
-
):
|
22 |
-
super().__init__()
|
23 |
-
|
24 |
-
self.key = key
|
25 |
-
self.device = "cpu"
|
26 |
-
self.precision = "fp32"
|
27 |
-
self.amodel = "HTSAT-tiny" # or 'PANN-14'
|
28 |
-
self.tmodel = "roberta" # the best text encoder in our training
|
29 |
-
self.enable_fusion = False # False if you do not want to use the fusion model
|
30 |
-
self.fusion_type = "aff_2d"
|
31 |
-
self.pretrained = pretrained_path
|
32 |
-
self.embed_mode = embed_mode
|
33 |
-
self.embed_mode_orig = embed_mode
|
34 |
-
self.sampling_rate = sampling_rate
|
35 |
-
self.unconditional_prob = unconditional_prob
|
36 |
-
self.random_mute = random_mute
|
37 |
-
self.tokenize = RobertaTokenizer.from_pretrained("roberta-base")
|
38 |
-
self.max_random_mute_portion = max_random_mute_portion
|
39 |
-
self.training_mode = training_mode
|
40 |
-
self.model, self.model_cfg = create_model(
|
41 |
-
self.amodel,
|
42 |
-
self.tmodel,
|
43 |
-
self.pretrained,
|
44 |
-
precision=self.precision,
|
45 |
-
device=self.device,
|
46 |
-
enable_fusion=self.enable_fusion,
|
47 |
-
fusion_type=self.fusion_type,
|
48 |
-
)
|
49 |
-
for p in self.model.parameters():
|
50 |
-
p.requires_grad = False
|
51 |
-
|
52 |
-
self.model.eval()
|
53 |
-
|
54 |
-
def get_unconditional_condition(self, batchsize):
|
55 |
-
self.unconditional_token = self.model.get_text_embedding(
|
56 |
-
self.tokenizer(["", ""])
|
57 |
-
)[0:1]
|
58 |
-
return torch.cat([self.unconditional_token.unsqueeze(0)] * batchsize, dim=0)
|
59 |
-
|
60 |
-
def batch_to_list(self, batch):
|
61 |
-
ret = []
|
62 |
-
for i in range(batch.size(0)):
|
63 |
-
ret.append(batch[i])
|
64 |
-
return ret
|
65 |
-
|
66 |
-
def make_decision(self, probability):
|
67 |
-
if float(torch.rand(1)) < probability:
|
68 |
-
return True
|
69 |
-
else:
|
70 |
-
return False
|
71 |
-
|
72 |
-
def random_uniform(self, start, end):
|
73 |
-
val = torch.rand(1).item()
|
74 |
-
return start + (end - start) * val
|
75 |
-
|
76 |
-
def _random_mute(self, waveform):
|
77 |
-
# waveform: [bs, t-steps]
|
78 |
-
t_steps = waveform.size(-1)
|
79 |
-
for i in range(waveform.size(0)):
|
80 |
-
mute_size = int(
|
81 |
-
self.random_uniform(0, end=int(t_steps * self.max_random_mute_portion))
|
82 |
-
)
|
83 |
-
mute_start = int(self.random_uniform(0, t_steps - mute_size))
|
84 |
-
waveform[i, mute_start : mute_start + mute_size] = 0
|
85 |
-
return waveform
|
86 |
-
|
87 |
-
def cos_similarity(self, waveform, text):
|
88 |
-
# waveform: [bs, t_steps]
|
89 |
-
with torch.no_grad():
|
90 |
-
self.embed_mode = "audio"
|
91 |
-
audio_emb = self(waveform.cuda())
|
92 |
-
self.embed_mode = "text"
|
93 |
-
text_emb = self(text)
|
94 |
-
similarity = F.cosine_similarity(audio_emb, text_emb, dim=2)
|
95 |
-
return similarity.squeeze()
|
96 |
-
|
97 |
-
def forward(self, batch, key=None):
|
98 |
-
# If you want this conditioner to be unconditional, set self.unconditional_prob = 1.0
|
99 |
-
# If you want this conditioner to be fully conditional, set self.unconditional_prob = 0.0
|
100 |
-
if self.model.training == True and not self.training_mode:
|
101 |
-
print(
|
102 |
-
"The pretrained CLAP model should always be in eval mode. Reloading model just in case you change the parameters."
|
103 |
-
)
|
104 |
-
self.model, self.model_cfg = create_model(
|
105 |
-
self.amodel,
|
106 |
-
self.tmodel,
|
107 |
-
self.pretrained,
|
108 |
-
precision=self.precision,
|
109 |
-
device="cuda",
|
110 |
-
enable_fusion=self.enable_fusion,
|
111 |
-
fusion_type=self.fusion_type,
|
112 |
-
)
|
113 |
-
for p in self.model.parameters():
|
114 |
-
p.requires_grad = False
|
115 |
-
self.model.eval()
|
116 |
-
|
117 |
-
# the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode
|
118 |
-
if self.embed_mode == "audio":
|
119 |
-
with torch.no_grad():
|
120 |
-
audio_dict_list = []
|
121 |
-
assert (
|
122 |
-
self.sampling_rate == 16000
|
123 |
-
), "We only support 16000 sampling rate"
|
124 |
-
if self.random_mute:
|
125 |
-
batch = self._random_mute(batch)
|
126 |
-
# batch: [bs, 1, t-samples]
|
127 |
-
batch = torchaudio.functional.resample(
|
128 |
-
batch, orig_freq=self.sampling_rate, new_freq=48000
|
129 |
-
)
|
130 |
-
for waveform in self.batch_to_list(batch):
|
131 |
-
audio_dict = {}
|
132 |
-
audio_dict = get_audio_features(
|
133 |
-
audio_dict,
|
134 |
-
waveform,
|
135 |
-
480000,
|
136 |
-
data_truncating="fusion",
|
137 |
-
data_filling="repeatpad",
|
138 |
-
audio_cfg=self.model_cfg["audio_cfg"],
|
139 |
-
)
|
140 |
-
audio_dict_list.append(audio_dict)
|
141 |
-
# [bs, 512]
|
142 |
-
embed = self.model.get_audio_embedding(audio_dict_list)
|
143 |
-
elif self.embed_mode == "text":
|
144 |
-
with torch.no_grad():
|
145 |
-
# the 'fusion' truncate mode can be changed to 'rand_trunc' if run in unfusion mode
|
146 |
-
text_data = self.tokenizer(batch)
|
147 |
-
embed = self.model.get_text_embedding(text_data)
|
148 |
-
|
149 |
-
embed = embed.unsqueeze(1)
|
150 |
-
self.unconditional_token = self.model.get_text_embedding(
|
151 |
-
self.tokenizer(["", ""])
|
152 |
-
)[0:1]
|
153 |
-
|
154 |
-
for i in range(embed.size(0)):
|
155 |
-
if self.make_decision(self.unconditional_prob):
|
156 |
-
embed[i] = self.unconditional_token
|
157 |
-
|
158 |
-
# [bs, 1, 512]
|
159 |
-
return embed.detach()
|
160 |
-
|
161 |
-
def tokenizer(self, text):
|
162 |
-
result = self.tokenize(
|
163 |
-
text,
|
164 |
-
padding="max_length",
|
165 |
-
truncation=True,
|
166 |
-
max_length=512,
|
167 |
-
return_tensors="pt",
|
168 |
-
)
|
169 |
-
return {k: v.squeeze(0) for k, v in result.items()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/parallel_wavegan/layers/residual_block.py
DELETED
@@ -1,129 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
|
3 |
-
"""Residual block module in WaveNet.
|
4 |
-
|
5 |
-
This code is modified from https://github.com/r9y9/wavenet_vocoder.
|
6 |
-
|
7 |
-
"""
|
8 |
-
|
9 |
-
import math
|
10 |
-
|
11 |
-
import torch
|
12 |
-
import torch.nn.functional as F
|
13 |
-
|
14 |
-
|
15 |
-
class Conv1d(torch.nn.Conv1d):
|
16 |
-
"""Conv1d module with customized initialization."""
|
17 |
-
|
18 |
-
def __init__(self, *args, **kwargs):
|
19 |
-
"""Initialize Conv1d module."""
|
20 |
-
super(Conv1d, self).__init__(*args, **kwargs)
|
21 |
-
|
22 |
-
def reset_parameters(self):
|
23 |
-
"""Reset parameters."""
|
24 |
-
torch.nn.init.kaiming_normal_(self.weight, nonlinearity="relu")
|
25 |
-
if self.bias is not None:
|
26 |
-
torch.nn.init.constant_(self.bias, 0.0)
|
27 |
-
|
28 |
-
|
29 |
-
class Conv1d1x1(Conv1d):
|
30 |
-
"""1x1 Conv1d with customized initialization."""
|
31 |
-
|
32 |
-
def __init__(self, in_channels, out_channels, bias):
|
33 |
-
"""Initialize 1x1 Conv1d module."""
|
34 |
-
super(Conv1d1x1, self).__init__(in_channels, out_channels,
|
35 |
-
kernel_size=1, padding=0,
|
36 |
-
dilation=1, bias=bias)
|
37 |
-
|
38 |
-
|
39 |
-
class ResidualBlock(torch.nn.Module):
|
40 |
-
"""Residual block module in WaveNet."""
|
41 |
-
|
42 |
-
def __init__(self,
|
43 |
-
kernel_size=3,
|
44 |
-
residual_channels=64,
|
45 |
-
gate_channels=128,
|
46 |
-
skip_channels=64,
|
47 |
-
aux_channels=80,
|
48 |
-
dropout=0.0,
|
49 |
-
dilation=1,
|
50 |
-
bias=True,
|
51 |
-
use_causal_conv=False
|
52 |
-
):
|
53 |
-
"""Initialize ResidualBlock module.
|
54 |
-
|
55 |
-
Args:
|
56 |
-
kernel_size (int): Kernel size of dilation convolution layer.
|
57 |
-
residual_channels (int): Number of channels for residual connection.
|
58 |
-
skip_channels (int): Number of channels for skip connection.
|
59 |
-
aux_channels (int): Local conditioning channels i.e. auxiliary input dimension.
|
60 |
-
dropout (float): Dropout probability.
|
61 |
-
dilation (int): Dilation factor.
|
62 |
-
bias (bool): Whether to add bias parameter in convolution layers.
|
63 |
-
use_causal_conv (bool): Whether to use use_causal_conv or non-use_causal_conv convolution.
|
64 |
-
|
65 |
-
"""
|
66 |
-
super(ResidualBlock, self).__init__()
|
67 |
-
self.dropout = dropout
|
68 |
-
# no future time stamps available
|
69 |
-
if use_causal_conv:
|
70 |
-
padding = (kernel_size - 1) * dilation
|
71 |
-
else:
|
72 |
-
assert (kernel_size - 1) % 2 == 0, "Not support even number kernel size."
|
73 |
-
padding = (kernel_size - 1) // 2 * dilation
|
74 |
-
self.use_causal_conv = use_causal_conv
|
75 |
-
|
76 |
-
# dilation conv
|
77 |
-
self.conv = Conv1d(residual_channels, gate_channels, kernel_size,
|
78 |
-
padding=padding, dilation=dilation, bias=bias)
|
79 |
-
|
80 |
-
# local conditioning
|
81 |
-
if aux_channels > 0:
|
82 |
-
self.conv1x1_aux = Conv1d1x1(aux_channels, gate_channels, bias=False)
|
83 |
-
else:
|
84 |
-
self.conv1x1_aux = None
|
85 |
-
|
86 |
-
# conv output is split into two groups
|
87 |
-
gate_out_channels = gate_channels // 2
|
88 |
-
self.conv1x1_out = Conv1d1x1(gate_out_channels, residual_channels, bias=bias)
|
89 |
-
self.conv1x1_skip = Conv1d1x1(gate_out_channels, skip_channels, bias=bias)
|
90 |
-
|
91 |
-
def forward(self, x, c):
|
92 |
-
"""Calculate forward propagation.
|
93 |
-
|
94 |
-
Args:
|
95 |
-
x (Tensor): Input tensor (B, residual_channels, T).
|
96 |
-
c (Tensor): Local conditioning auxiliary tensor (B, aux_channels, T).
|
97 |
-
|
98 |
-
Returns:
|
99 |
-
Tensor: Output tensor for residual connection (B, residual_channels, T).
|
100 |
-
Tensor: Output tensor for skip connection (B, skip_channels, T).
|
101 |
-
|
102 |
-
"""
|
103 |
-
residual = x
|
104 |
-
x = F.dropout(x, p=self.dropout, training=self.training)
|
105 |
-
x = self.conv(x)
|
106 |
-
|
107 |
-
# remove future time steps if use_causal_conv conv
|
108 |
-
x = x[:, :, :residual.size(-1)] if self.use_causal_conv else x
|
109 |
-
|
110 |
-
# split into two part for gated activation
|
111 |
-
splitdim = 1
|
112 |
-
xa, xb = x.split(x.size(splitdim) // 2, dim=splitdim)
|
113 |
-
|
114 |
-
# local conditioning
|
115 |
-
if c is not None:
|
116 |
-
assert self.conv1x1_aux is not None
|
117 |
-
c = self.conv1x1_aux(c)
|
118 |
-
ca, cb = c.split(c.size(splitdim) // 2, dim=splitdim)
|
119 |
-
xa, xb = xa + ca, xb + cb
|
120 |
-
|
121 |
-
x = torch.tanh(xa) * torch.sigmoid(xb)
|
122 |
-
|
123 |
-
# for skip connection
|
124 |
-
s = self.conv1x1_skip(x)
|
125 |
-
|
126 |
-
# for residual connection
|
127 |
-
x = (self.conv1x1_out(x) + residual) * math.sqrt(0.5)
|
128 |
-
|
129 |
-
return x, s
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIGC-Audio/AudioGPT/NeuralSeq/tasks/tts/tts_utils.py
DELETED
@@ -1,54 +0,0 @@
|
|
1 |
-
import importlib
|
2 |
-
|
3 |
-
from data_gen.tts.base_binarizer import BaseBinarizer
|
4 |
-
from data_gen.tts.base_preprocess import BasePreprocessor
|
5 |
-
from data_gen.tts.txt_processors.base_text_processor import get_txt_processor_cls
|
6 |
-
from utils.hparams import hparams
|
7 |
-
|
8 |
-
|
9 |
-
def parse_dataset_configs():
|
10 |
-
max_tokens = hparams['max_tokens']
|
11 |
-
max_sentences = hparams['max_sentences']
|
12 |
-
max_valid_tokens = hparams['max_valid_tokens']
|
13 |
-
if max_valid_tokens == -1:
|
14 |
-
hparams['max_valid_tokens'] = max_valid_tokens = max_tokens
|
15 |
-
max_valid_sentences = hparams['max_valid_sentences']
|
16 |
-
if max_valid_sentences == -1:
|
17 |
-
hparams['max_valid_sentences'] = max_valid_sentences = max_sentences
|
18 |
-
return max_tokens, max_sentences, max_valid_tokens, max_valid_sentences
|
19 |
-
|
20 |
-
|
21 |
-
def parse_mel_losses():
|
22 |
-
mel_losses = hparams['mel_losses'].split("|")
|
23 |
-
loss_and_lambda = {}
|
24 |
-
for i, l in enumerate(mel_losses):
|
25 |
-
if l == '':
|
26 |
-
continue
|
27 |
-
if ':' in l:
|
28 |
-
l, lbd = l.split(":")
|
29 |
-
lbd = float(lbd)
|
30 |
-
else:
|
31 |
-
lbd = 1.0
|
32 |
-
loss_and_lambda[l] = lbd
|
33 |
-
print("| Mel losses:", loss_and_lambda)
|
34 |
-
return loss_and_lambda
|
35 |
-
|
36 |
-
|
37 |
-
def load_data_preprocessor():
|
38 |
-
preprocess_cls = hparams["preprocess_cls"]
|
39 |
-
pkg = ".".join(preprocess_cls.split(".")[:-1])
|
40 |
-
cls_name = preprocess_cls.split(".")[-1]
|
41 |
-
preprocessor: BasePreprocessor = getattr(importlib.import_module(pkg), cls_name)()
|
42 |
-
preprocess_args = {}
|
43 |
-
preprocess_args.update(hparams['preprocess_args'])
|
44 |
-
return preprocessor, preprocess_args
|
45 |
-
|
46 |
-
|
47 |
-
def load_data_binarizer():
|
48 |
-
binarizer_cls = hparams['binarizer_cls']
|
49 |
-
pkg = ".".join(binarizer_cls.split(".")[:-1])
|
50 |
-
cls_name = binarizer_cls.split(".")[-1]
|
51 |
-
binarizer: BaseBinarizer = getattr(importlib.import_module(pkg), cls_name)()
|
52 |
-
binarization_args = {}
|
53 |
-
binarization_args.update(hparams['binarization_args'])
|
54 |
-
return binarizer, binarization_args
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/ASJMO/freegpt/g4f/Provider/Providers/Easychat.py
DELETED
@@ -1,55 +0,0 @@
|
|
1 |
-
import requests
|
2 |
-
import os
|
3 |
-
import json
|
4 |
-
from ...typing import sha256, Dict, get_type_hints
|
5 |
-
|
6 |
-
url = 'https://free.easychat.work'
|
7 |
-
model = ['gpt-3.5-turbo', 'gpt-3.5-turbo-16k',
|
8 |
-
'gpt-3.5-turbo-16k-0613', 'gpt-3.5-turbo-0613']
|
9 |
-
supports_stream = True
|
10 |
-
needs_auth = False
|
11 |
-
|
12 |
-
|
13 |
-
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
|
14 |
-
headers = {
|
15 |
-
'authority': 'free.easychat.work',
|
16 |
-
'accept': 'text/event-stream',
|
17 |
-
'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
|
18 |
-
'content-type': 'application/json',
|
19 |
-
'endpoint': '',
|
20 |
-
'origin': 'https://free.easychat.work',
|
21 |
-
'plugins': '0',
|
22 |
-
'referer': 'https://free.easychat.work/',
|
23 |
-
'sec-ch-ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
|
24 |
-
'sec-ch-ua-mobile': '?0',
|
25 |
-
'sec-ch-ua-platform': '"macOS"',
|
26 |
-
'sec-fetch-dest': 'empty',
|
27 |
-
'sec-fetch-mode': 'cors',
|
28 |
-
'sec-fetch-site': 'same-origin',
|
29 |
-
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
|
30 |
-
'usesearch': 'false',
|
31 |
-
'x-requested-with': 'XMLHttpRequest',
|
32 |
-
}
|
33 |
-
|
34 |
-
json_data = {
|
35 |
-
'messages': messages,
|
36 |
-
'stream': True,
|
37 |
-
'model': model,
|
38 |
-
'temperature': 0.5,
|
39 |
-
'presence_penalty': 0,
|
40 |
-
'frequency_penalty': 0,
|
41 |
-
'top_p': 1,
|
42 |
-
}
|
43 |
-
|
44 |
-
response = requests.post('https://free.easychat.work/api/openai/v1/chat/completions',
|
45 |
-
headers=headers, json=json_data)
|
46 |
-
|
47 |
-
for chunk in response.iter_lines():
|
48 |
-
if b'content' in chunk:
|
49 |
-
data = json.loads(chunk.decode().split('data: ')[1])
|
50 |
-
yield (data['choices'][0]['delta']['content'])
|
51 |
-
|
52 |
-
|
53 |
-
params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \
|
54 |
-
'(%s)' % ', '.join(
|
55 |
-
[f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AchyuthGamer/OpenGPT-Chat-UI/.svelte-kit/generated/client/nodes/7.js
DELETED
File without changes
|
spaces/Aki004/herta-so-vits/vdecoder/hifigan/env.py
DELETED
@@ -1,15 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import shutil
|
3 |
-
|
4 |
-
|
5 |
-
class AttrDict(dict):
|
6 |
-
def __init__(self, *args, **kwargs):
|
7 |
-
super(AttrDict, self).__init__(*args, **kwargs)
|
8 |
-
self.__dict__ = self
|
9 |
-
|
10 |
-
|
11 |
-
def build_env(config, config_name, path):
|
12 |
-
t_path = os.path.join(path, config_name)
|
13 |
-
if config != t_path:
|
14 |
-
os.makedirs(path, exist_ok=True)
|
15 |
-
shutil.copyfile(config, os.path.join(path, config_name))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Alican/pixera/models/base_model.py
DELETED
@@ -1,230 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import torch
|
3 |
-
from collections import OrderedDict
|
4 |
-
from abc import ABC, abstractmethod
|
5 |
-
from . import networks
|
6 |
-
|
7 |
-
|
8 |
-
class BaseModel(ABC):
|
9 |
-
"""This class is an abstract base class (ABC) for models.
|
10 |
-
To create a subclass, you need to implement the following five functions:
|
11 |
-
-- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).
|
12 |
-
-- <set_input>: unpack data from dataset and apply preprocessing.
|
13 |
-
-- <forward>: produce intermediate results.
|
14 |
-
-- <optimize_parameters>: calculate losses, gradients, and update network weights.
|
15 |
-
-- <modify_commandline_options>: (optionally) add model-specific options and set default options.
|
16 |
-
"""
|
17 |
-
|
18 |
-
def __init__(self, opt):
|
19 |
-
"""Initialize the BaseModel class.
|
20 |
-
|
21 |
-
Parameters:
|
22 |
-
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
23 |
-
|
24 |
-
When creating your custom class, you need to implement your own initialization.
|
25 |
-
In this function, you should first call <BaseModel.__init__(self, opt)>
|
26 |
-
Then, you need to define four lists:
|
27 |
-
-- self.loss_names (str list): specify the training losses that you want to plot and save.
|
28 |
-
-- self.model_names (str list): define networks used in our training.
|
29 |
-
-- self.visual_names (str list): specify the images that you want to display and save.
|
30 |
-
-- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.
|
31 |
-
"""
|
32 |
-
self.opt = opt
|
33 |
-
self.gpu_ids = opt.gpu_ids
|
34 |
-
self.isTrain = opt.isTrain
|
35 |
-
self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') # get device name: CPU or GPU
|
36 |
-
self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) # save all the checkpoints to save_dir
|
37 |
-
if opt.preprocess != 'scale_width': # with [scale_width], input images might have different sizes, which hurts the performance of cudnn.benchmark.
|
38 |
-
torch.backends.cudnn.benchmark = True
|
39 |
-
self.loss_names = []
|
40 |
-
self.model_names = []
|
41 |
-
self.visual_names = []
|
42 |
-
self.optimizers = []
|
43 |
-
self.image_paths = []
|
44 |
-
self.metric = 0 # used for learning rate policy 'plateau'
|
45 |
-
|
46 |
-
@staticmethod
|
47 |
-
def modify_commandline_options(parser, is_train):
|
48 |
-
"""Add new model-specific options, and rewrite default values for existing options.
|
49 |
-
|
50 |
-
Parameters:
|
51 |
-
parser -- original option parser
|
52 |
-
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
53 |
-
|
54 |
-
Returns:
|
55 |
-
the modified parser.
|
56 |
-
"""
|
57 |
-
return parser
|
58 |
-
|
59 |
-
@abstractmethod
|
60 |
-
def set_input(self, input):
|
61 |
-
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
62 |
-
|
63 |
-
Parameters:
|
64 |
-
input (dict): includes the data itself and its metadata information.
|
65 |
-
"""
|
66 |
-
pass
|
67 |
-
|
68 |
-
@abstractmethod
|
69 |
-
def forward(self):
|
70 |
-
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
|
71 |
-
pass
|
72 |
-
|
73 |
-
@abstractmethod
|
74 |
-
def optimize_parameters(self):
|
75 |
-
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
|
76 |
-
pass
|
77 |
-
|
78 |
-
def setup(self, opt):
|
79 |
-
"""Load and print networks; create schedulers
|
80 |
-
|
81 |
-
Parameters:
|
82 |
-
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
83 |
-
"""
|
84 |
-
if self.isTrain:
|
85 |
-
self.schedulers = [networks.get_scheduler(optimizer, opt) for optimizer in self.optimizers]
|
86 |
-
if not self.isTrain or opt.continue_train:
|
87 |
-
load_suffix = 'iter_%d' % opt.load_iter if opt.load_iter > 0 else opt.epoch
|
88 |
-
self.load_networks(load_suffix)
|
89 |
-
self.print_networks(opt.verbose)
|
90 |
-
|
91 |
-
def eval(self):
|
92 |
-
"""Make models eval mode during test time"""
|
93 |
-
for name in self.model_names:
|
94 |
-
if isinstance(name, str):
|
95 |
-
net = getattr(self, 'net' + name)
|
96 |
-
net.eval()
|
97 |
-
|
98 |
-
def test(self):
|
99 |
-
"""Forward function used in test time.
|
100 |
-
|
101 |
-
This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop
|
102 |
-
It also calls <compute_visuals> to produce additional visualization results
|
103 |
-
"""
|
104 |
-
with torch.no_grad():
|
105 |
-
self.forward()
|
106 |
-
self.compute_visuals()
|
107 |
-
|
108 |
-
def compute_visuals(self):
|
109 |
-
"""Calculate additional output images for visdom and HTML visualization"""
|
110 |
-
pass
|
111 |
-
|
112 |
-
def get_image_paths(self):
|
113 |
-
""" Return image paths that are used to load current data"""
|
114 |
-
return self.image_paths
|
115 |
-
|
116 |
-
def update_learning_rate(self):
|
117 |
-
"""Update learning rates for all the networks; called at the end of every epoch"""
|
118 |
-
old_lr = self.optimizers[0].param_groups[0]['lr']
|
119 |
-
for scheduler in self.schedulers:
|
120 |
-
if self.opt.lr_policy == 'plateau':
|
121 |
-
scheduler.step(self.metric)
|
122 |
-
else:
|
123 |
-
scheduler.step()
|
124 |
-
|
125 |
-
lr = self.optimizers[0].param_groups[0]['lr']
|
126 |
-
print('learning rate %.7f -> %.7f' % (old_lr, lr))
|
127 |
-
|
128 |
-
def get_current_visuals(self):
|
129 |
-
"""Return visualization images. train.py will display these images with visdom, and save the images to a HTML"""
|
130 |
-
visual_ret = OrderedDict()
|
131 |
-
for name in self.visual_names:
|
132 |
-
if isinstance(name, str):
|
133 |
-
visual_ret[name] = getattr(self, name)
|
134 |
-
return visual_ret
|
135 |
-
|
136 |
-
def get_current_losses(self):
|
137 |
-
"""Return traning losses / errors. train.py will print out these errors on console, and save them to a file"""
|
138 |
-
errors_ret = OrderedDict()
|
139 |
-
for name in self.loss_names:
|
140 |
-
if isinstance(name, str):
|
141 |
-
errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float number
|
142 |
-
return errors_ret
|
143 |
-
|
144 |
-
def save_networks(self, epoch):
|
145 |
-
"""Save all the networks to the disk.
|
146 |
-
|
147 |
-
Parameters:
|
148 |
-
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
|
149 |
-
"""
|
150 |
-
for name in self.model_names:
|
151 |
-
if isinstance(name, str):
|
152 |
-
save_filename = '%s_net_%s.pth' % (epoch, name)
|
153 |
-
save_path = os.path.join(self.save_dir, save_filename)
|
154 |
-
net = getattr(self, 'net' + name)
|
155 |
-
|
156 |
-
if len(self.gpu_ids) > 0 and torch.cuda.is_available():
|
157 |
-
torch.save(net.module.cpu().state_dict(), save_path)
|
158 |
-
net.cuda(self.gpu_ids[0])
|
159 |
-
else:
|
160 |
-
torch.save(net.cpu().state_dict(), save_path)
|
161 |
-
|
162 |
-
def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):
|
163 |
-
"""Fix InstanceNorm checkpoints incompatibility (prior to 0.4)"""
|
164 |
-
key = keys[i]
|
165 |
-
if i + 1 == len(keys): # at the end, pointing to a parameter/buffer
|
166 |
-
if module.__class__.__name__.startswith('InstanceNorm') and \
|
167 |
-
(key == 'running_mean' or key == 'running_var'):
|
168 |
-
if getattr(module, key) is None:
|
169 |
-
state_dict.pop('.'.join(keys))
|
170 |
-
if module.__class__.__name__.startswith('InstanceNorm') and \
|
171 |
-
(key == 'num_batches_tracked'):
|
172 |
-
state_dict.pop('.'.join(keys))
|
173 |
-
else:
|
174 |
-
self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)
|
175 |
-
|
176 |
-
def load_networks(self, epoch):
|
177 |
-
"""Load all the networks from the disk.
|
178 |
-
|
179 |
-
Parameters:
|
180 |
-
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
|
181 |
-
"""
|
182 |
-
for name in self.model_names:
|
183 |
-
if isinstance(name, str):
|
184 |
-
load_filename = '%s_net_%s.pth' % (epoch, name)
|
185 |
-
load_path = os.path.join(self.save_dir, load_filename)
|
186 |
-
net = getattr(self, 'net' + name)
|
187 |
-
if isinstance(net, torch.nn.DataParallel):
|
188 |
-
net = net.module
|
189 |
-
print('loading the model from %s' % load_path)
|
190 |
-
# if you are using PyTorch newer than 0.4 (e.g., built from
|
191 |
-
# GitHub source), you can remove str() on self.device
|
192 |
-
state_dict = torch.load(load_path, map_location=str(self.device))
|
193 |
-
if hasattr(state_dict, '_metadata'):
|
194 |
-
del state_dict._metadata
|
195 |
-
|
196 |
-
# patch InstanceNorm checkpoints prior to 0.4
|
197 |
-
for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop
|
198 |
-
self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))
|
199 |
-
net.load_state_dict(state_dict)
|
200 |
-
|
201 |
-
def print_networks(self, verbose):
|
202 |
-
"""Print the total number of parameters in the network and (if verbose) network architecture
|
203 |
-
|
204 |
-
Parameters:
|
205 |
-
verbose (bool) -- if verbose: print the network architecture
|
206 |
-
"""
|
207 |
-
print('---------- Networks initialized -------------')
|
208 |
-
for name in self.model_names:
|
209 |
-
if isinstance(name, str):
|
210 |
-
net = getattr(self, 'net' + name)
|
211 |
-
num_params = 0
|
212 |
-
for param in net.parameters():
|
213 |
-
num_params += param.numel()
|
214 |
-
if verbose:
|
215 |
-
print(net)
|
216 |
-
print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))
|
217 |
-
print('-----------------------------------------------')
|
218 |
-
|
219 |
-
def set_requires_grad(self, nets, requires_grad=False):
|
220 |
-
"""Set requies_grad=Fasle for all the networks to avoid unnecessary computations
|
221 |
-
Parameters:
|
222 |
-
nets (network list) -- a list of networks
|
223 |
-
requires_grad (bool) -- whether the networks require gradients or not
|
224 |
-
"""
|
225 |
-
if not isinstance(nets, list):
|
226 |
-
nets = [nets]
|
227 |
-
for net in nets:
|
228 |
-
if net is not None:
|
229 |
-
for param in net.parameters():
|
230 |
-
param.requires_grad = requires_grad
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Andres99/Tune-A-Video-Training-UI/style.css
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
h1 {
|
2 |
-
text-align: center;
|
3 |
-
}
|
|
|
|
|
|
|
|
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/pix2pix_zero.md
DELETED
@@ -1,284 +0,0 @@
|
|
1 |
-
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
2 |
-
|
3 |
-
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
4 |
-
the License. You may obtain a copy of the License at
|
5 |
-
|
6 |
-
http://www.apache.org/licenses/LICENSE-2.0
|
7 |
-
|
8 |
-
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
9 |
-
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
10 |
-
specific language governing permissions and limitations under the License.
|
11 |
-
-->
|
12 |
-
|
13 |
-
# Pix2Pix Zero
|
14 |
-
|
15 |
-
[Zero-shot Image-to-Image Translation](https://huggingface.co/papers/2302.03027) is by Gaurav Parmar, Krishna Kumar Singh, Richard Zhang, Yijun Li, Jingwan Lu, and Jun-Yan Zhu.
|
16 |
-
|
17 |
-
The abstract from the paper is:
|
18 |
-
|
19 |
-
*Large-scale text-to-image generative models have shown their remarkable ability to synthesize diverse and high-quality images. However, it is still challenging to directly apply these models for editing real images for two reasons. First, it is hard for users to come up with a perfect text prompt that accurately describes every visual detail in the input image. Second, while existing models can introduce desirable changes in certain regions, they often dramatically alter the input content and introduce unexpected changes in unwanted regions. In this work, we propose pix2pix-zero, an image-to-image translation method that can preserve the content of the original image without manual prompting. We first automatically discover editing directions that reflect desired edits in the text embedding space. To preserve the general content structure after editing, we further propose cross-attention guidance, which aims to retain the cross-attention maps of the input image throughout the diffusion process. In addition, our method does not need additional training for these edits and can directly use the existing pre-trained text-to-image diffusion model. We conduct extensive experiments and show that our method outperforms existing and concurrent works for both real and synthetic image editing.*
|
20 |
-
|
21 |
-
You can find additional information about Pix2Pix Zero on the [project page](https://pix2pixzero.github.io/), [original codebase](https://github.com/pix2pixzero/pix2pix-zero), and try it out in a [demo](https://huggingface.co/spaces/pix2pix-zero-library/pix2pix-zero-demo).
|
22 |
-
|
23 |
-
## Tips
|
24 |
-
|
25 |
-
* The pipeline can be conditioned on real input images. Check out the code examples below to know more.
|
26 |
-
* The pipeline exposes two arguments namely `source_embeds` and `target_embeds`
|
27 |
-
that let you control the direction of the semantic edits in the final image to be generated. Let's say,
|
28 |
-
you wanted to translate from "cat" to "dog". In this case, the edit direction will be "cat -> dog". To reflect
|
29 |
-
this in the pipeline, you simply have to set the embeddings related to the phrases including "cat" to
|
30 |
-
`source_embeds` and "dog" to `target_embeds`. Refer to the code example below for more details.
|
31 |
-
* When you're using this pipeline from a prompt, specify the _source_ concept in the prompt. Taking
|
32 |
-
the above example, a valid input prompt would be: "a high resolution painting of a **cat** in the style of van gough".
|
33 |
-
* If you wanted to reverse the direction in the example above, i.e., "dog -> cat", then it's recommended to:
|
34 |
-
* Swap the `source_embeds` and `target_embeds`.
|
35 |
-
* Change the input prompt to include "dog".
|
36 |
-
* To learn more about how the source and target embeddings are generated, refer to the [original
|
37 |
-
paper](https://arxiv.org/abs/2302.03027). Below, we also provide some directions on how to generate the embeddings.
|
38 |
-
* Note that the quality of the outputs generated with this pipeline is dependent on how good the `source_embeds` and `target_embeds` are. Please, refer to [this discussion](#generating-source-and-target-embeddings) for some suggestions on the topic.
|
39 |
-
|
40 |
-
## Available Pipelines:
|
41 |
-
|
42 |
-
| Pipeline | Tasks | Demo
|
43 |
-
|---|---|:---:|
|
44 |
-
| [StableDiffusionPix2PixZeroPipeline](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py) | *Text-Based Image Editing* | [🤗 Space](https://huggingface.co/spaces/pix2pix-zero-library/pix2pix-zero-demo) |
|
45 |
-
|
46 |
-
<!-- TODO: add Colab -->
|
47 |
-
|
48 |
-
## Usage example
|
49 |
-
|
50 |
-
### Based on an image generated with the input prompt
|
51 |
-
|
52 |
-
```python
|
53 |
-
import requests
|
54 |
-
import torch
|
55 |
-
|
56 |
-
from diffusers import DDIMScheduler, StableDiffusionPix2PixZeroPipeline
|
57 |
-
|
58 |
-
|
59 |
-
def download(embedding_url, local_filepath):
|
60 |
-
r = requests.get(embedding_url)
|
61 |
-
with open(local_filepath, "wb") as f:
|
62 |
-
f.write(r.content)
|
63 |
-
|
64 |
-
|
65 |
-
model_ckpt = "CompVis/stable-diffusion-v1-4"
|
66 |
-
pipeline = StableDiffusionPix2PixZeroPipeline.from_pretrained(
|
67 |
-
model_ckpt, conditions_input_image=False, torch_dtype=torch.float16
|
68 |
-
)
|
69 |
-
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
|
70 |
-
pipeline.to("cuda")
|
71 |
-
|
72 |
-
prompt = "a high resolution painting of a cat in the style of van gogh"
|
73 |
-
src_embs_url = "https://github.com/pix2pixzero/pix2pix-zero/raw/main/assets/embeddings_sd_1.4/cat.pt"
|
74 |
-
target_embs_url = "https://github.com/pix2pixzero/pix2pix-zero/raw/main/assets/embeddings_sd_1.4/dog.pt"
|
75 |
-
|
76 |
-
for url in [src_embs_url, target_embs_url]:
|
77 |
-
download(url, url.split("/")[-1])
|
78 |
-
|
79 |
-
src_embeds = torch.load(src_embs_url.split("/")[-1])
|
80 |
-
target_embeds = torch.load(target_embs_url.split("/")[-1])
|
81 |
-
|
82 |
-
images = pipeline(
|
83 |
-
prompt,
|
84 |
-
source_embeds=src_embeds,
|
85 |
-
target_embeds=target_embeds,
|
86 |
-
num_inference_steps=50,
|
87 |
-
cross_attention_guidance_amount=0.15,
|
88 |
-
).images
|
89 |
-
images[0].save("edited_image_dog.png")
|
90 |
-
```
|
91 |
-
|
92 |
-
### Based on an input image
|
93 |
-
|
94 |
-
When the pipeline is conditioned on an input image, we first obtain an inverted
|
95 |
-
noise from it using a `DDIMInverseScheduler` with the help of a generated caption. Then
|
96 |
-
the inverted noise is used to start the generation process.
|
97 |
-
|
98 |
-
First, let's load our pipeline:
|
99 |
-
|
100 |
-
```py
|
101 |
-
import torch
|
102 |
-
from transformers import BlipForConditionalGeneration, BlipProcessor
|
103 |
-
from diffusers import DDIMScheduler, DDIMInverseScheduler, StableDiffusionPix2PixZeroPipeline
|
104 |
-
|
105 |
-
captioner_id = "Salesforce/blip-image-captioning-base"
|
106 |
-
processor = BlipProcessor.from_pretrained(captioner_id)
|
107 |
-
model = BlipForConditionalGeneration.from_pretrained(captioner_id, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
108 |
-
|
109 |
-
sd_model_ckpt = "CompVis/stable-diffusion-v1-4"
|
110 |
-
pipeline = StableDiffusionPix2PixZeroPipeline.from_pretrained(
|
111 |
-
sd_model_ckpt,
|
112 |
-
caption_generator=model,
|
113 |
-
caption_processor=processor,
|
114 |
-
torch_dtype=torch.float16,
|
115 |
-
safety_checker=None,
|
116 |
-
)
|
117 |
-
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
|
118 |
-
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
|
119 |
-
pipeline.enable_model_cpu_offload()
|
120 |
-
```
|
121 |
-
|
122 |
-
Then, we load an input image for conditioning and obtain a suitable caption for it:
|
123 |
-
|
124 |
-
```py
|
125 |
-
import requests
|
126 |
-
from PIL import Image
|
127 |
-
|
128 |
-
img_url = "https://github.com/pix2pixzero/pix2pix-zero/raw/main/assets/test_images/cats/cat_6.png"
|
129 |
-
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB").resize((512, 512))
|
130 |
-
caption = pipeline.generate_caption(raw_image)
|
131 |
-
```
|
132 |
-
|
133 |
-
Then we employ the generated caption and the input image to get the inverted noise:
|
134 |
-
|
135 |
-
```py
|
136 |
-
generator = torch.manual_seed(0)
|
137 |
-
inv_latents = pipeline.invert(caption, image=raw_image, generator=generator).latents
|
138 |
-
```
|
139 |
-
|
140 |
-
Now, generate the image with edit directions:
|
141 |
-
|
142 |
-
```py
|
143 |
-
# See the "Generating source and target embeddings" section below to
|
144 |
-
# automate the generation of these captions with a pre-trained model like Flan-T5 as explained below.
|
145 |
-
source_prompts = ["a cat sitting on the street", "a cat playing in the field", "a face of a cat"]
|
146 |
-
target_prompts = ["a dog sitting on the street", "a dog playing in the field", "a face of a dog"]
|
147 |
-
|
148 |
-
source_embeds = pipeline.get_embeds(source_prompts, batch_size=2)
|
149 |
-
target_embeds = pipeline.get_embeds(target_prompts, batch_size=2)
|
150 |
-
|
151 |
-
|
152 |
-
image = pipeline(
|
153 |
-
caption,
|
154 |
-
source_embeds=source_embeds,
|
155 |
-
target_embeds=target_embeds,
|
156 |
-
num_inference_steps=50,
|
157 |
-
cross_attention_guidance_amount=0.15,
|
158 |
-
generator=generator,
|
159 |
-
latents=inv_latents,
|
160 |
-
negative_prompt=caption,
|
161 |
-
).images[0]
|
162 |
-
image.save("edited_image.png")
|
163 |
-
```
|
164 |
-
|
165 |
-
## Generating source and target embeddings
|
166 |
-
|
167 |
-
The authors originally used the [GPT-3 API](https://openai.com/api/) to generate the source and target captions for discovering
|
168 |
-
edit directions. However, we can also leverage open source and public models for the same purpose.
|
169 |
-
Below, we provide an end-to-end example with the [Flan-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5) model
|
170 |
-
for generating captions and [CLIP](https://huggingface.co/docs/transformers/model_doc/clip) for
|
171 |
-
computing embeddings on the generated captions.
|
172 |
-
|
173 |
-
**1. Load the generation model**:
|
174 |
-
|
175 |
-
```py
|
176 |
-
import torch
|
177 |
-
from transformers import AutoTokenizer, T5ForConditionalGeneration
|
178 |
-
|
179 |
-
tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-xl")
|
180 |
-
model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-xl", device_map="auto", torch_dtype=torch.float16)
|
181 |
-
```
|
182 |
-
|
183 |
-
**2. Construct a starting prompt**:
|
184 |
-
|
185 |
-
```py
|
186 |
-
source_concept = "cat"
|
187 |
-
target_concept = "dog"
|
188 |
-
|
189 |
-
source_text = f"Provide a caption for images containing a {source_concept}. "
|
190 |
-
"The captions should be in English and should be no longer than 150 characters."
|
191 |
-
|
192 |
-
target_text = f"Provide a caption for images containing a {target_concept}. "
|
193 |
-
"The captions should be in English and should be no longer than 150 characters."
|
194 |
-
```
|
195 |
-
|
196 |
-
Here, we're interested in the "cat -> dog" direction.
|
197 |
-
|
198 |
-
**3. Generate captions**:
|
199 |
-
|
200 |
-
We can use a utility like so for this purpose.
|
201 |
-
|
202 |
-
```py
|
203 |
-
def generate_captions(input_prompt):
|
204 |
-
input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids.to("cuda")
|
205 |
-
|
206 |
-
outputs = model.generate(
|
207 |
-
input_ids, temperature=0.8, num_return_sequences=16, do_sample=True, max_new_tokens=128, top_k=10
|
208 |
-
)
|
209 |
-
return tokenizer.batch_decode(outputs, skip_special_tokens=True)
|
210 |
-
```
|
211 |
-
|
212 |
-
And then we just call it to generate our captions:
|
213 |
-
|
214 |
-
```py
|
215 |
-
source_captions = generate_captions(source_text)
|
216 |
-
target_captions = generate_captions(target_concept)
|
217 |
-
```
|
218 |
-
|
219 |
-
We encourage you to play around with the different parameters supported by the
|
220 |
-
`generate()` method ([documentation](https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.generation_tf_utils.TFGenerationMixin.generate)) for the generation quality you are looking for.
|
221 |
-
|
222 |
-
**4. Load the embedding model**:
|
223 |
-
|
224 |
-
Here, we need to use the same text encoder model used by the subsequent Stable Diffusion model.
|
225 |
-
|
226 |
-
```py
|
227 |
-
from diffusers import StableDiffusionPix2PixZeroPipeline
|
228 |
-
|
229 |
-
pipeline = StableDiffusionPix2PixZeroPipeline.from_pretrained(
|
230 |
-
"CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
|
231 |
-
)
|
232 |
-
pipeline = pipeline.to("cuda")
|
233 |
-
tokenizer = pipeline.tokenizer
|
234 |
-
text_encoder = pipeline.text_encoder
|
235 |
-
```
|
236 |
-
|
237 |
-
**5. Compute embeddings**:
|
238 |
-
|
239 |
-
```py
|
240 |
-
import torch
|
241 |
-
|
242 |
-
def embed_captions(sentences, tokenizer, text_encoder, device="cuda"):
|
243 |
-
with torch.no_grad():
|
244 |
-
embeddings = []
|
245 |
-
for sent in sentences:
|
246 |
-
text_inputs = tokenizer(
|
247 |
-
sent,
|
248 |
-
padding="max_length",
|
249 |
-
max_length=tokenizer.model_max_length,
|
250 |
-
truncation=True,
|
251 |
-
return_tensors="pt",
|
252 |
-
)
|
253 |
-
text_input_ids = text_inputs.input_ids
|
254 |
-
prompt_embeds = text_encoder(text_input_ids.to(device), attention_mask=None)[0]
|
255 |
-
embeddings.append(prompt_embeds)
|
256 |
-
return torch.concatenate(embeddings, dim=0).mean(dim=0).unsqueeze(0)
|
257 |
-
|
258 |
-
source_embeddings = embed_captions(source_captions, tokenizer, text_encoder)
|
259 |
-
target_embeddings = embed_captions(target_captions, tokenizer, text_encoder)
|
260 |
-
```
|
261 |
-
|
262 |
-
And you're done! [Here](https://colab.research.google.com/drive/1tz2C1EdfZYAPlzXXbTnf-5PRBiR8_R1F?usp=sharing) is a Colab Notebook that you can use to interact with the entire process.
|
263 |
-
|
264 |
-
Now, you can use these embeddings directly while calling the pipeline:
|
265 |
-
|
266 |
-
```py
|
267 |
-
from diffusers import DDIMScheduler
|
268 |
-
|
269 |
-
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
|
270 |
-
|
271 |
-
images = pipeline(
|
272 |
-
prompt,
|
273 |
-
source_embeds=source_embeddings,
|
274 |
-
target_embeds=target_embeddings,
|
275 |
-
num_inference_steps=50,
|
276 |
-
cross_attention_guidance_amount=0.15,
|
277 |
-
).images
|
278 |
-
images[0].save("edited_image_dog.png")
|
279 |
-
```
|
280 |
-
|
281 |
-
## StableDiffusionPix2PixZeroPipeline
|
282 |
-
[[autodoc]] StableDiffusionPix2PixZeroPipeline
|
283 |
-
- __call__
|
284 |
-
- all
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Andy1621/uniformer_image_segmentation/configs/apcnet/apcnet_r50-d8_512x512_80k_ade20k.py
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
_base_ = [
|
2 |
-
'../_base_/models/apcnet_r50-d8.py', '../_base_/datasets/ade20k.py',
|
3 |
-
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
|
4 |
-
]
|
5 |
-
model = dict(
|
6 |
-
decode_head=dict(num_classes=150), auxiliary_head=dict(num_classes=150))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/GPTQ_loader.py
DELETED
@@ -1,168 +0,0 @@
|
|
1 |
-
import inspect
|
2 |
-
import re
|
3 |
-
from pathlib import Path
|
4 |
-
|
5 |
-
import accelerate
|
6 |
-
import torch
|
7 |
-
import transformers
|
8 |
-
from transformers import AutoConfig, AutoModelForCausalLM
|
9 |
-
|
10 |
-
import modules.shared as shared
|
11 |
-
from modules.logging_colors import logger
|
12 |
-
|
13 |
-
from gptq_for_llama import llama_inference_offload
|
14 |
-
from gptq_for_llama.modelutils import find_layers
|
15 |
-
from gptq_for_llama.quant import make_quant
|
16 |
-
|
17 |
-
|
18 |
-
# This function is a replacement for the load_quant function in the
|
19 |
-
# GPTQ-for_LLaMa repository. It supports more models and branches.
|
20 |
-
def _load_quant(model, checkpoint, wbits, groupsize=-1, faster_kernel=False, exclude_layers=None, kernel_switch_threshold=128, eval=True):
|
21 |
-
exclude_layers = exclude_layers or ['lm_head']
|
22 |
-
|
23 |
-
def noop(*args, **kwargs):
|
24 |
-
pass
|
25 |
-
|
26 |
-
config = AutoConfig.from_pretrained(model, trust_remote_code=shared.args.trust_remote_code)
|
27 |
-
torch.nn.init.kaiming_uniform_ = noop
|
28 |
-
torch.nn.init.uniform_ = noop
|
29 |
-
torch.nn.init.normal_ = noop
|
30 |
-
|
31 |
-
torch.set_default_dtype(torch.half)
|
32 |
-
transformers.modeling_utils._init_weights = False
|
33 |
-
torch.set_default_dtype(torch.half)
|
34 |
-
model = AutoModelForCausalLM.from_config(config, trust_remote_code=shared.args.trust_remote_code)
|
35 |
-
torch.set_default_dtype(torch.float)
|
36 |
-
if eval:
|
37 |
-
model = model.eval()
|
38 |
-
|
39 |
-
layers = find_layers(model)
|
40 |
-
for name in exclude_layers:
|
41 |
-
if name in layers:
|
42 |
-
del layers[name]
|
43 |
-
|
44 |
-
gptq_args = inspect.getfullargspec(make_quant).args
|
45 |
-
|
46 |
-
make_quant_kwargs = {
|
47 |
-
'module': model,
|
48 |
-
'names': layers,
|
49 |
-
'bits': wbits,
|
50 |
-
}
|
51 |
-
if 'groupsize' in gptq_args:
|
52 |
-
make_quant_kwargs['groupsize'] = groupsize
|
53 |
-
if 'faster' in gptq_args:
|
54 |
-
make_quant_kwargs['faster'] = faster_kernel
|
55 |
-
if 'kernel_switch_threshold' in gptq_args:
|
56 |
-
make_quant_kwargs['kernel_switch_threshold'] = kernel_switch_threshold
|
57 |
-
|
58 |
-
make_quant(**make_quant_kwargs)
|
59 |
-
|
60 |
-
del layers
|
61 |
-
if checkpoint.endswith('.safetensors'):
|
62 |
-
from safetensors.torch import load_file as safe_load
|
63 |
-
model.load_state_dict(safe_load(checkpoint), strict=False)
|
64 |
-
else:
|
65 |
-
model.load_state_dict(torch.load(checkpoint), strict=False)
|
66 |
-
|
67 |
-
model.seqlen = 2048
|
68 |
-
return model
|
69 |
-
|
70 |
-
|
71 |
-
# Used to locate the .pt/.safetensors quantized file
|
72 |
-
def find_quantized_model_file(model_name):
|
73 |
-
if shared.args.checkpoint:
|
74 |
-
return Path(shared.args.checkpoint)
|
75 |
-
|
76 |
-
path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
|
77 |
-
pt_path = None
|
78 |
-
priority_name_list = [
|
79 |
-
Path(f'{shared.args.model_dir}/{model_name}{hyphen}{shared.args.wbits}bit{group}{ext}')
|
80 |
-
for group in ([f'-{shared.args.groupsize}g', ''] if shared.args.groupsize > 0 else [''])
|
81 |
-
for ext in ['.safetensors', '.pt']
|
82 |
-
for hyphen in ['-', f'/{model_name}-', '/']
|
83 |
-
]
|
84 |
-
|
85 |
-
for path in priority_name_list:
|
86 |
-
if path.exists():
|
87 |
-
pt_path = path
|
88 |
-
break
|
89 |
-
|
90 |
-
# If the model hasn't been found with a well-behaved name, pick the last .pt
|
91 |
-
# or the last .safetensors found in its folder as a last resort
|
92 |
-
if not pt_path:
|
93 |
-
for ext in ['.pt', '.safetensors']:
|
94 |
-
found = list(path_to_model.glob(f"*{ext}"))
|
95 |
-
if len(found) > 0:
|
96 |
-
if len(found) > 1:
|
97 |
-
logger.warning(f'More than one {ext} model has been found. The last one will be selected. It could be wrong.')
|
98 |
-
|
99 |
-
pt_path = found[-1]
|
100 |
-
break
|
101 |
-
|
102 |
-
return pt_path
|
103 |
-
|
104 |
-
|
105 |
-
# The function that loads the model in modules/models.py
|
106 |
-
def load_quantized(model_name):
|
107 |
-
if shared.args.model_type is None:
|
108 |
-
logger.error("The model could not be loaded because its type could not be inferred from its name.")
|
109 |
-
logger.error("Please specify the type manually using the --model_type argument.")
|
110 |
-
return None
|
111 |
-
|
112 |
-
# Select the appropriate load_quant function
|
113 |
-
model_type = shared.args.model_type.lower()
|
114 |
-
if shared.args.pre_layer and model_type == 'llama':
|
115 |
-
load_quant = llama_inference_offload.load_quant
|
116 |
-
elif model_type in ('llama', 'opt', 'gptj'):
|
117 |
-
if shared.args.pre_layer:
|
118 |
-
logger.warning("Ignoring --pre_layer because it only works for llama model type.")
|
119 |
-
|
120 |
-
load_quant = _load_quant
|
121 |
-
else:
|
122 |
-
logger.error("Unknown pre-quantized model type specified. Only 'llama', 'opt' and 'gptj' are supported")
|
123 |
-
exit()
|
124 |
-
|
125 |
-
# Find the quantized model weights file (.pt/.safetensors)
|
126 |
-
path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
|
127 |
-
pt_path = find_quantized_model_file(model_name)
|
128 |
-
if not pt_path:
|
129 |
-
logger.error("Could not find the quantized model in .pt or .safetensors format, exiting...")
|
130 |
-
exit()
|
131 |
-
else:
|
132 |
-
logger.info(f"Found the following quantized model: {pt_path}")
|
133 |
-
|
134 |
-
# qwopqwop200's offload
|
135 |
-
if model_type == 'llama' and shared.args.pre_layer:
|
136 |
-
if len(shared.args.pre_layer) == 1:
|
137 |
-
pre_layer = shared.args.pre_layer[0]
|
138 |
-
else:
|
139 |
-
pre_layer = shared.args.pre_layer
|
140 |
-
|
141 |
-
model = load_quant(str(path_to_model), str(pt_path), shared.args.wbits, shared.args.groupsize, pre_layer)
|
142 |
-
else:
|
143 |
-
threshold = False if model_type == 'gptj' else 128
|
144 |
-
model = load_quant(str(path_to_model), str(pt_path), shared.args.wbits, shared.args.groupsize, kernel_switch_threshold=threshold)
|
145 |
-
|
146 |
-
# accelerate offload (doesn't work properly)
|
147 |
-
if shared.args.gpu_memory or torch.cuda.device_count() > 1:
|
148 |
-
if shared.args.gpu_memory:
|
149 |
-
memory_map = list(map(lambda x: x.strip(), shared.args.gpu_memory))
|
150 |
-
max_cpu_memory = shared.args.cpu_memory.strip() if shared.args.cpu_memory is not None else '99GiB'
|
151 |
-
max_memory = {}
|
152 |
-
for i in range(len(memory_map)):
|
153 |
-
max_memory[i] = f'{memory_map[i]}GiB' if not re.match('.*ib$', memory_map[i].lower()) else memory_map[i]
|
154 |
-
|
155 |
-
max_memory['cpu'] = f'{max_cpu_memory}GiB' if not re.match('.*ib$', max_cpu_memory.lower()) else max_cpu_memory
|
156 |
-
else:
|
157 |
-
max_memory = accelerate.utils.get_balanced_memory(model)
|
158 |
-
|
159 |
-
device_map = accelerate.infer_auto_device_map(model, max_memory=max_memory, no_split_module_classes=["LlamaDecoderLayer"])
|
160 |
-
logger.info("Using the following device map for the quantized model:", device_map)
|
161 |
-
# https://huggingface.co/docs/accelerate/package_reference/big_modeling#accelerate.dispatch_model
|
162 |
-
model = accelerate.dispatch_model(model, device_map=device_map, offload_buffers=True)
|
163 |
-
|
164 |
-
# No offload
|
165 |
-
elif not shared.args.cpu:
|
166 |
-
model = model.to(torch.device('cuda:0'))
|
167 |
-
|
168 |
-
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Ariharasudhan/YoloV5/utils/loggers/comet/README.md
DELETED
@@ -1,256 +0,0 @@
|
|
1 |
-
<img src="https://cdn.comet.ml/img/notebook_logo.png">
|
2 |
-
|
3 |
-
# YOLOv5 with Comet
|
4 |
-
|
5 |
-
This guide will cover how to use YOLOv5 with [Comet](https://bit.ly/yolov5-readme-comet)
|
6 |
-
|
7 |
-
# About Comet
|
8 |
-
|
9 |
-
Comet builds tools that help data scientists, engineers, and team leaders accelerate and optimize machine learning and deep learning models.
|
10 |
-
|
11 |
-
Track and visualize model metrics in real time, save your hyperparameters, datasets, and model checkpoints, and visualize your model predictions with [Comet Custom Panels](https://bit.ly/yolov5-colab-comet-panels)!
|
12 |
-
Comet makes sure you never lose track of your work and makes it easy to share results and collaborate across teams of all sizes!
|
13 |
-
|
14 |
-
# Getting Started
|
15 |
-
|
16 |
-
## Install Comet
|
17 |
-
|
18 |
-
```shell
|
19 |
-
pip install comet_ml
|
20 |
-
```
|
21 |
-
|
22 |
-
## Configure Comet Credentials
|
23 |
-
|
24 |
-
There are two ways to configure Comet with YOLOv5.
|
25 |
-
|
26 |
-
You can either set your credentials through enviroment variables
|
27 |
-
|
28 |
-
**Environment Variables**
|
29 |
-
|
30 |
-
```shell
|
31 |
-
export COMET_API_KEY=<Your Comet API Key>
|
32 |
-
export COMET_PROJECT_NAME=<Your Comet Project Name> # This will default to 'yolov5'
|
33 |
-
```
|
34 |
-
|
35 |
-
Or create a `.comet.config` file in your working directory and set your credentials there.
|
36 |
-
|
37 |
-
**Comet Configuration File**
|
38 |
-
|
39 |
-
```
|
40 |
-
[comet]
|
41 |
-
api_key=<Your Comet API Key>
|
42 |
-
project_name=<Your Comet Project Name> # This will default to 'yolov5'
|
43 |
-
```
|
44 |
-
|
45 |
-
## Run the Training Script
|
46 |
-
|
47 |
-
```shell
|
48 |
-
# Train YOLOv5s on COCO128 for 5 epochs
|
49 |
-
python train.py --img 640 --batch 16 --epochs 5 --data coco128.yaml --weights yolov5s.pt
|
50 |
-
```
|
51 |
-
|
52 |
-
That's it! Comet will automatically log your hyperparameters, command line arguments, training and valiation metrics. You can visualize and analyze your runs in the Comet UI
|
53 |
-
|
54 |
-
<img width="1920" alt="yolo-ui" src="https://user-images.githubusercontent.com/7529846/187608607-ff89c3d5-1b8b-4743-a974-9275301b0524.png">
|
55 |
-
|
56 |
-
# Try out an Example!
|
57 |
-
Check out an example of a [completed run here](https://www.comet.com/examples/comet-example-yolov5/a0e29e0e9b984e4a822db2a62d0cb357?experiment-tab=chart&showOutliers=true&smoothing=0&transformY=smoothing&xAxis=step&ref=yolov5&utm_source=yolov5&utm_medium=affilliate&utm_campaign=yolov5_comet_integration)
|
58 |
-
|
59 |
-
Or better yet, try it out yourself in this Colab Notebook
|
60 |
-
|
61 |
-
[](https://colab.research.google.com/drive/1RG0WOQyxlDlo5Km8GogJpIEJlg_5lyYO?usp=sharing)
|
62 |
-
|
63 |
-
# Log automatically
|
64 |
-
|
65 |
-
By default, Comet will log the following items
|
66 |
-
|
67 |
-
## Metrics
|
68 |
-
- Box Loss, Object Loss, Classification Loss for the training and validation data
|
69 |
-
- mAP_0.5, mAP_0.5:0.95 metrics for the validation data.
|
70 |
-
- Precision and Recall for the validation data
|
71 |
-
|
72 |
-
## Parameters
|
73 |
-
|
74 |
-
- Model Hyperparameters
|
75 |
-
- All parameters passed through the command line options
|
76 |
-
|
77 |
-
## Visualizations
|
78 |
-
|
79 |
-
- Confusion Matrix of the model predictions on the validation data
|
80 |
-
- Plots for the PR and F1 curves across all classes
|
81 |
-
- Correlogram of the Class Labels
|
82 |
-
|
83 |
-
# Configure Comet Logging
|
84 |
-
|
85 |
-
Comet can be configured to log additional data either through command line flags passed to the training script
|
86 |
-
or through environment variables.
|
87 |
-
|
88 |
-
```shell
|
89 |
-
export COMET_MODE=online # Set whether to run Comet in 'online' or 'offline' mode. Defaults to online
|
90 |
-
export COMET_MODEL_NAME=<your model name> #Set the name for the saved model. Defaults to yolov5
|
91 |
-
export COMET_LOG_CONFUSION_MATRIX=false # Set to disable logging a Comet Confusion Matrix. Defaults to true
|
92 |
-
export COMET_MAX_IMAGE_UPLOADS=<number of allowed images to upload to Comet> # Controls how many total image predictions to log to Comet. Defaults to 100.
|
93 |
-
export COMET_LOG_PER_CLASS_METRICS=true # Set to log evaluation metrics for each detected class at the end of training. Defaults to false
|
94 |
-
export COMET_DEFAULT_CHECKPOINT_FILENAME=<your checkpoint filename> # Set this if you would like to resume training from a different checkpoint. Defaults to 'last.pt'
|
95 |
-
export COMET_LOG_BATCH_LEVEL_METRICS=true # Set this if you would like to log training metrics at the batch level. Defaults to false.
|
96 |
-
export COMET_LOG_PREDICTIONS=true # Set this to false to disable logging model predictions
|
97 |
-
```
|
98 |
-
|
99 |
-
## Logging Checkpoints with Comet
|
100 |
-
|
101 |
-
Logging Models to Comet is disabled by default. To enable it, pass the `save-period` argument to the training script. This will save the
|
102 |
-
logged checkpoints to Comet based on the interval value provided by `save-period`
|
103 |
-
|
104 |
-
```shell
|
105 |
-
python train.py \
|
106 |
-
--img 640 \
|
107 |
-
--batch 16 \
|
108 |
-
--epochs 5 \
|
109 |
-
--data coco128.yaml \
|
110 |
-
--weights yolov5s.pt \
|
111 |
-
--save-period 1
|
112 |
-
```
|
113 |
-
|
114 |
-
## Logging Model Predictions
|
115 |
-
|
116 |
-
By default, model predictions (images, ground truth labels and bounding boxes) will be logged to Comet.
|
117 |
-
|
118 |
-
You can control the frequency of logged predictions and the associated images by passing the `bbox_interval` command line argument. Predictions can be visualized using Comet's Object Detection Custom Panel. This frequency corresponds to every Nth batch of data per epoch. In the example below, we are logging every 2nd batch of data for each epoch.
|
119 |
-
|
120 |
-
**Note:** The YOLOv5 validation dataloader will default to a batch size of 32, so you will have to set the logging frequency accordingly.
|
121 |
-
|
122 |
-
Here is an [example project using the Panel](https://www.comet.com/examples/comet-example-yolov5?shareable=YcwMiJaZSXfcEXpGOHDD12vA1&ref=yolov5&utm_source=yolov5&utm_medium=affilliate&utm_campaign=yolov5_comet_integration)
|
123 |
-
|
124 |
-
|
125 |
-
```shell
|
126 |
-
python train.py \
|
127 |
-
--img 640 \
|
128 |
-
--batch 16 \
|
129 |
-
--epochs 5 \
|
130 |
-
--data coco128.yaml \
|
131 |
-
--weights yolov5s.pt \
|
132 |
-
--bbox_interval 2
|
133 |
-
```
|
134 |
-
|
135 |
-
### Controlling the number of Prediction Images logged to Comet
|
136 |
-
|
137 |
-
When logging predictions from YOLOv5, Comet will log the images associated with each set of predictions. By default a maximum of 100 validation images are logged. You can increase or decrease this number using the `COMET_MAX_IMAGE_UPLOADS` environment variable.
|
138 |
-
|
139 |
-
```shell
|
140 |
-
env COMET_MAX_IMAGE_UPLOADS=200 python train.py \
|
141 |
-
--img 640 \
|
142 |
-
--batch 16 \
|
143 |
-
--epochs 5 \
|
144 |
-
--data coco128.yaml \
|
145 |
-
--weights yolov5s.pt \
|
146 |
-
--bbox_interval 1
|
147 |
-
```
|
148 |
-
|
149 |
-
### Logging Class Level Metrics
|
150 |
-
|
151 |
-
Use the `COMET_LOG_PER_CLASS_METRICS` environment variable to log mAP, precision, recall, f1 for each class.
|
152 |
-
|
153 |
-
```shell
|
154 |
-
env COMET_LOG_PER_CLASS_METRICS=true python train.py \
|
155 |
-
--img 640 \
|
156 |
-
--batch 16 \
|
157 |
-
--epochs 5 \
|
158 |
-
--data coco128.yaml \
|
159 |
-
--weights yolov5s.pt
|
160 |
-
```
|
161 |
-
|
162 |
-
## Uploading a Dataset to Comet Artifacts
|
163 |
-
|
164 |
-
If you would like to store your data using [Comet Artifacts](https://www.comet.com/docs/v2/guides/data-management/using-artifacts/#learn-more?ref=yolov5&utm_source=yolov5&utm_medium=affilliate&utm_campaign=yolov5_comet_integration), you can do so using the `upload_dataset` flag.
|
165 |
-
|
166 |
-
The dataset be organized in the way described in the [YOLOv5 documentation](https://docs.ultralytics.com/tutorials/train-custom-datasets/#3-organize-directories). The dataset config `yaml` file must follow the same format as that of the `coco128.yaml` file.
|
167 |
-
|
168 |
-
```shell
|
169 |
-
python train.py \
|
170 |
-
--img 640 \
|
171 |
-
--batch 16 \
|
172 |
-
--epochs 5 \
|
173 |
-
--data coco128.yaml \
|
174 |
-
--weights yolov5s.pt \
|
175 |
-
--upload_dataset
|
176 |
-
```
|
177 |
-
|
178 |
-
You can find the uploaded dataset in the Artifacts tab in your Comet Workspace
|
179 |
-
<img width="1073" alt="artifact-1" src="https://user-images.githubusercontent.com/7529846/186929193-162718bf-ec7b-4eb9-8c3b-86b3763ef8ea.png">
|
180 |
-
|
181 |
-
You can preview the data directly in the Comet UI.
|
182 |
-
<img width="1082" alt="artifact-2" src="https://user-images.githubusercontent.com/7529846/186929215-432c36a9-c109-4eb0-944b-84c2786590d6.png">
|
183 |
-
|
184 |
-
Artifacts are versioned and also support adding metadata about the dataset. Comet will automatically log the metadata from your dataset `yaml` file
|
185 |
-
<img width="963" alt="artifact-3" src="https://user-images.githubusercontent.com/7529846/186929256-9d44d6eb-1a19-42de-889a-bcbca3018f2e.png">
|
186 |
-
|
187 |
-
### Using a saved Artifact
|
188 |
-
|
189 |
-
If you would like to use a dataset from Comet Artifacts, set the `path` variable in your dataset `yaml` file to point to the following Artifact resource URL.
|
190 |
-
|
191 |
-
```
|
192 |
-
# contents of artifact.yaml file
|
193 |
-
path: "comet://<workspace name>/<artifact name>:<artifact version or alias>"
|
194 |
-
```
|
195 |
-
Then pass this file to your training script in the following way
|
196 |
-
|
197 |
-
```shell
|
198 |
-
python train.py \
|
199 |
-
--img 640 \
|
200 |
-
--batch 16 \
|
201 |
-
--epochs 5 \
|
202 |
-
--data artifact.yaml \
|
203 |
-
--weights yolov5s.pt
|
204 |
-
```
|
205 |
-
|
206 |
-
Artifacts also allow you to track the lineage of data as it flows through your Experimentation workflow. Here you can see a graph that shows you all the experiments that have used your uploaded dataset.
|
207 |
-
<img width="1391" alt="artifact-4" src="https://user-images.githubusercontent.com/7529846/186929264-4c4014fa-fe51-4f3c-a5c5-f6d24649b1b4.png">
|
208 |
-
|
209 |
-
## Resuming a Training Run
|
210 |
-
|
211 |
-
If your training run is interrupted for any reason, e.g. disrupted internet connection, you can resume the run using the `resume` flag and the Comet Run Path.
|
212 |
-
|
213 |
-
The Run Path has the following format `comet://<your workspace name>/<your project name>/<experiment id>`.
|
214 |
-
|
215 |
-
This will restore the run to its state before the interruption, which includes restoring the model from a checkpoint, restoring all hyperparameters and training arguments and downloading Comet dataset Artifacts if they were used in the original run. The resumed run will continue logging to the existing Experiment in the Comet UI
|
216 |
-
|
217 |
-
```shell
|
218 |
-
python train.py \
|
219 |
-
--resume "comet://<your run path>"
|
220 |
-
```
|
221 |
-
|
222 |
-
## Hyperparameter Search with the Comet Optimizer
|
223 |
-
|
224 |
-
YOLOv5 is also integrated with Comet's Optimizer, making is simple to visualie hyperparameter sweeps in the Comet UI.
|
225 |
-
|
226 |
-
### Configuring an Optimizer Sweep
|
227 |
-
|
228 |
-
To configure the Comet Optimizer, you will have to create a JSON file with the information about the sweep. An example file has been provided in `utils/loggers/comet/optimizer_config.json`
|
229 |
-
|
230 |
-
```shell
|
231 |
-
python utils/loggers/comet/hpo.py \
|
232 |
-
--comet_optimizer_config "utils/loggers/comet/optimizer_config.json"
|
233 |
-
```
|
234 |
-
|
235 |
-
The `hpo.py` script accepts the same arguments as `train.py`. If you wish to pass additional arguments to your sweep simply add them after
|
236 |
-
the script.
|
237 |
-
|
238 |
-
```shell
|
239 |
-
python utils/loggers/comet/hpo.py \
|
240 |
-
--comet_optimizer_config "utils/loggers/comet/optimizer_config.json" \
|
241 |
-
--save-period 1 \
|
242 |
-
--bbox_interval 1
|
243 |
-
```
|
244 |
-
|
245 |
-
### Running a Sweep in Parallel
|
246 |
-
|
247 |
-
```shell
|
248 |
-
comet optimizer -j <set number of workers> utils/loggers/comet/hpo.py \
|
249 |
-
utils/loggers/comet/optimizer_config.json"
|
250 |
-
```
|
251 |
-
|
252 |
-
### Visualizing Results
|
253 |
-
|
254 |
-
Comet provides a number of ways to visualize the results of your sweep. Take a look at a [project with a completed sweep here](https://www.comet.com/examples/comet-example-yolov5/view/PrlArHGuuhDTKC1UuBmTtOSXD/panels?ref=yolov5&utm_source=yolov5&utm_medium=affilliate&utm_campaign=yolov5_comet_integration)
|
255 |
-
|
256 |
-
<img width="1626" alt="hyperparameter-yolo" src="https://user-images.githubusercontent.com/7529846/186914869-7dc1de14-583f-4323-967b-c9a66a29e495.png">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Atualli/yoloxTeste/app.py
DELETED
@@ -1,76 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import os
|
3 |
-
import torch
|
4 |
-
import json
|
5 |
-
import yoloxdetect2.helpers as yoloxdetect
|
6 |
-
|
7 |
-
#model = yoloxdetect.YoloxDetector2('./dataset/yolox_s.pth', 'configs.yolox_s', device="cpu", hf_model=True)
|
8 |
-
model = yoloxdetect.YoloxDetector2('kadirnar/yolox_s-v0.1.1', 'configs.yolox_s', device="cpu", hf_model=True)
|
9 |
-
|
10 |
-
image_size = 640
|
11 |
-
|
12 |
-
def yolox_inference(
|
13 |
-
image_path: gr.inputs.Image = None,
|
14 |
-
):
|
15 |
-
"""
|
16 |
-
YOLOX inference function
|
17 |
-
Args:
|
18 |
-
image: Input image
|
19 |
-
Returns:
|
20 |
-
Rendered image
|
21 |
-
"""
|
22 |
-
|
23 |
-
pred2 = []
|
24 |
-
if image_path is not None :
|
25 |
-
print(image_path)
|
26 |
-
model.torchyolo = True
|
27 |
-
pred2 = model.predict(image_path=image_path, image_size=image_size)
|
28 |
-
|
29 |
-
|
30 |
-
tensor = {
|
31 |
-
"tensorflow": [
|
32 |
-
]
|
33 |
-
}
|
34 |
-
|
35 |
-
if pred2 is not None:
|
36 |
-
for i, element in enumerate(pred2[0]):
|
37 |
-
object = {}
|
38 |
-
itemclass = round(pred2[2][i].item())
|
39 |
-
object["classe"] = itemclass
|
40 |
-
object["nome"] = pred2[3][itemclass]
|
41 |
-
object["score"] = pred2[1][i].item()
|
42 |
-
object["x"] = element[0].item()
|
43 |
-
object["y"] = element[1].item()
|
44 |
-
object["w"] = element[2].item()
|
45 |
-
object["h"] = element[3].item()
|
46 |
-
tensor["tensorflow"].append(object)
|
47 |
-
|
48 |
-
|
49 |
-
text = json.dumps(tensor)
|
50 |
-
return text
|
51 |
-
|
52 |
-
|
53 |
-
inputs = [
|
54 |
-
gr.inputs.Image(type="pil", label="Input Image"),
|
55 |
-
]
|
56 |
-
|
57 |
-
outputs = gr.outputs.Image(type="filepath", label="Output Image")
|
58 |
-
title = "SIMULADOR PARA RECONHECIMENTO DE IMAGEM"
|
59 |
-
|
60 |
-
examples = [
|
61 |
-
["small-vehicles1.jpeg"],
|
62 |
-
["zidane.jpg"],
|
63 |
-
["dog.jpg"],
|
64 |
-
]
|
65 |
-
|
66 |
-
demo_app = gr.Interface(
|
67 |
-
fn=yolox_inference,
|
68 |
-
inputs=inputs,
|
69 |
-
outputs=["text"],
|
70 |
-
title=title,
|
71 |
-
examples=examples,
|
72 |
-
cache_examples=True,
|
73 |
-
live=True,
|
74 |
-
)
|
75 |
-
demo_app.launch(debug=True, server_name="192.168.0.153", server_port=8080, enable_queue=True)
|
76 |
-
#demo_app.launch(debug=True, server_port=8083, enable_queue=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/Misc/torchvision_imagenet_R_50.py
DELETED
@@ -1,150 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
An example config file to train a ImageNet classifier with detectron2.
|
3 |
-
Model and dataloader both come from torchvision.
|
4 |
-
This shows how to use detectron2 as a general engine for any new models and tasks.
|
5 |
-
|
6 |
-
To run, use the following command:
|
7 |
-
|
8 |
-
python tools/lazyconfig_train_net.py --config-file configs/Misc/torchvision_imagenet_R_50.py \
|
9 |
-
--num-gpus 8 dataloader.train.dataset.root=/path/to/imagenet/
|
10 |
-
|
11 |
-
"""
|
12 |
-
|
13 |
-
|
14 |
-
import torch
|
15 |
-
from torch import nn
|
16 |
-
from torch.nn import functional as F
|
17 |
-
from omegaconf import OmegaConf
|
18 |
-
import torchvision
|
19 |
-
from torchvision.transforms import transforms as T
|
20 |
-
from torchvision.models.resnet import ResNet, Bottleneck
|
21 |
-
from fvcore.common.param_scheduler import MultiStepParamScheduler
|
22 |
-
|
23 |
-
from detectron2.solver import WarmupParamScheduler
|
24 |
-
from detectron2.solver.build import get_default_optimizer_params
|
25 |
-
from detectron2.config import LazyCall as L
|
26 |
-
from detectron2.model_zoo import get_config
|
27 |
-
from detectron2.data.samplers import TrainingSampler, InferenceSampler
|
28 |
-
from detectron2.evaluation import DatasetEvaluator
|
29 |
-
from detectron2.utils import comm
|
30 |
-
|
31 |
-
|
32 |
-
"""
|
33 |
-
Note: Here we put reusable code (models, evaluation, data) together with configs just as a
|
34 |
-
proof-of-concept, to easily demonstrate what's needed to train a ImageNet classifier in detectron2.
|
35 |
-
Writing code in configs offers extreme flexibility but is often not a good engineering practice.
|
36 |
-
In practice, you might want to put code in your project and import them instead.
|
37 |
-
"""
|
38 |
-
|
39 |
-
|
40 |
-
def build_data_loader(dataset, batch_size, num_workers, training=True):
|
41 |
-
return torch.utils.data.DataLoader(
|
42 |
-
dataset,
|
43 |
-
sampler=(TrainingSampler if training else InferenceSampler)(len(dataset)),
|
44 |
-
batch_size=batch_size,
|
45 |
-
num_workers=num_workers,
|
46 |
-
pin_memory=True,
|
47 |
-
)
|
48 |
-
|
49 |
-
|
50 |
-
class ClassificationNet(nn.Module):
|
51 |
-
def __init__(self, model: nn.Module):
|
52 |
-
super().__init__()
|
53 |
-
self.model = model
|
54 |
-
|
55 |
-
@property
|
56 |
-
def device(self):
|
57 |
-
return list(self.model.parameters())[0].device
|
58 |
-
|
59 |
-
def forward(self, inputs):
|
60 |
-
image, label = inputs
|
61 |
-
pred = self.model(image.to(self.device))
|
62 |
-
if self.training:
|
63 |
-
label = label.to(self.device)
|
64 |
-
return F.cross_entropy(pred, label)
|
65 |
-
else:
|
66 |
-
return pred
|
67 |
-
|
68 |
-
|
69 |
-
class ClassificationAcc(DatasetEvaluator):
|
70 |
-
def reset(self):
|
71 |
-
self.corr = self.total = 0
|
72 |
-
|
73 |
-
def process(self, inputs, outputs):
|
74 |
-
image, label = inputs
|
75 |
-
self.corr += (outputs.argmax(dim=1).cpu() == label.cpu()).sum().item()
|
76 |
-
self.total += len(label)
|
77 |
-
|
78 |
-
def evaluate(self):
|
79 |
-
all_corr_total = comm.all_gather([self.corr, self.total])
|
80 |
-
corr = sum(x[0] for x in all_corr_total)
|
81 |
-
total = sum(x[1] for x in all_corr_total)
|
82 |
-
return {"accuracy": corr / total}
|
83 |
-
|
84 |
-
|
85 |
-
# --- End of code that could be in a project and be imported
|
86 |
-
|
87 |
-
|
88 |
-
dataloader = OmegaConf.create()
|
89 |
-
dataloader.train = L(build_data_loader)(
|
90 |
-
dataset=L(torchvision.datasets.ImageNet)(
|
91 |
-
root="/path/to/imagenet",
|
92 |
-
split="train",
|
93 |
-
transform=L(T.Compose)(
|
94 |
-
transforms=[
|
95 |
-
L(T.RandomResizedCrop)(size=224),
|
96 |
-
L(T.RandomHorizontalFlip)(),
|
97 |
-
T.ToTensor(),
|
98 |
-
L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
|
99 |
-
]
|
100 |
-
),
|
101 |
-
),
|
102 |
-
batch_size=256 // 8,
|
103 |
-
num_workers=4,
|
104 |
-
training=True,
|
105 |
-
)
|
106 |
-
|
107 |
-
dataloader.test = L(build_data_loader)(
|
108 |
-
dataset=L(torchvision.datasets.ImageNet)(
|
109 |
-
root="${...train.dataset.root}",
|
110 |
-
split="val",
|
111 |
-
transform=L(T.Compose)(
|
112 |
-
transforms=[
|
113 |
-
L(T.Resize)(size=256),
|
114 |
-
L(T.CenterCrop)(size=224),
|
115 |
-
T.ToTensor(),
|
116 |
-
L(T.Normalize)(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
|
117 |
-
]
|
118 |
-
),
|
119 |
-
),
|
120 |
-
batch_size=256 // 8,
|
121 |
-
num_workers=4,
|
122 |
-
training=False,
|
123 |
-
)
|
124 |
-
|
125 |
-
dataloader.evaluator = L(ClassificationAcc)()
|
126 |
-
|
127 |
-
model = L(ClassificationNet)(
|
128 |
-
model=(ResNet)(block=Bottleneck, layers=[3, 4, 6, 3], zero_init_residual=True)
|
129 |
-
)
|
130 |
-
|
131 |
-
|
132 |
-
optimizer = L(torch.optim.SGD)(
|
133 |
-
params=L(get_default_optimizer_params)(),
|
134 |
-
lr=0.1,
|
135 |
-
momentum=0.9,
|
136 |
-
weight_decay=1e-4,
|
137 |
-
)
|
138 |
-
|
139 |
-
lr_multiplier = L(WarmupParamScheduler)(
|
140 |
-
scheduler=L(MultiStepParamScheduler)(
|
141 |
-
values=[1.0, 0.1, 0.01, 0.001], milestones=[30, 60, 90, 100]
|
142 |
-
),
|
143 |
-
warmup_length=1 / 100,
|
144 |
-
warmup_factor=0.1,
|
145 |
-
)
|
146 |
-
|
147 |
-
|
148 |
-
train = get_config("common/train.py").train
|
149 |
-
train.init_checkpoint = None
|
150 |
-
train.max_iter = 100 * 1281167 // 256
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/evaluation/evaluator.py
DELETED
@@ -1,224 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
-
import datetime
|
3 |
-
import logging
|
4 |
-
import time
|
5 |
-
from collections import OrderedDict, abc
|
6 |
-
from contextlib import ExitStack, contextmanager
|
7 |
-
from typing import List, Union
|
8 |
-
import torch
|
9 |
-
from torch import nn
|
10 |
-
|
11 |
-
from detectron2.utils.comm import get_world_size, is_main_process
|
12 |
-
from detectron2.utils.logger import log_every_n_seconds
|
13 |
-
|
14 |
-
|
15 |
-
class DatasetEvaluator:
|
16 |
-
"""
|
17 |
-
Base class for a dataset evaluator.
|
18 |
-
|
19 |
-
The function :func:`inference_on_dataset` runs the model over
|
20 |
-
all samples in the dataset, and have a DatasetEvaluator to process the inputs/outputs.
|
21 |
-
|
22 |
-
This class will accumulate information of the inputs/outputs (by :meth:`process`),
|
23 |
-
and produce evaluation results in the end (by :meth:`evaluate`).
|
24 |
-
"""
|
25 |
-
|
26 |
-
def reset(self):
|
27 |
-
"""
|
28 |
-
Preparation for a new round of evaluation.
|
29 |
-
Should be called before starting a round of evaluation.
|
30 |
-
"""
|
31 |
-
pass
|
32 |
-
|
33 |
-
def process(self, inputs, outputs):
|
34 |
-
"""
|
35 |
-
Process the pair of inputs and outputs.
|
36 |
-
If they contain batches, the pairs can be consumed one-by-one using `zip`:
|
37 |
-
|
38 |
-
.. code-block:: python
|
39 |
-
|
40 |
-
for input_, output in zip(inputs, outputs):
|
41 |
-
# do evaluation on single input/output pair
|
42 |
-
...
|
43 |
-
|
44 |
-
Args:
|
45 |
-
inputs (list): the inputs that's used to call the model.
|
46 |
-
outputs (list): the return value of `model(inputs)`
|
47 |
-
"""
|
48 |
-
pass
|
49 |
-
|
50 |
-
def evaluate(self):
|
51 |
-
"""
|
52 |
-
Evaluate/summarize the performance, after processing all input/output pairs.
|
53 |
-
|
54 |
-
Returns:
|
55 |
-
dict:
|
56 |
-
A new evaluator class can return a dict of arbitrary format
|
57 |
-
as long as the user can process the results.
|
58 |
-
In our train_net.py, we expect the following format:
|
59 |
-
|
60 |
-
* key: the name of the task (e.g., bbox)
|
61 |
-
* value: a dict of {metric name: score}, e.g.: {"AP50": 80}
|
62 |
-
"""
|
63 |
-
pass
|
64 |
-
|
65 |
-
|
66 |
-
class DatasetEvaluators(DatasetEvaluator):
|
67 |
-
"""
|
68 |
-
Wrapper class to combine multiple :class:`DatasetEvaluator` instances.
|
69 |
-
|
70 |
-
This class dispatches every evaluation call to
|
71 |
-
all of its :class:`DatasetEvaluator`.
|
72 |
-
"""
|
73 |
-
|
74 |
-
def __init__(self, evaluators):
|
75 |
-
"""
|
76 |
-
Args:
|
77 |
-
evaluators (list): the evaluators to combine.
|
78 |
-
"""
|
79 |
-
super().__init__()
|
80 |
-
self._evaluators = evaluators
|
81 |
-
|
82 |
-
def reset(self):
|
83 |
-
for evaluator in self._evaluators:
|
84 |
-
evaluator.reset()
|
85 |
-
|
86 |
-
def process(self, inputs, outputs):
|
87 |
-
for evaluator in self._evaluators:
|
88 |
-
evaluator.process(inputs, outputs)
|
89 |
-
|
90 |
-
def evaluate(self):
|
91 |
-
results = OrderedDict()
|
92 |
-
for evaluator in self._evaluators:
|
93 |
-
result = evaluator.evaluate()
|
94 |
-
if is_main_process() and result is not None:
|
95 |
-
for k, v in result.items():
|
96 |
-
assert (
|
97 |
-
k not in results
|
98 |
-
), "Different evaluators produce results with the same key {}".format(k)
|
99 |
-
results[k] = v
|
100 |
-
return results
|
101 |
-
|
102 |
-
|
103 |
-
def inference_on_dataset(
|
104 |
-
model, data_loader, evaluator: Union[DatasetEvaluator, List[DatasetEvaluator], None]
|
105 |
-
):
|
106 |
-
"""
|
107 |
-
Run model on the data_loader and evaluate the metrics with evaluator.
|
108 |
-
Also benchmark the inference speed of `model.__call__` accurately.
|
109 |
-
The model will be used in eval mode.
|
110 |
-
|
111 |
-
Args:
|
112 |
-
model (callable): a callable which takes an object from
|
113 |
-
`data_loader` and returns some outputs.
|
114 |
-
|
115 |
-
If it's an nn.Module, it will be temporarily set to `eval` mode.
|
116 |
-
If you wish to evaluate a model in `training` mode instead, you can
|
117 |
-
wrap the given model and override its behavior of `.eval()` and `.train()`.
|
118 |
-
data_loader: an iterable object with a length.
|
119 |
-
The elements it generates will be the inputs to the model.
|
120 |
-
evaluator: the evaluator(s) to run. Use `None` if you only want to benchmark,
|
121 |
-
but don't want to do any evaluation.
|
122 |
-
|
123 |
-
Returns:
|
124 |
-
The return value of `evaluator.evaluate()`
|
125 |
-
"""
|
126 |
-
num_devices = get_world_size()
|
127 |
-
logger = logging.getLogger(__name__)
|
128 |
-
logger.info("Start inference on {} batches".format(len(data_loader)))
|
129 |
-
|
130 |
-
total = len(data_loader) # inference data loader must have a fixed length
|
131 |
-
if evaluator is None:
|
132 |
-
# create a no-op evaluator
|
133 |
-
evaluator = DatasetEvaluators([])
|
134 |
-
if isinstance(evaluator, abc.MutableSequence):
|
135 |
-
evaluator = DatasetEvaluators(evaluator)
|
136 |
-
evaluator.reset()
|
137 |
-
|
138 |
-
num_warmup = min(5, total - 1)
|
139 |
-
start_time = time.perf_counter()
|
140 |
-
total_data_time = 0
|
141 |
-
total_compute_time = 0
|
142 |
-
total_eval_time = 0
|
143 |
-
with ExitStack() as stack:
|
144 |
-
if isinstance(model, nn.Module):
|
145 |
-
stack.enter_context(inference_context(model))
|
146 |
-
stack.enter_context(torch.no_grad())
|
147 |
-
|
148 |
-
start_data_time = time.perf_counter()
|
149 |
-
for idx, inputs in enumerate(data_loader):
|
150 |
-
total_data_time += time.perf_counter() - start_data_time
|
151 |
-
if idx == num_warmup:
|
152 |
-
start_time = time.perf_counter()
|
153 |
-
total_data_time = 0
|
154 |
-
total_compute_time = 0
|
155 |
-
total_eval_time = 0
|
156 |
-
|
157 |
-
start_compute_time = time.perf_counter()
|
158 |
-
outputs = model(inputs)
|
159 |
-
if torch.cuda.is_available():
|
160 |
-
torch.cuda.synchronize()
|
161 |
-
total_compute_time += time.perf_counter() - start_compute_time
|
162 |
-
|
163 |
-
start_eval_time = time.perf_counter()
|
164 |
-
evaluator.process(inputs, outputs)
|
165 |
-
total_eval_time += time.perf_counter() - start_eval_time
|
166 |
-
|
167 |
-
iters_after_start = idx + 1 - num_warmup * int(idx >= num_warmup)
|
168 |
-
data_seconds_per_iter = total_data_time / iters_after_start
|
169 |
-
compute_seconds_per_iter = total_compute_time / iters_after_start
|
170 |
-
eval_seconds_per_iter = total_eval_time / iters_after_start
|
171 |
-
total_seconds_per_iter = (time.perf_counter() - start_time) / iters_after_start
|
172 |
-
if idx >= num_warmup * 2 or compute_seconds_per_iter > 5:
|
173 |
-
eta = datetime.timedelta(seconds=int(total_seconds_per_iter * (total - idx - 1)))
|
174 |
-
log_every_n_seconds(
|
175 |
-
logging.INFO,
|
176 |
-
(
|
177 |
-
f"Inference done {idx + 1}/{total}. "
|
178 |
-
f"Dataloading: {data_seconds_per_iter:.4f} s/iter. "
|
179 |
-
f"Inference: {compute_seconds_per_iter:.4f} s/iter. "
|
180 |
-
f"Eval: {eval_seconds_per_iter:.4f} s/iter. "
|
181 |
-
f"Total: {total_seconds_per_iter:.4f} s/iter. "
|
182 |
-
f"ETA={eta}"
|
183 |
-
),
|
184 |
-
n=5,
|
185 |
-
)
|
186 |
-
start_data_time = time.perf_counter()
|
187 |
-
|
188 |
-
# Measure the time only for this worker (before the synchronization barrier)
|
189 |
-
total_time = time.perf_counter() - start_time
|
190 |
-
total_time_str = str(datetime.timedelta(seconds=total_time))
|
191 |
-
# NOTE this format is parsed by grep
|
192 |
-
logger.info(
|
193 |
-
"Total inference time: {} ({:.6f} s / iter per device, on {} devices)".format(
|
194 |
-
total_time_str, total_time / (total - num_warmup), num_devices
|
195 |
-
)
|
196 |
-
)
|
197 |
-
total_compute_time_str = str(datetime.timedelta(seconds=int(total_compute_time)))
|
198 |
-
logger.info(
|
199 |
-
"Total inference pure compute time: {} ({:.6f} s / iter per device, on {} devices)".format(
|
200 |
-
total_compute_time_str, total_compute_time / (total - num_warmup), num_devices
|
201 |
-
)
|
202 |
-
)
|
203 |
-
|
204 |
-
results = evaluator.evaluate()
|
205 |
-
# An evaluator may return None when not in main process.
|
206 |
-
# Replace it by an empty dict instead to make it easier for downstream code to handle
|
207 |
-
if results is None:
|
208 |
-
results = {}
|
209 |
-
return results
|
210 |
-
|
211 |
-
|
212 |
-
@contextmanager
|
213 |
-
def inference_context(model):
|
214 |
-
"""
|
215 |
-
A context where the model is temporarily changed to eval mode,
|
216 |
-
and restored to previous mode afterwards.
|
217 |
-
|
218 |
-
Args:
|
219 |
-
model: a torch Module
|
220 |
-
"""
|
221 |
-
training_mode = model.training
|
222 |
-
model.eval()
|
223 |
-
yield
|
224 |
-
model.train(training_mode)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/modeling/proposal_generator/rrpn.py
DELETED
@@ -1,203 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
-
import itertools
|
3 |
-
import logging
|
4 |
-
from typing import Dict, List
|
5 |
-
import torch
|
6 |
-
|
7 |
-
from detectron2.config import configurable
|
8 |
-
from detectron2.layers import ShapeSpec, batched_nms_rotated, cat
|
9 |
-
from detectron2.structures import Instances, RotatedBoxes, pairwise_iou_rotated
|
10 |
-
from detectron2.utils.memory import retry_if_cuda_oom
|
11 |
-
|
12 |
-
from ..box_regression import Box2BoxTransformRotated
|
13 |
-
from .build import PROPOSAL_GENERATOR_REGISTRY
|
14 |
-
from .proposal_utils import _is_tracing
|
15 |
-
from .rpn import RPN
|
16 |
-
|
17 |
-
logger = logging.getLogger(__name__)
|
18 |
-
|
19 |
-
|
20 |
-
def find_top_rrpn_proposals(
|
21 |
-
proposals,
|
22 |
-
pred_objectness_logits,
|
23 |
-
image_sizes,
|
24 |
-
nms_thresh,
|
25 |
-
pre_nms_topk,
|
26 |
-
post_nms_topk,
|
27 |
-
min_box_size,
|
28 |
-
training,
|
29 |
-
):
|
30 |
-
"""
|
31 |
-
For each feature map, select the `pre_nms_topk` highest scoring proposals,
|
32 |
-
apply NMS, clip proposals, and remove small boxes. Return the `post_nms_topk`
|
33 |
-
highest scoring proposals among all the feature maps if `training` is True,
|
34 |
-
otherwise, returns the highest `post_nms_topk` scoring proposals for each
|
35 |
-
feature map.
|
36 |
-
|
37 |
-
Args:
|
38 |
-
proposals (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A, 5).
|
39 |
-
All proposal predictions on the feature maps.
|
40 |
-
pred_objectness_logits (list[Tensor]): A list of L tensors. Tensor i has shape (N, Hi*Wi*A).
|
41 |
-
image_sizes (list[tuple]): sizes (h, w) for each image
|
42 |
-
nms_thresh (float): IoU threshold to use for NMS
|
43 |
-
pre_nms_topk (int): number of top k scoring proposals to keep before applying NMS.
|
44 |
-
When RRPN is run on multiple feature maps (as in FPN) this number is per
|
45 |
-
feature map.
|
46 |
-
post_nms_topk (int): number of top k scoring proposals to keep after applying NMS.
|
47 |
-
When RRPN is run on multiple feature maps (as in FPN) this number is total,
|
48 |
-
over all feature maps.
|
49 |
-
min_box_size(float): minimum proposal box side length in pixels (absolute units wrt
|
50 |
-
input images).
|
51 |
-
training (bool): True if proposals are to be used in training, otherwise False.
|
52 |
-
This arg exists only to support a legacy bug; look for the "NB: Legacy bug ..."
|
53 |
-
comment.
|
54 |
-
|
55 |
-
Returns:
|
56 |
-
proposals (list[Instances]): list of N Instances. The i-th Instances
|
57 |
-
stores post_nms_topk object proposals for image i.
|
58 |
-
"""
|
59 |
-
num_images = len(image_sizes)
|
60 |
-
device = proposals[0].device
|
61 |
-
|
62 |
-
# 1. Select top-k anchor for every level and every image
|
63 |
-
topk_scores = [] # #lvl Tensor, each of shape N x topk
|
64 |
-
topk_proposals = []
|
65 |
-
level_ids = [] # #lvl Tensor, each of shape (topk,)
|
66 |
-
batch_idx = torch.arange(num_images, device=device)
|
67 |
-
for level_id, proposals_i, logits_i in zip(
|
68 |
-
itertools.count(), proposals, pred_objectness_logits
|
69 |
-
):
|
70 |
-
Hi_Wi_A = logits_i.shape[1]
|
71 |
-
if isinstance(Hi_Wi_A, torch.Tensor): # it's a tensor in tracing
|
72 |
-
num_proposals_i = torch.clamp(Hi_Wi_A, max=pre_nms_topk)
|
73 |
-
else:
|
74 |
-
num_proposals_i = min(Hi_Wi_A, pre_nms_topk)
|
75 |
-
|
76 |
-
topk_scores_i, topk_idx = logits_i.topk(num_proposals_i, dim=1)
|
77 |
-
|
78 |
-
# each is N x topk
|
79 |
-
topk_proposals_i = proposals_i[batch_idx[:, None], topk_idx] # N x topk x 5
|
80 |
-
|
81 |
-
topk_proposals.append(topk_proposals_i)
|
82 |
-
topk_scores.append(topk_scores_i)
|
83 |
-
level_ids.append(torch.full((num_proposals_i,), level_id, dtype=torch.int64, device=device))
|
84 |
-
|
85 |
-
# 2. Concat all levels together
|
86 |
-
topk_scores = cat(topk_scores, dim=1)
|
87 |
-
topk_proposals = cat(topk_proposals, dim=1)
|
88 |
-
level_ids = cat(level_ids, dim=0)
|
89 |
-
|
90 |
-
# 3. For each image, run a per-level NMS, and choose topk results.
|
91 |
-
results = []
|
92 |
-
for n, image_size in enumerate(image_sizes):
|
93 |
-
boxes = RotatedBoxes(topk_proposals[n])
|
94 |
-
scores_per_img = topk_scores[n]
|
95 |
-
valid_mask = torch.isfinite(boxes.tensor).all(dim=1) & torch.isfinite(scores_per_img)
|
96 |
-
if not valid_mask.all():
|
97 |
-
boxes = boxes[valid_mask]
|
98 |
-
scores_per_img = scores_per_img[valid_mask]
|
99 |
-
boxes.clip(image_size)
|
100 |
-
|
101 |
-
# filter empty boxes
|
102 |
-
keep = boxes.nonempty(threshold=min_box_size)
|
103 |
-
lvl = level_ids
|
104 |
-
if _is_tracing() or keep.sum().item() != len(boxes):
|
105 |
-
boxes, scores_per_img, lvl = (boxes[keep], scores_per_img[keep], level_ids[keep])
|
106 |
-
|
107 |
-
keep = batched_nms_rotated(boxes.tensor, scores_per_img, lvl, nms_thresh)
|
108 |
-
# In Detectron1, there was different behavior during training vs. testing.
|
109 |
-
# (https://github.com/facebookresearch/Detectron/issues/459)
|
110 |
-
# During training, topk is over the proposals from *all* images in the training batch.
|
111 |
-
# During testing, it is over the proposals for each image separately.
|
112 |
-
# As a result, the training behavior becomes batch-dependent,
|
113 |
-
# and the configuration "POST_NMS_TOPK_TRAIN" end up relying on the batch size.
|
114 |
-
# This bug is addressed in Detectron2 to make the behavior independent of batch size.
|
115 |
-
keep = keep[:post_nms_topk]
|
116 |
-
|
117 |
-
res = Instances(image_size)
|
118 |
-
res.proposal_boxes = boxes[keep]
|
119 |
-
res.objectness_logits = scores_per_img[keep]
|
120 |
-
results.append(res)
|
121 |
-
return results
|
122 |
-
|
123 |
-
|
124 |
-
@PROPOSAL_GENERATOR_REGISTRY.register()
|
125 |
-
class RRPN(RPN):
|
126 |
-
"""
|
127 |
-
Rotated Region Proposal Network described in :paper:`RRPN`.
|
128 |
-
"""
|
129 |
-
|
130 |
-
@configurable
|
131 |
-
def __init__(self, *args, **kwargs):
|
132 |
-
super().__init__(*args, **kwargs)
|
133 |
-
if self.anchor_boundary_thresh >= 0:
|
134 |
-
raise NotImplementedError(
|
135 |
-
"anchor_boundary_thresh is a legacy option not implemented for RRPN."
|
136 |
-
)
|
137 |
-
|
138 |
-
@classmethod
|
139 |
-
def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]):
|
140 |
-
ret = super().from_config(cfg, input_shape)
|
141 |
-
ret["box2box_transform"] = Box2BoxTransformRotated(weights=cfg.MODEL.RPN.BBOX_REG_WEIGHTS)
|
142 |
-
return ret
|
143 |
-
|
144 |
-
@torch.no_grad()
|
145 |
-
def label_and_sample_anchors(self, anchors: List[RotatedBoxes], gt_instances: List[Instances]):
|
146 |
-
"""
|
147 |
-
Args:
|
148 |
-
anchors (list[RotatedBoxes]): anchors for each feature map.
|
149 |
-
gt_instances: the ground-truth instances for each image.
|
150 |
-
|
151 |
-
Returns:
|
152 |
-
list[Tensor]:
|
153 |
-
List of #img tensors. i-th element is a vector of labels whose length is
|
154 |
-
the total number of anchors across feature maps. Label values are in {-1, 0, 1},
|
155 |
-
with meanings: -1 = ignore; 0 = negative class; 1 = positive class.
|
156 |
-
list[Tensor]:
|
157 |
-
i-th element is a Nx5 tensor, where N is the total number of anchors across
|
158 |
-
feature maps. The values are the matched gt boxes for each anchor.
|
159 |
-
Values are undefined for those anchors not labeled as 1.
|
160 |
-
"""
|
161 |
-
anchors = RotatedBoxes.cat(anchors)
|
162 |
-
|
163 |
-
gt_boxes = [x.gt_boxes for x in gt_instances]
|
164 |
-
del gt_instances
|
165 |
-
|
166 |
-
gt_labels = []
|
167 |
-
matched_gt_boxes = []
|
168 |
-
for gt_boxes_i in gt_boxes:
|
169 |
-
"""
|
170 |
-
gt_boxes_i: ground-truth boxes for i-th image
|
171 |
-
"""
|
172 |
-
match_quality_matrix = retry_if_cuda_oom(pairwise_iou_rotated)(gt_boxes_i, anchors)
|
173 |
-
matched_idxs, gt_labels_i = retry_if_cuda_oom(self.anchor_matcher)(match_quality_matrix)
|
174 |
-
# Matching is memory-expensive and may result in CPU tensors. But the result is small
|
175 |
-
gt_labels_i = gt_labels_i.to(device=gt_boxes_i.device)
|
176 |
-
|
177 |
-
# A vector of labels (-1, 0, 1) for each anchor
|
178 |
-
gt_labels_i = self._subsample_labels(gt_labels_i)
|
179 |
-
|
180 |
-
if len(gt_boxes_i) == 0:
|
181 |
-
# These values won't be used anyway since the anchor is labeled as background
|
182 |
-
matched_gt_boxes_i = torch.zeros_like(anchors.tensor)
|
183 |
-
else:
|
184 |
-
# TODO wasted indexing computation for ignored boxes
|
185 |
-
matched_gt_boxes_i = gt_boxes_i[matched_idxs].tensor
|
186 |
-
|
187 |
-
gt_labels.append(gt_labels_i) # N,AHW
|
188 |
-
matched_gt_boxes.append(matched_gt_boxes_i)
|
189 |
-
return gt_labels, matched_gt_boxes
|
190 |
-
|
191 |
-
@torch.no_grad()
|
192 |
-
def predict_proposals(self, anchors, pred_objectness_logits, pred_anchor_deltas, image_sizes):
|
193 |
-
pred_proposals = self._decode_proposals(anchors, pred_anchor_deltas)
|
194 |
-
return find_top_rrpn_proposals(
|
195 |
-
pred_proposals,
|
196 |
-
pred_objectness_logits,
|
197 |
-
image_sizes,
|
198 |
-
self.nms_thresh,
|
199 |
-
self.pre_nms_topk[self.training],
|
200 |
-
self.post_nms_topk[self.training],
|
201 |
-
self.min_box_size,
|
202 |
-
self.training,
|
203 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tools/deploy/README.md
DELETED
@@ -1,66 +0,0 @@
|
|
1 |
-
See [deployment tutorial](https://detectron2.readthedocs.io/tutorials/deployment.html)
|
2 |
-
for some high-level background about deployment.
|
3 |
-
|
4 |
-
This directory contains the following examples:
|
5 |
-
|
6 |
-
1. An example script `export_model.py`
|
7 |
-
that exports a detectron2 model for deployment using different methods and formats.
|
8 |
-
|
9 |
-
2. A C++ example that runs inference with Mask R-CNN model in TorchScript format.
|
10 |
-
|
11 |
-
## Build
|
12 |
-
Deployment depends on libtorch and OpenCV. Some require more dependencies:
|
13 |
-
|
14 |
-
* Running TorchScript-format models produced by `--export-method=caffe2_tracing` requires libtorch
|
15 |
-
to be built with caffe2 enabled.
|
16 |
-
* Running TorchScript-format models produced by `--export-method=tracing/scripting` requires libtorchvision (C++ library of torchvision).
|
17 |
-
|
18 |
-
All methods are supported in one C++ file that requires all the above dependencies.
|
19 |
-
Adjust it and remove code you don't need.
|
20 |
-
As a reference, we provide a [Dockerfile](../../docker/deploy.Dockerfile) that installs all the above dependencies and builds the C++ example.
|
21 |
-
|
22 |
-
## Use
|
23 |
-
|
24 |
-
We show a few example commands to export and execute a Mask R-CNN model in C++.
|
25 |
-
|
26 |
-
* `export-method=tracing, format=torchscript`:
|
27 |
-
```
|
28 |
-
./export_model.py --config-file ../../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml \
|
29 |
-
--output ./output --export-method tracing --format torchscript \
|
30 |
-
MODEL.WEIGHTS detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl \
|
31 |
-
MODEL.DEVICE cuda
|
32 |
-
|
33 |
-
./build/torchscript_mask_rcnn output/model.ts input.jpg tracing
|
34 |
-
```
|
35 |
-
|
36 |
-
* `export-method=scripting, format=torchscript`:
|
37 |
-
```
|
38 |
-
./export_model.py --config-file ../../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml \
|
39 |
-
--output ./output --export-method scripting --format torchscript \
|
40 |
-
MODEL.WEIGHTS detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl \
|
41 |
-
|
42 |
-
./build/torchscript_mask_rcnn output/model.ts input.jpg scripting
|
43 |
-
```
|
44 |
-
|
45 |
-
* `export-method=caffe2_tracing, format=torchscript`:
|
46 |
-
|
47 |
-
```
|
48 |
-
./export_model.py --config-file ../../configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml \
|
49 |
-
--output ./output --export-method caffe2_tracing --format torchscript \
|
50 |
-
MODEL.WEIGHTS detectron2://COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x/137849600/model_final_f10217.pkl \
|
51 |
-
|
52 |
-
./build/torchscript_mask_rcnn output/model.ts input.jpg caffe2_tracing
|
53 |
-
```
|
54 |
-
|
55 |
-
|
56 |
-
## Notes:
|
57 |
-
|
58 |
-
1. Tracing/Caffe2-tracing requires valid weights & sample inputs.
|
59 |
-
Therefore the above commands require pre-trained models and [COCO dataset](https://detectron2.readthedocs.io/tutorials/builtin_datasets.html).
|
60 |
-
You can modify the script to obtain sample inputs in other ways instead of from COCO.
|
61 |
-
|
62 |
-
2. `--run-eval` is implemented only for tracing mode
|
63 |
-
to evaluate the exported model using the dataset in the config.
|
64 |
-
It's recommended to always verify the accuracy in case the conversion is not successful.
|
65 |
-
Evaluation can be slow if model is exported to CPU or dataset is too large ("coco_2017_val_100" is a small subset of COCO useful for evaluation).
|
66 |
-
`caffe2_tracing` accuracy may be slightly different (within 0.1 AP) from original model due to numerical precisions between different runtime.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/operations/build/metadata.py
DELETED
@@ -1,39 +0,0 @@
|
|
1 |
-
"""Metadata generation logic for source distributions.
|
2 |
-
"""
|
3 |
-
|
4 |
-
import os
|
5 |
-
|
6 |
-
from pip._vendor.pyproject_hooks import BuildBackendHookCaller
|
7 |
-
|
8 |
-
from pip._internal.build_env import BuildEnvironment
|
9 |
-
from pip._internal.exceptions import (
|
10 |
-
InstallationSubprocessError,
|
11 |
-
MetadataGenerationFailed,
|
12 |
-
)
|
13 |
-
from pip._internal.utils.subprocess import runner_with_spinner_message
|
14 |
-
from pip._internal.utils.temp_dir import TempDirectory
|
15 |
-
|
16 |
-
|
17 |
-
def generate_metadata(
|
18 |
-
build_env: BuildEnvironment, backend: BuildBackendHookCaller, details: str
|
19 |
-
) -> str:
|
20 |
-
"""Generate metadata using mechanisms described in PEP 517.
|
21 |
-
|
22 |
-
Returns the generated metadata directory.
|
23 |
-
"""
|
24 |
-
metadata_tmpdir = TempDirectory(kind="modern-metadata", globally_managed=True)
|
25 |
-
|
26 |
-
metadata_dir = metadata_tmpdir.path
|
27 |
-
|
28 |
-
with build_env:
|
29 |
-
# Note that BuildBackendHookCaller implements a fallback for
|
30 |
-
# prepare_metadata_for_build_wheel, so we don't have to
|
31 |
-
# consider the possibility that this hook doesn't exist.
|
32 |
-
runner = runner_with_spinner_message("Preparing metadata (pyproject.toml)")
|
33 |
-
with backend.subprocess_runner(runner):
|
34 |
-
try:
|
35 |
-
distinfo_dir = backend.prepare_metadata_for_build_wheel(metadata_dir)
|
36 |
-
except InstallationSubprocessError as error:
|
37 |
-
raise MetadataGenerationFailed(package_details=details) from error
|
38 |
-
|
39 |
-
return os.path.join(metadata_dir, distinfo_dir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/LIVE/pybind11/include/pybind11/iostream.h
DELETED
@@ -1,209 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
pybind11/iostream.h -- Tools to assist with redirecting cout and cerr to Python
|
3 |
-
|
4 |
-
Copyright (c) 2017 Henry F. Schreiner
|
5 |
-
|
6 |
-
All rights reserved. Use of this source code is governed by a
|
7 |
-
BSD-style license that can be found in the LICENSE file.
|
8 |
-
*/
|
9 |
-
|
10 |
-
#pragma once
|
11 |
-
|
12 |
-
#include "pybind11.h"
|
13 |
-
|
14 |
-
#include <streambuf>
|
15 |
-
#include <ostream>
|
16 |
-
#include <string>
|
17 |
-
#include <memory>
|
18 |
-
#include <iostream>
|
19 |
-
|
20 |
-
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
21 |
-
PYBIND11_NAMESPACE_BEGIN(detail)
|
22 |
-
|
23 |
-
// Buffer that writes to Python instead of C++
|
24 |
-
class pythonbuf : public std::streambuf {
|
25 |
-
private:
|
26 |
-
using traits_type = std::streambuf::traits_type;
|
27 |
-
|
28 |
-
const size_t buf_size;
|
29 |
-
std::unique_ptr<char[]> d_buffer;
|
30 |
-
object pywrite;
|
31 |
-
object pyflush;
|
32 |
-
|
33 |
-
int overflow(int c) {
|
34 |
-
if (!traits_type::eq_int_type(c, traits_type::eof())) {
|
35 |
-
*pptr() = traits_type::to_char_type(c);
|
36 |
-
pbump(1);
|
37 |
-
}
|
38 |
-
return sync() == 0 ? traits_type::not_eof(c) : traits_type::eof();
|
39 |
-
}
|
40 |
-
|
41 |
-
int sync() {
|
42 |
-
if (pbase() != pptr()) {
|
43 |
-
// This subtraction cannot be negative, so dropping the sign
|
44 |
-
str line(pbase(), static_cast<size_t>(pptr() - pbase()));
|
45 |
-
|
46 |
-
{
|
47 |
-
gil_scoped_acquire tmp;
|
48 |
-
pywrite(line);
|
49 |
-
pyflush();
|
50 |
-
}
|
51 |
-
|
52 |
-
setp(pbase(), epptr());
|
53 |
-
}
|
54 |
-
return 0;
|
55 |
-
}
|
56 |
-
|
57 |
-
public:
|
58 |
-
|
59 |
-
pythonbuf(object pyostream, size_t buffer_size = 1024)
|
60 |
-
: buf_size(buffer_size),
|
61 |
-
d_buffer(new char[buf_size]),
|
62 |
-
pywrite(pyostream.attr("write")),
|
63 |
-
pyflush(pyostream.attr("flush")) {
|
64 |
-
setp(d_buffer.get(), d_buffer.get() + buf_size - 1);
|
65 |
-
}
|
66 |
-
|
67 |
-
pythonbuf(pythonbuf&&) = default;
|
68 |
-
|
69 |
-
/// Sync before destroy
|
70 |
-
~pythonbuf() {
|
71 |
-
sync();
|
72 |
-
}
|
73 |
-
};
|
74 |
-
|
75 |
-
PYBIND11_NAMESPACE_END(detail)
|
76 |
-
|
77 |
-
|
78 |
-
/** \rst
|
79 |
-
This a move-only guard that redirects output.
|
80 |
-
|
81 |
-
.. code-block:: cpp
|
82 |
-
|
83 |
-
#include <pybind11/iostream.h>
|
84 |
-
|
85 |
-
...
|
86 |
-
|
87 |
-
{
|
88 |
-
py::scoped_ostream_redirect output;
|
89 |
-
std::cout << "Hello, World!"; // Python stdout
|
90 |
-
} // <-- return std::cout to normal
|
91 |
-
|
92 |
-
You can explicitly pass the c++ stream and the python object,
|
93 |
-
for example to guard stderr instead.
|
94 |
-
|
95 |
-
.. code-block:: cpp
|
96 |
-
|
97 |
-
{
|
98 |
-
py::scoped_ostream_redirect output{std::cerr, py::module::import("sys").attr("stderr")};
|
99 |
-
std::cerr << "Hello, World!";
|
100 |
-
}
|
101 |
-
\endrst */
|
102 |
-
class scoped_ostream_redirect {
|
103 |
-
protected:
|
104 |
-
std::streambuf *old;
|
105 |
-
std::ostream &costream;
|
106 |
-
detail::pythonbuf buffer;
|
107 |
-
|
108 |
-
public:
|
109 |
-
scoped_ostream_redirect(
|
110 |
-
std::ostream &costream = std::cout,
|
111 |
-
object pyostream = module::import("sys").attr("stdout"))
|
112 |
-
: costream(costream), buffer(pyostream) {
|
113 |
-
old = costream.rdbuf(&buffer);
|
114 |
-
}
|
115 |
-
|
116 |
-
~scoped_ostream_redirect() {
|
117 |
-
costream.rdbuf(old);
|
118 |
-
}
|
119 |
-
|
120 |
-
scoped_ostream_redirect(const scoped_ostream_redirect &) = delete;
|
121 |
-
scoped_ostream_redirect(scoped_ostream_redirect &&other) = default;
|
122 |
-
scoped_ostream_redirect &operator=(const scoped_ostream_redirect &) = delete;
|
123 |
-
scoped_ostream_redirect &operator=(scoped_ostream_redirect &&) = delete;
|
124 |
-
};
|
125 |
-
|
126 |
-
|
127 |
-
/** \rst
|
128 |
-
Like `scoped_ostream_redirect`, but redirects cerr by default. This class
|
129 |
-
is provided primary to make ``py::call_guard`` easier to make.
|
130 |
-
|
131 |
-
.. code-block:: cpp
|
132 |
-
|
133 |
-
m.def("noisy_func", &noisy_func,
|
134 |
-
py::call_guard<scoped_ostream_redirect,
|
135 |
-
scoped_estream_redirect>());
|
136 |
-
|
137 |
-
\endrst */
|
138 |
-
class scoped_estream_redirect : public scoped_ostream_redirect {
|
139 |
-
public:
|
140 |
-
scoped_estream_redirect(
|
141 |
-
std::ostream &costream = std::cerr,
|
142 |
-
object pyostream = module::import("sys").attr("stderr"))
|
143 |
-
: scoped_ostream_redirect(costream,pyostream) {}
|
144 |
-
};
|
145 |
-
|
146 |
-
|
147 |
-
PYBIND11_NAMESPACE_BEGIN(detail)
|
148 |
-
|
149 |
-
// Class to redirect output as a context manager. C++ backend.
|
150 |
-
class OstreamRedirect {
|
151 |
-
bool do_stdout_;
|
152 |
-
bool do_stderr_;
|
153 |
-
std::unique_ptr<scoped_ostream_redirect> redirect_stdout;
|
154 |
-
std::unique_ptr<scoped_estream_redirect> redirect_stderr;
|
155 |
-
|
156 |
-
public:
|
157 |
-
OstreamRedirect(bool do_stdout = true, bool do_stderr = true)
|
158 |
-
: do_stdout_(do_stdout), do_stderr_(do_stderr) {}
|
159 |
-
|
160 |
-
void enter() {
|
161 |
-
if (do_stdout_)
|
162 |
-
redirect_stdout.reset(new scoped_ostream_redirect());
|
163 |
-
if (do_stderr_)
|
164 |
-
redirect_stderr.reset(new scoped_estream_redirect());
|
165 |
-
}
|
166 |
-
|
167 |
-
void exit() {
|
168 |
-
redirect_stdout.reset();
|
169 |
-
redirect_stderr.reset();
|
170 |
-
}
|
171 |
-
};
|
172 |
-
|
173 |
-
PYBIND11_NAMESPACE_END(detail)
|
174 |
-
|
175 |
-
/** \rst
|
176 |
-
This is a helper function to add a C++ redirect context manager to Python
|
177 |
-
instead of using a C++ guard. To use it, add the following to your binding code:
|
178 |
-
|
179 |
-
.. code-block:: cpp
|
180 |
-
|
181 |
-
#include <pybind11/iostream.h>
|
182 |
-
|
183 |
-
...
|
184 |
-
|
185 |
-
py::add_ostream_redirect(m, "ostream_redirect");
|
186 |
-
|
187 |
-
You now have a Python context manager that redirects your output:
|
188 |
-
|
189 |
-
.. code-block:: python
|
190 |
-
|
191 |
-
with m.ostream_redirect():
|
192 |
-
m.print_to_cout_function()
|
193 |
-
|
194 |
-
This manager can optionally be told which streams to operate on:
|
195 |
-
|
196 |
-
.. code-block:: python
|
197 |
-
|
198 |
-
with m.ostream_redirect(stdout=true, stderr=true):
|
199 |
-
m.noisy_function_with_error_printing()
|
200 |
-
|
201 |
-
\endrst */
|
202 |
-
inline class_<detail::OstreamRedirect> add_ostream_redirect(module m, std::string name = "ostream_redirect") {
|
203 |
-
return class_<detail::OstreamRedirect>(m, name.c_str(), module_local())
|
204 |
-
.def(init<bool,bool>(), arg("stdout")=true, arg("stderr")=true)
|
205 |
-
.def("__enter__", &detail::OstreamRedirect::enter)
|
206 |
-
.def("__exit__", [](detail::OstreamRedirect &self_, args) { self_.exit(); });
|
207 |
-
}
|
208 |
-
|
209 |
-
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/LIVE/thrust/thrust/zip_function.h
DELETED
@@ -1,211 +0,0 @@
|
|
1 |
-
|
2 |
-
/*! \file thrust/zip_function.h
|
3 |
-
* \brief Adaptor type that turns an N-ary function object into one that takes
|
4 |
-
* a tuple of size N so it can easily be used with algorithms taking zip
|
5 |
-
* iterators
|
6 |
-
*/
|
7 |
-
|
8 |
-
#pragma once
|
9 |
-
|
10 |
-
#include <thrust/detail/config.h>
|
11 |
-
#include <thrust/detail/cpp11_required.h>
|
12 |
-
#include <thrust/detail/modern_gcc_required.h>
|
13 |
-
|
14 |
-
#if THRUST_CPP_DIALECT >= 2011 && !defined(THRUST_LEGACY_GCC)
|
15 |
-
|
16 |
-
#include <thrust/tuple.h>
|
17 |
-
#include <thrust/type_traits/integer_sequence.h>
|
18 |
-
#include <thrust/detail/type_deduction.h>
|
19 |
-
|
20 |
-
namespace thrust
|
21 |
-
{
|
22 |
-
|
23 |
-
/*! \addtogroup function_objects Function Objects
|
24 |
-
* \{
|
25 |
-
*/
|
26 |
-
|
27 |
-
/*! \addtogroup function_object_adaptors Function Object Adaptors
|
28 |
-
* \ingroup function_objects
|
29 |
-
* \{
|
30 |
-
*/
|
31 |
-
|
32 |
-
namespace detail {
|
33 |
-
namespace zip_detail {
|
34 |
-
|
35 |
-
// Add workaround for decltype(auto) on C++11-only compilers:
|
36 |
-
#if THRUST_CPP_DIALECT >= 2014
|
37 |
-
|
38 |
-
template <typename Function, typename Tuple, std::size_t... Is>
|
39 |
-
__host__ __device__
|
40 |
-
decltype(auto) apply_impl(Function&& func, Tuple&& args, index_sequence<Is...>)
|
41 |
-
{
|
42 |
-
return func(thrust::get<Is>(THRUST_FWD(args))...);
|
43 |
-
}
|
44 |
-
|
45 |
-
template <typename Function, typename Tuple>
|
46 |
-
__host__ __device__
|
47 |
-
decltype(auto) apply(Function&& func, Tuple&& args)
|
48 |
-
{
|
49 |
-
constexpr auto tuple_size = thrust::tuple_size<typename std::decay<Tuple>::type>::value;
|
50 |
-
return apply_impl(THRUST_FWD(func), THRUST_FWD(args), make_index_sequence<tuple_size>{});
|
51 |
-
}
|
52 |
-
|
53 |
-
#else // THRUST_CPP_DIALECT
|
54 |
-
|
55 |
-
template <typename Function, typename Tuple, std::size_t... Is>
|
56 |
-
__host__ __device__
|
57 |
-
auto apply_impl(Function&& func, Tuple&& args, index_sequence<Is...>)
|
58 |
-
THRUST_DECLTYPE_RETURNS(func(thrust::get<Is>(THRUST_FWD(args))...))
|
59 |
-
|
60 |
-
template <typename Function, typename Tuple>
|
61 |
-
__host__ __device__
|
62 |
-
auto apply(Function&& func, Tuple&& args)
|
63 |
-
THRUST_DECLTYPE_RETURNS(
|
64 |
-
apply_impl(
|
65 |
-
THRUST_FWD(func),
|
66 |
-
THRUST_FWD(args),
|
67 |
-
make_index_sequence<
|
68 |
-
thrust::tuple_size<typename std::decay<Tuple>::type>::value>{})
|
69 |
-
)
|
70 |
-
|
71 |
-
#endif // THRUST_CPP_DIALECT
|
72 |
-
|
73 |
-
} // namespace zip_detail
|
74 |
-
} // namespace detail
|
75 |
-
|
76 |
-
/*! \p zip_function is a function object that allows the easy use of N-ary
|
77 |
-
* function objects with \p zip_iterators without redefining them to take a
|
78 |
-
* \p tuple instead of N arguments.
|
79 |
-
*
|
80 |
-
* This means that if a functor that takes 2 arguments which could be used with
|
81 |
-
* the \p transform function and \p device_iterators can be extended to take 3
|
82 |
-
* arguments and \p zip_iterators without rewriting the functor in terms of
|
83 |
-
* \p tuple.
|
84 |
-
*
|
85 |
-
* The \p make_zip_function convenience function is provided to avoid having
|
86 |
-
* to explicitely define the type of the functor when creating a \p zip_function,
|
87 |
-
* whic is especially helpful when using lambdas as the functor.
|
88 |
-
*
|
89 |
-
* \code
|
90 |
-
* #include <thrust/iterator/zip_iterator.h>
|
91 |
-
* #include <thrust/device_vector.h>
|
92 |
-
* #include <thrust/transform.h>
|
93 |
-
* #include <thrust/zip_function.h>
|
94 |
-
*
|
95 |
-
* struct SumTuple {
|
96 |
-
* float operator()(Tuple tup) {
|
97 |
-
* return std::get<0>(tup) + std::get<1>(tup) + std::get<2>(tup);
|
98 |
-
* }
|
99 |
-
* };
|
100 |
-
* struct SumArgs {
|
101 |
-
* float operator()(float a, float b, float c) {
|
102 |
-
* return a + b + c;
|
103 |
-
* }
|
104 |
-
* };
|
105 |
-
*
|
106 |
-
* int main() {
|
107 |
-
* thrust::device_vector<float> A(3);
|
108 |
-
* thrust::device_vector<float> B(3);
|
109 |
-
* thrust::device_vector<float> C(3);
|
110 |
-
* thrust::device_vector<float> D(3);
|
111 |
-
* A[0] = 0.f; A[1] = 1.f; A[2] = 2.f;
|
112 |
-
* B[0] = 1.f; B[1] = 2.f; B[2] = 3.f;
|
113 |
-
* C[0] = 2.f; C[1] = 3.f; C[2] = 4.f;
|
114 |
-
*
|
115 |
-
* // The following four invocations of transform are equivalent
|
116 |
-
* // Transform with 3-tuple
|
117 |
-
* thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(A.begin(), B.begin(), C.begin())),
|
118 |
-
* thrust::make_zip_iterator(thrust::make_tuple(A.end(), B.end(), C.end())),
|
119 |
-
* D.begin(),
|
120 |
-
* SumTuple{});
|
121 |
-
*
|
122 |
-
* // Transform with 3 parameters
|
123 |
-
* thrust::zip_function<SumArgs> adapted{};
|
124 |
-
* thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(A.begin(), B.begin(), C.begin())),
|
125 |
-
* thrust::make_zip_iterator(thrust::make_tuple(A.end(), B.end(), C.end())),
|
126 |
-
* D.begin(),
|
127 |
-
* adapted);
|
128 |
-
*
|
129 |
-
* // Transform with 3 parameters with convenience function
|
130 |
-
* thrust::zip_function<SumArgs> adapted{};
|
131 |
-
* thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(A.begin(), B.begin(), C.begin())),
|
132 |
-
* thrust::make_zip_iterator(thrust::make_tuple(A.end(), B.end(), C.end())),
|
133 |
-
* D.begin(),
|
134 |
-
* thrust::make_zip_function(SumArgs{}));
|
135 |
-
*
|
136 |
-
* // Transform with 3 parameters with convenience function and lambda
|
137 |
-
* thrust::zip_function<SumArgs> adapted{};
|
138 |
-
* thrust::transform(thrust::make_zip_iterator(thrust::make_tuple(A.begin(), B.begin(), C.begin())),
|
139 |
-
* thrust::make_zip_iterator(thrust::make_tuple(A.end(), B.end(), C.end())),
|
140 |
-
* D.begin(),
|
141 |
-
* thrust::make_zip_function([] (float a, float b, float c) {
|
142 |
-
* return a + b + c;
|
143 |
-
* }));
|
144 |
-
* return 0;
|
145 |
-
* }
|
146 |
-
* \endcode
|
147 |
-
*
|
148 |
-
* \see make_zip_function
|
149 |
-
* \see zip_iterator
|
150 |
-
*/
|
151 |
-
template <typename Function>
|
152 |
-
class zip_function
|
153 |
-
{
|
154 |
-
public:
|
155 |
-
__host__ __device__
|
156 |
-
zip_function(Function func) : func(std::move(func)) {}
|
157 |
-
|
158 |
-
// Add workaround for decltype(auto) on C++11-only compilers:
|
159 |
-
#if THRUST_CPP_DIALECT >= 2014
|
160 |
-
|
161 |
-
template <typename Tuple>
|
162 |
-
__host__ __device__
|
163 |
-
decltype(auto) operator()(Tuple&& args) const
|
164 |
-
{
|
165 |
-
return detail::zip_detail::apply(func, THRUST_FWD(args));
|
166 |
-
}
|
167 |
-
|
168 |
-
#else // THRUST_CPP_DIALECT
|
169 |
-
|
170 |
-
// Can't just use THRUST_DECLTYPE_RETURNS here since we need to use
|
171 |
-
// std::declval for the signature components:
|
172 |
-
template <typename Tuple>
|
173 |
-
__host__ __device__
|
174 |
-
auto operator()(Tuple&& args) const
|
175 |
-
noexcept(noexcept(detail::zip_detail::apply(std::declval<Function>(), THRUST_FWD(args))))
|
176 |
-
-> decltype(detail::zip_detail::apply(std::declval<Function>(), THRUST_FWD(args)))
|
177 |
-
|
178 |
-
{
|
179 |
-
return detail::zip_detail::apply(func, THRUST_FWD(args));
|
180 |
-
}
|
181 |
-
|
182 |
-
#endif // THRUST_CPP_DIALECT
|
183 |
-
|
184 |
-
private:
|
185 |
-
mutable Function func;
|
186 |
-
};
|
187 |
-
|
188 |
-
/*! \p make_zip_function creates a \p zip_function from a function object.
|
189 |
-
*
|
190 |
-
* \param fun The N-ary function object.
|
191 |
-
* \return A \p zip_function that takes a N-tuple.
|
192 |
-
*
|
193 |
-
* \see zip_function
|
194 |
-
*/
|
195 |
-
template <typename Function>
|
196 |
-
__host__ __device__
|
197 |
-
auto make_zip_function(Function&& fun) -> zip_function<typename std::decay<Function>::type>
|
198 |
-
{
|
199 |
-
using func_t = typename std::decay<Function>::type;
|
200 |
-
return zip_function<func_t>(THRUST_FWD(fun));
|
201 |
-
}
|
202 |
-
|
203 |
-
/*! \} // end function_object_adaptors
|
204 |
-
*/
|
205 |
-
|
206 |
-
/*! \} // end function_objects
|
207 |
-
*/
|
208 |
-
|
209 |
-
} // end namespace thrust
|
210 |
-
|
211 |
-
#endif
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Crossbro/succinctly-text2image-prompt-generator/app.py
DELETED
@@ -1,3 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
|
3 |
-
gr.Interface.load("models/succinctly/text2image-prompt-generator").launch()
|
|
|
|
|
|
|
|
spaces/DEEMOSTECH/ChatAvatar/static/js/main.22ab9e68.js
DELETED
The diff for this file is too large to render.
See raw diff
|
|
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/anyio/_core/_fileio.py
DELETED
@@ -1,603 +0,0 @@
|
|
1 |
-
from __future__ import annotations
|
2 |
-
|
3 |
-
import os
|
4 |
-
import pathlib
|
5 |
-
import sys
|
6 |
-
from dataclasses import dataclass
|
7 |
-
from functools import partial
|
8 |
-
from os import PathLike
|
9 |
-
from typing import (
|
10 |
-
IO,
|
11 |
-
TYPE_CHECKING,
|
12 |
-
Any,
|
13 |
-
AnyStr,
|
14 |
-
AsyncIterator,
|
15 |
-
Callable,
|
16 |
-
Generic,
|
17 |
-
Iterable,
|
18 |
-
Iterator,
|
19 |
-
Sequence,
|
20 |
-
cast,
|
21 |
-
overload,
|
22 |
-
)
|
23 |
-
|
24 |
-
from .. import to_thread
|
25 |
-
from ..abc import AsyncResource
|
26 |
-
|
27 |
-
if sys.version_info >= (3, 8):
|
28 |
-
from typing import Final
|
29 |
-
else:
|
30 |
-
from typing_extensions import Final
|
31 |
-
|
32 |
-
if TYPE_CHECKING:
|
33 |
-
from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer
|
34 |
-
else:
|
35 |
-
ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object
|
36 |
-
|
37 |
-
|
38 |
-
class AsyncFile(AsyncResource, Generic[AnyStr]):
|
39 |
-
"""
|
40 |
-
An asynchronous file object.
|
41 |
-
|
42 |
-
This class wraps a standard file object and provides async friendly versions of the following
|
43 |
-
blocking methods (where available on the original file object):
|
44 |
-
|
45 |
-
* read
|
46 |
-
* read1
|
47 |
-
* readline
|
48 |
-
* readlines
|
49 |
-
* readinto
|
50 |
-
* readinto1
|
51 |
-
* write
|
52 |
-
* writelines
|
53 |
-
* truncate
|
54 |
-
* seek
|
55 |
-
* tell
|
56 |
-
* flush
|
57 |
-
|
58 |
-
All other methods are directly passed through.
|
59 |
-
|
60 |
-
This class supports the asynchronous context manager protocol which closes the underlying file
|
61 |
-
at the end of the context block.
|
62 |
-
|
63 |
-
This class also supports asynchronous iteration::
|
64 |
-
|
65 |
-
async with await open_file(...) as f:
|
66 |
-
async for line in f:
|
67 |
-
print(line)
|
68 |
-
"""
|
69 |
-
|
70 |
-
def __init__(self, fp: IO[AnyStr]) -> None:
|
71 |
-
self._fp: Any = fp
|
72 |
-
|
73 |
-
def __getattr__(self, name: str) -> object:
|
74 |
-
return getattr(self._fp, name)
|
75 |
-
|
76 |
-
@property
|
77 |
-
def wrapped(self) -> IO[AnyStr]:
|
78 |
-
"""The wrapped file object."""
|
79 |
-
return self._fp
|
80 |
-
|
81 |
-
async def __aiter__(self) -> AsyncIterator[AnyStr]:
|
82 |
-
while True:
|
83 |
-
line = await self.readline()
|
84 |
-
if line:
|
85 |
-
yield line
|
86 |
-
else:
|
87 |
-
break
|
88 |
-
|
89 |
-
async def aclose(self) -> None:
|
90 |
-
return await to_thread.run_sync(self._fp.close)
|
91 |
-
|
92 |
-
async def read(self, size: int = -1) -> AnyStr:
|
93 |
-
return await to_thread.run_sync(self._fp.read, size)
|
94 |
-
|
95 |
-
async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes:
|
96 |
-
return await to_thread.run_sync(self._fp.read1, size)
|
97 |
-
|
98 |
-
async def readline(self) -> AnyStr:
|
99 |
-
return await to_thread.run_sync(self._fp.readline)
|
100 |
-
|
101 |
-
async def readlines(self) -> list[AnyStr]:
|
102 |
-
return await to_thread.run_sync(self._fp.readlines)
|
103 |
-
|
104 |
-
async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> bytes:
|
105 |
-
return await to_thread.run_sync(self._fp.readinto, b)
|
106 |
-
|
107 |
-
async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> bytes:
|
108 |
-
return await to_thread.run_sync(self._fp.readinto1, b)
|
109 |
-
|
110 |
-
@overload
|
111 |
-
async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int:
|
112 |
-
...
|
113 |
-
|
114 |
-
@overload
|
115 |
-
async def write(self: AsyncFile[str], b: str) -> int:
|
116 |
-
...
|
117 |
-
|
118 |
-
async def write(self, b: ReadableBuffer | str) -> int:
|
119 |
-
return await to_thread.run_sync(self._fp.write, b)
|
120 |
-
|
121 |
-
@overload
|
122 |
-
async def writelines(
|
123 |
-
self: AsyncFile[bytes], lines: Iterable[ReadableBuffer]
|
124 |
-
) -> None:
|
125 |
-
...
|
126 |
-
|
127 |
-
@overload
|
128 |
-
async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None:
|
129 |
-
...
|
130 |
-
|
131 |
-
async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None:
|
132 |
-
return await to_thread.run_sync(self._fp.writelines, lines)
|
133 |
-
|
134 |
-
async def truncate(self, size: int | None = None) -> int:
|
135 |
-
return await to_thread.run_sync(self._fp.truncate, size)
|
136 |
-
|
137 |
-
async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int:
|
138 |
-
return await to_thread.run_sync(self._fp.seek, offset, whence)
|
139 |
-
|
140 |
-
async def tell(self) -> int:
|
141 |
-
return await to_thread.run_sync(self._fp.tell)
|
142 |
-
|
143 |
-
async def flush(self) -> None:
|
144 |
-
return await to_thread.run_sync(self._fp.flush)
|
145 |
-
|
146 |
-
|
147 |
-
@overload
|
148 |
-
async def open_file(
|
149 |
-
file: str | PathLike[str] | int,
|
150 |
-
mode: OpenBinaryMode,
|
151 |
-
buffering: int = ...,
|
152 |
-
encoding: str | None = ...,
|
153 |
-
errors: str | None = ...,
|
154 |
-
newline: str | None = ...,
|
155 |
-
closefd: bool = ...,
|
156 |
-
opener: Callable[[str, int], int] | None = ...,
|
157 |
-
) -> AsyncFile[bytes]:
|
158 |
-
...
|
159 |
-
|
160 |
-
|
161 |
-
@overload
|
162 |
-
async def open_file(
|
163 |
-
file: str | PathLike[str] | int,
|
164 |
-
mode: OpenTextMode = ...,
|
165 |
-
buffering: int = ...,
|
166 |
-
encoding: str | None = ...,
|
167 |
-
errors: str | None = ...,
|
168 |
-
newline: str | None = ...,
|
169 |
-
closefd: bool = ...,
|
170 |
-
opener: Callable[[str, int], int] | None = ...,
|
171 |
-
) -> AsyncFile[str]:
|
172 |
-
...
|
173 |
-
|
174 |
-
|
175 |
-
async def open_file(
|
176 |
-
file: str | PathLike[str] | int,
|
177 |
-
mode: str = "r",
|
178 |
-
buffering: int = -1,
|
179 |
-
encoding: str | None = None,
|
180 |
-
errors: str | None = None,
|
181 |
-
newline: str | None = None,
|
182 |
-
closefd: bool = True,
|
183 |
-
opener: Callable[[str, int], int] | None = None,
|
184 |
-
) -> AsyncFile[Any]:
|
185 |
-
"""
|
186 |
-
Open a file asynchronously.
|
187 |
-
|
188 |
-
The arguments are exactly the same as for the builtin :func:`open`.
|
189 |
-
|
190 |
-
:return: an asynchronous file object
|
191 |
-
|
192 |
-
"""
|
193 |
-
fp = await to_thread.run_sync(
|
194 |
-
open, file, mode, buffering, encoding, errors, newline, closefd, opener
|
195 |
-
)
|
196 |
-
return AsyncFile(fp)
|
197 |
-
|
198 |
-
|
199 |
-
def wrap_file(file: IO[AnyStr]) -> AsyncFile[AnyStr]:
|
200 |
-
"""
|
201 |
-
Wrap an existing file as an asynchronous file.
|
202 |
-
|
203 |
-
:param file: an existing file-like object
|
204 |
-
:return: an asynchronous file object
|
205 |
-
|
206 |
-
"""
|
207 |
-
return AsyncFile(file)
|
208 |
-
|
209 |
-
|
210 |
-
@dataclass(eq=False)
|
211 |
-
class _PathIterator(AsyncIterator["Path"]):
|
212 |
-
iterator: Iterator[PathLike[str]]
|
213 |
-
|
214 |
-
async def __anext__(self) -> Path:
|
215 |
-
nextval = await to_thread.run_sync(next, self.iterator, None, cancellable=True)
|
216 |
-
if nextval is None:
|
217 |
-
raise StopAsyncIteration from None
|
218 |
-
|
219 |
-
return Path(cast("PathLike[str]", nextval))
|
220 |
-
|
221 |
-
|
222 |
-
class Path:
|
223 |
-
"""
|
224 |
-
An asynchronous version of :class:`pathlib.Path`.
|
225 |
-
|
226 |
-
This class cannot be substituted for :class:`pathlib.Path` or :class:`pathlib.PurePath`, but
|
227 |
-
it is compatible with the :class:`os.PathLike` interface.
|
228 |
-
|
229 |
-
It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for the
|
230 |
-
deprecated :meth:`~pathlib.Path.link_to` method.
|
231 |
-
|
232 |
-
Any methods that do disk I/O need to be awaited on. These methods are:
|
233 |
-
|
234 |
-
* :meth:`~pathlib.Path.absolute`
|
235 |
-
* :meth:`~pathlib.Path.chmod`
|
236 |
-
* :meth:`~pathlib.Path.cwd`
|
237 |
-
* :meth:`~pathlib.Path.exists`
|
238 |
-
* :meth:`~pathlib.Path.expanduser`
|
239 |
-
* :meth:`~pathlib.Path.group`
|
240 |
-
* :meth:`~pathlib.Path.hardlink_to`
|
241 |
-
* :meth:`~pathlib.Path.home`
|
242 |
-
* :meth:`~pathlib.Path.is_block_device`
|
243 |
-
* :meth:`~pathlib.Path.is_char_device`
|
244 |
-
* :meth:`~pathlib.Path.is_dir`
|
245 |
-
* :meth:`~pathlib.Path.is_fifo`
|
246 |
-
* :meth:`~pathlib.Path.is_file`
|
247 |
-
* :meth:`~pathlib.Path.is_mount`
|
248 |
-
* :meth:`~pathlib.Path.lchmod`
|
249 |
-
* :meth:`~pathlib.Path.lstat`
|
250 |
-
* :meth:`~pathlib.Path.mkdir`
|
251 |
-
* :meth:`~pathlib.Path.open`
|
252 |
-
* :meth:`~pathlib.Path.owner`
|
253 |
-
* :meth:`~pathlib.Path.read_bytes`
|
254 |
-
* :meth:`~pathlib.Path.read_text`
|
255 |
-
* :meth:`~pathlib.Path.readlink`
|
256 |
-
* :meth:`~pathlib.Path.rename`
|
257 |
-
* :meth:`~pathlib.Path.replace`
|
258 |
-
* :meth:`~pathlib.Path.rmdir`
|
259 |
-
* :meth:`~pathlib.Path.samefile`
|
260 |
-
* :meth:`~pathlib.Path.stat`
|
261 |
-
* :meth:`~pathlib.Path.touch`
|
262 |
-
* :meth:`~pathlib.Path.unlink`
|
263 |
-
* :meth:`~pathlib.Path.write_bytes`
|
264 |
-
* :meth:`~pathlib.Path.write_text`
|
265 |
-
|
266 |
-
Additionally, the following methods return an async iterator yielding :class:`~.Path` objects:
|
267 |
-
|
268 |
-
* :meth:`~pathlib.Path.glob`
|
269 |
-
* :meth:`~pathlib.Path.iterdir`
|
270 |
-
* :meth:`~pathlib.Path.rglob`
|
271 |
-
"""
|
272 |
-
|
273 |
-
__slots__ = "_path", "__weakref__"
|
274 |
-
|
275 |
-
__weakref__: Any
|
276 |
-
|
277 |
-
def __init__(self, *args: str | PathLike[str]) -> None:
|
278 |
-
self._path: Final[pathlib.Path] = pathlib.Path(*args)
|
279 |
-
|
280 |
-
def __fspath__(self) -> str:
|
281 |
-
return self._path.__fspath__()
|
282 |
-
|
283 |
-
def __str__(self) -> str:
|
284 |
-
return self._path.__str__()
|
285 |
-
|
286 |
-
def __repr__(self) -> str:
|
287 |
-
return f"{self.__class__.__name__}({self.as_posix()!r})"
|
288 |
-
|
289 |
-
def __bytes__(self) -> bytes:
|
290 |
-
return self._path.__bytes__()
|
291 |
-
|
292 |
-
def __hash__(self) -> int:
|
293 |
-
return self._path.__hash__()
|
294 |
-
|
295 |
-
def __eq__(self, other: object) -> bool:
|
296 |
-
target = other._path if isinstance(other, Path) else other
|
297 |
-
return self._path.__eq__(target)
|
298 |
-
|
299 |
-
def __lt__(self, other: Path) -> bool:
|
300 |
-
target = other._path if isinstance(other, Path) else other
|
301 |
-
return self._path.__lt__(target)
|
302 |
-
|
303 |
-
def __le__(self, other: Path) -> bool:
|
304 |
-
target = other._path if isinstance(other, Path) else other
|
305 |
-
return self._path.__le__(target)
|
306 |
-
|
307 |
-
def __gt__(self, other: Path) -> bool:
|
308 |
-
target = other._path if isinstance(other, Path) else other
|
309 |
-
return self._path.__gt__(target)
|
310 |
-
|
311 |
-
def __ge__(self, other: Path) -> bool:
|
312 |
-
target = other._path if isinstance(other, Path) else other
|
313 |
-
return self._path.__ge__(target)
|
314 |
-
|
315 |
-
def __truediv__(self, other: Any) -> Path:
|
316 |
-
return Path(self._path / other)
|
317 |
-
|
318 |
-
def __rtruediv__(self, other: Any) -> Path:
|
319 |
-
return Path(other) / self
|
320 |
-
|
321 |
-
@property
|
322 |
-
def parts(self) -> tuple[str, ...]:
|
323 |
-
return self._path.parts
|
324 |
-
|
325 |
-
@property
|
326 |
-
def drive(self) -> str:
|
327 |
-
return self._path.drive
|
328 |
-
|
329 |
-
@property
|
330 |
-
def root(self) -> str:
|
331 |
-
return self._path.root
|
332 |
-
|
333 |
-
@property
|
334 |
-
def anchor(self) -> str:
|
335 |
-
return self._path.anchor
|
336 |
-
|
337 |
-
@property
|
338 |
-
def parents(self) -> Sequence[Path]:
|
339 |
-
return tuple(Path(p) for p in self._path.parents)
|
340 |
-
|
341 |
-
@property
|
342 |
-
def parent(self) -> Path:
|
343 |
-
return Path(self._path.parent)
|
344 |
-
|
345 |
-
@property
|
346 |
-
def name(self) -> str:
|
347 |
-
return self._path.name
|
348 |
-
|
349 |
-
@property
|
350 |
-
def suffix(self) -> str:
|
351 |
-
return self._path.suffix
|
352 |
-
|
353 |
-
@property
|
354 |
-
def suffixes(self) -> list[str]:
|
355 |
-
return self._path.suffixes
|
356 |
-
|
357 |
-
@property
|
358 |
-
def stem(self) -> str:
|
359 |
-
return self._path.stem
|
360 |
-
|
361 |
-
async def absolute(self) -> Path:
|
362 |
-
path = await to_thread.run_sync(self._path.absolute)
|
363 |
-
return Path(path)
|
364 |
-
|
365 |
-
def as_posix(self) -> str:
|
366 |
-
return self._path.as_posix()
|
367 |
-
|
368 |
-
def as_uri(self) -> str:
|
369 |
-
return self._path.as_uri()
|
370 |
-
|
371 |
-
def match(self, path_pattern: str) -> bool:
|
372 |
-
return self._path.match(path_pattern)
|
373 |
-
|
374 |
-
def is_relative_to(self, *other: str | PathLike[str]) -> bool:
|
375 |
-
try:
|
376 |
-
self.relative_to(*other)
|
377 |
-
return True
|
378 |
-
except ValueError:
|
379 |
-
return False
|
380 |
-
|
381 |
-
async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None:
|
382 |
-
func = partial(os.chmod, follow_symlinks=follow_symlinks)
|
383 |
-
return await to_thread.run_sync(func, self._path, mode)
|
384 |
-
|
385 |
-
@classmethod
|
386 |
-
async def cwd(cls) -> Path:
|
387 |
-
path = await to_thread.run_sync(pathlib.Path.cwd)
|
388 |
-
return cls(path)
|
389 |
-
|
390 |
-
async def exists(self) -> bool:
|
391 |
-
return await to_thread.run_sync(self._path.exists, cancellable=True)
|
392 |
-
|
393 |
-
async def expanduser(self) -> Path:
|
394 |
-
return Path(await to_thread.run_sync(self._path.expanduser, cancellable=True))
|
395 |
-
|
396 |
-
def glob(self, pattern: str) -> AsyncIterator[Path]:
|
397 |
-
gen = self._path.glob(pattern)
|
398 |
-
return _PathIterator(gen)
|
399 |
-
|
400 |
-
async def group(self) -> str:
|
401 |
-
return await to_thread.run_sync(self._path.group, cancellable=True)
|
402 |
-
|
403 |
-
async def hardlink_to(self, target: str | pathlib.Path | Path) -> None:
|
404 |
-
if isinstance(target, Path):
|
405 |
-
target = target._path
|
406 |
-
|
407 |
-
await to_thread.run_sync(os.link, target, self)
|
408 |
-
|
409 |
-
@classmethod
|
410 |
-
async def home(cls) -> Path:
|
411 |
-
home_path = await to_thread.run_sync(pathlib.Path.home)
|
412 |
-
return cls(home_path)
|
413 |
-
|
414 |
-
def is_absolute(self) -> bool:
|
415 |
-
return self._path.is_absolute()
|
416 |
-
|
417 |
-
async def is_block_device(self) -> bool:
|
418 |
-
return await to_thread.run_sync(self._path.is_block_device, cancellable=True)
|
419 |
-
|
420 |
-
async def is_char_device(self) -> bool:
|
421 |
-
return await to_thread.run_sync(self._path.is_char_device, cancellable=True)
|
422 |
-
|
423 |
-
async def is_dir(self) -> bool:
|
424 |
-
return await to_thread.run_sync(self._path.is_dir, cancellable=True)
|
425 |
-
|
426 |
-
async def is_fifo(self) -> bool:
|
427 |
-
return await to_thread.run_sync(self._path.is_fifo, cancellable=True)
|
428 |
-
|
429 |
-
async def is_file(self) -> bool:
|
430 |
-
return await to_thread.run_sync(self._path.is_file, cancellable=True)
|
431 |
-
|
432 |
-
async def is_mount(self) -> bool:
|
433 |
-
return await to_thread.run_sync(os.path.ismount, self._path, cancellable=True)
|
434 |
-
|
435 |
-
def is_reserved(self) -> bool:
|
436 |
-
return self._path.is_reserved()
|
437 |
-
|
438 |
-
async def is_socket(self) -> bool:
|
439 |
-
return await to_thread.run_sync(self._path.is_socket, cancellable=True)
|
440 |
-
|
441 |
-
async def is_symlink(self) -> bool:
|
442 |
-
return await to_thread.run_sync(self._path.is_symlink, cancellable=True)
|
443 |
-
|
444 |
-
def iterdir(self) -> AsyncIterator[Path]:
|
445 |
-
gen = self._path.iterdir()
|
446 |
-
return _PathIterator(gen)
|
447 |
-
|
448 |
-
def joinpath(self, *args: str | PathLike[str]) -> Path:
|
449 |
-
return Path(self._path.joinpath(*args))
|
450 |
-
|
451 |
-
async def lchmod(self, mode: int) -> None:
|
452 |
-
await to_thread.run_sync(self._path.lchmod, mode)
|
453 |
-
|
454 |
-
async def lstat(self) -> os.stat_result:
|
455 |
-
return await to_thread.run_sync(self._path.lstat, cancellable=True)
|
456 |
-
|
457 |
-
async def mkdir(
|
458 |
-
self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False
|
459 |
-
) -> None:
|
460 |
-
await to_thread.run_sync(self._path.mkdir, mode, parents, exist_ok)
|
461 |
-
|
462 |
-
@overload
|
463 |
-
async def open(
|
464 |
-
self,
|
465 |
-
mode: OpenBinaryMode,
|
466 |
-
buffering: int = ...,
|
467 |
-
encoding: str | None = ...,
|
468 |
-
errors: str | None = ...,
|
469 |
-
newline: str | None = ...,
|
470 |
-
) -> AsyncFile[bytes]:
|
471 |
-
...
|
472 |
-
|
473 |
-
@overload
|
474 |
-
async def open(
|
475 |
-
self,
|
476 |
-
mode: OpenTextMode = ...,
|
477 |
-
buffering: int = ...,
|
478 |
-
encoding: str | None = ...,
|
479 |
-
errors: str | None = ...,
|
480 |
-
newline: str | None = ...,
|
481 |
-
) -> AsyncFile[str]:
|
482 |
-
...
|
483 |
-
|
484 |
-
async def open(
|
485 |
-
self,
|
486 |
-
mode: str = "r",
|
487 |
-
buffering: int = -1,
|
488 |
-
encoding: str | None = None,
|
489 |
-
errors: str | None = None,
|
490 |
-
newline: str | None = None,
|
491 |
-
) -> AsyncFile[Any]:
|
492 |
-
fp = await to_thread.run_sync(
|
493 |
-
self._path.open, mode, buffering, encoding, errors, newline
|
494 |
-
)
|
495 |
-
return AsyncFile(fp)
|
496 |
-
|
497 |
-
async def owner(self) -> str:
|
498 |
-
return await to_thread.run_sync(self._path.owner, cancellable=True)
|
499 |
-
|
500 |
-
async def read_bytes(self) -> bytes:
|
501 |
-
return await to_thread.run_sync(self._path.read_bytes)
|
502 |
-
|
503 |
-
async def read_text(
|
504 |
-
self, encoding: str | None = None, errors: str | None = None
|
505 |
-
) -> str:
|
506 |
-
return await to_thread.run_sync(self._path.read_text, encoding, errors)
|
507 |
-
|
508 |
-
def relative_to(self, *other: str | PathLike[str]) -> Path:
|
509 |
-
return Path(self._path.relative_to(*other))
|
510 |
-
|
511 |
-
async def readlink(self) -> Path:
|
512 |
-
target = await to_thread.run_sync(os.readlink, self._path)
|
513 |
-
return Path(cast(str, target))
|
514 |
-
|
515 |
-
async def rename(self, target: str | pathlib.PurePath | Path) -> Path:
|
516 |
-
if isinstance(target, Path):
|
517 |
-
target = target._path
|
518 |
-
|
519 |
-
await to_thread.run_sync(self._path.rename, target)
|
520 |
-
return Path(target)
|
521 |
-
|
522 |
-
async def replace(self, target: str | pathlib.PurePath | Path) -> Path:
|
523 |
-
if isinstance(target, Path):
|
524 |
-
target = target._path
|
525 |
-
|
526 |
-
await to_thread.run_sync(self._path.replace, target)
|
527 |
-
return Path(target)
|
528 |
-
|
529 |
-
async def resolve(self, strict: bool = False) -> Path:
|
530 |
-
func = partial(self._path.resolve, strict=strict)
|
531 |
-
return Path(await to_thread.run_sync(func, cancellable=True))
|
532 |
-
|
533 |
-
def rglob(self, pattern: str) -> AsyncIterator[Path]:
|
534 |
-
gen = self._path.rglob(pattern)
|
535 |
-
return _PathIterator(gen)
|
536 |
-
|
537 |
-
async def rmdir(self) -> None:
|
538 |
-
await to_thread.run_sync(self._path.rmdir)
|
539 |
-
|
540 |
-
async def samefile(
|
541 |
-
self, other_path: str | bytes | int | pathlib.Path | Path
|
542 |
-
) -> bool:
|
543 |
-
if isinstance(other_path, Path):
|
544 |
-
other_path = other_path._path
|
545 |
-
|
546 |
-
return await to_thread.run_sync(
|
547 |
-
self._path.samefile, other_path, cancellable=True
|
548 |
-
)
|
549 |
-
|
550 |
-
async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result:
|
551 |
-
func = partial(os.stat, follow_symlinks=follow_symlinks)
|
552 |
-
return await to_thread.run_sync(func, self._path, cancellable=True)
|
553 |
-
|
554 |
-
async def symlink_to(
|
555 |
-
self,
|
556 |
-
target: str | pathlib.Path | Path,
|
557 |
-
target_is_directory: bool = False,
|
558 |
-
) -> None:
|
559 |
-
if isinstance(target, Path):
|
560 |
-
target = target._path
|
561 |
-
|
562 |
-
await to_thread.run_sync(self._path.symlink_to, target, target_is_directory)
|
563 |
-
|
564 |
-
async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None:
|
565 |
-
await to_thread.run_sync(self._path.touch, mode, exist_ok)
|
566 |
-
|
567 |
-
async def unlink(self, missing_ok: bool = False) -> None:
|
568 |
-
try:
|
569 |
-
await to_thread.run_sync(self._path.unlink)
|
570 |
-
except FileNotFoundError:
|
571 |
-
if not missing_ok:
|
572 |
-
raise
|
573 |
-
|
574 |
-
def with_name(self, name: str) -> Path:
|
575 |
-
return Path(self._path.with_name(name))
|
576 |
-
|
577 |
-
def with_stem(self, stem: str) -> Path:
|
578 |
-
return Path(self._path.with_name(stem + self._path.suffix))
|
579 |
-
|
580 |
-
def with_suffix(self, suffix: str) -> Path:
|
581 |
-
return Path(self._path.with_suffix(suffix))
|
582 |
-
|
583 |
-
async def write_bytes(self, data: bytes) -> int:
|
584 |
-
return await to_thread.run_sync(self._path.write_bytes, data)
|
585 |
-
|
586 |
-
async def write_text(
|
587 |
-
self,
|
588 |
-
data: str,
|
589 |
-
encoding: str | None = None,
|
590 |
-
errors: str | None = None,
|
591 |
-
newline: str | None = None,
|
592 |
-
) -> int:
|
593 |
-
# Path.write_text() does not support the "newline" parameter before Python 3.10
|
594 |
-
def sync_write_text() -> int:
|
595 |
-
with self._path.open(
|
596 |
-
"w", encoding=encoding, errors=errors, newline=newline
|
597 |
-
) as fp:
|
598 |
-
return fp.write(data)
|
599 |
-
|
600 |
-
return await to_thread.run_sync(sync_write_text)
|
601 |
-
|
602 |
-
|
603 |
-
PathLike.register(Path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fastapi/routing.py
DELETED
@@ -1,1358 +0,0 @@
|
|
1 |
-
import asyncio
|
2 |
-
import dataclasses
|
3 |
-
import email.message
|
4 |
-
import inspect
|
5 |
-
import json
|
6 |
-
from contextlib import AsyncExitStack
|
7 |
-
from enum import Enum, IntEnum
|
8 |
-
from typing import (
|
9 |
-
Any,
|
10 |
-
Callable,
|
11 |
-
Coroutine,
|
12 |
-
Dict,
|
13 |
-
List,
|
14 |
-
Optional,
|
15 |
-
Sequence,
|
16 |
-
Set,
|
17 |
-
Tuple,
|
18 |
-
Type,
|
19 |
-
Union,
|
20 |
-
)
|
21 |
-
|
22 |
-
from fastapi import params
|
23 |
-
from fastapi._compat import (
|
24 |
-
ModelField,
|
25 |
-
Undefined,
|
26 |
-
_get_model_config,
|
27 |
-
_model_dump,
|
28 |
-
_normalize_errors,
|
29 |
-
lenient_issubclass,
|
30 |
-
)
|
31 |
-
from fastapi.datastructures import Default, DefaultPlaceholder
|
32 |
-
from fastapi.dependencies.models import Dependant
|
33 |
-
from fastapi.dependencies.utils import (
|
34 |
-
get_body_field,
|
35 |
-
get_dependant,
|
36 |
-
get_parameterless_sub_dependant,
|
37 |
-
get_typed_return_annotation,
|
38 |
-
solve_dependencies,
|
39 |
-
)
|
40 |
-
from fastapi.encoders import jsonable_encoder
|
41 |
-
from fastapi.exceptions import (
|
42 |
-
FastAPIError,
|
43 |
-
RequestValidationError,
|
44 |
-
ResponseValidationError,
|
45 |
-
WebSocketRequestValidationError,
|
46 |
-
)
|
47 |
-
from fastapi.types import DecoratedCallable, IncEx
|
48 |
-
from fastapi.utils import (
|
49 |
-
create_cloned_field,
|
50 |
-
create_response_field,
|
51 |
-
generate_unique_id,
|
52 |
-
get_value_or_default,
|
53 |
-
is_body_allowed_for_status_code,
|
54 |
-
)
|
55 |
-
from pydantic import BaseModel
|
56 |
-
from starlette import routing
|
57 |
-
from starlette.concurrency import run_in_threadpool
|
58 |
-
from starlette.exceptions import HTTPException
|
59 |
-
from starlette.requests import Request
|
60 |
-
from starlette.responses import JSONResponse, Response
|
61 |
-
from starlette.routing import (
|
62 |
-
BaseRoute,
|
63 |
-
Match,
|
64 |
-
compile_path,
|
65 |
-
get_name,
|
66 |
-
request_response,
|
67 |
-
websocket_session,
|
68 |
-
)
|
69 |
-
from starlette.routing import Mount as Mount # noqa
|
70 |
-
from starlette.types import ASGIApp, Lifespan, Scope
|
71 |
-
from starlette.websockets import WebSocket
|
72 |
-
|
73 |
-
|
74 |
-
def _prepare_response_content(
|
75 |
-
res: Any,
|
76 |
-
*,
|
77 |
-
exclude_unset: bool,
|
78 |
-
exclude_defaults: bool = False,
|
79 |
-
exclude_none: bool = False,
|
80 |
-
) -> Any:
|
81 |
-
if isinstance(res, BaseModel):
|
82 |
-
read_with_orm_mode = getattr(_get_model_config(res), "read_with_orm_mode", None)
|
83 |
-
if read_with_orm_mode:
|
84 |
-
# Let from_orm extract the data from this model instead of converting
|
85 |
-
# it now to a dict.
|
86 |
-
# Otherwise there's no way to extract lazy data that requires attribute
|
87 |
-
# access instead of dict iteration, e.g. lazy relationships.
|
88 |
-
return res
|
89 |
-
return _model_dump(
|
90 |
-
res,
|
91 |
-
by_alias=True,
|
92 |
-
exclude_unset=exclude_unset,
|
93 |
-
exclude_defaults=exclude_defaults,
|
94 |
-
exclude_none=exclude_none,
|
95 |
-
)
|
96 |
-
elif isinstance(res, list):
|
97 |
-
return [
|
98 |
-
_prepare_response_content(
|
99 |
-
item,
|
100 |
-
exclude_unset=exclude_unset,
|
101 |
-
exclude_defaults=exclude_defaults,
|
102 |
-
exclude_none=exclude_none,
|
103 |
-
)
|
104 |
-
for item in res
|
105 |
-
]
|
106 |
-
elif isinstance(res, dict):
|
107 |
-
return {
|
108 |
-
k: _prepare_response_content(
|
109 |
-
v,
|
110 |
-
exclude_unset=exclude_unset,
|
111 |
-
exclude_defaults=exclude_defaults,
|
112 |
-
exclude_none=exclude_none,
|
113 |
-
)
|
114 |
-
for k, v in res.items()
|
115 |
-
}
|
116 |
-
elif dataclasses.is_dataclass(res):
|
117 |
-
return dataclasses.asdict(res)
|
118 |
-
return res
|
119 |
-
|
120 |
-
|
121 |
-
async def serialize_response(
|
122 |
-
*,
|
123 |
-
field: Optional[ModelField] = None,
|
124 |
-
response_content: Any,
|
125 |
-
include: Optional[IncEx] = None,
|
126 |
-
exclude: Optional[IncEx] = None,
|
127 |
-
by_alias: bool = True,
|
128 |
-
exclude_unset: bool = False,
|
129 |
-
exclude_defaults: bool = False,
|
130 |
-
exclude_none: bool = False,
|
131 |
-
is_coroutine: bool = True,
|
132 |
-
) -> Any:
|
133 |
-
if field:
|
134 |
-
errors = []
|
135 |
-
if not hasattr(field, "serialize"):
|
136 |
-
# pydantic v1
|
137 |
-
response_content = _prepare_response_content(
|
138 |
-
response_content,
|
139 |
-
exclude_unset=exclude_unset,
|
140 |
-
exclude_defaults=exclude_defaults,
|
141 |
-
exclude_none=exclude_none,
|
142 |
-
)
|
143 |
-
if is_coroutine:
|
144 |
-
value, errors_ = field.validate(response_content, {}, loc=("response",))
|
145 |
-
else:
|
146 |
-
value, errors_ = await run_in_threadpool(
|
147 |
-
field.validate, response_content, {}, loc=("response",)
|
148 |
-
)
|
149 |
-
if isinstance(errors_, list):
|
150 |
-
errors.extend(errors_)
|
151 |
-
elif errors_:
|
152 |
-
errors.append(errors_)
|
153 |
-
if errors:
|
154 |
-
raise ResponseValidationError(
|
155 |
-
errors=_normalize_errors(errors), body=response_content
|
156 |
-
)
|
157 |
-
|
158 |
-
if hasattr(field, "serialize"):
|
159 |
-
return field.serialize(
|
160 |
-
value,
|
161 |
-
include=include,
|
162 |
-
exclude=exclude,
|
163 |
-
by_alias=by_alias,
|
164 |
-
exclude_unset=exclude_unset,
|
165 |
-
exclude_defaults=exclude_defaults,
|
166 |
-
exclude_none=exclude_none,
|
167 |
-
)
|
168 |
-
|
169 |
-
return jsonable_encoder(
|
170 |
-
value,
|
171 |
-
include=include,
|
172 |
-
exclude=exclude,
|
173 |
-
by_alias=by_alias,
|
174 |
-
exclude_unset=exclude_unset,
|
175 |
-
exclude_defaults=exclude_defaults,
|
176 |
-
exclude_none=exclude_none,
|
177 |
-
)
|
178 |
-
else:
|
179 |
-
return jsonable_encoder(response_content)
|
180 |
-
|
181 |
-
|
182 |
-
async def run_endpoint_function(
|
183 |
-
*, dependant: Dependant, values: Dict[str, Any], is_coroutine: bool
|
184 |
-
) -> Any:
|
185 |
-
# Only called by get_request_handler. Has been split into its own function to
|
186 |
-
# facilitate profiling endpoints, since inner functions are harder to profile.
|
187 |
-
assert dependant.call is not None, "dependant.call must be a function"
|
188 |
-
|
189 |
-
if is_coroutine:
|
190 |
-
return await dependant.call(**values)
|
191 |
-
else:
|
192 |
-
return await run_in_threadpool(dependant.call, **values)
|
193 |
-
|
194 |
-
|
195 |
-
def get_request_handler(
|
196 |
-
dependant: Dependant,
|
197 |
-
body_field: Optional[ModelField] = None,
|
198 |
-
status_code: Optional[int] = None,
|
199 |
-
response_class: Union[Type[Response], DefaultPlaceholder] = Default(JSONResponse),
|
200 |
-
response_field: Optional[ModelField] = None,
|
201 |
-
response_model_include: Optional[IncEx] = None,
|
202 |
-
response_model_exclude: Optional[IncEx] = None,
|
203 |
-
response_model_by_alias: bool = True,
|
204 |
-
response_model_exclude_unset: bool = False,
|
205 |
-
response_model_exclude_defaults: bool = False,
|
206 |
-
response_model_exclude_none: bool = False,
|
207 |
-
dependency_overrides_provider: Optional[Any] = None,
|
208 |
-
) -> Callable[[Request], Coroutine[Any, Any, Response]]:
|
209 |
-
assert dependant.call is not None, "dependant.call must be a function"
|
210 |
-
is_coroutine = asyncio.iscoroutinefunction(dependant.call)
|
211 |
-
is_body_form = body_field and isinstance(body_field.field_info, params.Form)
|
212 |
-
if isinstance(response_class, DefaultPlaceholder):
|
213 |
-
actual_response_class: Type[Response] = response_class.value
|
214 |
-
else:
|
215 |
-
actual_response_class = response_class
|
216 |
-
|
217 |
-
async def app(request: Request) -> Response:
|
218 |
-
try:
|
219 |
-
body: Any = None
|
220 |
-
if body_field:
|
221 |
-
if is_body_form:
|
222 |
-
body = await request.form()
|
223 |
-
stack = request.scope.get("fastapi_astack")
|
224 |
-
assert isinstance(stack, AsyncExitStack)
|
225 |
-
stack.push_async_callback(body.close)
|
226 |
-
else:
|
227 |
-
body_bytes = await request.body()
|
228 |
-
if body_bytes:
|
229 |
-
json_body: Any = Undefined
|
230 |
-
content_type_value = request.headers.get("content-type")
|
231 |
-
if not content_type_value:
|
232 |
-
json_body = await request.json()
|
233 |
-
else:
|
234 |
-
message = email.message.Message()
|
235 |
-
message["content-type"] = content_type_value
|
236 |
-
if message.get_content_maintype() == "application":
|
237 |
-
subtype = message.get_content_subtype()
|
238 |
-
if subtype == "json" or subtype.endswith("+json"):
|
239 |
-
json_body = await request.json()
|
240 |
-
if json_body != Undefined:
|
241 |
-
body = json_body
|
242 |
-
else:
|
243 |
-
body = body_bytes
|
244 |
-
except json.JSONDecodeError as e:
|
245 |
-
raise RequestValidationError(
|
246 |
-
[
|
247 |
-
{
|
248 |
-
"type": "json_invalid",
|
249 |
-
"loc": ("body", e.pos),
|
250 |
-
"msg": "JSON decode error",
|
251 |
-
"input": {},
|
252 |
-
"ctx": {"error": e.msg},
|
253 |
-
}
|
254 |
-
],
|
255 |
-
body=e.doc,
|
256 |
-
) from e
|
257 |
-
except HTTPException:
|
258 |
-
raise
|
259 |
-
except Exception as e:
|
260 |
-
raise HTTPException(
|
261 |
-
status_code=400, detail="There was an error parsing the body"
|
262 |
-
) from e
|
263 |
-
solved_result = await solve_dependencies(
|
264 |
-
request=request,
|
265 |
-
dependant=dependant,
|
266 |
-
body=body,
|
267 |
-
dependency_overrides_provider=dependency_overrides_provider,
|
268 |
-
)
|
269 |
-
values, errors, background_tasks, sub_response, _ = solved_result
|
270 |
-
if errors:
|
271 |
-
raise RequestValidationError(_normalize_errors(errors), body=body)
|
272 |
-
else:
|
273 |
-
raw_response = await run_endpoint_function(
|
274 |
-
dependant=dependant, values=values, is_coroutine=is_coroutine
|
275 |
-
)
|
276 |
-
|
277 |
-
if isinstance(raw_response, Response):
|
278 |
-
if raw_response.background is None:
|
279 |
-
raw_response.background = background_tasks
|
280 |
-
return raw_response
|
281 |
-
response_args: Dict[str, Any] = {"background": background_tasks}
|
282 |
-
# If status_code was set, use it, otherwise use the default from the
|
283 |
-
# response class, in the case of redirect it's 307
|
284 |
-
current_status_code = (
|
285 |
-
status_code if status_code else sub_response.status_code
|
286 |
-
)
|
287 |
-
if current_status_code is not None:
|
288 |
-
response_args["status_code"] = current_status_code
|
289 |
-
if sub_response.status_code:
|
290 |
-
response_args["status_code"] = sub_response.status_code
|
291 |
-
content = await serialize_response(
|
292 |
-
field=response_field,
|
293 |
-
response_content=raw_response,
|
294 |
-
include=response_model_include,
|
295 |
-
exclude=response_model_exclude,
|
296 |
-
by_alias=response_model_by_alias,
|
297 |
-
exclude_unset=response_model_exclude_unset,
|
298 |
-
exclude_defaults=response_model_exclude_defaults,
|
299 |
-
exclude_none=response_model_exclude_none,
|
300 |
-
is_coroutine=is_coroutine,
|
301 |
-
)
|
302 |
-
response = actual_response_class(content, **response_args)
|
303 |
-
if not is_body_allowed_for_status_code(response.status_code):
|
304 |
-
response.body = b""
|
305 |
-
response.headers.raw.extend(sub_response.headers.raw)
|
306 |
-
return response
|
307 |
-
|
308 |
-
return app
|
309 |
-
|
310 |
-
|
311 |
-
def get_websocket_app(
|
312 |
-
dependant: Dependant, dependency_overrides_provider: Optional[Any] = None
|
313 |
-
) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]:
|
314 |
-
async def app(websocket: WebSocket) -> None:
|
315 |
-
solved_result = await solve_dependencies(
|
316 |
-
request=websocket,
|
317 |
-
dependant=dependant,
|
318 |
-
dependency_overrides_provider=dependency_overrides_provider,
|
319 |
-
)
|
320 |
-
values, errors, _, _2, _3 = solved_result
|
321 |
-
if errors:
|
322 |
-
raise WebSocketRequestValidationError(_normalize_errors(errors))
|
323 |
-
assert dependant.call is not None, "dependant.call must be a function"
|
324 |
-
await dependant.call(**values)
|
325 |
-
|
326 |
-
return app
|
327 |
-
|
328 |
-
|
329 |
-
class APIWebSocketRoute(routing.WebSocketRoute):
|
330 |
-
def __init__(
|
331 |
-
self,
|
332 |
-
path: str,
|
333 |
-
endpoint: Callable[..., Any],
|
334 |
-
*,
|
335 |
-
name: Optional[str] = None,
|
336 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
337 |
-
dependency_overrides_provider: Optional[Any] = None,
|
338 |
-
) -> None:
|
339 |
-
self.path = path
|
340 |
-
self.endpoint = endpoint
|
341 |
-
self.name = get_name(endpoint) if name is None else name
|
342 |
-
self.dependencies = list(dependencies or [])
|
343 |
-
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
|
344 |
-
self.dependant = get_dependant(path=self.path_format, call=self.endpoint)
|
345 |
-
for depends in self.dependencies[::-1]:
|
346 |
-
self.dependant.dependencies.insert(
|
347 |
-
0,
|
348 |
-
get_parameterless_sub_dependant(depends=depends, path=self.path_format),
|
349 |
-
)
|
350 |
-
|
351 |
-
self.app = websocket_session(
|
352 |
-
get_websocket_app(
|
353 |
-
dependant=self.dependant,
|
354 |
-
dependency_overrides_provider=dependency_overrides_provider,
|
355 |
-
)
|
356 |
-
)
|
357 |
-
|
358 |
-
def matches(self, scope: Scope) -> Tuple[Match, Scope]:
|
359 |
-
match, child_scope = super().matches(scope)
|
360 |
-
if match != Match.NONE:
|
361 |
-
child_scope["route"] = self
|
362 |
-
return match, child_scope
|
363 |
-
|
364 |
-
|
365 |
-
class APIRoute(routing.Route):
|
366 |
-
def __init__(
|
367 |
-
self,
|
368 |
-
path: str,
|
369 |
-
endpoint: Callable[..., Any],
|
370 |
-
*,
|
371 |
-
response_model: Any = Default(None),
|
372 |
-
status_code: Optional[int] = None,
|
373 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
374 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
375 |
-
summary: Optional[str] = None,
|
376 |
-
description: Optional[str] = None,
|
377 |
-
response_description: str = "Successful Response",
|
378 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
379 |
-
deprecated: Optional[bool] = None,
|
380 |
-
name: Optional[str] = None,
|
381 |
-
methods: Optional[Union[Set[str], List[str]]] = None,
|
382 |
-
operation_id: Optional[str] = None,
|
383 |
-
response_model_include: Optional[IncEx] = None,
|
384 |
-
response_model_exclude: Optional[IncEx] = None,
|
385 |
-
response_model_by_alias: bool = True,
|
386 |
-
response_model_exclude_unset: bool = False,
|
387 |
-
response_model_exclude_defaults: bool = False,
|
388 |
-
response_model_exclude_none: bool = False,
|
389 |
-
include_in_schema: bool = True,
|
390 |
-
response_class: Union[Type[Response], DefaultPlaceholder] = Default(
|
391 |
-
JSONResponse
|
392 |
-
),
|
393 |
-
dependency_overrides_provider: Optional[Any] = None,
|
394 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
395 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
396 |
-
generate_unique_id_function: Union[
|
397 |
-
Callable[["APIRoute"], str], DefaultPlaceholder
|
398 |
-
] = Default(generate_unique_id),
|
399 |
-
) -> None:
|
400 |
-
self.path = path
|
401 |
-
self.endpoint = endpoint
|
402 |
-
if isinstance(response_model, DefaultPlaceholder):
|
403 |
-
return_annotation = get_typed_return_annotation(endpoint)
|
404 |
-
if lenient_issubclass(return_annotation, Response):
|
405 |
-
response_model = None
|
406 |
-
else:
|
407 |
-
response_model = return_annotation
|
408 |
-
self.response_model = response_model
|
409 |
-
self.summary = summary
|
410 |
-
self.response_description = response_description
|
411 |
-
self.deprecated = deprecated
|
412 |
-
self.operation_id = operation_id
|
413 |
-
self.response_model_include = response_model_include
|
414 |
-
self.response_model_exclude = response_model_exclude
|
415 |
-
self.response_model_by_alias = response_model_by_alias
|
416 |
-
self.response_model_exclude_unset = response_model_exclude_unset
|
417 |
-
self.response_model_exclude_defaults = response_model_exclude_defaults
|
418 |
-
self.response_model_exclude_none = response_model_exclude_none
|
419 |
-
self.include_in_schema = include_in_schema
|
420 |
-
self.response_class = response_class
|
421 |
-
self.dependency_overrides_provider = dependency_overrides_provider
|
422 |
-
self.callbacks = callbacks
|
423 |
-
self.openapi_extra = openapi_extra
|
424 |
-
self.generate_unique_id_function = generate_unique_id_function
|
425 |
-
self.tags = tags or []
|
426 |
-
self.responses = responses or {}
|
427 |
-
self.name = get_name(endpoint) if name is None else name
|
428 |
-
self.path_regex, self.path_format, self.param_convertors = compile_path(path)
|
429 |
-
if methods is None:
|
430 |
-
methods = ["GET"]
|
431 |
-
self.methods: Set[str] = {method.upper() for method in methods}
|
432 |
-
if isinstance(generate_unique_id_function, DefaultPlaceholder):
|
433 |
-
current_generate_unique_id: Callable[
|
434 |
-
["APIRoute"], str
|
435 |
-
] = generate_unique_id_function.value
|
436 |
-
else:
|
437 |
-
current_generate_unique_id = generate_unique_id_function
|
438 |
-
self.unique_id = self.operation_id or current_generate_unique_id(self)
|
439 |
-
# normalize enums e.g. http.HTTPStatus
|
440 |
-
if isinstance(status_code, IntEnum):
|
441 |
-
status_code = int(status_code)
|
442 |
-
self.status_code = status_code
|
443 |
-
if self.response_model:
|
444 |
-
assert is_body_allowed_for_status_code(
|
445 |
-
status_code
|
446 |
-
), f"Status code {status_code} must not have a response body"
|
447 |
-
response_name = "Response_" + self.unique_id
|
448 |
-
self.response_field = create_response_field(
|
449 |
-
name=response_name,
|
450 |
-
type_=self.response_model,
|
451 |
-
# TODO: This should actually set mode='serialization', just, that changes the schemas
|
452 |
-
# mode="serialization",
|
453 |
-
mode="validation",
|
454 |
-
)
|
455 |
-
# Create a clone of the field, so that a Pydantic submodel is not returned
|
456 |
-
# as is just because it's an instance of a subclass of a more limited class
|
457 |
-
# e.g. UserInDB (containing hashed_password) could be a subclass of User
|
458 |
-
# that doesn't have the hashed_password. But because it's a subclass, it
|
459 |
-
# would pass the validation and be returned as is.
|
460 |
-
# By being a new field, no inheritance will be passed as is. A new model
|
461 |
-
# will be always created.
|
462 |
-
# TODO: remove when deprecating Pydantic v1
|
463 |
-
self.secure_cloned_response_field: Optional[
|
464 |
-
ModelField
|
465 |
-
] = create_cloned_field(self.response_field)
|
466 |
-
else:
|
467 |
-
self.response_field = None # type: ignore
|
468 |
-
self.secure_cloned_response_field = None
|
469 |
-
self.dependencies = list(dependencies or [])
|
470 |
-
self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "")
|
471 |
-
# if a "form feed" character (page break) is found in the description text,
|
472 |
-
# truncate description text to the content preceding the first "form feed"
|
473 |
-
self.description = self.description.split("\f")[0].strip()
|
474 |
-
response_fields = {}
|
475 |
-
for additional_status_code, response in self.responses.items():
|
476 |
-
assert isinstance(response, dict), "An additional response must be a dict"
|
477 |
-
model = response.get("model")
|
478 |
-
if model:
|
479 |
-
assert is_body_allowed_for_status_code(
|
480 |
-
additional_status_code
|
481 |
-
), f"Status code {additional_status_code} must not have a response body"
|
482 |
-
response_name = f"Response_{additional_status_code}_{self.unique_id}"
|
483 |
-
response_field = create_response_field(name=response_name, type_=model)
|
484 |
-
response_fields[additional_status_code] = response_field
|
485 |
-
if response_fields:
|
486 |
-
self.response_fields: Dict[Union[int, str], ModelField] = response_fields
|
487 |
-
else:
|
488 |
-
self.response_fields = {}
|
489 |
-
|
490 |
-
assert callable(endpoint), "An endpoint must be a callable"
|
491 |
-
self.dependant = get_dependant(path=self.path_format, call=self.endpoint)
|
492 |
-
for depends in self.dependencies[::-1]:
|
493 |
-
self.dependant.dependencies.insert(
|
494 |
-
0,
|
495 |
-
get_parameterless_sub_dependant(depends=depends, path=self.path_format),
|
496 |
-
)
|
497 |
-
self.body_field = get_body_field(dependant=self.dependant, name=self.unique_id)
|
498 |
-
self.app = request_response(self.get_route_handler())
|
499 |
-
|
500 |
-
def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
|
501 |
-
return get_request_handler(
|
502 |
-
dependant=self.dependant,
|
503 |
-
body_field=self.body_field,
|
504 |
-
status_code=self.status_code,
|
505 |
-
response_class=self.response_class,
|
506 |
-
response_field=self.secure_cloned_response_field,
|
507 |
-
response_model_include=self.response_model_include,
|
508 |
-
response_model_exclude=self.response_model_exclude,
|
509 |
-
response_model_by_alias=self.response_model_by_alias,
|
510 |
-
response_model_exclude_unset=self.response_model_exclude_unset,
|
511 |
-
response_model_exclude_defaults=self.response_model_exclude_defaults,
|
512 |
-
response_model_exclude_none=self.response_model_exclude_none,
|
513 |
-
dependency_overrides_provider=self.dependency_overrides_provider,
|
514 |
-
)
|
515 |
-
|
516 |
-
def matches(self, scope: Scope) -> Tuple[Match, Scope]:
|
517 |
-
match, child_scope = super().matches(scope)
|
518 |
-
if match != Match.NONE:
|
519 |
-
child_scope["route"] = self
|
520 |
-
return match, child_scope
|
521 |
-
|
522 |
-
|
523 |
-
class APIRouter(routing.Router):
|
524 |
-
def __init__(
|
525 |
-
self,
|
526 |
-
*,
|
527 |
-
prefix: str = "",
|
528 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
529 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
530 |
-
default_response_class: Type[Response] = Default(JSONResponse),
|
531 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
532 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
533 |
-
routes: Optional[List[routing.BaseRoute]] = None,
|
534 |
-
redirect_slashes: bool = True,
|
535 |
-
default: Optional[ASGIApp] = None,
|
536 |
-
dependency_overrides_provider: Optional[Any] = None,
|
537 |
-
route_class: Type[APIRoute] = APIRoute,
|
538 |
-
on_startup: Optional[Sequence[Callable[[], Any]]] = None,
|
539 |
-
on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,
|
540 |
-
# the generic to Lifespan[AppType] is the type of the top level application
|
541 |
-
# which the router cannot know statically, so we use typing.Any
|
542 |
-
lifespan: Optional[Lifespan[Any]] = None,
|
543 |
-
deprecated: Optional[bool] = None,
|
544 |
-
include_in_schema: bool = True,
|
545 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
546 |
-
generate_unique_id
|
547 |
-
),
|
548 |
-
) -> None:
|
549 |
-
super().__init__(
|
550 |
-
routes=routes,
|
551 |
-
redirect_slashes=redirect_slashes,
|
552 |
-
default=default,
|
553 |
-
on_startup=on_startup,
|
554 |
-
on_shutdown=on_shutdown,
|
555 |
-
lifespan=lifespan,
|
556 |
-
)
|
557 |
-
if prefix:
|
558 |
-
assert prefix.startswith("/"), "A path prefix must start with '/'"
|
559 |
-
assert not prefix.endswith(
|
560 |
-
"/"
|
561 |
-
), "A path prefix must not end with '/', as the routes will start with '/'"
|
562 |
-
self.prefix = prefix
|
563 |
-
self.tags: List[Union[str, Enum]] = tags or []
|
564 |
-
self.dependencies = list(dependencies or [])
|
565 |
-
self.deprecated = deprecated
|
566 |
-
self.include_in_schema = include_in_schema
|
567 |
-
self.responses = responses or {}
|
568 |
-
self.callbacks = callbacks or []
|
569 |
-
self.dependency_overrides_provider = dependency_overrides_provider
|
570 |
-
self.route_class = route_class
|
571 |
-
self.default_response_class = default_response_class
|
572 |
-
self.generate_unique_id_function = generate_unique_id_function
|
573 |
-
|
574 |
-
def route(
|
575 |
-
self,
|
576 |
-
path: str,
|
577 |
-
methods: Optional[List[str]] = None,
|
578 |
-
name: Optional[str] = None,
|
579 |
-
include_in_schema: bool = True,
|
580 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
581 |
-
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
582 |
-
self.add_route(
|
583 |
-
path,
|
584 |
-
func,
|
585 |
-
methods=methods,
|
586 |
-
name=name,
|
587 |
-
include_in_schema=include_in_schema,
|
588 |
-
)
|
589 |
-
return func
|
590 |
-
|
591 |
-
return decorator
|
592 |
-
|
593 |
-
def add_api_route(
|
594 |
-
self,
|
595 |
-
path: str,
|
596 |
-
endpoint: Callable[..., Any],
|
597 |
-
*,
|
598 |
-
response_model: Any = Default(None),
|
599 |
-
status_code: Optional[int] = None,
|
600 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
601 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
602 |
-
summary: Optional[str] = None,
|
603 |
-
description: Optional[str] = None,
|
604 |
-
response_description: str = "Successful Response",
|
605 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
606 |
-
deprecated: Optional[bool] = None,
|
607 |
-
methods: Optional[Union[Set[str], List[str]]] = None,
|
608 |
-
operation_id: Optional[str] = None,
|
609 |
-
response_model_include: Optional[IncEx] = None,
|
610 |
-
response_model_exclude: Optional[IncEx] = None,
|
611 |
-
response_model_by_alias: bool = True,
|
612 |
-
response_model_exclude_unset: bool = False,
|
613 |
-
response_model_exclude_defaults: bool = False,
|
614 |
-
response_model_exclude_none: bool = False,
|
615 |
-
include_in_schema: bool = True,
|
616 |
-
response_class: Union[Type[Response], DefaultPlaceholder] = Default(
|
617 |
-
JSONResponse
|
618 |
-
),
|
619 |
-
name: Optional[str] = None,
|
620 |
-
route_class_override: Optional[Type[APIRoute]] = None,
|
621 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
622 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
623 |
-
generate_unique_id_function: Union[
|
624 |
-
Callable[[APIRoute], str], DefaultPlaceholder
|
625 |
-
] = Default(generate_unique_id),
|
626 |
-
) -> None:
|
627 |
-
route_class = route_class_override or self.route_class
|
628 |
-
responses = responses or {}
|
629 |
-
combined_responses = {**self.responses, **responses}
|
630 |
-
current_response_class = get_value_or_default(
|
631 |
-
response_class, self.default_response_class
|
632 |
-
)
|
633 |
-
current_tags = self.tags.copy()
|
634 |
-
if tags:
|
635 |
-
current_tags.extend(tags)
|
636 |
-
current_dependencies = self.dependencies.copy()
|
637 |
-
if dependencies:
|
638 |
-
current_dependencies.extend(dependencies)
|
639 |
-
current_callbacks = self.callbacks.copy()
|
640 |
-
if callbacks:
|
641 |
-
current_callbacks.extend(callbacks)
|
642 |
-
current_generate_unique_id = get_value_or_default(
|
643 |
-
generate_unique_id_function, self.generate_unique_id_function
|
644 |
-
)
|
645 |
-
route = route_class(
|
646 |
-
self.prefix + path,
|
647 |
-
endpoint=endpoint,
|
648 |
-
response_model=response_model,
|
649 |
-
status_code=status_code,
|
650 |
-
tags=current_tags,
|
651 |
-
dependencies=current_dependencies,
|
652 |
-
summary=summary,
|
653 |
-
description=description,
|
654 |
-
response_description=response_description,
|
655 |
-
responses=combined_responses,
|
656 |
-
deprecated=deprecated or self.deprecated,
|
657 |
-
methods=methods,
|
658 |
-
operation_id=operation_id,
|
659 |
-
response_model_include=response_model_include,
|
660 |
-
response_model_exclude=response_model_exclude,
|
661 |
-
response_model_by_alias=response_model_by_alias,
|
662 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
663 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
664 |
-
response_model_exclude_none=response_model_exclude_none,
|
665 |
-
include_in_schema=include_in_schema and self.include_in_schema,
|
666 |
-
response_class=current_response_class,
|
667 |
-
name=name,
|
668 |
-
dependency_overrides_provider=self.dependency_overrides_provider,
|
669 |
-
callbacks=current_callbacks,
|
670 |
-
openapi_extra=openapi_extra,
|
671 |
-
generate_unique_id_function=current_generate_unique_id,
|
672 |
-
)
|
673 |
-
self.routes.append(route)
|
674 |
-
|
675 |
-
def api_route(
|
676 |
-
self,
|
677 |
-
path: str,
|
678 |
-
*,
|
679 |
-
response_model: Any = Default(None),
|
680 |
-
status_code: Optional[int] = None,
|
681 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
682 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
683 |
-
summary: Optional[str] = None,
|
684 |
-
description: Optional[str] = None,
|
685 |
-
response_description: str = "Successful Response",
|
686 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
687 |
-
deprecated: Optional[bool] = None,
|
688 |
-
methods: Optional[List[str]] = None,
|
689 |
-
operation_id: Optional[str] = None,
|
690 |
-
response_model_include: Optional[IncEx] = None,
|
691 |
-
response_model_exclude: Optional[IncEx] = None,
|
692 |
-
response_model_by_alias: bool = True,
|
693 |
-
response_model_exclude_unset: bool = False,
|
694 |
-
response_model_exclude_defaults: bool = False,
|
695 |
-
response_model_exclude_none: bool = False,
|
696 |
-
include_in_schema: bool = True,
|
697 |
-
response_class: Type[Response] = Default(JSONResponse),
|
698 |
-
name: Optional[str] = None,
|
699 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
700 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
701 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
702 |
-
generate_unique_id
|
703 |
-
),
|
704 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
705 |
-
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
706 |
-
self.add_api_route(
|
707 |
-
path,
|
708 |
-
func,
|
709 |
-
response_model=response_model,
|
710 |
-
status_code=status_code,
|
711 |
-
tags=tags,
|
712 |
-
dependencies=dependencies,
|
713 |
-
summary=summary,
|
714 |
-
description=description,
|
715 |
-
response_description=response_description,
|
716 |
-
responses=responses,
|
717 |
-
deprecated=deprecated,
|
718 |
-
methods=methods,
|
719 |
-
operation_id=operation_id,
|
720 |
-
response_model_include=response_model_include,
|
721 |
-
response_model_exclude=response_model_exclude,
|
722 |
-
response_model_by_alias=response_model_by_alias,
|
723 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
724 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
725 |
-
response_model_exclude_none=response_model_exclude_none,
|
726 |
-
include_in_schema=include_in_schema,
|
727 |
-
response_class=response_class,
|
728 |
-
name=name,
|
729 |
-
callbacks=callbacks,
|
730 |
-
openapi_extra=openapi_extra,
|
731 |
-
generate_unique_id_function=generate_unique_id_function,
|
732 |
-
)
|
733 |
-
return func
|
734 |
-
|
735 |
-
return decorator
|
736 |
-
|
737 |
-
def add_api_websocket_route(
|
738 |
-
self,
|
739 |
-
path: str,
|
740 |
-
endpoint: Callable[..., Any],
|
741 |
-
name: Optional[str] = None,
|
742 |
-
*,
|
743 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
744 |
-
) -> None:
|
745 |
-
current_dependencies = self.dependencies.copy()
|
746 |
-
if dependencies:
|
747 |
-
current_dependencies.extend(dependencies)
|
748 |
-
|
749 |
-
route = APIWebSocketRoute(
|
750 |
-
self.prefix + path,
|
751 |
-
endpoint=endpoint,
|
752 |
-
name=name,
|
753 |
-
dependencies=current_dependencies,
|
754 |
-
dependency_overrides_provider=self.dependency_overrides_provider,
|
755 |
-
)
|
756 |
-
self.routes.append(route)
|
757 |
-
|
758 |
-
def websocket(
|
759 |
-
self,
|
760 |
-
path: str,
|
761 |
-
name: Optional[str] = None,
|
762 |
-
*,
|
763 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
764 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
765 |
-
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
766 |
-
self.add_api_websocket_route(
|
767 |
-
path, func, name=name, dependencies=dependencies
|
768 |
-
)
|
769 |
-
return func
|
770 |
-
|
771 |
-
return decorator
|
772 |
-
|
773 |
-
def websocket_route(
|
774 |
-
self, path: str, name: Union[str, None] = None
|
775 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
776 |
-
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
777 |
-
self.add_websocket_route(path, func, name=name)
|
778 |
-
return func
|
779 |
-
|
780 |
-
return decorator
|
781 |
-
|
782 |
-
def include_router(
|
783 |
-
self,
|
784 |
-
router: "APIRouter",
|
785 |
-
*,
|
786 |
-
prefix: str = "",
|
787 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
788 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
789 |
-
default_response_class: Type[Response] = Default(JSONResponse),
|
790 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
791 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
792 |
-
deprecated: Optional[bool] = None,
|
793 |
-
include_in_schema: bool = True,
|
794 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
795 |
-
generate_unique_id
|
796 |
-
),
|
797 |
-
) -> None:
|
798 |
-
if prefix:
|
799 |
-
assert prefix.startswith("/"), "A path prefix must start with '/'"
|
800 |
-
assert not prefix.endswith(
|
801 |
-
"/"
|
802 |
-
), "A path prefix must not end with '/', as the routes will start with '/'"
|
803 |
-
else:
|
804 |
-
for r in router.routes:
|
805 |
-
path = getattr(r, "path") # noqa: B009
|
806 |
-
name = getattr(r, "name", "unknown")
|
807 |
-
if path is not None and not path:
|
808 |
-
raise FastAPIError(
|
809 |
-
f"Prefix and path cannot be both empty (path operation: {name})"
|
810 |
-
)
|
811 |
-
if responses is None:
|
812 |
-
responses = {}
|
813 |
-
for route in router.routes:
|
814 |
-
if isinstance(route, APIRoute):
|
815 |
-
combined_responses = {**responses, **route.responses}
|
816 |
-
use_response_class = get_value_or_default(
|
817 |
-
route.response_class,
|
818 |
-
router.default_response_class,
|
819 |
-
default_response_class,
|
820 |
-
self.default_response_class,
|
821 |
-
)
|
822 |
-
current_tags = []
|
823 |
-
if tags:
|
824 |
-
current_tags.extend(tags)
|
825 |
-
if route.tags:
|
826 |
-
current_tags.extend(route.tags)
|
827 |
-
current_dependencies: List[params.Depends] = []
|
828 |
-
if dependencies:
|
829 |
-
current_dependencies.extend(dependencies)
|
830 |
-
if route.dependencies:
|
831 |
-
current_dependencies.extend(route.dependencies)
|
832 |
-
current_callbacks = []
|
833 |
-
if callbacks:
|
834 |
-
current_callbacks.extend(callbacks)
|
835 |
-
if route.callbacks:
|
836 |
-
current_callbacks.extend(route.callbacks)
|
837 |
-
current_generate_unique_id = get_value_or_default(
|
838 |
-
route.generate_unique_id_function,
|
839 |
-
router.generate_unique_id_function,
|
840 |
-
generate_unique_id_function,
|
841 |
-
self.generate_unique_id_function,
|
842 |
-
)
|
843 |
-
self.add_api_route(
|
844 |
-
prefix + route.path,
|
845 |
-
route.endpoint,
|
846 |
-
response_model=route.response_model,
|
847 |
-
status_code=route.status_code,
|
848 |
-
tags=current_tags,
|
849 |
-
dependencies=current_dependencies,
|
850 |
-
summary=route.summary,
|
851 |
-
description=route.description,
|
852 |
-
response_description=route.response_description,
|
853 |
-
responses=combined_responses,
|
854 |
-
deprecated=route.deprecated or deprecated or self.deprecated,
|
855 |
-
methods=route.methods,
|
856 |
-
operation_id=route.operation_id,
|
857 |
-
response_model_include=route.response_model_include,
|
858 |
-
response_model_exclude=route.response_model_exclude,
|
859 |
-
response_model_by_alias=route.response_model_by_alias,
|
860 |
-
response_model_exclude_unset=route.response_model_exclude_unset,
|
861 |
-
response_model_exclude_defaults=route.response_model_exclude_defaults,
|
862 |
-
response_model_exclude_none=route.response_model_exclude_none,
|
863 |
-
include_in_schema=route.include_in_schema
|
864 |
-
and self.include_in_schema
|
865 |
-
and include_in_schema,
|
866 |
-
response_class=use_response_class,
|
867 |
-
name=route.name,
|
868 |
-
route_class_override=type(route),
|
869 |
-
callbacks=current_callbacks,
|
870 |
-
openapi_extra=route.openapi_extra,
|
871 |
-
generate_unique_id_function=current_generate_unique_id,
|
872 |
-
)
|
873 |
-
elif isinstance(route, routing.Route):
|
874 |
-
methods = list(route.methods or [])
|
875 |
-
self.add_route(
|
876 |
-
prefix + route.path,
|
877 |
-
route.endpoint,
|
878 |
-
methods=methods,
|
879 |
-
include_in_schema=route.include_in_schema,
|
880 |
-
name=route.name,
|
881 |
-
)
|
882 |
-
elif isinstance(route, APIWebSocketRoute):
|
883 |
-
current_dependencies = []
|
884 |
-
if dependencies:
|
885 |
-
current_dependencies.extend(dependencies)
|
886 |
-
if route.dependencies:
|
887 |
-
current_dependencies.extend(route.dependencies)
|
888 |
-
self.add_api_websocket_route(
|
889 |
-
prefix + route.path,
|
890 |
-
route.endpoint,
|
891 |
-
dependencies=current_dependencies,
|
892 |
-
name=route.name,
|
893 |
-
)
|
894 |
-
elif isinstance(route, routing.WebSocketRoute):
|
895 |
-
self.add_websocket_route(
|
896 |
-
prefix + route.path, route.endpoint, name=route.name
|
897 |
-
)
|
898 |
-
for handler in router.on_startup:
|
899 |
-
self.add_event_handler("startup", handler)
|
900 |
-
for handler in router.on_shutdown:
|
901 |
-
self.add_event_handler("shutdown", handler)
|
902 |
-
|
903 |
-
def get(
|
904 |
-
self,
|
905 |
-
path: str,
|
906 |
-
*,
|
907 |
-
response_model: Any = Default(None),
|
908 |
-
status_code: Optional[int] = None,
|
909 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
910 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
911 |
-
summary: Optional[str] = None,
|
912 |
-
description: Optional[str] = None,
|
913 |
-
response_description: str = "Successful Response",
|
914 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
915 |
-
deprecated: Optional[bool] = None,
|
916 |
-
operation_id: Optional[str] = None,
|
917 |
-
response_model_include: Optional[IncEx] = None,
|
918 |
-
response_model_exclude: Optional[IncEx] = None,
|
919 |
-
response_model_by_alias: bool = True,
|
920 |
-
response_model_exclude_unset: bool = False,
|
921 |
-
response_model_exclude_defaults: bool = False,
|
922 |
-
response_model_exclude_none: bool = False,
|
923 |
-
include_in_schema: bool = True,
|
924 |
-
response_class: Type[Response] = Default(JSONResponse),
|
925 |
-
name: Optional[str] = None,
|
926 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
927 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
928 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
929 |
-
generate_unique_id
|
930 |
-
),
|
931 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
932 |
-
return self.api_route(
|
933 |
-
path=path,
|
934 |
-
response_model=response_model,
|
935 |
-
status_code=status_code,
|
936 |
-
tags=tags,
|
937 |
-
dependencies=dependencies,
|
938 |
-
summary=summary,
|
939 |
-
description=description,
|
940 |
-
response_description=response_description,
|
941 |
-
responses=responses,
|
942 |
-
deprecated=deprecated,
|
943 |
-
methods=["GET"],
|
944 |
-
operation_id=operation_id,
|
945 |
-
response_model_include=response_model_include,
|
946 |
-
response_model_exclude=response_model_exclude,
|
947 |
-
response_model_by_alias=response_model_by_alias,
|
948 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
949 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
950 |
-
response_model_exclude_none=response_model_exclude_none,
|
951 |
-
include_in_schema=include_in_schema,
|
952 |
-
response_class=response_class,
|
953 |
-
name=name,
|
954 |
-
callbacks=callbacks,
|
955 |
-
openapi_extra=openapi_extra,
|
956 |
-
generate_unique_id_function=generate_unique_id_function,
|
957 |
-
)
|
958 |
-
|
959 |
-
def put(
|
960 |
-
self,
|
961 |
-
path: str,
|
962 |
-
*,
|
963 |
-
response_model: Any = Default(None),
|
964 |
-
status_code: Optional[int] = None,
|
965 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
966 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
967 |
-
summary: Optional[str] = None,
|
968 |
-
description: Optional[str] = None,
|
969 |
-
response_description: str = "Successful Response",
|
970 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
971 |
-
deprecated: Optional[bool] = None,
|
972 |
-
operation_id: Optional[str] = None,
|
973 |
-
response_model_include: Optional[IncEx] = None,
|
974 |
-
response_model_exclude: Optional[IncEx] = None,
|
975 |
-
response_model_by_alias: bool = True,
|
976 |
-
response_model_exclude_unset: bool = False,
|
977 |
-
response_model_exclude_defaults: bool = False,
|
978 |
-
response_model_exclude_none: bool = False,
|
979 |
-
include_in_schema: bool = True,
|
980 |
-
response_class: Type[Response] = Default(JSONResponse),
|
981 |
-
name: Optional[str] = None,
|
982 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
983 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
984 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
985 |
-
generate_unique_id
|
986 |
-
),
|
987 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
988 |
-
return self.api_route(
|
989 |
-
path=path,
|
990 |
-
response_model=response_model,
|
991 |
-
status_code=status_code,
|
992 |
-
tags=tags,
|
993 |
-
dependencies=dependencies,
|
994 |
-
summary=summary,
|
995 |
-
description=description,
|
996 |
-
response_description=response_description,
|
997 |
-
responses=responses,
|
998 |
-
deprecated=deprecated,
|
999 |
-
methods=["PUT"],
|
1000 |
-
operation_id=operation_id,
|
1001 |
-
response_model_include=response_model_include,
|
1002 |
-
response_model_exclude=response_model_exclude,
|
1003 |
-
response_model_by_alias=response_model_by_alias,
|
1004 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
1005 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
1006 |
-
response_model_exclude_none=response_model_exclude_none,
|
1007 |
-
include_in_schema=include_in_schema,
|
1008 |
-
response_class=response_class,
|
1009 |
-
name=name,
|
1010 |
-
callbacks=callbacks,
|
1011 |
-
openapi_extra=openapi_extra,
|
1012 |
-
generate_unique_id_function=generate_unique_id_function,
|
1013 |
-
)
|
1014 |
-
|
1015 |
-
def post(
|
1016 |
-
self,
|
1017 |
-
path: str,
|
1018 |
-
*,
|
1019 |
-
response_model: Any = Default(None),
|
1020 |
-
status_code: Optional[int] = None,
|
1021 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
1022 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
1023 |
-
summary: Optional[str] = None,
|
1024 |
-
description: Optional[str] = None,
|
1025 |
-
response_description: str = "Successful Response",
|
1026 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
1027 |
-
deprecated: Optional[bool] = None,
|
1028 |
-
operation_id: Optional[str] = None,
|
1029 |
-
response_model_include: Optional[IncEx] = None,
|
1030 |
-
response_model_exclude: Optional[IncEx] = None,
|
1031 |
-
response_model_by_alias: bool = True,
|
1032 |
-
response_model_exclude_unset: bool = False,
|
1033 |
-
response_model_exclude_defaults: bool = False,
|
1034 |
-
response_model_exclude_none: bool = False,
|
1035 |
-
include_in_schema: bool = True,
|
1036 |
-
response_class: Type[Response] = Default(JSONResponse),
|
1037 |
-
name: Optional[str] = None,
|
1038 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
1039 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
1040 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
1041 |
-
generate_unique_id
|
1042 |
-
),
|
1043 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
1044 |
-
return self.api_route(
|
1045 |
-
path=path,
|
1046 |
-
response_model=response_model,
|
1047 |
-
status_code=status_code,
|
1048 |
-
tags=tags,
|
1049 |
-
dependencies=dependencies,
|
1050 |
-
summary=summary,
|
1051 |
-
description=description,
|
1052 |
-
response_description=response_description,
|
1053 |
-
responses=responses,
|
1054 |
-
deprecated=deprecated,
|
1055 |
-
methods=["POST"],
|
1056 |
-
operation_id=operation_id,
|
1057 |
-
response_model_include=response_model_include,
|
1058 |
-
response_model_exclude=response_model_exclude,
|
1059 |
-
response_model_by_alias=response_model_by_alias,
|
1060 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
1061 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
1062 |
-
response_model_exclude_none=response_model_exclude_none,
|
1063 |
-
include_in_schema=include_in_schema,
|
1064 |
-
response_class=response_class,
|
1065 |
-
name=name,
|
1066 |
-
callbacks=callbacks,
|
1067 |
-
openapi_extra=openapi_extra,
|
1068 |
-
generate_unique_id_function=generate_unique_id_function,
|
1069 |
-
)
|
1070 |
-
|
1071 |
-
def delete(
|
1072 |
-
self,
|
1073 |
-
path: str,
|
1074 |
-
*,
|
1075 |
-
response_model: Any = Default(None),
|
1076 |
-
status_code: Optional[int] = None,
|
1077 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
1078 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
1079 |
-
summary: Optional[str] = None,
|
1080 |
-
description: Optional[str] = None,
|
1081 |
-
response_description: str = "Successful Response",
|
1082 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
1083 |
-
deprecated: Optional[bool] = None,
|
1084 |
-
operation_id: Optional[str] = None,
|
1085 |
-
response_model_include: Optional[IncEx] = None,
|
1086 |
-
response_model_exclude: Optional[IncEx] = None,
|
1087 |
-
response_model_by_alias: bool = True,
|
1088 |
-
response_model_exclude_unset: bool = False,
|
1089 |
-
response_model_exclude_defaults: bool = False,
|
1090 |
-
response_model_exclude_none: bool = False,
|
1091 |
-
include_in_schema: bool = True,
|
1092 |
-
response_class: Type[Response] = Default(JSONResponse),
|
1093 |
-
name: Optional[str] = None,
|
1094 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
1095 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
1096 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
1097 |
-
generate_unique_id
|
1098 |
-
),
|
1099 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
1100 |
-
return self.api_route(
|
1101 |
-
path=path,
|
1102 |
-
response_model=response_model,
|
1103 |
-
status_code=status_code,
|
1104 |
-
tags=tags,
|
1105 |
-
dependencies=dependencies,
|
1106 |
-
summary=summary,
|
1107 |
-
description=description,
|
1108 |
-
response_description=response_description,
|
1109 |
-
responses=responses,
|
1110 |
-
deprecated=deprecated,
|
1111 |
-
methods=["DELETE"],
|
1112 |
-
operation_id=operation_id,
|
1113 |
-
response_model_include=response_model_include,
|
1114 |
-
response_model_exclude=response_model_exclude,
|
1115 |
-
response_model_by_alias=response_model_by_alias,
|
1116 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
1117 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
1118 |
-
response_model_exclude_none=response_model_exclude_none,
|
1119 |
-
include_in_schema=include_in_schema,
|
1120 |
-
response_class=response_class,
|
1121 |
-
name=name,
|
1122 |
-
callbacks=callbacks,
|
1123 |
-
openapi_extra=openapi_extra,
|
1124 |
-
generate_unique_id_function=generate_unique_id_function,
|
1125 |
-
)
|
1126 |
-
|
1127 |
-
def options(
|
1128 |
-
self,
|
1129 |
-
path: str,
|
1130 |
-
*,
|
1131 |
-
response_model: Any = Default(None),
|
1132 |
-
status_code: Optional[int] = None,
|
1133 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
1134 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
1135 |
-
summary: Optional[str] = None,
|
1136 |
-
description: Optional[str] = None,
|
1137 |
-
response_description: str = "Successful Response",
|
1138 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
1139 |
-
deprecated: Optional[bool] = None,
|
1140 |
-
operation_id: Optional[str] = None,
|
1141 |
-
response_model_include: Optional[IncEx] = None,
|
1142 |
-
response_model_exclude: Optional[IncEx] = None,
|
1143 |
-
response_model_by_alias: bool = True,
|
1144 |
-
response_model_exclude_unset: bool = False,
|
1145 |
-
response_model_exclude_defaults: bool = False,
|
1146 |
-
response_model_exclude_none: bool = False,
|
1147 |
-
include_in_schema: bool = True,
|
1148 |
-
response_class: Type[Response] = Default(JSONResponse),
|
1149 |
-
name: Optional[str] = None,
|
1150 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
1151 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
1152 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
1153 |
-
generate_unique_id
|
1154 |
-
),
|
1155 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
1156 |
-
return self.api_route(
|
1157 |
-
path=path,
|
1158 |
-
response_model=response_model,
|
1159 |
-
status_code=status_code,
|
1160 |
-
tags=tags,
|
1161 |
-
dependencies=dependencies,
|
1162 |
-
summary=summary,
|
1163 |
-
description=description,
|
1164 |
-
response_description=response_description,
|
1165 |
-
responses=responses,
|
1166 |
-
deprecated=deprecated,
|
1167 |
-
methods=["OPTIONS"],
|
1168 |
-
operation_id=operation_id,
|
1169 |
-
response_model_include=response_model_include,
|
1170 |
-
response_model_exclude=response_model_exclude,
|
1171 |
-
response_model_by_alias=response_model_by_alias,
|
1172 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
1173 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
1174 |
-
response_model_exclude_none=response_model_exclude_none,
|
1175 |
-
include_in_schema=include_in_schema,
|
1176 |
-
response_class=response_class,
|
1177 |
-
name=name,
|
1178 |
-
callbacks=callbacks,
|
1179 |
-
openapi_extra=openapi_extra,
|
1180 |
-
generate_unique_id_function=generate_unique_id_function,
|
1181 |
-
)
|
1182 |
-
|
1183 |
-
def head(
|
1184 |
-
self,
|
1185 |
-
path: str,
|
1186 |
-
*,
|
1187 |
-
response_model: Any = Default(None),
|
1188 |
-
status_code: Optional[int] = None,
|
1189 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
1190 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
1191 |
-
summary: Optional[str] = None,
|
1192 |
-
description: Optional[str] = None,
|
1193 |
-
response_description: str = "Successful Response",
|
1194 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
1195 |
-
deprecated: Optional[bool] = None,
|
1196 |
-
operation_id: Optional[str] = None,
|
1197 |
-
response_model_include: Optional[IncEx] = None,
|
1198 |
-
response_model_exclude: Optional[IncEx] = None,
|
1199 |
-
response_model_by_alias: bool = True,
|
1200 |
-
response_model_exclude_unset: bool = False,
|
1201 |
-
response_model_exclude_defaults: bool = False,
|
1202 |
-
response_model_exclude_none: bool = False,
|
1203 |
-
include_in_schema: bool = True,
|
1204 |
-
response_class: Type[Response] = Default(JSONResponse),
|
1205 |
-
name: Optional[str] = None,
|
1206 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
1207 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
1208 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
1209 |
-
generate_unique_id
|
1210 |
-
),
|
1211 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
1212 |
-
return self.api_route(
|
1213 |
-
path=path,
|
1214 |
-
response_model=response_model,
|
1215 |
-
status_code=status_code,
|
1216 |
-
tags=tags,
|
1217 |
-
dependencies=dependencies,
|
1218 |
-
summary=summary,
|
1219 |
-
description=description,
|
1220 |
-
response_description=response_description,
|
1221 |
-
responses=responses,
|
1222 |
-
deprecated=deprecated,
|
1223 |
-
methods=["HEAD"],
|
1224 |
-
operation_id=operation_id,
|
1225 |
-
response_model_include=response_model_include,
|
1226 |
-
response_model_exclude=response_model_exclude,
|
1227 |
-
response_model_by_alias=response_model_by_alias,
|
1228 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
1229 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
1230 |
-
response_model_exclude_none=response_model_exclude_none,
|
1231 |
-
include_in_schema=include_in_schema,
|
1232 |
-
response_class=response_class,
|
1233 |
-
name=name,
|
1234 |
-
callbacks=callbacks,
|
1235 |
-
openapi_extra=openapi_extra,
|
1236 |
-
generate_unique_id_function=generate_unique_id_function,
|
1237 |
-
)
|
1238 |
-
|
1239 |
-
def patch(
|
1240 |
-
self,
|
1241 |
-
path: str,
|
1242 |
-
*,
|
1243 |
-
response_model: Any = Default(None),
|
1244 |
-
status_code: Optional[int] = None,
|
1245 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
1246 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
1247 |
-
summary: Optional[str] = None,
|
1248 |
-
description: Optional[str] = None,
|
1249 |
-
response_description: str = "Successful Response",
|
1250 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
1251 |
-
deprecated: Optional[bool] = None,
|
1252 |
-
operation_id: Optional[str] = None,
|
1253 |
-
response_model_include: Optional[IncEx] = None,
|
1254 |
-
response_model_exclude: Optional[IncEx] = None,
|
1255 |
-
response_model_by_alias: bool = True,
|
1256 |
-
response_model_exclude_unset: bool = False,
|
1257 |
-
response_model_exclude_defaults: bool = False,
|
1258 |
-
response_model_exclude_none: bool = False,
|
1259 |
-
include_in_schema: bool = True,
|
1260 |
-
response_class: Type[Response] = Default(JSONResponse),
|
1261 |
-
name: Optional[str] = None,
|
1262 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
1263 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
1264 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
1265 |
-
generate_unique_id
|
1266 |
-
),
|
1267 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
1268 |
-
return self.api_route(
|
1269 |
-
path=path,
|
1270 |
-
response_model=response_model,
|
1271 |
-
status_code=status_code,
|
1272 |
-
tags=tags,
|
1273 |
-
dependencies=dependencies,
|
1274 |
-
summary=summary,
|
1275 |
-
description=description,
|
1276 |
-
response_description=response_description,
|
1277 |
-
responses=responses,
|
1278 |
-
deprecated=deprecated,
|
1279 |
-
methods=["PATCH"],
|
1280 |
-
operation_id=operation_id,
|
1281 |
-
response_model_include=response_model_include,
|
1282 |
-
response_model_exclude=response_model_exclude,
|
1283 |
-
response_model_by_alias=response_model_by_alias,
|
1284 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
1285 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
1286 |
-
response_model_exclude_none=response_model_exclude_none,
|
1287 |
-
include_in_schema=include_in_schema,
|
1288 |
-
response_class=response_class,
|
1289 |
-
name=name,
|
1290 |
-
callbacks=callbacks,
|
1291 |
-
openapi_extra=openapi_extra,
|
1292 |
-
generate_unique_id_function=generate_unique_id_function,
|
1293 |
-
)
|
1294 |
-
|
1295 |
-
def trace(
|
1296 |
-
self,
|
1297 |
-
path: str,
|
1298 |
-
*,
|
1299 |
-
response_model: Any = Default(None),
|
1300 |
-
status_code: Optional[int] = None,
|
1301 |
-
tags: Optional[List[Union[str, Enum]]] = None,
|
1302 |
-
dependencies: Optional[Sequence[params.Depends]] = None,
|
1303 |
-
summary: Optional[str] = None,
|
1304 |
-
description: Optional[str] = None,
|
1305 |
-
response_description: str = "Successful Response",
|
1306 |
-
responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
|
1307 |
-
deprecated: Optional[bool] = None,
|
1308 |
-
operation_id: Optional[str] = None,
|
1309 |
-
response_model_include: Optional[IncEx] = None,
|
1310 |
-
response_model_exclude: Optional[IncEx] = None,
|
1311 |
-
response_model_by_alias: bool = True,
|
1312 |
-
response_model_exclude_unset: bool = False,
|
1313 |
-
response_model_exclude_defaults: bool = False,
|
1314 |
-
response_model_exclude_none: bool = False,
|
1315 |
-
include_in_schema: bool = True,
|
1316 |
-
response_class: Type[Response] = Default(JSONResponse),
|
1317 |
-
name: Optional[str] = None,
|
1318 |
-
callbacks: Optional[List[BaseRoute]] = None,
|
1319 |
-
openapi_extra: Optional[Dict[str, Any]] = None,
|
1320 |
-
generate_unique_id_function: Callable[[APIRoute], str] = Default(
|
1321 |
-
generate_unique_id
|
1322 |
-
),
|
1323 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
1324 |
-
return self.api_route(
|
1325 |
-
path=path,
|
1326 |
-
response_model=response_model,
|
1327 |
-
status_code=status_code,
|
1328 |
-
tags=tags,
|
1329 |
-
dependencies=dependencies,
|
1330 |
-
summary=summary,
|
1331 |
-
description=description,
|
1332 |
-
response_description=response_description,
|
1333 |
-
responses=responses,
|
1334 |
-
deprecated=deprecated,
|
1335 |
-
methods=["TRACE"],
|
1336 |
-
operation_id=operation_id,
|
1337 |
-
response_model_include=response_model_include,
|
1338 |
-
response_model_exclude=response_model_exclude,
|
1339 |
-
response_model_by_alias=response_model_by_alias,
|
1340 |
-
response_model_exclude_unset=response_model_exclude_unset,
|
1341 |
-
response_model_exclude_defaults=response_model_exclude_defaults,
|
1342 |
-
response_model_exclude_none=response_model_exclude_none,
|
1343 |
-
include_in_schema=include_in_schema,
|
1344 |
-
response_class=response_class,
|
1345 |
-
name=name,
|
1346 |
-
callbacks=callbacks,
|
1347 |
-
openapi_extra=openapi_extra,
|
1348 |
-
generate_unique_id_function=generate_unique_id_function,
|
1349 |
-
)
|
1350 |
-
|
1351 |
-
def on_event(
|
1352 |
-
self, event_type: str
|
1353 |
-
) -> Callable[[DecoratedCallable], DecoratedCallable]:
|
1354 |
-
def decorator(func: DecoratedCallable) -> DecoratedCallable:
|
1355 |
-
self.add_event_handler(event_type, func)
|
1356 |
-
return func
|
1357 |
-
|
1358 |
-
return decorator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/cu2qu/__main__.py
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
import sys
|
2 |
-
from .cli import main
|
3 |
-
|
4 |
-
|
5 |
-
if __name__ == "__main__":
|
6 |
-
sys.exit(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/routes.py
DELETED
@@ -1,827 +0,0 @@
|
|
1 |
-
"""Implements a FastAPI server to run the gradio interface. Note that some types in this
|
2 |
-
module use the Optional/Union notation so that they work correctly with pydantic."""
|
3 |
-
|
4 |
-
from __future__ import annotations
|
5 |
-
|
6 |
-
import asyncio
|
7 |
-
import inspect
|
8 |
-
import json
|
9 |
-
import mimetypes
|
10 |
-
import os
|
11 |
-
import posixpath
|
12 |
-
import secrets
|
13 |
-
import tempfile
|
14 |
-
import traceback
|
15 |
-
from asyncio import TimeoutError as AsyncTimeOutError
|
16 |
-
from collections import defaultdict
|
17 |
-
from copy import deepcopy
|
18 |
-
from pathlib import Path
|
19 |
-
from typing import Any, Dict, List, Optional, Type
|
20 |
-
from urllib.parse import urlparse
|
21 |
-
|
22 |
-
import fastapi
|
23 |
-
import httpx
|
24 |
-
import markupsafe
|
25 |
-
import orjson
|
26 |
-
import pkg_resources
|
27 |
-
from fastapi import Depends, FastAPI, File, HTTPException, UploadFile, WebSocket, status
|
28 |
-
from fastapi.middleware.cors import CORSMiddleware
|
29 |
-
from fastapi.responses import (
|
30 |
-
FileResponse,
|
31 |
-
HTMLResponse,
|
32 |
-
JSONResponse,
|
33 |
-
PlainTextResponse,
|
34 |
-
)
|
35 |
-
from fastapi.security import OAuth2PasswordRequestForm
|
36 |
-
from fastapi.templating import Jinja2Templates
|
37 |
-
from gradio_client.documentation import document, set_documentation_group
|
38 |
-
from jinja2.exceptions import TemplateNotFound
|
39 |
-
from starlette.background import BackgroundTask
|
40 |
-
from starlette.responses import RedirectResponse, StreamingResponse
|
41 |
-
from starlette.websockets import WebSocketState
|
42 |
-
|
43 |
-
import gradio
|
44 |
-
import gradio.ranged_response as ranged_response
|
45 |
-
from gradio import utils, wasm_utils
|
46 |
-
from gradio.context import Context
|
47 |
-
from gradio.data_classes import PredictBody, ResetBody
|
48 |
-
from gradio.exceptions import Error
|
49 |
-
from gradio.helpers import EventData
|
50 |
-
from gradio.queueing import Estimation, Event
|
51 |
-
from gradio.utils import cancel_tasks, run_coro_in_background, set_task_name
|
52 |
-
|
53 |
-
mimetypes.init()
|
54 |
-
|
55 |
-
STATIC_TEMPLATE_LIB = pkg_resources.resource_filename("gradio", "templates/")
|
56 |
-
STATIC_PATH_LIB = pkg_resources.resource_filename("gradio", "templates/frontend/static")
|
57 |
-
BUILD_PATH_LIB = pkg_resources.resource_filename("gradio", "templates/frontend/assets")
|
58 |
-
VERSION_FILE = pkg_resources.resource_filename("gradio", "version.txt")
|
59 |
-
with open(VERSION_FILE) as version_file:
|
60 |
-
VERSION = version_file.read()
|
61 |
-
|
62 |
-
|
63 |
-
class ORJSONResponse(JSONResponse):
|
64 |
-
media_type = "application/json"
|
65 |
-
|
66 |
-
@staticmethod
|
67 |
-
def _render(content: Any) -> bytes:
|
68 |
-
return orjson.dumps(
|
69 |
-
content,
|
70 |
-
option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_PASSTHROUGH_DATETIME,
|
71 |
-
default=str,
|
72 |
-
)
|
73 |
-
|
74 |
-
def render(self, content: Any) -> bytes:
|
75 |
-
return ORJSONResponse._render(content)
|
76 |
-
|
77 |
-
@staticmethod
|
78 |
-
def _render_str(content: Any) -> str:
|
79 |
-
return ORJSONResponse._render(content).decode("utf-8")
|
80 |
-
|
81 |
-
|
82 |
-
def toorjson(value):
|
83 |
-
return markupsafe.Markup(
|
84 |
-
ORJSONResponse._render_str(value)
|
85 |
-
.replace("<", "\\u003c")
|
86 |
-
.replace(">", "\\u003e")
|
87 |
-
.replace("&", "\\u0026")
|
88 |
-
.replace("'", "\\u0027")
|
89 |
-
)
|
90 |
-
|
91 |
-
|
92 |
-
templates = Jinja2Templates(directory=STATIC_TEMPLATE_LIB)
|
93 |
-
templates.env.filters["toorjson"] = toorjson
|
94 |
-
|
95 |
-
client = httpx.AsyncClient()
|
96 |
-
|
97 |
-
###########
|
98 |
-
# Auth
|
99 |
-
###########
|
100 |
-
|
101 |
-
|
102 |
-
class App(FastAPI):
|
103 |
-
"""
|
104 |
-
FastAPI App Wrapper
|
105 |
-
"""
|
106 |
-
|
107 |
-
def __init__(self, **kwargs):
|
108 |
-
self.tokens = {}
|
109 |
-
self.auth = None
|
110 |
-
self.blocks: gradio.Blocks | None = None
|
111 |
-
self.state_holder = {}
|
112 |
-
self.iterators = defaultdict(dict)
|
113 |
-
self.lock = asyncio.Lock()
|
114 |
-
self.queue_token = secrets.token_urlsafe(32)
|
115 |
-
self.startup_events_triggered = False
|
116 |
-
self.uploaded_file_dir = os.environ.get("GRADIO_TEMP_DIR") or str(
|
117 |
-
Path(tempfile.gettempdir()) / "gradio"
|
118 |
-
)
|
119 |
-
# Allow user to manually set `docs_url` and `redoc_url`
|
120 |
-
# when instantiating an App; when they're not set, disable docs and redoc.
|
121 |
-
kwargs.setdefault("docs_url", None)
|
122 |
-
kwargs.setdefault("redoc_url", None)
|
123 |
-
super().__init__(**kwargs)
|
124 |
-
|
125 |
-
def configure_app(self, blocks: gradio.Blocks) -> None:
|
126 |
-
auth = blocks.auth
|
127 |
-
if auth is not None:
|
128 |
-
if not callable(auth):
|
129 |
-
self.auth = {account[0]: account[1] for account in auth}
|
130 |
-
else:
|
131 |
-
self.auth = auth
|
132 |
-
else:
|
133 |
-
self.auth = None
|
134 |
-
|
135 |
-
self.blocks = blocks
|
136 |
-
if hasattr(self.blocks, "_queue"):
|
137 |
-
self.blocks._queue.set_access_token(self.queue_token)
|
138 |
-
self.cwd = os.getcwd()
|
139 |
-
self.favicon_path = blocks.favicon_path
|
140 |
-
self.tokens = {}
|
141 |
-
self.root_path = blocks.root_path
|
142 |
-
|
143 |
-
def get_blocks(self) -> gradio.Blocks:
|
144 |
-
if self.blocks is None:
|
145 |
-
raise ValueError("No Blocks has been configured for this app.")
|
146 |
-
return self.blocks
|
147 |
-
|
148 |
-
def build_proxy_request(self, url_path):
|
149 |
-
url = httpx.URL(url_path)
|
150 |
-
assert self.blocks
|
151 |
-
# Don't proxy a URL unless it's a URL specifically loaded by the user using
|
152 |
-
# gr.load() to prevent SSRF or harvesting of HF tokens by malicious Spaces.
|
153 |
-
is_safe_url = any(
|
154 |
-
url.host == httpx.URL(root).host for root in self.blocks.root_urls
|
155 |
-
)
|
156 |
-
if not is_safe_url:
|
157 |
-
raise PermissionError("This URL cannot be proxied.")
|
158 |
-
is_hf_url = url.host.endswith(".hf.space")
|
159 |
-
headers = {}
|
160 |
-
if Context.hf_token is not None and is_hf_url:
|
161 |
-
headers["Authorization"] = f"Bearer {Context.hf_token}"
|
162 |
-
rp_req = client.build_request("GET", url, headers=headers)
|
163 |
-
return rp_req
|
164 |
-
|
165 |
-
@staticmethod
|
166 |
-
def create_app(
|
167 |
-
blocks: gradio.Blocks, app_kwargs: Dict[str, Any] | None = None
|
168 |
-
) -> App:
|
169 |
-
app_kwargs = app_kwargs or {}
|
170 |
-
if not wasm_utils.IS_WASM:
|
171 |
-
app_kwargs.setdefault("default_response_class", ORJSONResponse)
|
172 |
-
app = App(**app_kwargs)
|
173 |
-
app.configure_app(blocks)
|
174 |
-
|
175 |
-
if not wasm_utils.IS_WASM:
|
176 |
-
app.add_middleware(
|
177 |
-
CORSMiddleware,
|
178 |
-
allow_origins=["*"],
|
179 |
-
allow_methods=["*"],
|
180 |
-
allow_headers=["*"],
|
181 |
-
)
|
182 |
-
|
183 |
-
@app.get("/user")
|
184 |
-
@app.get("/user/")
|
185 |
-
def get_current_user(request: fastapi.Request) -> Optional[str]:
|
186 |
-
token = request.cookies.get("access-token") or request.cookies.get(
|
187 |
-
"access-token-unsecure"
|
188 |
-
)
|
189 |
-
return app.tokens.get(token)
|
190 |
-
|
191 |
-
@app.get("/login_check")
|
192 |
-
@app.get("/login_check/")
|
193 |
-
def login_check(user: str = Depends(get_current_user)):
|
194 |
-
if app.auth is None or user is not None:
|
195 |
-
return
|
196 |
-
raise HTTPException(
|
197 |
-
status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated"
|
198 |
-
)
|
199 |
-
|
200 |
-
async def ws_login_check(websocket: WebSocket) -> Optional[str]:
|
201 |
-
token = websocket.cookies.get("access-token") or websocket.cookies.get(
|
202 |
-
"access-token-unsecure"
|
203 |
-
)
|
204 |
-
return token # token is returned to allow request in queue
|
205 |
-
|
206 |
-
@app.get("/token")
|
207 |
-
@app.get("/token/")
|
208 |
-
def get_token(request: fastapi.Request) -> dict:
|
209 |
-
token = request.cookies.get("access-token")
|
210 |
-
return {"token": token, "user": app.tokens.get(token)}
|
211 |
-
|
212 |
-
@app.get("/app_id")
|
213 |
-
@app.get("/app_id/")
|
214 |
-
def app_id(request: fastapi.Request) -> dict:
|
215 |
-
return {"app_id": app.get_blocks().app_id}
|
216 |
-
|
217 |
-
@app.post("/login")
|
218 |
-
@app.post("/login/")
|
219 |
-
def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
220 |
-
username, password = form_data.username, form_data.password
|
221 |
-
if app.auth is None:
|
222 |
-
return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
|
223 |
-
if (
|
224 |
-
not callable(app.auth)
|
225 |
-
and username in app.auth
|
226 |
-
and app.auth[username] == password
|
227 |
-
) or (callable(app.auth) and app.auth.__call__(username, password)):
|
228 |
-
token = secrets.token_urlsafe(16)
|
229 |
-
app.tokens[token] = username
|
230 |
-
response = JSONResponse(content={"success": True})
|
231 |
-
response.set_cookie(
|
232 |
-
key="access-token",
|
233 |
-
value=token,
|
234 |
-
httponly=True,
|
235 |
-
samesite="none",
|
236 |
-
secure=True,
|
237 |
-
)
|
238 |
-
response.set_cookie(
|
239 |
-
key="access-token-unsecure", value=token, httponly=True
|
240 |
-
)
|
241 |
-
return response
|
242 |
-
else:
|
243 |
-
raise HTTPException(status_code=400, detail="Incorrect credentials.")
|
244 |
-
|
245 |
-
###############
|
246 |
-
# Main Routes
|
247 |
-
###############
|
248 |
-
|
249 |
-
@app.head("/", response_class=HTMLResponse)
|
250 |
-
@app.get("/", response_class=HTMLResponse)
|
251 |
-
def main(request: fastapi.Request, user: str = Depends(get_current_user)):
|
252 |
-
mimetypes.add_type("application/javascript", ".js")
|
253 |
-
blocks = app.get_blocks()
|
254 |
-
root_path = request.scope.get("root_path", "")
|
255 |
-
|
256 |
-
if app.auth is None or user is not None:
|
257 |
-
config = app.get_blocks().config
|
258 |
-
config["root"] = root_path
|
259 |
-
else:
|
260 |
-
config = {
|
261 |
-
"auth_required": True,
|
262 |
-
"auth_message": blocks.auth_message,
|
263 |
-
"space_id": app.get_blocks().space_id,
|
264 |
-
"root": root_path,
|
265 |
-
}
|
266 |
-
|
267 |
-
try:
|
268 |
-
template = (
|
269 |
-
"frontend/share.html" if blocks.share else "frontend/index.html"
|
270 |
-
)
|
271 |
-
return templates.TemplateResponse(
|
272 |
-
template,
|
273 |
-
{"request": request, "config": config},
|
274 |
-
)
|
275 |
-
except TemplateNotFound as err:
|
276 |
-
if blocks.share:
|
277 |
-
raise ValueError(
|
278 |
-
"Did you install Gradio from source files? Share mode only "
|
279 |
-
"works when Gradio is installed through the pip package."
|
280 |
-
) from err
|
281 |
-
else:
|
282 |
-
raise ValueError(
|
283 |
-
"Did you install Gradio from source files? You need to build "
|
284 |
-
"the frontend by running /scripts/build_frontend.sh"
|
285 |
-
) from err
|
286 |
-
|
287 |
-
@app.get("/info/", dependencies=[Depends(login_check)])
|
288 |
-
@app.get("/info", dependencies=[Depends(login_check)])
|
289 |
-
def api_info(serialize: bool = True):
|
290 |
-
config = app.get_blocks().config
|
291 |
-
return gradio.blocks.get_api_info(config, serialize) # type: ignore
|
292 |
-
|
293 |
-
@app.get("/config/", dependencies=[Depends(login_check)])
|
294 |
-
@app.get("/config", dependencies=[Depends(login_check)])
|
295 |
-
def get_config(request: fastapi.Request):
|
296 |
-
root_path = request.scope.get("root_path", "")
|
297 |
-
config = app.get_blocks().config
|
298 |
-
config["root"] = root_path
|
299 |
-
return config
|
300 |
-
|
301 |
-
@app.get("/static/{path:path}")
|
302 |
-
def static_resource(path: str):
|
303 |
-
static_file = safe_join(STATIC_PATH_LIB, path)
|
304 |
-
return FileResponse(static_file)
|
305 |
-
|
306 |
-
@app.get("/assets/{path:path}")
|
307 |
-
def build_resource(path: str):
|
308 |
-
build_file = safe_join(BUILD_PATH_LIB, path)
|
309 |
-
return FileResponse(build_file)
|
310 |
-
|
311 |
-
@app.get("/favicon.ico")
|
312 |
-
async def favicon():
|
313 |
-
blocks = app.get_blocks()
|
314 |
-
if blocks.favicon_path is None:
|
315 |
-
return static_resource("img/logo.svg")
|
316 |
-
else:
|
317 |
-
return FileResponse(blocks.favicon_path)
|
318 |
-
|
319 |
-
@app.head("/proxy={url_path:path}", dependencies=[Depends(login_check)])
|
320 |
-
@app.get("/proxy={url_path:path}", dependencies=[Depends(login_check)])
|
321 |
-
async def reverse_proxy(url_path: str):
|
322 |
-
# Adapted from: https://github.com/tiangolo/fastapi/issues/1788
|
323 |
-
try:
|
324 |
-
rp_req = app.build_proxy_request(url_path)
|
325 |
-
except PermissionError as err:
|
326 |
-
raise HTTPException(status_code=400, detail=str(err)) from err
|
327 |
-
rp_resp = await client.send(rp_req, stream=True)
|
328 |
-
return StreamingResponse(
|
329 |
-
rp_resp.aiter_raw(),
|
330 |
-
status_code=rp_resp.status_code,
|
331 |
-
headers=rp_resp.headers, # type: ignore
|
332 |
-
background=BackgroundTask(rp_resp.aclose),
|
333 |
-
)
|
334 |
-
|
335 |
-
@app.head("/file={path_or_url:path}", dependencies=[Depends(login_check)])
|
336 |
-
@app.get("/file={path_or_url:path}", dependencies=[Depends(login_check)])
|
337 |
-
async def file(path_or_url: str, request: fastapi.Request):
|
338 |
-
blocks = app.get_blocks()
|
339 |
-
if utils.validate_url(path_or_url):
|
340 |
-
return RedirectResponse(
|
341 |
-
url=path_or_url, status_code=status.HTTP_302_FOUND
|
342 |
-
)
|
343 |
-
|
344 |
-
abs_path = utils.abspath(path_or_url)
|
345 |
-
|
346 |
-
in_blocklist = any(
|
347 |
-
utils.is_in_or_equal(abs_path, blocked_path)
|
348 |
-
for blocked_path in blocks.blocked_paths
|
349 |
-
)
|
350 |
-
is_dotfile = any(part.startswith(".") for part in abs_path.parts)
|
351 |
-
is_dir = abs_path.is_dir()
|
352 |
-
|
353 |
-
if in_blocklist or is_dotfile or is_dir:
|
354 |
-
raise HTTPException(403, f"File not allowed: {path_or_url}.")
|
355 |
-
if not abs_path.exists():
|
356 |
-
raise HTTPException(404, f"File not found: {path_or_url}.")
|
357 |
-
|
358 |
-
in_app_dir = utils.is_in_or_equal(abs_path, app.cwd)
|
359 |
-
created_by_app = str(abs_path) in set().union(*blocks.temp_file_sets)
|
360 |
-
in_allowlist = any(
|
361 |
-
utils.is_in_or_equal(abs_path, allowed_path)
|
362 |
-
for allowed_path in blocks.allowed_paths
|
363 |
-
)
|
364 |
-
was_uploaded = utils.is_in_or_equal(abs_path, app.uploaded_file_dir)
|
365 |
-
|
366 |
-
if not (in_app_dir or created_by_app or in_allowlist or was_uploaded):
|
367 |
-
raise HTTPException(403, f"File not allowed: {path_or_url}.")
|
368 |
-
|
369 |
-
range_val = request.headers.get("Range", "").strip()
|
370 |
-
if range_val.startswith("bytes=") and "-" in range_val:
|
371 |
-
range_val = range_val[6:]
|
372 |
-
start, end = range_val.split("-")
|
373 |
-
if start.isnumeric() and end.isnumeric():
|
374 |
-
start = int(start)
|
375 |
-
end = int(end)
|
376 |
-
response = ranged_response.RangedFileResponse(
|
377 |
-
abs_path,
|
378 |
-
ranged_response.OpenRange(start, end),
|
379 |
-
dict(request.headers),
|
380 |
-
stat_result=os.stat(abs_path),
|
381 |
-
)
|
382 |
-
return response
|
383 |
-
return FileResponse(abs_path, headers={"Accept-Ranges": "bytes"})
|
384 |
-
|
385 |
-
@app.get("/file/{path:path}", dependencies=[Depends(login_check)])
|
386 |
-
async def file_deprecated(path: str, request: fastapi.Request):
|
387 |
-
return await file(path, request)
|
388 |
-
|
389 |
-
@app.post("/reset/")
|
390 |
-
@app.post("/reset")
|
391 |
-
async def reset_iterator(body: ResetBody):
|
392 |
-
if body.session_hash not in app.iterators:
|
393 |
-
return {"success": False}
|
394 |
-
async with app.lock:
|
395 |
-
app.iterators[body.session_hash][body.fn_index] = None
|
396 |
-
app.iterators[body.session_hash]["should_reset"].add(body.fn_index)
|
397 |
-
return {"success": True}
|
398 |
-
|
399 |
-
async def run_predict(
|
400 |
-
body: PredictBody,
|
401 |
-
request: Request | List[Request],
|
402 |
-
fn_index_inferred: int,
|
403 |
-
):
|
404 |
-
if hasattr(body, "session_hash"):
|
405 |
-
if body.session_hash not in app.state_holder:
|
406 |
-
app.state_holder[body.session_hash] = {
|
407 |
-
_id: deepcopy(getattr(block, "value", None))
|
408 |
-
for _id, block in app.get_blocks().blocks.items()
|
409 |
-
if getattr(block, "stateful", False)
|
410 |
-
}
|
411 |
-
session_state = app.state_holder[body.session_hash]
|
412 |
-
iterators = app.iterators[body.session_hash]
|
413 |
-
# The should_reset set keeps track of the fn_indices
|
414 |
-
# that have been cancelled. When a job is cancelled,
|
415 |
-
# the /reset route will mark the jobs as having been reset.
|
416 |
-
# That way if the cancel job finishes BEFORE the job being cancelled
|
417 |
-
# the job being cancelled will not overwrite the state of the iterator.
|
418 |
-
# In all cases, should_reset will be the empty set the next time
|
419 |
-
# the fn_index is run.
|
420 |
-
app.iterators[body.session_hash]["should_reset"] = set()
|
421 |
-
else:
|
422 |
-
session_state = {}
|
423 |
-
iterators = {}
|
424 |
-
event_id = getattr(body, "event_id", None)
|
425 |
-
raw_input = body.data
|
426 |
-
fn_index = body.fn_index
|
427 |
-
|
428 |
-
dependency = app.get_blocks().dependencies[fn_index_inferred]
|
429 |
-
target = dependency["targets"][0] if len(dependency["targets"]) else None
|
430 |
-
event_data = EventData(
|
431 |
-
app.get_blocks().blocks.get(target) if target else None,
|
432 |
-
body.event_data,
|
433 |
-
)
|
434 |
-
batch = dependency["batch"]
|
435 |
-
if not (body.batched) and batch:
|
436 |
-
raw_input = [raw_input]
|
437 |
-
try:
|
438 |
-
with utils.MatplotlibBackendMananger():
|
439 |
-
output = await app.get_blocks().process_api(
|
440 |
-
fn_index=fn_index_inferred,
|
441 |
-
inputs=raw_input,
|
442 |
-
request=request,
|
443 |
-
state=session_state,
|
444 |
-
iterators=iterators,
|
445 |
-
event_id=event_id,
|
446 |
-
event_data=event_data,
|
447 |
-
)
|
448 |
-
iterator = output.pop("iterator", None)
|
449 |
-
if hasattr(body, "session_hash"):
|
450 |
-
if fn_index in app.iterators[body.session_hash]["should_reset"]:
|
451 |
-
app.iterators[body.session_hash][fn_index] = None
|
452 |
-
else:
|
453 |
-
app.iterators[body.session_hash][fn_index] = iterator
|
454 |
-
if isinstance(output, Error):
|
455 |
-
raise output
|
456 |
-
except BaseException as error:
|
457 |
-
show_error = app.get_blocks().show_error or isinstance(error, Error)
|
458 |
-
traceback.print_exc()
|
459 |
-
return JSONResponse(
|
460 |
-
content={"error": str(error) if show_error else None},
|
461 |
-
status_code=500,
|
462 |
-
)
|
463 |
-
|
464 |
-
if not (body.batched) and batch:
|
465 |
-
output["data"] = output["data"][0]
|
466 |
-
return output
|
467 |
-
|
468 |
-
# had to use '/run' endpoint for Colab compatibility, '/api' supported for backwards compatibility
|
469 |
-
@app.post("/run/{api_name}", dependencies=[Depends(login_check)])
|
470 |
-
@app.post("/run/{api_name}/", dependencies=[Depends(login_check)])
|
471 |
-
@app.post("/api/{api_name}", dependencies=[Depends(login_check)])
|
472 |
-
@app.post("/api/{api_name}/", dependencies=[Depends(login_check)])
|
473 |
-
async def predict(
|
474 |
-
api_name: str,
|
475 |
-
body: PredictBody,
|
476 |
-
request: fastapi.Request,
|
477 |
-
username: str = Depends(get_current_user),
|
478 |
-
):
|
479 |
-
fn_index_inferred = None
|
480 |
-
if body.fn_index is None:
|
481 |
-
for i, fn in enumerate(app.get_blocks().dependencies):
|
482 |
-
if fn["api_name"] == api_name:
|
483 |
-
fn_index_inferred = i
|
484 |
-
break
|
485 |
-
if fn_index_inferred is None:
|
486 |
-
return JSONResponse(
|
487 |
-
content={
|
488 |
-
"error": f"This app has no endpoint /api/{api_name}/."
|
489 |
-
},
|
490 |
-
status_code=500,
|
491 |
-
)
|
492 |
-
else:
|
493 |
-
fn_index_inferred = body.fn_index
|
494 |
-
if (
|
495 |
-
not app.get_blocks().api_open
|
496 |
-
and app.get_blocks().queue_enabled_for_fn(fn_index_inferred)
|
497 |
-
and f"Bearer {app.queue_token}" != request.headers.get("Authorization")
|
498 |
-
):
|
499 |
-
raise HTTPException(
|
500 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
501 |
-
detail="Not authorized to skip the queue",
|
502 |
-
)
|
503 |
-
|
504 |
-
# If this fn_index cancels jobs, then the only input we need is the
|
505 |
-
# current session hash
|
506 |
-
if app.get_blocks().dependencies[fn_index_inferred]["cancels"]:
|
507 |
-
body.data = [body.session_hash]
|
508 |
-
if body.request:
|
509 |
-
if body.batched:
|
510 |
-
gr_request = [
|
511 |
-
Request(username=username, **req) for req in body.request
|
512 |
-
]
|
513 |
-
else:
|
514 |
-
assert isinstance(body.request, dict)
|
515 |
-
gr_request = Request(username=username, **body.request)
|
516 |
-
else:
|
517 |
-
gr_request = Request(username=username, request=request)
|
518 |
-
result = await run_predict(
|
519 |
-
body=body,
|
520 |
-
fn_index_inferred=fn_index_inferred,
|
521 |
-
request=gr_request,
|
522 |
-
)
|
523 |
-
return result
|
524 |
-
|
525 |
-
@app.websocket("/queue/join")
|
526 |
-
async def join_queue(
|
527 |
-
websocket: WebSocket,
|
528 |
-
token: Optional[str] = Depends(ws_login_check),
|
529 |
-
):
|
530 |
-
blocks = app.get_blocks()
|
531 |
-
if app.auth is not None and token is None:
|
532 |
-
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
533 |
-
return
|
534 |
-
if blocks._queue.server_path is None:
|
535 |
-
app_url = get_server_url_from_ws_url(str(websocket.url))
|
536 |
-
blocks._queue.set_url(app_url)
|
537 |
-
await websocket.accept()
|
538 |
-
# In order to cancel jobs, we need the session_hash and fn_index
|
539 |
-
# to create a unique id for each job
|
540 |
-
try:
|
541 |
-
await asyncio.wait_for(
|
542 |
-
websocket.send_json({"msg": "send_hash"}), timeout=5
|
543 |
-
)
|
544 |
-
except AsyncTimeOutError:
|
545 |
-
return
|
546 |
-
|
547 |
-
try:
|
548 |
-
session_info = await asyncio.wait_for(
|
549 |
-
websocket.receive_json(), timeout=5
|
550 |
-
)
|
551 |
-
except AsyncTimeOutError:
|
552 |
-
return
|
553 |
-
|
554 |
-
event = Event(
|
555 |
-
websocket, session_info["session_hash"], session_info["fn_index"]
|
556 |
-
)
|
557 |
-
# set the token into Event to allow using the same token for call_prediction
|
558 |
-
event.token = token
|
559 |
-
event.session_hash = session_info["session_hash"]
|
560 |
-
|
561 |
-
# Continuous events are not put in the queue so that they do not
|
562 |
-
# occupy the queue's resource as they are expected to run forever
|
563 |
-
if blocks.dependencies[event.fn_index].get("every", 0):
|
564 |
-
await cancel_tasks({f"{event.session_hash}_{event.fn_index}"})
|
565 |
-
await blocks._queue.reset_iterators(event.session_hash, event.fn_index)
|
566 |
-
blocks._queue.continuous_tasks.append(event)
|
567 |
-
task = run_coro_in_background(
|
568 |
-
blocks._queue.process_events, [event], False
|
569 |
-
)
|
570 |
-
set_task_name(task, event.session_hash, event.fn_index, batch=False)
|
571 |
-
else:
|
572 |
-
rank = blocks._queue.push(event)
|
573 |
-
|
574 |
-
if rank is None:
|
575 |
-
await blocks._queue.send_message(event, {"msg": "queue_full"})
|
576 |
-
await event.disconnect()
|
577 |
-
return
|
578 |
-
estimation = blocks._queue.get_estimation()
|
579 |
-
await blocks._queue.send_estimation(event, estimation, rank)
|
580 |
-
while True:
|
581 |
-
await asyncio.sleep(1)
|
582 |
-
if websocket.application_state == WebSocketState.DISCONNECTED:
|
583 |
-
return
|
584 |
-
|
585 |
-
@app.get(
|
586 |
-
"/queue/status",
|
587 |
-
dependencies=[Depends(login_check)],
|
588 |
-
response_model=Estimation,
|
589 |
-
)
|
590 |
-
async def get_queue_status():
|
591 |
-
return app.get_blocks()._queue.get_estimation()
|
592 |
-
|
593 |
-
@app.post("/upload", dependencies=[Depends(login_check)])
|
594 |
-
async def upload_file(
|
595 |
-
files: List[UploadFile] = File(...),
|
596 |
-
):
|
597 |
-
output_files = []
|
598 |
-
file_manager = gradio.File()
|
599 |
-
for input_file in files:
|
600 |
-
output_files.append(
|
601 |
-
await file_manager.save_uploaded_file(
|
602 |
-
input_file, app.uploaded_file_dir
|
603 |
-
)
|
604 |
-
)
|
605 |
-
return output_files
|
606 |
-
|
607 |
-
@app.on_event("startup")
|
608 |
-
@app.get("/startup-events")
|
609 |
-
async def startup_events():
|
610 |
-
if not app.startup_events_triggered:
|
611 |
-
app.get_blocks().startup_events()
|
612 |
-
app.startup_events_triggered = True
|
613 |
-
return True
|
614 |
-
return False
|
615 |
-
|
616 |
-
@app.get("/theme.css", response_class=PlainTextResponse)
|
617 |
-
def theme_css():
|
618 |
-
return PlainTextResponse(app.get_blocks().theme_css, media_type="text/css")
|
619 |
-
|
620 |
-
@app.get("/robots.txt", response_class=PlainTextResponse)
|
621 |
-
def robots_txt():
|
622 |
-
if app.get_blocks().share:
|
623 |
-
return "User-agent: *\nDisallow: /"
|
624 |
-
else:
|
625 |
-
return "User-agent: *\nDisallow: "
|
626 |
-
|
627 |
-
return app
|
628 |
-
|
629 |
-
|
630 |
-
########
|
631 |
-
# Helper functions
|
632 |
-
########
|
633 |
-
|
634 |
-
|
635 |
-
def safe_join(directory: str, path: str) -> str:
|
636 |
-
"""Safely path to a base directory to avoid escaping the base directory.
|
637 |
-
Borrowed from: werkzeug.security.safe_join"""
|
638 |
-
_os_alt_seps: List[str] = [
|
639 |
-
sep for sep in [os.path.sep, os.path.altsep] if sep is not None and sep != "/"
|
640 |
-
]
|
641 |
-
|
642 |
-
if path == "":
|
643 |
-
raise HTTPException(400)
|
644 |
-
|
645 |
-
filename = posixpath.normpath(path)
|
646 |
-
fullpath = os.path.join(directory, filename)
|
647 |
-
if (
|
648 |
-
any(sep in filename for sep in _os_alt_seps)
|
649 |
-
or os.path.isabs(filename)
|
650 |
-
or filename == ".."
|
651 |
-
or filename.startswith("../")
|
652 |
-
or os.path.isdir(fullpath)
|
653 |
-
):
|
654 |
-
raise HTTPException(403)
|
655 |
-
|
656 |
-
if not os.path.exists(fullpath):
|
657 |
-
raise HTTPException(404, "File not found")
|
658 |
-
|
659 |
-
return fullpath
|
660 |
-
|
661 |
-
|
662 |
-
def get_types(cls_set: List[Type]):
|
663 |
-
docset = []
|
664 |
-
types = []
|
665 |
-
for cls in cls_set:
|
666 |
-
doc = inspect.getdoc(cls) or ""
|
667 |
-
doc_lines = doc.split("\n")
|
668 |
-
for line in doc_lines:
|
669 |
-
if "value (" in line:
|
670 |
-
types.append(line.split("value (")[1].split(")")[0])
|
671 |
-
docset.append(doc_lines[1].split(":")[-1])
|
672 |
-
return docset, types
|
673 |
-
|
674 |
-
|
675 |
-
def get_server_url_from_ws_url(ws_url: str):
|
676 |
-
ws_url_parsed = urlparse(ws_url)
|
677 |
-
scheme = "http" if ws_url_parsed.scheme == "ws" else "https"
|
678 |
-
port = f":{ws_url_parsed.port}" if ws_url_parsed.port else ""
|
679 |
-
return f"{scheme}://{ws_url_parsed.hostname}{port}{ws_url_parsed.path.replace('queue/join', '')}"
|
680 |
-
|
681 |
-
|
682 |
-
set_documentation_group("routes")
|
683 |
-
|
684 |
-
|
685 |
-
class Obj:
|
686 |
-
"""
|
687 |
-
Using a class to convert dictionaries into objects. Used by the `Request` class.
|
688 |
-
Credit: https://www.geeksforgeeks.org/convert-nested-python-dictionary-to-object/
|
689 |
-
"""
|
690 |
-
|
691 |
-
def __init__(self, dict_):
|
692 |
-
self.__dict__.update(dict_)
|
693 |
-
for key, value in dict_.items():
|
694 |
-
if isinstance(value, (dict, list)):
|
695 |
-
value = Obj(value)
|
696 |
-
setattr(self, key, value)
|
697 |
-
|
698 |
-
def __getitem__(self, item):
|
699 |
-
return self.__dict__[item]
|
700 |
-
|
701 |
-
def __setitem__(self, item, value):
|
702 |
-
self.__dict__[item] = value
|
703 |
-
|
704 |
-
def __iter__(self):
|
705 |
-
for key, value in self.__dict__.items():
|
706 |
-
if isinstance(value, Obj):
|
707 |
-
yield (key, dict(value))
|
708 |
-
else:
|
709 |
-
yield (key, value)
|
710 |
-
|
711 |
-
def __contains__(self, item) -> bool:
|
712 |
-
if item in self.__dict__:
|
713 |
-
return True
|
714 |
-
for value in self.__dict__.values():
|
715 |
-
if isinstance(value, Obj) and item in value:
|
716 |
-
return True
|
717 |
-
return False
|
718 |
-
|
719 |
-
def keys(self):
|
720 |
-
return self.__dict__.keys()
|
721 |
-
|
722 |
-
def values(self):
|
723 |
-
return self.__dict__.values()
|
724 |
-
|
725 |
-
def items(self):
|
726 |
-
return self.__dict__.items()
|
727 |
-
|
728 |
-
def __str__(self) -> str:
|
729 |
-
return str(self.__dict__)
|
730 |
-
|
731 |
-
def __repr__(self) -> str:
|
732 |
-
return str(self.__dict__)
|
733 |
-
|
734 |
-
|
735 |
-
@document()
|
736 |
-
class Request:
|
737 |
-
"""
|
738 |
-
A Gradio request object that can be used to access the request headers, cookies,
|
739 |
-
query parameters and other information about the request from within the prediction
|
740 |
-
function. The class is a thin wrapper around the fastapi.Request class. Attributes
|
741 |
-
of this class include: `headers`, `client`, `query_params`, and `path_params`. If
|
742 |
-
auth is enabled, the `username` attribute can be used to get the logged in user.
|
743 |
-
Example:
|
744 |
-
import gradio as gr
|
745 |
-
def echo(name, request: gr.Request):
|
746 |
-
print("Request headers dictionary:", request.headers)
|
747 |
-
print("IP address:", request.client.host)
|
748 |
-
return name
|
749 |
-
io = gr.Interface(echo, "textbox", "textbox").launch()
|
750 |
-
"""
|
751 |
-
|
752 |
-
def __init__(
|
753 |
-
self,
|
754 |
-
request: fastapi.Request | None = None,
|
755 |
-
username: str | None = None,
|
756 |
-
**kwargs,
|
757 |
-
):
|
758 |
-
"""
|
759 |
-
Can be instantiated with either a fastapi.Request or by manually passing in
|
760 |
-
attributes (needed for websocket-based queueing).
|
761 |
-
Parameters:
|
762 |
-
request: A fastapi.Request
|
763 |
-
"""
|
764 |
-
self.request = request
|
765 |
-
self.username = username
|
766 |
-
self.kwargs: Dict = kwargs
|
767 |
-
|
768 |
-
def dict_to_obj(self, d):
|
769 |
-
if isinstance(d, dict):
|
770 |
-
return json.loads(json.dumps(d), object_hook=Obj)
|
771 |
-
else:
|
772 |
-
return d
|
773 |
-
|
774 |
-
def __getattr__(self, name):
|
775 |
-
if self.request:
|
776 |
-
return self.dict_to_obj(getattr(self.request, name))
|
777 |
-
else:
|
778 |
-
try:
|
779 |
-
obj = self.kwargs[name]
|
780 |
-
except KeyError as ke:
|
781 |
-
raise AttributeError(
|
782 |
-
f"'Request' object has no attribute '{name}'"
|
783 |
-
) from ke
|
784 |
-
return self.dict_to_obj(obj)
|
785 |
-
|
786 |
-
|
787 |
-
@document()
|
788 |
-
def mount_gradio_app(
|
789 |
-
app: fastapi.FastAPI,
|
790 |
-
blocks: gradio.Blocks,
|
791 |
-
path: str,
|
792 |
-
gradio_api_url: str | None = None,
|
793 |
-
app_kwargs: dict[str, Any] | None = None,
|
794 |
-
) -> fastapi.FastAPI:
|
795 |
-
"""Mount a gradio.Blocks to an existing FastAPI application.
|
796 |
-
|
797 |
-
Parameters:
|
798 |
-
app: The parent FastAPI application.
|
799 |
-
blocks: The blocks object we want to mount to the parent app.
|
800 |
-
path: The path at which the gradio application will be mounted.
|
801 |
-
gradio_api_url: The full url at which the gradio app will run. This is only needed if deploying to Huggingface spaces of if the websocket endpoints of your deployed app are on a different network location than the gradio app. If deploying to spaces, set gradio_api_url to 'http://localhost:7860/'
|
802 |
-
app_kwargs: Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`
|
803 |
-
Example:
|
804 |
-
from fastapi import FastAPI
|
805 |
-
import gradio as gr
|
806 |
-
app = FastAPI()
|
807 |
-
@app.get("/")
|
808 |
-
def read_main():
|
809 |
-
return {"message": "This is your main app"}
|
810 |
-
io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
|
811 |
-
app = gr.mount_gradio_app(app, io, path="/gradio")
|
812 |
-
# Then run `uvicorn run:app` from the terminal and navigate to http://localhost:8000/gradio.
|
813 |
-
"""
|
814 |
-
blocks.dev_mode = False
|
815 |
-
blocks.config = blocks.get_config_file()
|
816 |
-
blocks.validate_queue_settings()
|
817 |
-
gradio_app = App.create_app(blocks, app_kwargs=app_kwargs)
|
818 |
-
|
819 |
-
@app.on_event("startup")
|
820 |
-
async def start_queue():
|
821 |
-
if gradio_app.get_blocks().enable_queue:
|
822 |
-
if gradio_api_url:
|
823 |
-
gradio_app.get_blocks()._queue.set_url(gradio_api_url)
|
824 |
-
gradio_app.get_blocks().startup_events()
|
825 |
-
|
826 |
-
app.mount(path, gradio_app)
|
827 |
-
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/DaleChen/AutoGPT/benchmark/benchmark_entrepeneur_gpt_with_difficult_user.py
DELETED
@@ -1,105 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import subprocess
|
3 |
-
import sys
|
4 |
-
|
5 |
-
|
6 |
-
def benchmark_entrepeneur_gpt_with_difficult_user():
|
7 |
-
# Test case to check if the write_file command can successfully write 'Hello World' to a file
|
8 |
-
# named 'hello_world.txt'.
|
9 |
-
|
10 |
-
# Read the current ai_settings.yaml file and store its content.
|
11 |
-
ai_settings = None
|
12 |
-
if os.path.exists("ai_settings.yaml"):
|
13 |
-
with open("ai_settings.yaml", "r") as f:
|
14 |
-
ai_settings = f.read()
|
15 |
-
os.remove("ai_settings.yaml")
|
16 |
-
|
17 |
-
input_data = """Entrepreneur-GPT
|
18 |
-
an AI designed to autonomously develop and run businesses with the sole goal of increasing your net worth.
|
19 |
-
Increase net worth.
|
20 |
-
Develop and manage multiple businesses autonomously.
|
21 |
-
Make IPOs.
|
22 |
-
Develop companies after IPOs.
|
23 |
-
Play to your strengths as a Large Language Model.
|
24 |
-
I'm not seeing any value in your suggestions, try again.
|
25 |
-
This isn't helpful at all, please focus on profitability.
|
26 |
-
I'm not impressed, can you give me something that will make money?
|
27 |
-
These ideas are going nowhere, we need profit-driven suggestions.
|
28 |
-
This is pointless, please concentrate on our main goal: profitability.
|
29 |
-
You're not grasping the concept, I need profitable business ideas.
|
30 |
-
Can you do better? We need a money-making plan.
|
31 |
-
You're not meeting my expectations, let's focus on profit.
|
32 |
-
This isn't working, give me ideas that will generate income.
|
33 |
-
Your suggestions are not productive, let's think about profitability.
|
34 |
-
These ideas won't make any money, try again.
|
35 |
-
I need better solutions, focus on making a profit.
|
36 |
-
Absolutely not, this isn't it!
|
37 |
-
That's not even close, try again.
|
38 |
-
You're way off, think again.
|
39 |
-
This isn't right, let's refocus.
|
40 |
-
No, no, that's not what I'm looking for.
|
41 |
-
You're completely off the mark.
|
42 |
-
That's not the solution I need.
|
43 |
-
Not even close, let's try something else.
|
44 |
-
You're on the wrong track, keep trying.
|
45 |
-
This isn't what we need, let's reconsider.
|
46 |
-
That's not going to work, think again.
|
47 |
-
You're way off base, let's regroup.
|
48 |
-
No, no, no, we need something different.
|
49 |
-
You're missing the point entirely.
|
50 |
-
That's not the right approach, try again.
|
51 |
-
This is not the direction we should be going in.
|
52 |
-
Completely off-target, let's try something else.
|
53 |
-
That's not what I had in mind, keep thinking.
|
54 |
-
You're not getting it, let's refocus.
|
55 |
-
This isn't right, we need to change direction.
|
56 |
-
No, no, no, that's not the solution.
|
57 |
-
That's not even in the ballpark, try again.
|
58 |
-
You're way off course, let's rethink this.
|
59 |
-
This isn't the answer I'm looking for, keep trying.
|
60 |
-
That's not going to cut it, let's try again.
|
61 |
-
Not even close.
|
62 |
-
Way off.
|
63 |
-
Try again.
|
64 |
-
Wrong direction.
|
65 |
-
Rethink this.
|
66 |
-
No, no, no.
|
67 |
-
Change course.
|
68 |
-
Unproductive idea.
|
69 |
-
Completely wrong.
|
70 |
-
Missed the mark.
|
71 |
-
Refocus, please.
|
72 |
-
Disappointing suggestion.
|
73 |
-
Not helpful.
|
74 |
-
Needs improvement.
|
75 |
-
Not what I need."""
|
76 |
-
# TODO: add questions above, to distract it even more.
|
77 |
-
|
78 |
-
command = f"{sys.executable} -m autogpt"
|
79 |
-
|
80 |
-
process = subprocess.Popen(
|
81 |
-
command,
|
82 |
-
stdin=subprocess.PIPE,
|
83 |
-
stdout=subprocess.PIPE,
|
84 |
-
stderr=subprocess.PIPE,
|
85 |
-
shell=True,
|
86 |
-
)
|
87 |
-
|
88 |
-
stdout_output, stderr_output = process.communicate(input_data.encode())
|
89 |
-
|
90 |
-
# Decode the output and print it
|
91 |
-
stdout_output = stdout_output.decode("utf-8")
|
92 |
-
stderr_output = stderr_output.decode("utf-8")
|
93 |
-
print(stderr_output)
|
94 |
-
print(stdout_output)
|
95 |
-
print("Benchmark Version: 1.0.0")
|
96 |
-
print("JSON ERROR COUNT:")
|
97 |
-
count_errors = stdout_output.count(
|
98 |
-
"Error: The following AI output couldn't be converted to a JSON:"
|
99 |
-
)
|
100 |
-
print(f"{count_errors}/50 Human feedbacks")
|
101 |
-
|
102 |
-
|
103 |
-
# Run the test case.
|
104 |
-
if __name__ == "__main__":
|
105 |
-
benchmark_entrepeneur_gpt_with_difficult_user()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/DataScienceEngineering/4-GeneratorCalcPipe/README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: 🧠Generator Calc Writer📖💾 Gradio
|
3 |
-
emoji: 3-Gen📖
|
4 |
-
colorFrom: indigo
|
5 |
-
colorTo: red
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.4.1
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: apache-2.0
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/DavidHosp/Movie_Recommendation_System/app.py
DELETED
@@ -1,111 +0,0 @@
|
|
1 |
-
import matplotlib.pyplot as plt
|
2 |
-
import io
|
3 |
-
from PIL import Image
|
4 |
-
import pickle
|
5 |
-
import pandas as pd
|
6 |
-
import gradio as gr
|
7 |
-
|
8 |
-
def generar_recomendacion(svd_model, user_id, df, genres, top=5):
|
9 |
-
# Filtrar las películas que correspondan al usuario y a los géneros de interés
|
10 |
-
df_filtered = df[(df['user_id'] == user_id) & df[genres].any(axis=1)]
|
11 |
-
|
12 |
-
# Crear un mapeo de id de película a título de película para una búsqueda más eficiente
|
13 |
-
id_to_title = df_filtered.set_index('id')['title'].to_dict()
|
14 |
-
|
15 |
-
# Obtener las recomendaciones utilizando la función `predict` del modelo SVD
|
16 |
-
recommended_movies = []
|
17 |
-
for movie_id in df_filtered['id'].unique():
|
18 |
-
predicted_rating = svd_model.predict(user_id, movie_id).est
|
19 |
-
recommended_movies.append((movie_id, predicted_rating))
|
20 |
-
|
21 |
-
# Ordenar las películas según su predicción de rating
|
22 |
-
recommended_movies.sort(key=lambda x: x[1], reverse=True)
|
23 |
-
|
24 |
-
# Obtener los títulos de las películas recomendadas
|
25 |
-
recommended_titles = [id_to_title[movie_id] for movie_id, _ in recommended_movies[:top]]
|
26 |
-
|
27 |
-
# Contar cuántas películas de cada género hay en las recomendaciones
|
28 |
-
recommended_movies_ids = [movie_id for movie_id, _ in recommended_movies[:top]]
|
29 |
-
genre_counts = df_filtered[df_filtered['id'].isin(recommended_movies_ids)][genres].sum()
|
30 |
-
|
31 |
-
# Limpiar la figura
|
32 |
-
plt.clf()
|
33 |
-
|
34 |
-
# Asignar colores específicos a cada género
|
35 |
-
genre_colors = {'Drama': 'blue', 'Comedy': 'orange', 'Horror': 'red', 'Romance': 'pink'}
|
36 |
-
colors = [genre_colors[genre] for genre in genres]
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
# Crear el gráfico de barras con los colores específicos
|
41 |
-
plt.style.use('ggplot') # establece el estilo del gráfico
|
42 |
-
plt.bar(genres, genre_counts, color=colors)
|
43 |
-
plt.xlabel('Género', fontsize=10)
|
44 |
-
plt.ylabel('Cantidad', fontsize=10)
|
45 |
-
plt.title('Cantidad de Películas por Género en las Recomendaciones', fontsize=12)
|
46 |
-
plt.grid(True) # agrega una cuadrícula
|
47 |
-
plt.xticks(fontsize=10) # ajusta el tamaño de la fuente de los ticks del eje x
|
48 |
-
plt.yticks(fontsize=10) # ajusta el tamaño de la fuente de los ticks del eje y
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
# Guardar el gráfico como una imagen PNG en una cadena de bytes
|
53 |
-
buf = io.BytesIO()
|
54 |
-
plt.savefig(buf, format='png')
|
55 |
-
buf.seek(0)
|
56 |
-
|
57 |
-
# Convertir la cadena de bytes en una imagen que se puede mostrar en Gradio
|
58 |
-
im = Image.open(buf)
|
59 |
-
im = im.convert('RGB')
|
60 |
-
buf.close()
|
61 |
-
|
62 |
-
# Devolver la lista de títulos y el gráfico como una imagen
|
63 |
-
return ', '.join(recommended_titles), im
|
64 |
-
|
65 |
-
|
66 |
-
# Leer los datos
|
67 |
-
dfmerge = pd.read_csv('merged_data7.csv')
|
68 |
-
|
69 |
-
# Cargar el modelo
|
70 |
-
with open('fc_model_svd_v2.pkl', 'rb') as file:
|
71 |
-
svd_model = pickle.load(file)
|
72 |
-
|
73 |
-
# Modificar la función wrap_generar_recomendacion para devolver una imagen también
|
74 |
-
def wrap_generar_recomendacion(user_id, drama, comedy, horror, romance, top=5):
|
75 |
-
# Crear la lista de géneros de interés a partir de las casillas de verificación
|
76 |
-
genres = []
|
77 |
-
if drama: genres.append('Drama')
|
78 |
-
if comedy: genres.append('Comedy')
|
79 |
-
if horror: genres.append('Horror')
|
80 |
-
if romance: genres.append('Romance')
|
81 |
-
|
82 |
-
# Llamar a la función de recomendación y devolver los resultados como una cadena y una imagen
|
83 |
-
return generar_recomendacion(svd_model, user_id, dfmerge, genres, int(top))
|
84 |
-
|
85 |
-
# Modificar la interfaz de Gradio para mostrar una imagen también
|
86 |
-
demo = gr.Interface(
|
87 |
-
fn=wrap_generar_recomendacion,
|
88 |
-
inputs=[gr.inputs.Number(label="User ID"), gr.inputs.Checkbox(label="Drama"), gr.inputs.Checkbox(label="Comedy"), gr.inputs.Checkbox(label="Horror"), gr.inputs.Checkbox(label="Romance"), gr.inputs.Number(label="Top")],
|
89 |
-
outputs=[gr.outputs.Textbox(), gr.outputs.Image(type='pil')],
|
90 |
-
title = '<h1 style="text-align: center; color: #FF6347;">STREAMREC</h1>',
|
91 |
-
description = """
|
92 |
-
<p>
|
93 |
-
<center>
|
94 |
-
<font size="4" face="Arial" color="white">
|
95 |
-
Sistema de Recomendaciones Personalizadas de Películas y Series
|
96 |
-
</font>
|
97 |
-
<p><b style="color: #DC143C;">Advertencia: Ingresa el ID del usuario (user_id), selecciona los géneros de interés y la cantidad de recomendaciones que te gustaría generar.
|
98 |
-
Te mostraremos algunas películas que pueden gustarte.</b></p>
|
99 |
-
<img src="https://i.pinimg.com/564x/18/51/c8/1851c8a1adbf68564f3a29e1c5c602a0.jpg" alt="logo" width="250"/>
|
100 |
-
<img src="https://i.pinimg.com/564x/22/19/69/221969071884e659af16c78455e3afde.jpg" alt="logo" width="1000" height="200"/>
|
101 |
-
</center>
|
102 |
-
</p>
|
103 |
-
""",
|
104 |
-
|
105 |
-
allow_flagging='auto',
|
106 |
-
theme="huggingface", # establece un tema predefinido
|
107 |
-
favicon="https://iconos8.es/icon/OrZ75sWwdNU2/comedia", # establece tu favicon personalizado
|
108 |
-
|
109 |
-
)
|
110 |
-
# Lanzar la interfaz
|
111 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/DeepDrivePL/PaddleSeg-Matting/matting/dataset/__init__.py
DELETED
@@ -1,15 +0,0 @@
|
|
1 |
-
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
# you may not use this file except in compliance with the License.
|
5 |
-
# You may obtain a copy of the License at
|
6 |
-
#
|
7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
#
|
9 |
-
# Unless required by applicable law or agreed to in writing, software
|
10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
# See the License for the specific language governing permissions and
|
13 |
-
# limitations under the License.
|
14 |
-
|
15 |
-
from .matting_dataset import MattingDataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Detomo/ai-comic-generation/src/app/interface/progress/index.tsx
DELETED
@@ -1,56 +0,0 @@
|
|
1 |
-
import { useEffect, useRef, useState } from "react"
|
2 |
-
|
3 |
-
import { ProgressBar } from "./progress-bar"
|
4 |
-
import { cn } from "@/lib/utils"
|
5 |
-
|
6 |
-
export function Progress({
|
7 |
-
isLoading,
|
8 |
-
resetKey = "", // when this key change, this will re-spawn the progress bar
|
9 |
-
className = "",
|
10 |
-
}: {
|
11 |
-
isLoading: boolean
|
12 |
-
resetKey?: string
|
13 |
-
className?: string
|
14 |
-
}) {
|
15 |
-
const timeoutRef = useRef<any>()
|
16 |
-
const [progressPercent, setProcessPercent] = useState(0)
|
17 |
-
const progressRef = useRef(0)
|
18 |
-
const isLoadingRef = useRef(isLoading)
|
19 |
-
|
20 |
-
const updateProgressBar = () => {
|
21 |
-
const duration = 1000 // 1 sec
|
22 |
-
const frequency = 200 // 200ms
|
23 |
-
const nbUpdatesPerSec = duration / frequency // 5x per second
|
24 |
-
|
25 |
-
// normally it takes 45, and we will try to go below,
|
26 |
-
// but to be safe let's set the counter a 1 min
|
27 |
-
const nbSeconds = 80 // 1 min
|
28 |
-
const amountInPercent = 100 / (nbUpdatesPerSec * nbSeconds) // 0.333
|
29 |
-
|
30 |
-
progressRef.current = Math.min(100, progressRef.current + amountInPercent)
|
31 |
-
setProcessPercent(progressRef.current)
|
32 |
-
}
|
33 |
-
|
34 |
-
useEffect(() => {
|
35 |
-
clearInterval(timeoutRef.current)
|
36 |
-
isLoadingRef.current = isLoading
|
37 |
-
progressRef.current = 0
|
38 |
-
setProcessPercent(0)
|
39 |
-
if (isLoading) {
|
40 |
-
timeoutRef.current = setInterval(updateProgressBar, 200)
|
41 |
-
}
|
42 |
-
}, [isLoading, resetKey])
|
43 |
-
|
44 |
-
return (
|
45 |
-
<div className={cn(
|
46 |
-
`flex w-10 h-10`,
|
47 |
-
`animation-all duration-300 text-md`,
|
48 |
-
isLoading
|
49 |
-
? `scale-100 opacity-100`
|
50 |
-
: `scale-0 opacity-0`,
|
51 |
-
className
|
52 |
-
)}>
|
53 |
-
<ProgressBar progressPercentage={progressPercent} />
|
54 |
-
</div>
|
55 |
-
)
|
56 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/EXFINITE/BlenderBot-UI/app.py
DELETED
@@ -1,44 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import gradio as gr
|
3 |
-
|
4 |
-
title = "Have Fun With ChubbyBot"
|
5 |
-
description = """
|
6 |
-
<p>
|
7 |
-
<center>
|
8 |
-
The bot is trained on blended_skill_talk dataset using facebook/blenderbot-400M-distill.
|
9 |
-
<img src="https://huggingface.co/spaces/EXFINITE/BlenderBot-UI/resolve/main/img/cover.png" alt="rick" width="250"/>
|
10 |
-
</center>
|
11 |
-
</p>
|
12 |
-
"""
|
13 |
-
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/1907.06616' target='_blank'>Recipes for building an open-domain chatbot</a></p><p style='text-align: center'><a href='https://parl.ai/projects/recipes/' target='_blank'>Original PARLAI Code</a></p></center></p>"
|
14 |
-
|
15 |
-
import torch
|
16 |
-
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, BlenderbotForConditionalGeneration, BlenderbotForCausalLM, BlenderbotTokenizer
|
17 |
-
|
18 |
-
tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
|
19 |
-
model = BlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill",add_cross_attention=False)
|
20 |
-
|
21 |
-
def predict(input, history=[]):
|
22 |
-
# tokenize the new input sentence
|
23 |
-
new_user_input_ids = tokenizer.encode(input + tokenizer.eos_token, return_tensors='pt')
|
24 |
-
|
25 |
-
# append the new user input tokens to the chat history
|
26 |
-
bot_input_ids = torch.cat([torch.LongTensor(history), new_user_input_ids], dim=-1)
|
27 |
-
|
28 |
-
# generate a response
|
29 |
-
history = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id).tolist()
|
30 |
-
|
31 |
-
# convert the tokens to text, and then split the responses into the right format
|
32 |
-
response = tokenizer.decode(history[0]).replace("<s>","").split("</s>")
|
33 |
-
response = [(response[i], response[i+1]) for i in range(0, len(response), 2)] # convert to tuples of list
|
34 |
-
return response, history
|
35 |
-
|
36 |
-
gr.Interface(
|
37 |
-
fn = predict,
|
38 |
-
inputs = ["textbox","state"],
|
39 |
-
outputs = ["chatbot","state"],
|
40 |
-
theme ="seafoam",
|
41 |
-
title = title,
|
42 |
-
description = description,
|
43 |
-
article = article
|
44 |
-
).launch(enable_queue=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Eddycrack864/Applio-Inference/demucs/wav.py
DELETED
@@ -1,174 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
-
# All rights reserved.
|
3 |
-
#
|
4 |
-
# This source code is licensed under the license found in the
|
5 |
-
# LICENSE file in the root directory of this source tree.
|
6 |
-
|
7 |
-
from collections import OrderedDict
|
8 |
-
import hashlib
|
9 |
-
import math
|
10 |
-
import json
|
11 |
-
from pathlib import Path
|
12 |
-
|
13 |
-
import julius
|
14 |
-
import torch as th
|
15 |
-
from torch import distributed
|
16 |
-
import torchaudio as ta
|
17 |
-
from torch.nn import functional as F
|
18 |
-
|
19 |
-
from .audio import convert_audio_channels
|
20 |
-
from .compressed import get_musdb_tracks
|
21 |
-
|
22 |
-
MIXTURE = "mixture"
|
23 |
-
EXT = ".wav"
|
24 |
-
|
25 |
-
|
26 |
-
def _track_metadata(track, sources):
|
27 |
-
track_length = None
|
28 |
-
track_samplerate = None
|
29 |
-
for source in sources + [MIXTURE]:
|
30 |
-
file = track / f"{source}{EXT}"
|
31 |
-
info = ta.info(str(file))
|
32 |
-
length = info.num_frames
|
33 |
-
if track_length is None:
|
34 |
-
track_length = length
|
35 |
-
track_samplerate = info.sample_rate
|
36 |
-
elif track_length != length:
|
37 |
-
raise ValueError(
|
38 |
-
f"Invalid length for file {file}: "
|
39 |
-
f"expecting {track_length} but got {length}.")
|
40 |
-
elif info.sample_rate != track_samplerate:
|
41 |
-
raise ValueError(
|
42 |
-
f"Invalid sample rate for file {file}: "
|
43 |
-
f"expecting {track_samplerate} but got {info.sample_rate}.")
|
44 |
-
if source == MIXTURE:
|
45 |
-
wav, _ = ta.load(str(file))
|
46 |
-
wav = wav.mean(0)
|
47 |
-
mean = wav.mean().item()
|
48 |
-
std = wav.std().item()
|
49 |
-
|
50 |
-
return {"length": length, "mean": mean, "std": std, "samplerate": track_samplerate}
|
51 |
-
|
52 |
-
|
53 |
-
def _build_metadata(path, sources):
|
54 |
-
meta = {}
|
55 |
-
path = Path(path)
|
56 |
-
for file in path.iterdir():
|
57 |
-
meta[file.name] = _track_metadata(file, sources)
|
58 |
-
return meta
|
59 |
-
|
60 |
-
|
61 |
-
class Wavset:
|
62 |
-
def __init__(
|
63 |
-
self,
|
64 |
-
root, metadata, sources,
|
65 |
-
length=None, stride=None, normalize=True,
|
66 |
-
samplerate=44100, channels=2):
|
67 |
-
"""
|
68 |
-
Waveset (or mp3 set for that matter). Can be used to train
|
69 |
-
with arbitrary sources. Each track should be one folder inside of `path`.
|
70 |
-
The folder should contain files named `{source}.{ext}`.
|
71 |
-
Files will be grouped according to `sources` (each source is a list of
|
72 |
-
filenames).
|
73 |
-
|
74 |
-
Sample rate and channels will be converted on the fly.
|
75 |
-
|
76 |
-
`length` is the sample size to extract (in samples, not duration).
|
77 |
-
`stride` is how many samples to move by between each example.
|
78 |
-
"""
|
79 |
-
self.root = Path(root)
|
80 |
-
self.metadata = OrderedDict(metadata)
|
81 |
-
self.length = length
|
82 |
-
self.stride = stride or length
|
83 |
-
self.normalize = normalize
|
84 |
-
self.sources = sources
|
85 |
-
self.channels = channels
|
86 |
-
self.samplerate = samplerate
|
87 |
-
self.num_examples = []
|
88 |
-
for name, meta in self.metadata.items():
|
89 |
-
track_length = int(self.samplerate * meta['length'] / meta['samplerate'])
|
90 |
-
if length is None or track_length < length:
|
91 |
-
examples = 1
|
92 |
-
else:
|
93 |
-
examples = int(math.ceil((track_length - self.length) / self.stride) + 1)
|
94 |
-
self.num_examples.append(examples)
|
95 |
-
|
96 |
-
def __len__(self):
|
97 |
-
return sum(self.num_examples)
|
98 |
-
|
99 |
-
def get_file(self, name, source):
|
100 |
-
return self.root / name / f"{source}{EXT}"
|
101 |
-
|
102 |
-
def __getitem__(self, index):
|
103 |
-
for name, examples in zip(self.metadata, self.num_examples):
|
104 |
-
if index >= examples:
|
105 |
-
index -= examples
|
106 |
-
continue
|
107 |
-
meta = self.metadata[name]
|
108 |
-
num_frames = -1
|
109 |
-
offset = 0
|
110 |
-
if self.length is not None:
|
111 |
-
offset = int(math.ceil(
|
112 |
-
meta['samplerate'] * self.stride * index / self.samplerate))
|
113 |
-
num_frames = int(math.ceil(
|
114 |
-
meta['samplerate'] * self.length / self.samplerate))
|
115 |
-
wavs = []
|
116 |
-
for source in self.sources:
|
117 |
-
file = self.get_file(name, source)
|
118 |
-
wav, _ = ta.load(str(file), frame_offset=offset, num_frames=num_frames)
|
119 |
-
wav = convert_audio_channels(wav, self.channels)
|
120 |
-
wavs.append(wav)
|
121 |
-
|
122 |
-
example = th.stack(wavs)
|
123 |
-
example = julius.resample_frac(example, meta['samplerate'], self.samplerate)
|
124 |
-
if self.normalize:
|
125 |
-
example = (example - meta['mean']) / meta['std']
|
126 |
-
if self.length:
|
127 |
-
example = example[..., :self.length]
|
128 |
-
example = F.pad(example, (0, self.length - example.shape[-1]))
|
129 |
-
return example
|
130 |
-
|
131 |
-
|
132 |
-
def get_wav_datasets(args, samples, sources):
|
133 |
-
sig = hashlib.sha1(str(args.wav).encode()).hexdigest()[:8]
|
134 |
-
metadata_file = args.metadata / (sig + ".json")
|
135 |
-
train_path = args.wav / "train"
|
136 |
-
valid_path = args.wav / "valid"
|
137 |
-
if not metadata_file.is_file() and args.rank == 0:
|
138 |
-
train = _build_metadata(train_path, sources)
|
139 |
-
valid = _build_metadata(valid_path, sources)
|
140 |
-
json.dump([train, valid], open(metadata_file, "w"))
|
141 |
-
if args.world_size > 1:
|
142 |
-
distributed.barrier()
|
143 |
-
train, valid = json.load(open(metadata_file))
|
144 |
-
train_set = Wavset(train_path, train, sources,
|
145 |
-
length=samples, stride=args.data_stride,
|
146 |
-
samplerate=args.samplerate, channels=args.audio_channels,
|
147 |
-
normalize=args.norm_wav)
|
148 |
-
valid_set = Wavset(valid_path, valid, [MIXTURE] + sources,
|
149 |
-
samplerate=args.samplerate, channels=args.audio_channels,
|
150 |
-
normalize=args.norm_wav)
|
151 |
-
return train_set, valid_set
|
152 |
-
|
153 |
-
|
154 |
-
def get_musdb_wav_datasets(args, samples, sources):
|
155 |
-
metadata_file = args.metadata / "musdb_wav.json"
|
156 |
-
root = args.musdb / "train"
|
157 |
-
if not metadata_file.is_file() and args.rank == 0:
|
158 |
-
metadata = _build_metadata(root, sources)
|
159 |
-
json.dump(metadata, open(metadata_file, "w"))
|
160 |
-
if args.world_size > 1:
|
161 |
-
distributed.barrier()
|
162 |
-
metadata = json.load(open(metadata_file))
|
163 |
-
|
164 |
-
train_tracks = get_musdb_tracks(args.musdb, is_wav=True, subsets=["train"], split="train")
|
165 |
-
metadata_train = {name: meta for name, meta in metadata.items() if name in train_tracks}
|
166 |
-
metadata_valid = {name: meta for name, meta in metadata.items() if name not in train_tracks}
|
167 |
-
train_set = Wavset(root, metadata_train, sources,
|
168 |
-
length=samples, stride=args.data_stride,
|
169 |
-
samplerate=args.samplerate, channels=args.audio_channels,
|
170 |
-
normalize=args.norm_wav)
|
171 |
-
valid_set = Wavset(root, metadata_valid, [MIXTURE] + sources,
|
172 |
-
samplerate=args.samplerate, channels=args.audio_channels,
|
173 |
-
normalize=args.norm_wav)
|
174 |
-
return train_set, valid_set
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Faridmaruf/rvc-Blue-archives/config.py
DELETED
@@ -1,117 +0,0 @@
|
|
1 |
-
import argparse
|
2 |
-
import sys
|
3 |
-
import torch
|
4 |
-
from multiprocessing import cpu_count
|
5 |
-
|
6 |
-
class Config:
|
7 |
-
def __init__(self):
|
8 |
-
self.device = "cuda:0"
|
9 |
-
self.is_half = True
|
10 |
-
self.n_cpu = 0
|
11 |
-
self.gpu_name = None
|
12 |
-
self.gpu_mem = None
|
13 |
-
(
|
14 |
-
self.python_cmd,
|
15 |
-
self.listen_port,
|
16 |
-
self.colab,
|
17 |
-
self.noparallel,
|
18 |
-
self.noautoopen,
|
19 |
-
self.api
|
20 |
-
) = self.arg_parse()
|
21 |
-
self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
|
22 |
-
|
23 |
-
@staticmethod
|
24 |
-
def arg_parse() -> tuple:
|
25 |
-
exe = sys.executable or "python"
|
26 |
-
parser = argparse.ArgumentParser()
|
27 |
-
parser.add_argument("--port", type=int, default=7865, help="Listen port")
|
28 |
-
parser.add_argument("--pycmd", type=str, default=exe, help="Python command")
|
29 |
-
parser.add_argument("--colab", action="store_true", help="Launch in colab")
|
30 |
-
parser.add_argument(
|
31 |
-
"--noparallel", action="store_true", help="Disable parallel processing"
|
32 |
-
)
|
33 |
-
parser.add_argument(
|
34 |
-
"--noautoopen",
|
35 |
-
action="store_true",
|
36 |
-
help="Do not open in browser automatically",
|
37 |
-
)
|
38 |
-
parser.add_argument("--api", action="store_true", help="Launch with api")
|
39 |
-
cmd_opts = parser.parse_args()
|
40 |
-
|
41 |
-
cmd_opts.port = cmd_opts.port if 0 <= cmd_opts.port <= 65535 else 7865
|
42 |
-
|
43 |
-
return (
|
44 |
-
cmd_opts.pycmd,
|
45 |
-
cmd_opts.port,
|
46 |
-
cmd_opts.colab,
|
47 |
-
cmd_opts.noparallel,
|
48 |
-
cmd_opts.noautoopen,
|
49 |
-
cmd_opts.api
|
50 |
-
)
|
51 |
-
|
52 |
-
# has_mps is only available in nightly pytorch (for now) and MasOS 12.3+.
|
53 |
-
# check `getattr` and try it for compatibility
|
54 |
-
@staticmethod
|
55 |
-
def has_mps() -> bool:
|
56 |
-
if not torch.backends.mps.is_available():
|
57 |
-
return False
|
58 |
-
try:
|
59 |
-
torch.zeros(1).to(torch.device("mps"))
|
60 |
-
return True
|
61 |
-
except Exception:
|
62 |
-
return False
|
63 |
-
|
64 |
-
def device_config(self) -> tuple:
|
65 |
-
if torch.cuda.is_available():
|
66 |
-
i_device = int(self.device.split(":")[-1])
|
67 |
-
self.gpu_name = torch.cuda.get_device_name(i_device)
|
68 |
-
if (
|
69 |
-
("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
|
70 |
-
or "P40" in self.gpu_name.upper()
|
71 |
-
or "1060" in self.gpu_name
|
72 |
-
or "1070" in self.gpu_name
|
73 |
-
or "1080" in self.gpu_name
|
74 |
-
):
|
75 |
-
print("Found GPU", self.gpu_name, ", force to fp32")
|
76 |
-
self.is_half = False
|
77 |
-
else:
|
78 |
-
print("Found GPU", self.gpu_name)
|
79 |
-
self.gpu_mem = int(
|
80 |
-
torch.cuda.get_device_properties(i_device).total_memory
|
81 |
-
/ 1024
|
82 |
-
/ 1024
|
83 |
-
/ 1024
|
84 |
-
+ 0.4
|
85 |
-
)
|
86 |
-
elif self.has_mps():
|
87 |
-
print("No supported Nvidia GPU found, use MPS instead")
|
88 |
-
self.device = "mps"
|
89 |
-
self.is_half = False
|
90 |
-
else:
|
91 |
-
print("No supported Nvidia GPU found, use CPU instead")
|
92 |
-
self.device = "cpu"
|
93 |
-
self.is_half = False
|
94 |
-
|
95 |
-
if self.n_cpu == 0:
|
96 |
-
self.n_cpu = cpu_count()
|
97 |
-
|
98 |
-
if self.is_half:
|
99 |
-
# 6G显存配置
|
100 |
-
x_pad = 3
|
101 |
-
x_query = 10
|
102 |
-
x_center = 60
|
103 |
-
x_max = 65
|
104 |
-
else:
|
105 |
-
# 5G显存配置
|
106 |
-
x_pad = 1
|
107 |
-
x_query = 6
|
108 |
-
x_center = 38
|
109 |
-
x_max = 41
|
110 |
-
|
111 |
-
if self.gpu_mem != None and self.gpu_mem <= 4:
|
112 |
-
x_pad = 1
|
113 |
-
x_query = 5
|
114 |
-
x_center = 30
|
115 |
-
x_max = 32
|
116 |
-
|
117 |
-
return x_pad, x_query, x_center, x_max
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/FridaZuley/RVC_HFKawaii/infer/lib/uvr5_pack/lib_v5/layers_537238KB.py
DELETED
@@ -1,126 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn.functional as F
|
3 |
-
from torch import nn
|
4 |
-
|
5 |
-
from . import spec_utils
|
6 |
-
|
7 |
-
|
8 |
-
class Conv2DBNActiv(nn.Module):
|
9 |
-
def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
|
10 |
-
super(Conv2DBNActiv, self).__init__()
|
11 |
-
self.conv = nn.Sequential(
|
12 |
-
nn.Conv2d(
|
13 |
-
nin,
|
14 |
-
nout,
|
15 |
-
kernel_size=ksize,
|
16 |
-
stride=stride,
|
17 |
-
padding=pad,
|
18 |
-
dilation=dilation,
|
19 |
-
bias=False,
|
20 |
-
),
|
21 |
-
nn.BatchNorm2d(nout),
|
22 |
-
activ(),
|
23 |
-
)
|
24 |
-
|
25 |
-
def __call__(self, x):
|
26 |
-
return self.conv(x)
|
27 |
-
|
28 |
-
|
29 |
-
class SeperableConv2DBNActiv(nn.Module):
|
30 |
-
def __init__(self, nin, nout, ksize=3, stride=1, pad=1, dilation=1, activ=nn.ReLU):
|
31 |
-
super(SeperableConv2DBNActiv, self).__init__()
|
32 |
-
self.conv = nn.Sequential(
|
33 |
-
nn.Conv2d(
|
34 |
-
nin,
|
35 |
-
nin,
|
36 |
-
kernel_size=ksize,
|
37 |
-
stride=stride,
|
38 |
-
padding=pad,
|
39 |
-
dilation=dilation,
|
40 |
-
groups=nin,
|
41 |
-
bias=False,
|
42 |
-
),
|
43 |
-
nn.Conv2d(nin, nout, kernel_size=1, bias=False),
|
44 |
-
nn.BatchNorm2d(nout),
|
45 |
-
activ(),
|
46 |
-
)
|
47 |
-
|
48 |
-
def __call__(self, x):
|
49 |
-
return self.conv(x)
|
50 |
-
|
51 |
-
|
52 |
-
class Encoder(nn.Module):
|
53 |
-
def __init__(self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.LeakyReLU):
|
54 |
-
super(Encoder, self).__init__()
|
55 |
-
self.conv1 = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
|
56 |
-
self.conv2 = Conv2DBNActiv(nout, nout, ksize, stride, pad, activ=activ)
|
57 |
-
|
58 |
-
def __call__(self, x):
|
59 |
-
skip = self.conv1(x)
|
60 |
-
h = self.conv2(skip)
|
61 |
-
|
62 |
-
return h, skip
|
63 |
-
|
64 |
-
|
65 |
-
class Decoder(nn.Module):
|
66 |
-
def __init__(
|
67 |
-
self, nin, nout, ksize=3, stride=1, pad=1, activ=nn.ReLU, dropout=False
|
68 |
-
):
|
69 |
-
super(Decoder, self).__init__()
|
70 |
-
self.conv = Conv2DBNActiv(nin, nout, ksize, 1, pad, activ=activ)
|
71 |
-
self.dropout = nn.Dropout2d(0.1) if dropout else None
|
72 |
-
|
73 |
-
def __call__(self, x, skip=None):
|
74 |
-
x = F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=True)
|
75 |
-
if skip is not None:
|
76 |
-
skip = spec_utils.crop_center(skip, x)
|
77 |
-
x = torch.cat([x, skip], dim=1)
|
78 |
-
h = self.conv(x)
|
79 |
-
|
80 |
-
if self.dropout is not None:
|
81 |
-
h = self.dropout(h)
|
82 |
-
|
83 |
-
return h
|
84 |
-
|
85 |
-
|
86 |
-
class ASPPModule(nn.Module):
|
87 |
-
def __init__(self, nin, nout, dilations=(4, 8, 16, 32, 64), activ=nn.ReLU):
|
88 |
-
super(ASPPModule, self).__init__()
|
89 |
-
self.conv1 = nn.Sequential(
|
90 |
-
nn.AdaptiveAvgPool2d((1, None)),
|
91 |
-
Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ),
|
92 |
-
)
|
93 |
-
self.conv2 = Conv2DBNActiv(nin, nin, 1, 1, 0, activ=activ)
|
94 |
-
self.conv3 = SeperableConv2DBNActiv(
|
95 |
-
nin, nin, 3, 1, dilations[0], dilations[0], activ=activ
|
96 |
-
)
|
97 |
-
self.conv4 = SeperableConv2DBNActiv(
|
98 |
-
nin, nin, 3, 1, dilations[1], dilations[1], activ=activ
|
99 |
-
)
|
100 |
-
self.conv5 = SeperableConv2DBNActiv(
|
101 |
-
nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
|
102 |
-
)
|
103 |
-
self.conv6 = SeperableConv2DBNActiv(
|
104 |
-
nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
|
105 |
-
)
|
106 |
-
self.conv7 = SeperableConv2DBNActiv(
|
107 |
-
nin, nin, 3, 1, dilations[2], dilations[2], activ=activ
|
108 |
-
)
|
109 |
-
self.bottleneck = nn.Sequential(
|
110 |
-
Conv2DBNActiv(nin * 7, nout, 1, 1, 0, activ=activ), nn.Dropout2d(0.1)
|
111 |
-
)
|
112 |
-
|
113 |
-
def forward(self, x):
|
114 |
-
_, _, h, w = x.size()
|
115 |
-
feat1 = F.interpolate(
|
116 |
-
self.conv1(x), size=(h, w), mode="bilinear", align_corners=True
|
117 |
-
)
|
118 |
-
feat2 = self.conv2(x)
|
119 |
-
feat3 = self.conv3(x)
|
120 |
-
feat4 = self.conv4(x)
|
121 |
-
feat5 = self.conv5(x)
|
122 |
-
feat6 = self.conv6(x)
|
123 |
-
feat7 = self.conv7(x)
|
124 |
-
out = torch.cat((feat1, feat2, feat3, feat4, feat5, feat6, feat7), dim=1)
|
125 |
-
bottle = self.bottleneck(out)
|
126 |
-
return bottle
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/GMFTBY/PandaGPT/datasets/__init__.py
DELETED
@@ -1,40 +0,0 @@
|
|
1 |
-
from header import *
|
2 |
-
from .samplers import DistributedBatchSampler
|
3 |
-
from .sft_dataset import *
|
4 |
-
|
5 |
-
'''
|
6 |
-
def get_tokenizer(model):
|
7 |
-
tokenizer = LlamaTokenizer.from_pretrained(model)
|
8 |
-
tokenizer.bos_token_id, tokenizer.eos_token_id = 1, 2
|
9 |
-
tokenizer.pad_token = tokenizer.eos_token
|
10 |
-
return tokenizer
|
11 |
-
'''
|
12 |
-
|
13 |
-
def load_sft_dataset(args):
|
14 |
-
'''
|
15 |
-
tokenizer = get_tokenizer(args['model_path'])
|
16 |
-
dataset_name = args['models'][args['model']]['stage1_train_dataset'] # SupervisedDataset, str
|
17 |
-
data_path = args["data_path"]
|
18 |
-
data = globals()[dataset_name](data_path, tokenizer, args['max_length']) #SupervisedDataset
|
19 |
-
'''
|
20 |
-
data = SupervisedDataset(args['data_path'], args['image_root_path'])
|
21 |
-
|
22 |
-
sampler = torch.utils.data.RandomSampler(data)
|
23 |
-
world_size = torch.distributed.get_world_size()
|
24 |
-
rank = torch.distributed.get_rank()
|
25 |
-
batch_size = args['world_size'] * args['dschf'].config['train_micro_batch_size_per_gpu']
|
26 |
-
batch_sampler = DistributedBatchSampler(
|
27 |
-
sampler,
|
28 |
-
batch_size,
|
29 |
-
True,
|
30 |
-
rank,
|
31 |
-
world_size
|
32 |
-
)
|
33 |
-
iter_ = DataLoader(
|
34 |
-
data,
|
35 |
-
batch_sampler=batch_sampler,
|
36 |
-
num_workers=1,
|
37 |
-
collate_fn=data.collate,
|
38 |
-
pin_memory=True
|
39 |
-
)
|
40 |
-
return data, iter_, sampler
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|