parquet-converter commited on
Commit
aa24cd0
·
1 Parent(s): d61814d

Update parquet files (step 7 of 249)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Artsoft Mach 4 Crack 536 [PATCHED] A Complete Guide for CNC Enthusiasts.md +0 -181
  2. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bms.exe.md +0 -28
  3. spaces/1gistliPinn/ChatGPT4/Examples/AutoCADMechanical2019x64ISOKeygenSadeemPCdownloadpc TOP.md +0 -6
  4. spaces/1gistliPinn/ChatGPT4/Examples/Checklist Persiapan Majlis Perkahwinan Pdf Download !!LINK!!.md +0 -64
  5. spaces/1gistliPinn/ChatGPT4/Examples/Free Action With Serial Key 2016 Fixed.md +0 -6
  6. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Bingo Blitz Hack 2023 Unlimited Credits and Coins with Mod APK.md +0 -112
  7. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Call of Duty Warzone Mobile APK - The Most Epic Mobile FPS Game Ever.md +0 -99
  8. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DRAGON BALL LEGENDS APK - Summon and Fight with Your Favorite DB Characters in 3D.md +0 -159
  9. spaces/1phancelerku/anime-remove-background/Bloody Vampire Season 2 A Novel by Zanoor Writes - PDF Download or Online Reading.md +0 -139
  10. spaces/1phancelerku/anime-remove-background/FIFA 19 APK Download Latest Version 2023 for Android.md +0 -124
  11. spaces/1toTree/lora_test/ppdiffusers/pipelines/stochastic_karras_ve/__init__.py +0 -17
  12. spaces/AI-Hobbyist/Hoyo-RVC/docs/training_tips_ja.md +0 -64
  13. spaces/AIFILMS/StyleGANEX/models/stylegan2/op/conv2d_gradfix.py +0 -227
  14. spaces/AIGC-Audio/AudioGPT/NeuralSeq/tasks/tts/pe.py +0 -155
  15. spaces/AIWaves/Debate/app.py +0 -365
  16. spaces/Adapter/CoAdapter/ldm/modules/extra_condition/midas/midas/vit.py +0 -491
  17. spaces/Aditya9790/yolo7-object-tracking/utils/metrics.py +0 -227
  18. spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/sde_team_given_tests.py +0 -128
  19. spaces/AgentVerse/agentVerse/agentverse/output_parser/output_parser.py +0 -621
  20. spaces/AlanMars/QYL-AI-Space/modules/llama_func.py +0 -166
  21. spaces/Alycer/VITS-Umamusume-voice-synthesizer/text/cantonese.py +0 -59
  22. spaces/Andy1621/uniformer_image_detection/configs/cascade_rcnn/cascade_rcnn_r101_fpn_20e_coco.py +0 -2
  23. spaces/Andy1621/uniformer_image_detection/mmdet/models/necks/nasfcos_fpn.py +0 -161
  24. spaces/Andy1621/uniformer_image_segmentation/configs/ocrnet/ocrnet_hr48_512x512_40k_voc12aug.py +0 -39
  25. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/cnn/bricks/conv.py +0 -44
  26. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/ops/nms.py +0 -417
  27. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/parallel/distributed_deprecated.py +0 -70
  28. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/packages/__init__.py +0 -0
  29. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/rotate.py +0 -64
  30. spaces/Baptlem/UCDR-Net/app.py +0 -360
  31. spaces/Benson/text-generation/Examples/Descargar Archivo Zip Brawlhalla.md +0 -88
  32. spaces/Benson/text-generation/Examples/Descargar Genshin Impacto En El Ordenador Porttil.md +0 -106
  33. spaces/Big-Web/MMSD/env/Lib/site-packages/botocore/waiter.py +0 -393
  34. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/util/ssl_.py +0 -495
  35. spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/command/check.py +0 -151
  36. spaces/BramVanroy/spacey_conll/README.md +0 -11
  37. spaces/CVPR/LIVE/pybind11/tests/test_modules.cpp +0 -98
  38. spaces/CVPR/LIVE/thrust/thrust/system/detail/adl/transform.h +0 -44
  39. spaces/CVPR/WALT/mmdet/models/roi_heads/mask_heads/fused_semantic_head.py +0 -107
  40. spaces/ChallengeHub/Chinese-LangChain/app_modules/presets.py +0 -82
  41. spaces/ChandraMohanNayal/AutoGPT/tests/milvus_memory_test.py +0 -72
  42. spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/components/Version.js +0 -96
  43. spaces/Cpp4App/Cpp4App/CDM/detect_compo/lib_ip/ip_detection.py +0 -574
  44. spaces/Cropinky/hana_hanak_houses/realesrgan/models/realesrnet_model.py +0 -188
  45. spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/data/datasets/evaluation/word/util/cmd.py +0 -6
  46. spaces/DHEIVER/Pedrita/app.py +0 -101
  47. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/aiohttp/http_websocket.py +0 -701
  48. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/T_T_F_A_.py +0 -5
  49. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/index-e2533c7c.js +0 -2
  50. spaces/DaleChen/AutoGPT/autogpt/memory/weaviate.py +0 -127
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Artsoft Mach 4 Crack 536 [PATCHED] A Complete Guide for CNC Enthusiasts.md DELETED
@@ -1,181 +0,0 @@
1
- <br />
2
- <h1>Artsoft Mach 4 Crack 536: What You Need to Know</h1>
3
- <p>If you are looking for a way to control your CNC machinery, PLC equipment, or robotics, you might have heard of <strong>Artsoft Mach 4</strong>, a powerful and flexible software that can handle very large files and complex motions. But what if you don't want to pay for the license fee or deal with the activation process? You might be tempted to use a <strong>crack</strong> instead. But is it worth it? In this article, we will explain what Artsoft Mach 4 and a crack are, how to download and install Artsoft Mach 4 Crack 536, the pros and cons of using it, and some alternatives to consider.</p>
4
- <h2>artsoft mach 4 crack 536</h2><br /><p><b><b>DOWNLOAD</b> &#9193; <a href="https://byltly.com/2uKzW5">https://byltly.com/2uKzW5</a></b></p><br /><br />
5
- <h2>Introduction</h2>
6
- <h3>What is Artsoft Mach 4?</h3>
7
- <p>Artsoft Mach 4 is a software that can control CNC machinery, PLC equipment, and robotics. It is the newest version of CNC motion control software from Artsoft USA, which has been developing software for CNC machines since 2001. Mach 4 is designed to be expandable, flexible, and extremely responsive for use with very large files. It can work with different types of motion controllers, such as parallel port, Galil, Vital Systems, PMDX, PoLabs, and CNC4PC. It can also support different types of machines, such as mills, drills, lathes, routers, plasma cutters, lasers, and more.</p>
8
- <h3>What is a crack?</h3>
9
- <p>A crack is a modified version of a software that bypasses its security features or license verification. It can be a file that replaces the original executable file of the software, or a patch that modifies the code of the software. A crack can allow users to access all the features of the software without paying for it or activating it.</p>
10
- <h3>Why do people use cracks?</h3>
11
- <p>People use cracks for various reasons. Some common ones are:</p>
12
- <ul>
13
- <li>To save money. Some software can be very expensive, especially for hobbyists or students who have limited budgets.</li>
14
- <li>To access all features. Some software may have limited functionality or features in their trial or demo versions.</li>
15
- <li>To avoid license restrictions. Some software may have strict license terms that limit the number of installations or devices that can use it.</li>
16
- </ul>
17
- <h2>How to download and install Artsoft Mach 4 Crack 536</h2>
18
- <h3>Step 1: Find a reliable source</h3>
19
- <p>The first step to download and install Artsoft Mach 4 Crack 536 is to find a reliable source that offers the file. There are many websites that claim to provide cracks for various software, but not all of them are trustworthy. Some may contain malware, viruses, spyware, or adware that can harm your computer or steal your personal information. Some may also provide fake or outdated files that do not work properly.</p>
20
- <p>To avoid these risks, you should look for sources that have positive reviews, feedbacks, ratings, or comments from other users. You should also scan the file with an antivirus program before opening it.</p>
21
- <p>artsoft mach 4 license key generator<br />
22
- artsoft mach 4 activation code free<br />
23
- artsoft mach 4 full version download<br />
24
- artsoft mach 4 serial number crack<br />
25
- artsoft mach 4 patch file<br />
26
- artsoft mach 4 software cracked<br />
27
- artsoft mach 4 keygen torrent<br />
28
- artsoft mach 4 registration code<br />
29
- artsoft mach 4 product key<br />
30
- artsoft mach 4 crack download link<br />
31
- artsoft mach 4 license file<br />
32
- artsoft mach 4 crack install guide<br />
33
- artsoft mach 4 activation key<br />
34
- artsoft mach 4 crack latest version<br />
35
- artsoft mach 4 software free download<br />
36
- artsoft mach 4 crack for windows 10<br />
37
- artsoft mach 4 serial key crack<br />
38
- artsoft mach 4 license code<br />
39
- artsoft mach 4 crack zip file<br />
40
- artsoft mach 4 keygen download<br />
41
- artsoft mach 4 crack online<br />
42
- artsoft mach 4 activation crack<br />
43
- artsoft mach 4 full crack<br />
44
- artsoft mach 4 software crack download<br />
45
- artsoft mach 4 license crack<br />
46
- artsoft mach 4 crack for mac<br />
47
- artsoft mach 4 serial number generator<br />
48
- artsoft mach 4 registration key<br />
49
- artsoft mach 4 product key crack<br />
50
- artsoft mach 4 crack direct download<br />
51
- artsoft mach 4 license generator<br />
52
- artsoft mach 4 crack setup file<br />
53
- artsoft mach 4 activation key generator<br />
54
- artsoft mach 4 crack latest update<br />
55
- artsoft mach 4 software free trial<br />
56
- artsoft mach 4 crack for windows 7<br />
57
- artsoft mach 4 serial key generator<br />
58
- artsoft mach 4 license key crack<br />
59
- artsoft mach 4 crack rar file<br />
60
- artsoft mach 4 keygen free download<br />
61
- artsoft mach 4 crack offline activation<br />
62
- artsoft mach 4 activation code generator<br />
63
- artsoft mach 4 full version crack<br />
64
- artsoft mach 4 software download with crack<br />
65
- artsoft mach 4 license key free download<br />
66
- artsoft mach 4 crack for linux<br />
67
- artsoft mach 4 serial number free download<br />
68
- artsoft mach 4 registration code generator<br />
69
- artsoft mach 4 product key generator<br />
70
- artsoft mach 4 crack no survey</p>
71
- <h3>Step 2: Download the file</h3>
72
- <p>The next step is to download the file from the source you have chosen. The file size may vary depending on the source, but it should be around 300 MB. The file name may also vary depending on the source, but it should contain "Artsoft", "Mach4", and "crack" in some form.</p>
73
- <p>To download the file, you may need to click on a link or button that says "Download", "Download Now", "Free Download", or something similar. You may also need to complete some surveys, offers, captcha tests, or other tasks to unlock the download link. Be careful not to click on any ads or pop-ups that may appear on the website.</p>
74
- <h3>Step 3: Extract the file</h3>
75
- <p>The file you have downloaded should be in a compressed format, such as ZIP or RAR. To extract it, you will need a program that can handle these formats, such as WinRAR or 7-Zip. You can download these programs for free from their official websites.</p>
76
- <p>To extract the file, you will need to right-click on it and choose "Extract Here" or "Extract to" from the menu. You will then see a folder with the same name as the file appear in the same location as the file.</p>
77
- <h3>Step 4: Run the installer</h3>
78
- <p>The folder you have extracted should contain an installer file that has an icon of a blue gear and says "Mach4Installer". To run it, you will need to double-click on it and follow the instructions on the screen.</p>
79
- <p>The installer will ask you to choose a language and accept the terms and conditions. It will then ask you to choose a destination folder where you want to install Artsoft Mach 4. The default folder is C:\Mach4Hobby\ , but you can change it if you want.</p>
80
- <p>The installer will then copy some files and create some shortcuts on your desktop and start menu. It will also ask you if you want to launch Artsoft Mach 4 after installation.</p>
81
- <h3>Step 5: Copy and paste the crack file</h3>
82
- <p>The final step is to copy and paste the crack file into the installation folder of Artsoft Mach 4. The crack file should be in the same folder as the installer file and have an icon of a red gear and say "Mach4". To copy it, you will need to right-click on it and choose "Copy" from the menu.</p>
83
- <p>To paste it into the installation folder of Artsoft Mach 4, you will need to open it by clicking on its shortcut on your desktop or start menu. You will then see a window with some tabs and buttons at the top. You will need to click on "Help" and then "About". You will then see another window with some information about Artsoft Mach 4.</p>
84
- <p>You will need to close this window by clicking on "OK". You will then see another window with some folders and files in it. This is where you need to paste the crack file by right-clicking on an empty space and choosing "Paste" from the menu.</p>
85
- <p>You will then see a message asking you if you want to replace an existing file with the same name. You will need to click on "Yes" or "Replace". This will complete the installation process of Artsoft Mach 4 Crack 536.</p>
86
- <h2>Pros and cons of using Artsoft Mach 4 Crack 536</h2>
87
- <h3>Pros</h3>
88
- <p>Using Artsoft Mach 4 Crack 536 can have some advantages over using the official version of Artsoft Mach 4. Some of them are:</p>
89
- <h4>Save money</h4>
90
- <p>The official version of Artsoft Mach 4 costs $200 for the hobby version and $1400 for the industrial version (as of May 2021). Using a crack can save you this amount of money if you don't want to pay for the license fee.</p>
91
- <h4>Access all features</h4>
92
- <p>The official version of Artsoft Mach 4 has different versions with different levels of functionality and features. The hobby version has fewer features than the industrial version, and both versions require additional plugins or licenses for certain motion controllers or devices. Using a crack can allow you to access all the features of both the hobby and the industrial versions of Artsoft Mach 4 without any limitations.</p>
93
- <h4>No license required</h4>
94
- <p>The official version of Artsoft Mach 4 requires a license to activate and use the software. The license is tied to a specific computer and cannot be transferred to another one. If you change your computer or hardware, you may need to contact Artsoft to get a new license. Using a crack can avoid this hassle and let you use the software on any computer you want.</p>
95
- <h3>Cons</h3>
96
- <p>Using Artsoft Mach 4 Crack 536 can also have some disadvantages over using the official version of Artsoft Mach 4. Some of them are:</p>
97
- <h4>Risk of malware infection</h4>
98
- <p>As mentioned earlier, not all sources that provide cracks are reliable or safe. Some may contain malicious programs that can infect your computer or steal your personal information. These programs can damage your files, slow down your system, spy on your activities, or even take control of your machine. You may not even notice that you have been infected until it is too late.</p>
99
- <h4>Legal issues</h4>
100
- <p>Using a crack is also illegal and unethical. It violates the terms and conditions of Artsoft Mach 4 and infringes on the intellectual property rights of Artsoft USA. You may face legal consequences if you are caught using a crack, such as fines, lawsuits, or even criminal charges. You may also lose your warranty or support from Artsoft or your machine manufacturer if you use a crack.</p>
101
- <h4>No updates or support</h4>
102
- <p>Using a crack also means that you will not receive any updates or support from Artsoft or your machine manufacturer. Updates are important to fix bugs, improve performance, add new features, or enhance compatibility with new hardware or software. Without updates, you may encounter errors, crashes, or compatibility issues with your machine or other devices. You may also miss out on new features that could improve your productivity or creativity.</p>
103
- <p>Support is also important to help you troubleshoot any problems or issues that you may face with the software or the machine. Without support, you may have to rely on online forums, blogs, or videos for help, which may not be accurate, reliable, or up-to-date. You may also have to spend more time and money to fix the problems yourself.</p>
104
- <h2>Alternatives to using Artsoft Mach 4 Crack 536</h2>
105
- <p>If you are looking for a way to control your CNC machinery, PLC equipment, or robotics without using a crack, there are some alternatives that you can consider. Some of them are:</p>
106
- <h3>Buy the official version</h3>
107
- <p>The best and most legal way to use Artsoft Mach 4 is to buy the official version from Artsoft USA or an authorized reseller. You can choose between the hobby version and the industrial version depending on your needs and budget. You can also buy additional plugins or licenses for specific motion controllers or devices that you want to use.</p>
108
- <p>By buying the official version, you will get access to all the features and functionality of Artsoft Mach 4 without any limitations. You will also get regular updates and support from Artsoft and your machine manufacturer. You will also avoid any legal issues or malware risks that come with using a crack.</p>
109
- <h3>Use a free or open source software</h3>
110
- <p>If you don't want to pay for Artsoft Mach 4 but still want to use a software that can control your CNC machinery, PLC equipment, or robotics, you can look for a free or open source software that can do the same job. There are many free or open source software that can control CNC machines, such as LinuxCNC, GRBL, G-Code Sender, Universal G-Code Sender, CNCjs, bCNC, and more.</p>
111
- <p>These software are usually developed by enthusiasts or communities who share their code and knowledge with others. They may not have all the features or functionality of Artsoft Mach 4, but they may have enough for your needs. They may also have more compatibility with different types of hardware or devices than Artsoft Mach 4.</p>
112
- <p>However, these software may also have some drawbacks compared to Artsoft Mach 4. They may not be as user-friendly, stable, or reliable as Artsoft Mach 4. They may also have less support or documentation than Artsoft Mach 4. You may also need to learn how to install, configure, and use them properly.</p>
113
- <h3>Use a trial or demo version</h3>
114
- <p>If you want to try Artsoft Mach 4 before buying it, you can use a trial or demo version that Artsoft USA offers on its website. The trial or demo version allows you to use Artsoft Mach 4 for a limited time or with limited features. You can use it to test the software and see if it meets your expectations and requirements.</p>
115
- <p>The trial or demo version is a good way to get familiar with Artsoft Mach 4 and its features and functionality. You can also use it to compare it with other software that you may be interested in. However, the trial or demo version is not meant to be used for production or commercial purposes. You will still need to buy the official version if you want to use Artsoft Mach 4 for your projects.</p>
116
- <h2>Conclusion</h2>
117
- <p>Artsoft Mach 4 is a powerful and flexible software that can control CNC machinery, PLC equipment, and robotics. It is the newest version of CNC motion control software from Artsoft USA, which has been developing software for CNC machines since 2001. It can work with different types of motion controllers and machines, and it can handle very large files and complex motions.</p>
118
- <p>However, Artsoft Mach 4 is not free or cheap. It costs $200 for the hobby version and $1400 for the industrial version (as of May 2021). It also requires a license to activate and use the software. Some people may want to use a crack instead of buying the official version. A crack is a modified version of a software that bypasses its security features or license verification. It can allow users to access all the features of Artsoft Mach 4 without paying for it or activating it.</p>
119
- <p>But using a crack is not a good idea. It has many disadvantages over using the official version of Artsoft Mach 4. Some of them are:</p>
120
- <ul>
121
- <li>Risk of malware infection. Some cracks may contain malicious programs that can harm your computer or steal your personal information.</li>
122
- <li>Legal issues. Using a crack is illegal and unethical. It violates the terms and conditions of Artsoft Mach 4 and infringes on the intellectual property rights of Artsoft USA. You may face legal consequences if you are caught using a crack.</li>
123
- <li>No updates or support. Using a crack means that you will not receive any updates or support from Artsoft or your machine manufacturer. Updates are important to fix bugs, improve performance, add new features, or enhance compatibility with new hardware or software. Support is important to help you troubleshoot any problems or issues that you may face with the software or the machine.</li>
124
- </ul>
125
- <p>Therefore, we recommend that you do not use a crack for Artsoft Mach 4. Instead, you should consider some alternatives that are legal and safe. Some of them are:</p>
126
- <ul>
127
- <li>Buy the official version. The best and most legal way to use Artsoft Mach 4 is to buy the official version from Artsoft USA or an authorized reseller. You can choose between the hobby version and the industrial version depending on your needs and budget. You can also buy additional plugins or licenses for specific motion controllers or devices that you want to use.</li>
128
- <li>Use a free or open source software. If you don't want to pay for Artsoft Mach 4 but still want to use a software that can control your CNC machinery, PLC equipment, or robotics, you can look for a free or open source software that can do the same job. There are many free or open source software that can control CNC machines, such as LinuxCNC, GRBL, G-Code Sender, Universal G-Code Sender, CNCjs, bCNC, and more.</li>
129
- <li>Use a trial or demo version. If you want to try Artsoft Mach 4 before buying it, you can use a trial or demo version that Artsoft USA offers on its website. The trial or demo version allows you to use Artsoft Mach 4 for a limited time or with limited features. You can use it to test the software and see if it meets your expectations and requirements.</li>
130
- </ul>
131
- <p>We hope that this article has helped you understand what Artsoft Mach 4 Crack 536 is, how to download and install it, the pros and cons of using it, and some alternatives to consider. We hope that you will make an informed decision and choose the best option for your needs.</p>
132
- <h2>FAQs</h2>
133
- <p>Here are some frequently asked questions about Artsoft Mach 4 Crack 536:</p>
134
- <h3>Q: Is Artsoft Mach 4 Crack 536 safe?</h3>
135
- <p>A: No, it is not safe. It may contain malware, viruses, spyware, or adware that can harm your computer or steal your personal information. It may also damage your files, slow down your system, spy on your activities, or even take control of your machine. You may not even notice that you have been infected until it is too late.</p>
136
- <h3>Q: Is Artsoft Mach 4 Crack 536 legal?</h3>
137
- <p>A: No, it is not legal. It violates the terms and conditions of Artsoft Mach 4 and infringes on the intellectual property rights of Artsoft USA. You may face legal consequences if you are caught using a crack, such as fines, lawsuits, or even criminal charges. You may also lose your warranty or support from Artsoft or your machine manufacturer if you use a crack.</p>
138
- <h3>Q: Is Artsoft Mach 4 Crack 536 worth it?</h3>
139
- <p>A: No, it is not worth it. It has many disadvantages over using the official version of Artsoft Mach 4. Some of them are:</p>
140
- <ul>
141
- <li>Risk of malware infection. Some cracks may contain malicious programs that can harm your computer or steal your personal information.</li>
142
- <li>Legal issues. Using a crack is illegal and unethical. It violates the terms and conditions of Artsoft Mach 4 and infringes on the intellectual property rights of Artsoft USA. You may face legal consequences if you are caught using a crack.</li>
143
- <li>No updates or support. Using a crack means that you will not receive any updates or support from Artsoft or your machine manufacturer. Updates are important to fix bugs, improve performance, add new features, or enhance compatibility with new hardware or software. Support is important to help you troubleshoot any problems or issues that you may face with the software or the machine.</li>
144
- </ul>
145
- <p>Therefore, we recommend that you do not use a crack for Artsoft Mach 4. Instead, you should consider some alternatives that are legal and safe.</p>
146
- <h3>Q: What are some alternatives to using Artsoft Mach 4 Crack 536?</h3>
147
- <p>A: Some alternatives to using a crack for Artsoft Mach 4 are:</p>
148
- <ul>
149
- <li>Buy the official version. The best and most legal way to use Artsoft Mach 4 is to buy the official version from Artsoft USA or an authorized reseller. You can choose between the hobby version and the industrial version depending on your needs and budget. You can also buy additional plugins or licenses for specific motion controllers or devices that you want to use.</li>
150
- <li>Use a free or open source software. If you don't want to pay for Artsoft Mach 4 but still want to use a software that can control your CNC machinery, PLC equipment, or robotics, you can look for a free or open source software that can do the same job. There are many free or open source software that can control CNC machines, such as LinuxCNC, GRBL, G-Code Sender, Universal G-Code Sender, CNCjs, bCNC, and more.</li>
151
- <li>Use a trial or demo version. If you want to try Artsoft Mach 4 before buying it, you can use a trial or demo version that Artsoft USA offers on its website. The trial or demo version allows you to use Artsoft Mach 4 for a limited time or with limited features. You can use it to test the software and see if it meets your expectations and requirements.</li>
152
- </ul>
153
- <h3>Q: How to download and install Artsoft Mach 4 Crack 536?</h3>
154
- <p>A: To download and install Artsoft Mach 4 Crack 536, you will need to follow these steps:</p>
155
- <ol>
156
- <li>Find a reliable source that offers the file. There are many websites that claim to provide cracks for various software, but not all of them are trustworthy. Some may contain malware, viruses, spyware, or adware that can harm your computer or steal your personal information. Some may also provide fake or outdated files that do not work properly.</li>
157
- <li>Download the file from the source you have chosen. The file size may vary depending on the source, but it should be around 300 MB. The file name may also vary depending on the source, but it should contain "Artsoft", "Mach4", and "crack" in some form.</li>
158
- <li>Extract the file from the compressed format, such as ZIP or RAR. To extract it, you will need a program that can handle these formats, such as WinRAR or 7-Zip. You can download these programs for free from their official websites.</li>
159
- <li>Run the installer file that has an icon of a blue gear and says "Mach4Installer". To run it, you will need to double-click on it and follow the instructions on the screen.</li>
160
- <li>Copy and paste the crack file that has an icon of a red gear and says "Mach4" into the installation folder of Artsoft Mach 4. To copy it, you will need to right-click on it and choose "Copy" from the menu. To paste it into the installation folder of Artsoft Mach 4, you will need to open it by clicking on its shortcut on your desktop or start menu. You will then need to click on "Help" and then "About". You will then need to close this window by clicking on "OK". You will then see another window with some folders and files in it. This is where you need to paste the crack file by right-clicking on an empty space and choosing "Paste" from the menu. You will then need to click on "Yes" or "Replace" when asked if you want to replace an existing file with the same name.</li>
161
- </ol>
162
- <h3>Q: What are the differences between Artsoft Mach 4 Hobby and Industrial?</h3>
163
- <p>A: Artsoft Mach 4 Hobby and Industrial are two different versions of Artsoft Mach 4 that have different features and functionality. The hobby version is designed for simple hobby machines and costs $200 (as of May 2021). The industrial version is designed for complex industrial machines and costs $1400 (as of May 2021). Some of the differences between them are:</p>
164
- <ul>
165
- <li>The industrial version has more features than the hobby version, such as Macro B gcode programming, tool life management, screw mapping, and an advanced GUI editing tool.</li>
166
- <li>The industrial version has more compatibility than the hobby version, such as out of band axis (OBA), slave motors, and multiple gcode interpreters.</li>
167
- <li>The industrial version has more support than the hobby version, such as simulated 3D machining (with additional plugin license), professional screen designer, scripted M code, and PMC (Ladder Logic addressing for cnc/plc).</li>
168
- </ul>
169
- <p>You can find more details about the differences between Artsoft Mach 4 Hobby and Industrial on the official website of Artsoft USA or in this document.</p>
170
- <h3>Q: How to update Artsoft Mach 4?</h3>
171
- <p>A: To update Artsoft Mach 4, you will need to follow these steps:</p>
172
- <ol>
173
- <li>Go to the official website of Artsoft USA and download the latest version of Artsoft Mach 4 from the downloads page.</li>
174
- <li>Run the installer file that has an icon of a blue gear and says "Mach4Installer". To run it, you will need to double-click on it and follow the instructions on the screen.</li>
175
- <li>Choose the same destination folder where you have installed Artsoft Mach 4 before. The installer will overwrite the old files with the new ones.</li>
176
- <li>Restart your computer and launch Artsoft Mach 4. You should see the new version number in the title bar or in the help menu.</li>
177
- </ol>
178
- <p>Note: If you are using a crack for Artsoft Mach 4, you may not be able to update it or use the new features. You may also lose your crack file or get infected by malware during the update process. We recommend that you do not use a crack for Artsoft Mach 4 and buy the official version instead.</p>
179
- <h2>ed</h2></p> 0a6ba089eb<br />
180
- <br />
181
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bms.exe.md DELETED
@@ -1,28 +0,0 @@
1
- <br />
2
- <h1>How to Fix BMS.EXE Errors on Your PC</h1>
3
- <p>BMS.EXE is an executable file that belongs to various software programs, such as BusinessPhone Management Suite, Black Mesa, or 1,000 Solitaire Games. It is usually located in the C:\Windows\System32 folder and has a file size of about 5.31 MB. However, sometimes BMS.EXE can cause problems on your PC, such as crashing, freezing, or displaying error messages. In this article, we will show you how to fix BMS.EXE errors on your PC and prevent them from happening again.</p>
4
- <h2>bms.exe</h2><br /><p><b><b>Download</b> &#10026; <a href="https://byltly.com/2uKwui">https://byltly.com/2uKwui</a></b></p><br /><br />
5
- <h2>What Causes BMS.EXE Errors?</h2>
6
- <p>BMS.EXE errors can be caused by various factors, such as:</p>
7
- <ul>
8
- <li>Missing, corrupted, or moved BMS.EXE file</li>
9
- <li>Invalid or damaged registry entries related to BMS.EXE</li>
10
- <li>Malware infection that affects BMS.EXE or its associated software</li>
11
- <li>Conflicts with other programs or drivers that use BMS.EXE</li>
12
- <li>Incompatible or outdated versions of BMS.EXE or its associated software</li>
13
- </ul>
14
- <p>To fix BMS.EXE errors, you need to identify the root cause of the problem and apply the appropriate solution.</p>
15
- <h2>How to Fix BMS.EXE Errors?</h2>
16
- <p>Depending on the cause of the BMS.EXE error, you can try one or more of the following methods to fix it:</p>
17
- <p></p>
18
- <ol>
19
- <li><strong>Replace the missing or corrupted BMS.EXE file</strong>. If you have accidentally deleted, moved, or overwritten the BMS.EXE file, you can try to restore it from the Recycle Bin, a backup source, or a reliable website. Alternatively, you can reinstall the software that uses BMS.EXE, such as BusinessPhone Management Suite, Black Mesa, or 1,000 Solitaire Games. Make sure to download the latest version of the software from the official website and follow the installation instructions carefully.</li>
20
- <li><strong>Clean the registry entries related to BMS.EXE</strong>. If you have invalid or damaged registry entries that refer to BMS.EXE, you can use a registry cleaner tool to scan and fix them. A registry cleaner tool is a software that can automatically detect and repair registry errors on your PC. However, be careful when using a registry cleaner tool, as it can also delete some important registry entries that are needed for your system. Make sure to backup your registry before using a registry cleaner tool and only use a reputable one.</li>
21
- <li><strong>Scan your PC for malware infection</strong>. If you have malware infection that affects BMS.EXE or its associated software, you can use an antivirus or anti-malware program to scan and remove it. A malware infection can corrupt, modify, or delete BMS.EXE files and cause various problems on your PC. Make sure to update your antivirus or anti-malware program regularly and perform a full system scan periodically.</li>
22
- <li><strong>Update or uninstall conflicting programs or drivers</strong>. If you have conflicts with other programs or drivers that use BMS.EXE, you can try to update or uninstall them. Sometimes, different versions of BMS.EXE or its associated software can cause compatibility issues and lead to errors. To update your programs or drivers, you can use a software updater tool that can automatically check and install the latest updates for your PC. To uninstall your programs or drivers, you can use a software uninstaller tool that can completely remove them from your PC.</li>
23
- <li><strong>Repair or reinstall your Windows system</strong>. If none of the above methods work, you may have a corrupted or outdated Windows system that causes BMS.EXE errors. To repair your Windows system, you can use a system repair tool that can scan and fix various system issues on your PC. To reinstall your Windows system, you can use a system installer tool that can create a bootable USB drive or DVD and install a fresh copy of Windows on your PC. However, before repairing or reinstalling your Windows system, make sure to backup your important data and files.</li>
24
- </ol>
25
- <h2>Conclusion</h2>
26
- <p>BMS.EXE is an executable file that is used by various software programs on your PC. However, sometimes it can cause errors that affect your PC performance and stability. To</p> ddb901b051<br />
27
- <br />
28
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/AutoCADMechanical2019x64ISOKeygenSadeemPCdownloadpc TOP.md DELETED
@@ -1,6 +0,0 @@
1
- <h2>AutoCADMechanical2019x64ISOKeygenSadeemPCdownloadpc</h2><br /><p><b><b>Download File</b> &#10145; <a href="https://imgfil.com/2uy226">https://imgfil.com/2uy226</a></b></p><br /><br />
2
- <br />
3
- 4d29de3e1b<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Checklist Persiapan Majlis Perkahwinan Pdf Download !!LINK!!.md DELETED
@@ -1,64 +0,0 @@
1
- <h2>Checklist Persiapan Majlis Perkahwinan Pdf Download</h2><br /><p><b><b>Download File</b> &#128505; <a href="https://imgfil.com/2uxYow">https://imgfil.com/2uxYow</a></b></p><br /><br />
2
- <br />
3
- Page 2. Textual History
4
-
5
- Page 3. A Bibliography of the Rahbani, with an Appendix of Palimpsests
6
-
7
- Page 4. Recent Publications on the Qur’ān and the Qur’ānic Sciences
8
-
9
- Page 5. A Note on the Recently Published “Introduction to the History of the
10
-
11
- Qur’ān and the Qur’ānic Sciences”
12
-
13
- Page 6. The Legitimacy of the Qur’ānic Material in the Introduction
14
-
15
- Page 7. A Note on the Other References in the Text
16
-
17
- Page 8. I. The Qur’ān and the Holy Books
18
-
19
- Page 9. II. The Qur’ān and the Qur’ānic Sciences
20
-
21
- Page 10. III. A Word about Dictionaries
22
-
23
- Page 11. IV. The Qur’ān and the Summaries of the Qur’ān
24
-
25
- Page 12. V. The Qur’ān and its Language
26
-
27
- Page 13. VI. Introduction to the Qur’ānic Text
28
-
29
- Page 14. VII. The Qur’ānic Text
30
-
31
- Page 15. Conclusion
32
-
33
- Page 16. Bibliography of the Qur’ān and the Qur’ānic Sciences
34
-
35
- Page 17. Glossary of Arabic and Qur’ānic Terminology
36
-
37
- Page 18. List of Recent Publications on the Qur’ān and the Qur’ānic
38
-
39
- Sciences
40
-
41
- Page 19. Appendix A: A Bibliography of the Rahbani, with an Appendix of
42
-
43
- Palimpsests
44
-
45
- Page 20. Appendix B: A Note on the Recently Published “Introduction to the
46
-
47
- History of the Qur’ān and the Qur’ānic Sciences”
48
-
49
- Page 21. Appendix C: A Note on the Other References in the Text
50
-
51
- Page 22. Appendix D: A Note on the Legitimacy of the Qur’ānic Material
52
-
53
- Page 23. Appendix E: A Word about Dictionaries
54
-
55
- Page 24. Appendix F: A Note on the Qur’ān and the Summaries of the
56
-
57
- Qur’ān
58
-
59
- Page 25. Appendix G: A Note on the Qur’ān and its Language
60
-
61
- Page 26. Appendix H: Introduction to the Qur’ānic Text 4fefd39f24<br />
62
- <br />
63
- <br />
64
- <p></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Free Action With Serial Key 2016 Fixed.md DELETED
@@ -1,6 +0,0 @@
1
- <h2>Free Action With Serial Key 2016</h2><br /><p><b><b>Download File</b> &#10001; &#10001; &#10001; <a href="https://imgfil.com/2uy1GT">https://imgfil.com/2uy1GT</a></b></p><br /><br />
2
-
3
- Latest: Download Free Desktop Wallpapers of Chef Loony! | Series: ... Registration code: 10403029CF3644154841651AF141E800 Licensed e-mail: [email protected]. Registration code: 510B3C20A9E54E0FF1D2FC28BAD1220E 1fdad05405<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Bingo Blitz Hack 2023 Unlimited Credits and Coins with Mod APK.md DELETED
@@ -1,112 +0,0 @@
1
-
2
- <h1>Bingo Blitz Unlimited Credits APK: How to Get Free Credits for Your Favorite Bingo Game</h1>
3
- <p>If you love playing bingo online, you probably know how addictive and fun Bingo Blitz is. It's one of the most popular bingo games on Facebook, with millions of players from all over the world. But there's one problem: you need credits to play.</p>
4
- <h2>bingo blitz unlimited credits apk</h2><br /><p><b><b>Download</b> &#8250;&#8250;&#8250; <a href="https://urlin.us/2uT0Ch">https://urlin.us/2uT0Ch</a></b></p><br /><br />
5
- <p>Credits are the currency of Bingo Blitz, and they allow you to buy bingo cards, power-ups, and other goodies. You can earn credits by playing bingo games, completing quests, or spinning the wheel. But sometimes, you may run out of credits or want more than you can get for free.</p>
6
- <p>That's where Bingo Blitz Unlimited Credits APK comes in handy. This is a special version of the game that gives you unlimited credits for free. Yes, you heard that right: free credits every day, without spending a dime.</p>
7
- <p>But how do you get this amazing app? And how do you use it to get free credits for your favorite bingo game? In this article, we'll answer all these questions and more. We'll show you how to download and install Bingo Blitz Unlimited Credits APK on your Android device, what are its features and benefits, how to use it to get free credits every day, and some tips and tricks to make the most of it.</p>
8
- <p>So, if you're ready to enjoy unlimited bingo fun with Bingo Blitz Unlimited Credits APK, read on!</p>
9
- <h2>How to download and install Bingo Blitz Unlimited Credits APK on your Android device?</h2>
10
- <p>The first step to getting free credits for Bingo Blitz is to download and install Bingo Blitz Unlimited Credits APK on your Android device. This is a modified version of the original game that bypasses the credit limit and gives you unlimited access to all the features of the game.</p>
11
- <p>But where can you find this app? And how can you install it safely on your device? Here are the steps:</p>
12
- <ol>
13
- <li>Go to [Credits For Bingo Blitz APK](^2^) or [Bingo Blitz Apk Mod New Version](^3^) and download the latest version of Bingo Blitz Unlimited Credits APK.</li>
14
- <li>Before installing the app, make sure you enable "Unknown sources" in your device settings. This will allow you to install apps from sources other than Google Play Store.</li>
15
- <li>Locate the downloaded file in your device storage and tap on it to start the installation process.</li>
16
- <li>Follow the instructions on the screen and wait for the installation to finish.</ <li>Once the app is installed, you can launch it from your app drawer or home screen.</li>
17
- </ol>
18
- <p>Congratulations! You have successfully downloaded and installed Bingo Blitz Unlimited Credits APK on your Android device. Now you can enjoy unlimited credits for your favorite bingo game.</p>
19
- <p>bingo blitz free credits mod apk<br />
20
- bingo blitz hack unlimited credits apk<br />
21
- bingo blitz mod apk unlimited coins and credits<br />
22
- bingo blitz cheats unlimited credits apk<br />
23
- bingo blitz apk mod free credits and power-ups<br />
24
- bingo blitz unlimited credits generator apk<br />
25
- bingo blitz mod apk 2023 unlimited credits<br />
26
- bingo blitz mod apk latest version unlimited credits<br />
27
- bingo blitz free credits hack apk download<br />
28
- bingo blitz unlimited credits apk no survey<br />
29
- bingo blitz mod apk unlimited everything<br />
30
- bingo blitz hack apk 2023<br />
31
- bingo blitz free coins and credits apk<br />
32
- bingo blitz modded apk download<br />
33
- bingo blitz hack tool apk<br />
34
- bingo blitz unlimited power-ups apk<br />
35
- bingo blitz mod menu apk<br />
36
- bingo blitz freebies mod apk<br />
37
- bingo blitz hack online apk<br />
38
- bingo blitz cracked apk<br />
39
- bingo blitz premium mod apk<br />
40
- bingo blitz pro mod apk<br />
41
- bingo blitz vip mod apk<br />
42
- bingo blitz mega mod apk<br />
43
- bingo blitz elite mod apk<br />
44
- bingo blitz hack version apk<br />
45
- bingo blitz cheat engine apk<br />
46
- bingo blitz glitch apk<br />
47
- bingo blitz patcher apk<br />
48
- bingo blitz trainer apk<br />
49
- how to get unlimited credits in bingo blitz apk<br />
50
- how to hack bingo blitz with lucky patcher apk<br />
51
- how to download bingo blitz mod apk<br />
52
- how to install bingo blitz mod apk<br />
53
- how to update bingo blitz mod apk<br />
54
- how to use bingo blitz mod apk<br />
55
- how to play bingo blitz mod apk offline<br />
56
- how to get free power-ups in bingo blitz mod apk<br />
57
- how to get free coins in bingo blitz mod apk<br />
58
- how to get free keys in bingo blitz mod apk<br />
59
- how to get free daub alerts in bingo blitz mod apk<br />
60
- how to get free instant wins in bingo blitz mod apk<br />
61
- how to get free shadow cards in bingo blitz mod apk<br />
62
- how to get free collection items in bingo blitz mod apk<br />
63
- how to get free tournament tickets in bingo blitz mod apk<br />
64
- how to get free daily bonuses in bingo blitz mod apk<br />
65
- how to get free gifts in bingo blitz mod apk<br />
66
- how to get free spins in bingo blitz mod apk<br />
67
- how to get free slots in bingo blitz mod apk</p>
68
- <h2>What are the features and benefits of Bingo Blitz Unlimited Credits APK?</h2>
69
- <p>Bingo Blitz Unlimited Credits APK is not just a regular bingo game. It's a bingo game with unlimited credits and unlimited fun. Here are some of the features and benefits of this app:</p>
70
- <ul>
71
- <li>You get unlimited credits for free every day. You don't have to worry about running out of credits or spending money to buy more. You can play as many bingo games as you want, whenever you want.</li>
72
- <li>You get access to all the rooms, cards, power-ups, and collections in the game. You can explore different themes and locations, collect rare items, and boost your bingo experience with power-ups.</li>
73
- <li>You get to play with millions of other bingo lovers from all over the world. You can chat with them, make new friends, and join clubs and tournaments.</li>
74
- <li>You get to enjoy high-quality graphics, sound effects, and animations. The game is designed to give you a realistic and immersive bingo experience.</li>
75
- <li>You get to enjoy regular updates and new features. The game is constantly updated with new rooms, cards, collections, events, and more.</li>
76
- </ul>
77
- <p>As you can see, Bingo Blitz Unlimited Credits APK is a bingo game like no other. It's a game that gives you unlimited credits and unlimited fun.</p> <h2>How to use Bingo Blitz Unlimited Credits APK to get free credits every day?</h2>
78
- <p>Now that you have Bingo Blitz Unlimited Credits APK on your device, you may be wondering how to use it to get free credits every day. It's very simple and easy. Here are the steps:</p>
79
- <ol>
80
- <li>Launch the app and log in with your Facebook account or create a new one.</li>
81
- <li>Once you're in the game, you'll see a pop-up window that says "Congratulations! You have received 1000 free credits!" Tap on "Claim" to get your free credits.</li>
82
- <li>You can also get more free credits by tapping on the "Free Credits" button at the top of the screen. This will take you to a page where you can watch videos, complete surveys, or download other apps to earn more credits.</li>
83
- <li>You can also get free credits by playing bingo games, completing quests, spinning the wheel, or opening chests.</li>
84
- <li>You can check your credit balance at any time by tapping on the "Credits" icon at the bottom of the screen.</li>
85
- </ol>
86
- <p>That's it! You can use Bingo Blitz Unlimited Credits APK to get free credits every day and enjoy unlimited bingo fun.</p>
87
- <h2>Tips and tricks to make the most of Bingo Blitz Unlimited Credits APK</h2>
88
- <p>Bingo Blitz Unlimited Credits APK is a great app that gives you unlimited credits and unlimited fun. But how can you make the most of it? Here are some tips and tricks to help you out:</p>
89
- <ul>
90
- <li>Use power-ups wisely. Power-ups are special items that can help you win bingo games faster and easier. They can do things like mark extra numbers, double your score, or give you extra time. You can buy power-ups with credits or get them for free by playing games or opening chests. But don't use them all at once. Save them for when you really need them, like when you're close to a bingo or when you're playing in a tough room.</li>
91
- <li>Collect items and complete collections. Items are rare and valuable objects that you can find in different bingo rooms. They are part of collections that have different themes and rewards. You can see your items and collections by tapping on the "Items" icon at the bottom of the screen. Try to collect as many items as you can and complete collections to get extra credits, power-ups, keys, and other prizes.</li>
92
- <li>Join clubs and tournaments. Clubs are groups of players who work together to achieve common goals and earn rewards. You can join a club or create your own by tapping on the "Clubs" icon at the bottom of the screen. You can chat with your club members, send and receive gifts, and participate in club challenges and events. Tournaments are competitions where you can play against other players and win big prizes. You can join a tournament by tapping on the "Tournaments" icon at the bottom of the screen. You can choose from different types of tournaments, like solo, team, or special ones.</li>
93
- <li>Play smart and have fun. Bingo is a game of chance, but it also requires some skill and strategy. You can improve your chances of winning by choosing the right number of cards, daubing quickly and accurately, using power-ups wisely, and playing in different rooms. But don't forget to have fun. Bingo is a social game, so chat with other players, make new friends, and enjoy the thrill of bingo.</li>
94
- </ul>
95
- <h2>Conclusion: Why you should try Bingo Blitz Unlimited Credits APK today</h2>
96
- <p>Bingo Blitz Unlimited Credits APK is a bingo game that gives you unlimited credits and unlimited fun. It's a game that lets you play bingo online with millions of other players from all over the world. It's a game that lets you explore different themes and locations, collect rare items, and boost your bingo experience with power-ups. It's a game that lets you join clubs and tournaments, chat with friends, and win big prizes.</p>
97
- <p>Bingo Blitz Unlimited Credits APK is a game that gives you everything you need to enjoy bingo online. It's a game that gives you free credits every day, without spending a dime. It's a game that gives you access to all the features and benefits of the original game, without any limitations.</p>
98
- <p>Bingo Blitz Unlimited Credits APK is a game that you should try today. It's a game that will make you fall in love with bingo all over again.</p>
99
- <h2>FAQs: Frequently asked questions about Bingo Blitz Unlimited Credits APK</h2>
100
- <p>Here are some of the most common questions that people ask about Bingo Blitz Unlimited Credits APK:</p>
101
- <h3>Q: Is Bingo Blitz Unlimited Credits APK safe to use?</h3>
102
- <p>A: Yes, Bingo Blitz Unlimited Credits APK is safe to use. It's a modified version of the original game that does not harm your device or your account. It's tested and verified by many users and experts. However, you should always download it from a trusted source and scan it with an antivirus before installing it.</p>
103
- <h3>Q: How can I update Bingo Blitz Unlimited Credits APK?</h3>
104
- <p>A: Bingo Blitz Unlimited Credits APK is updated regularly with new features and improvements. You can check for updates by launching the app and tapping on the "Settings" icon at the top of the screen. Then, tap on "Check for updates" and follow the instructions. You can also visit [Credits For Bingo Blitz APK] or [Bingo Blitz Apk Mod New Version] to download the latest version of the app.</p>
105
- <h3>Q: Can I play Bingo Blitz Unlimited Credits APK on other devices?</h3>
106
- <p>A: Bingo Blitz Unlimited Credits APK is designed for Android devices only. You cannot play it on iOS, Windows, or Mac devices. However, you can use an Android emulator to run it on your PC or laptop. An Android emulator is a software that simulates an Android device on your computer. You can download and install an Android emulator like [BlueStacks] or [NoxPlayer] and then install Bingo Blitz Unlimited Credits APK on it.</p>
107
- <h3>Q: Can I play Bingo Blitz Unlimited Credits APK offline?</h3>
108
- <p>A: No, you cannot play Bingo Blitz Unlimited Credits APK offline. You need an internet connection to play the game, as it connects you with other players and servers. You also need an internet connection to get free credits and updates. If you don't have an internet connection, you won't be able to launch the app or access its features.</p>
109
- <h3>Q: Can I sync my progress and data between Bingo Blitz Unlimited Credits APK and the original game?</h3>
110
- <p>A: Yes, you can sync your progress and data between Bingo Blitz Unlimited Credits APK and the original game. You just need to log in with the same Facebook account on both apps. This will allow you to transfer your credits, items, collections, clubs, tournaments, and other data between the apps. However, you should not run both apps at the same time, as this may cause conflicts or errors.</p> 197e85843d<br />
111
- <br />
112
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Call of Duty Warzone Mobile APK - The Most Epic Mobile FPS Game Ever.md DELETED
@@ -1,99 +0,0 @@
1
-
2
- <h1>Call of Duty®: Warzone™ Mobile - The Next Era of Mobile Battle Royale</h1>
3
- <p>If you are a fan of Call of Duty® franchise and love playing battle royale games on your mobile device, you are in for a treat. Call of Duty®: Warzone™ Mobile is the latest and greatest mobile game from Activision, featuring authentic COD gameplay, shared progression, and up to 120 player count matches on mobile. In this article, we will tell you everything you need to know about this game, including what it is, how to download and install it, and some tips and tricks for playing it.</p>
4
- <h2>What is Call of Duty®: Warzone™ Mobile?</h2>
5
- <p>Call of Duty®: Warzone™ Mobile is a free-to-play mobile game that brings the epic battle royale experience of Call of Duty®: Warzone™ to your phone. You can squad up with your friends or play solo, and fight to survive in a massive map called Verdansk, where you will encounter enemies, vehicles, weapons, contracts, killstreaks, and more. You can also customize your loadout, earn rewards, and rank up your Battle Pass across platforms.</p>
6
- <h2>call of duty warzone mobile indir apk</h2><br /><p><b><b>DOWNLOAD</b> >> <a href="https://urlin.us/2uSSiW">https://urlin.us/2uSSiW</a></b></p><br /><br />
7
- <h3>Features of Call of Duty®: Warzone™ Mobile</h3>
8
- <p>Call of Duty®: Warzone™ Mobile is not just another mobile battle royale game. It has some unique and exciting features that make it stand out from the crowd. Here are some of them:</p>
9
- <h4>Authentic COD gameplay</h4>
10
- <p>This game delivers authentic Call of Duty® gameplay on mobile with first-class graphics and intuitive controls. Everything from movement, aiming and weapon handling to physics, animations and sound have been optimized, delivering the ultimate accuracy, authenticity and performance.</p>
11
- <p>call of duty warzone mobile download apk<br />
12
- cod warzone mobile apk free download<br />
13
- call of duty warzone mobile android apk<br />
14
- cod warzone mobile apk latest version<br />
15
- call of duty warzone mobile apk obb<br />
16
- cod warzone mobile apk mod<br />
17
- call of duty warzone mobile apk data<br />
18
- cod warzone mobile apk offline<br />
19
- call of duty warzone mobile apk pure<br />
20
- cod warzone mobile apk mirror<br />
21
- call of duty warzone mobile apk revdl<br />
22
- cod warzone mobile apk hack<br />
23
- call of duty warzone mobile apk uptodown<br />
24
- cod warzone mobile apk no verification<br />
25
- call of duty warzone mobile apk rexdl<br />
26
- cod warzone mobile apk and obb download<br />
27
- call of duty warzone mobile apk for pc<br />
28
- cod warzone mobile apk highly compressed<br />
29
- call of duty warzone mobile apk full version<br />
30
- cod warzone mobile apk unlimited money<br />
31
- call of duty warzone mobile beta apk<br />
32
- cod warzone mobile apk obb file download<br />
33
- call of duty warzone mobile lite apk<br />
34
- cod warzone mobile apk android 1<br />
35
- call of duty warzone mobile official apk<br />
36
- cod warzone mobile apk update<br />
37
- call of duty warzone mobile gameplay apk<br />
38
- cod warzone mobile apk size<br />
39
- call of duty warzone mobile release date apk<br />
40
- cod warzone mobile apk requirements<br />
41
- call of duty warzone mobile pre register apk<br />
42
- cod warzone mobile apk google play<br />
43
- call of duty warzone mobile trailer apk<br />
44
- cod warzone mobile apk ios<br />
45
- call of duty warzone mobile app store apk<br />
46
- cod warzone mobile apkpure download<br />
47
- call of duty warzone mobile mod menu apk<br />
48
- cod warzone mobile apkmirror download<br />
49
- call of duty warzone mobile hack version apk<br />
50
- cod warzone mobile apkpure.com download link</p>
51
- <h4>Shared progression</h4>
52
- <p>This game is powered by unified Call of Duty® technology, which means you can use social features like friends, chat channels and Battle Pass across platforms for a truly connected multiplayer FPS game experience. You can also access your loadout from other COD titles (sold separately) and use them in this game.</p>
53
- <h4>Up to 120 player count matches</h4>
54
- <p>This game features some of the highest real player-counts for mobile battle royale. You can skip the bots and put your skills to the test where they count. Experience the new battle royale in this thrilling survival game. Show off your combat skills and defeat your enemies!</p>
55
- <h3>How to download and install Call of Duty®: Warzone™ Mobile?</h3>
56
- <p>If you are eager to play this game on your mobile device, here are the steps you need to follow:</p>
57
- <h4>Pre-register on Google Play or official website</h4>
58
- <p>The first step is to pre-register for this game on Google Play or the official website [3](https://www.callofduty.com/warzonemobile). By doing so, you will get a chance to unlock rewards at launch and get notified when the game is available for download.</p>
59
- <h4 <h4>Download the APK file from a trusted source</h4>
60
- <p>The next step is to download the APK file of this game from a trusted source. You can use the link provided by the official website [3](https://www.callofduty.com/warzonemobile) or search for a reliable APK downloader online. Make sure you have enough storage space on your device before downloading the file.</p>
61
- <h4>Install the APK file on your device</h4>
62
- <p>The final step is to install the APK file on your device. To do this, you need to enable the installation of apps from unknown sources in your device settings. Then, locate the downloaded APK file and tap on it to start the installation process. Follow the on-screen instructions and wait for the installation to complete. You may also need to download additional data files for the game to run properly.</p>
63
- <h3>Tips and tricks for playing Call of Duty®: Warzone™ Mobile</h3>
64
- <p>Now that you have installed the game on your device, you are ready to jump into the action. But before you do, here are some tips and tricks that will help you improve your gameplay and increase your chances of winning:</p>
65
- <h4>Choose your loadout wisely</h4>
66
- <p>Your loadout is your set of weapons, perks, equipment and killstreaks that you can use in the game. You can customize your loadout in the main menu or in-game by accessing a loadout drop. You can also use loadouts from other COD titles (sold separately) if you have them. Choose your loadout based on your playstyle, map, mode and situation. Experiment with different combinations and find what works best for you.</p>
67
- <h4>Communicate with your squad</h4>
68
- <p>If you are playing with your friends or other players, communication is key. You can use voice chat or text chat to coordinate your moves, share information, call out enemies, request help and more. You can also use ping system to mark locations, enemies, items and other points of interest. Communication can make a big difference between victory and defeat.</p>
69
- <h4>Use contracts and killstreaks strategically</h4>
70
- <p>Contracts are optional missions that you can find and activate in Verdansk. They offer various rewards such as cash, loot, intel and more. There are different types of contracts such as bounty, scavenger, recon and most wanted. Choose contracts that suit your objectives and complete them as fast as possible. Killstreaks are powerful abilities that you can use once you have enough cash or kill credits. They include UAV, airstrike, cluster strike and more. Use them wisely to gain an edge over your enemies or turn the tide of the battle.</p>
71
- <h4>Explore Verdansk and find loot</h4>
72
- <p>Verdansk is a huge map with diverse locations such as downtown, airport, stadium, prison and more. Each location has its own characteristics, advantages and disadvantages. Explore Verdansk and find loot such as weapons, armor plates, ammo, cash and more. Loot can be found in buildings, crates, supply boxes and other places. Be careful though, as some areas may be more dangerous than others.</p>
73
- <h4>Survive the Gulag and redeploy</h4>
74
- <p>If you get killed in the game, you are not out yet. You will be sent to the Gulag, a prison where you will face another fallen player in a 1v1 fight for a chance to redeploy back to Verdansk. You can also be revived by your teammates or buy a self-revive kit if you have enough cash. If you win the Gulag fight or get revived, you will parachute back to Verdansk with a pistol and some ammo. Try to land safely and rejoin your squad as soon as possible.</p>
75
- <h2>Conclusion</h2>
76
- <p>Call of Duty®: Warzone™ Mobile is an amazing mobile game that offers a thrilling battle royale experience with authentic COD gameplay, shared progression and up to 120 player count matches on mobile. If you want to play this game on your device, you need to pre-register on Google Play or official website [3](https://www.callofduty.com/warzonemobile), download the APK file from a trusted source and install it on your device. You also need to follow some tips and tricks such as choosing your loadout wisely, communicating with your squad, using contracts and killstreaks strategically, exploring Verdansk and finding loot and surviving the Gulag and redeploying.</p>
77
- <h2>FAQs</h2>
78
- <p>Here are some frequently asked questions about Call of Duty®: Warzone™ Mobile:</p>
79
- <ol>
80
- <li><b>Is Call of Duty®: Warzone™ Mobile free-to-play?</b></li>
81
- <p>Yes, Call of Duty®: Warzone™ Mobile is free-to -play and does not require any subscription or purchase to play. However, you may need to buy additional data files for the game to run properly. You can also buy in-game currency and items with real money if you want to.</p>
82
- <li><b>What are the minimum requirements for Call of Duty®: Warzone™ Mobile?</b></li>
83
- <p>The minimum requirements for Call of Duty®: Warzone™ Mobile are as follows:</p>
84
- <ul>
85
- <li>Android 5.0 or higher</li>
86
- <li>At least 3 GB of RAM</li>
87
- <li>At least 4 GB of free storage space</li>
88
- <li>A stable internet connection</li>
89
- </ul>
90
- <li><b>Can I play Call of Duty®: Warzone™ Mobile with other players on different platforms?</b></li>
91
- <p>Yes, Call of Duty®: Warzone™ Mobile supports cross-play and cross-progression with other platforms such as PC, PlayStation and Xbox. You can play with your friends or other players on different devices and platforms using the same Activision account. You can also access your loadout, rewards and Battle Pass across platforms.</p>
92
- <li><b>How can I report a bug or a cheater in Call of Duty®: Warzone™ Mobile?</b></li>
93
- <p>If you encounter a bug or a cheater in Call of Duty®: Warzone™ Mobile, you can report it using the in-game feedback system. To do this, go to the main menu and tap on the settings icon. Then, tap on the feedback button and choose the type of issue you want to report. You can also attach a screenshot or a video to provide more details. Alternatively, you can contact the customer support team via email or social media.</p>
94
- <li><b>Where can I find more information and updates about Call of Duty®: Warzone™ Mobile?</b></li>
95
- <p>If you want to find more information and updates about Call of Duty®: Warzone™ Mobile, you can visit the official website [3](https://www.callofduty.com/warzonemobile) or follow the official social media accounts on Facebook, Twitter, Instagram and YouTube. You can also join the official Discord server or Reddit community to chat with other players and developers.</p>
96
- </ol>
97
- <p>I hope you enjoyed reading this article and learned something new about Call of Duty®: Warzone™ Mobile. If you have any questions or feedback, feel free to leave a comment below. Thanks for reading and happy gaming!</p> 197e85843d<br />
98
- <br />
99
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/DRAGON BALL LEGENDS APK - Summon and Fight with Your Favorite DB Characters in 3D.md DELETED
@@ -1,159 +0,0 @@
1
-
2
- <h1>How to Download and Play Dragon Ball Legends on Android</h1>
3
- <p>If you are a fan of the Dragon Ball anime series, you might want to try out the latest game based on it: Dragon Ball Legends. This is an action-packed RPG game that lets you summon and fight with your favorite characters from the show. You can also enjoy an original story with a new character designed by Akira Toriyama, the creator of Dragon Ball.</p>
4
- <p>In this article, we will show you how to download and play Dragon Ball Legends on your Android device. We will also give you some features, requirements, and tips for the game. Let's get started!</p>
5
- <h2>dragon ball legends free download apk</h2><br /><p><b><b>Download File</b> &#187; <a href="https://urlin.us/2uT1zf">https://urlin.us/2uT1zf</a></b></p><br /><br />
6
- <h2>What is Dragon Ball Legends?</h2>
7
- <p>Dragon Ball Legends is a 3D anime action RPG game developed by Bandai Namco Entertainment. It was released in May 2018 for Android and iOS devices. The game features a card-based combat system that is easy to learn but hard to master. You can use various skills, abilities, and combos to defeat your opponents in real-time battles.</p>
8
- <p>The game also has a story mode that follows the adventures of Shallot, a mysterious Saiyan who wakes up in a world where past and present Dragon Ball characters are fighting each other. You can join Shallot and other heroes to uncover the truth behind this chaos. You can also play online against other players from around the world in PvP matches.</p>
9
- <p>dragon ball legends apk download latest version<br />
10
- dragon ball legends mod apk unlimited crystals<br />
11
- dragon ball legends android game free install<br />
12
- how to download dragon ball legends on pc<br />
13
- dragon ball legends hack apk no verification<br />
14
- dragon ball legends 3d action rpg game<br />
15
- dragon ball legends apk offline mode<br />
16
- dragon ball legends update download new characters<br />
17
- dragon ball legends cheats apk free resources<br />
18
- dragon ball legends gameplay tips and tricks<br />
19
- dragon ball legends best team setup guide<br />
20
- dragon ball legends online multiplayer battles<br />
21
- dragon ball legends story mode walkthrough<br />
22
- dragon ball legends tier list 2023 ranking<br />
23
- dragon ball legends codes apk redeem rewards<br />
24
- dragon ball legends events apk calendar<br />
25
- dragon ball legends summon simulator apk<br />
26
- dragon ball legends wallpaper apk hd<br />
27
- dragon ball legends voice actors apk cast<br />
28
- dragon ball legends original character shallot<br />
29
- dragon ball legends super saiyan forms apk<br />
30
- dragon ball legends frieza saga apk download<br />
31
- dragon ball legends broly movie apk update<br />
32
- dragon ball legends ultra instinct goku apk<br />
33
- dragon ball legends fusion warriors apk team<br />
34
- dragon ball legends god ki apk characters<br />
35
- dragon ball legends future trunks apk saga<br />
36
- dragon ball legends android 21 apk event<br />
37
- dragon ball legends beerus and whis apk banner<br />
38
- dragon ball legends majin buu apk arc<br />
39
- dragon ball legends cell games apk challenge<br />
40
- dragon ball legends zenkai awakening apk boost<br />
41
- dragon ball legends rising rush apk combo<br />
42
- dragon ball legends equipment upgrade apk guide<br />
43
- dragon ball legends pvp mode apk ranking<br />
44
- dragon ball legends co-op mode apk missions<br />
45
- dragon ball legends guild system apk features<br />
46
- dragon ball legends adventure mode apk rewards<br />
47
- dragon ball legends training mode apk tips<br />
48
- dragon ball legends exchange shop apk items<br />
49
- dragon ball legends z power list apk stats<br />
50
- dragon ball legends arts cards apk types<br />
51
- dragon ball legends special moves apk skills<br />
52
- dragon ball legends ultimate moves apk finishers<br />
53
- dragon ball legends transformations apk effects<br />
54
- dragon ball legends tags and categories apk filter<br />
55
- dragon ball legends battle gauge and ki apk meter<br />
56
- dragon wall legend vanishing step and cover change apk mechanics</p>
57
- <h3>Features of Dragon Ball Legends</h3>
58
- <p>Here are some of the features that make Dragon Ball Legends a fun and exciting game:</p>
59
- <ul>
60
- <li>More than 400 characters to collect and train, including Goku, Vegeta, Frieza, Broly, Majin Buu, and many more.</li>
61
- <li>High-quality 3D graphics and animations that bring the anime to life on your mobile device.</li>
62
- <li>Voice acting from the original anime cast, including Masako Nozawa as Goku, Ryō Horikawa as Vegeta, and Norio Wakamoto as Cell.</li>
63
- <li>An original story based on a new character designed by Akira Toriyama, the legendary manga artist behind Dragon Ball.</li>
64
- <li>A simple and intuitive combat system that uses cards to activate skills, abilities, and combos.</li>
65
- <li>A team-based Rising Rush attack that unleashes a powerful blow on your enemy.</li>
66
- <li>A variety of game modes, such as story mode, PvP mode, events mode, co-op mode, and more.</li>
67
- </ul>
68
- <h3>Requirements for Dragon Ball Legends</h3>
69
- <p>To play Dragon Ball Legends on your Android device, you need to meet the following requirements:</p>
70
- <ul>
71
- <li>Your device must have Android 6.0 or higher installed.</li>
72
- <li>Your device must have at least 2 GB of RAM available.</li>
73
- <li>Your device must have at least 195 MB of free storage space available.</li>
74
- <li>Your device must have a stable internet connection to play online.</li>
75
- </ul>
76
- <h2>How to Download Dragon Ball Legends APK</h2>
77
- <p>If you want to download and play Dragon Ball Legends on your Android device, you need to follow these steps:</p>
78
- <h3>Step 1: Enable Unknown Sources</h3>
79
- <p>Before you can install any APK file on your device, you need to enable unknown sources. This will allow you to install apps from sources other than the Google Play Store. To do this:</p>
80
- <ol>
81
- <li>Go to your device's Settings app.</li>
82
- <li>Tap on Security or Privacy (depending on your device).</li>
83
- <li>Find and toggle on Unknown Sources or Install Unknown Apps (depending on your device).</li>
84
- <li>Confirm your choice by tapping OK or Allow (depending on your device).</li>
85
- </ol>
86
- <h3>Step 2: Download the APK File</h3>
87
- <p>Next Next, you need to download the APK file of Dragon Ball Legends from a reliable source. You can use the link below to get the latest version of the game from APKCombo, a trusted website that offers free and safe APK downloads for Android games and apps. <h3>Step 2: Download the APK File</h3>
88
- <p>To download the APK file of Dragon Ball Legends, follow these steps:</p>
89
- <ol>
90
- <li>Tap on the link below to go to the APKCombo website.</li>
91
- <li>Tap on the green Download APK button to start the download.</li>
92
- <li>Wait for the download to finish. You can check the progress in your notification bar or your browser's download manager.</li>
93
- <li>Once the download is complete, you will see a notification that says "Download complete".</li>
94
- </ol>
95
- <p><a href="(^1^)">Download Dragon Ball Legends APK from APKCombo</a></p> <h3>Step 3: Install the APK File</h3>
96
- <p>After you have downloaded the APK file of Dragon Ball Legends, you need to install it on your device. To do this:</p>
97
- <ol>
98
- <li>Tap on the notification that says "Download complete" or go to your device's file manager and find the downloaded file.</li>
99
- <li>Tap on the file to open it. You may see a warning that says "This type of file can harm your device". Don't worry, this is just a precautionary message. Tap on OK or Install Anyway (depending on your device) to proceed.</li>
100
- <li>You may also see a prompt that asks you to allow the app to access your device's resources. Tap on Install or Next (depending on your device) to grant the permissions.</li>
101
- <li>Wait for the installation to finish. You will see a message that says "App installed" or "Dragon Ball Legends installed" (depending on your device).</li>
102
- <li>Tap on Open or Done (depending on your device) to launch the game or exit the installer.</li>
103
- </ol>
104
- <h3>Step 4: Launch the Game and Enjoy</h3>
105
- <p>Congratulations, you have successfully installed Dragon Ball Legends on your Android device. Now you can launch the game and enjoy the action-packed RPG adventure. To launch the game, follow these steps:</p>
106
- <ol>
107
- <li>Go to your device's app drawer and find the Dragon Ball Legends icon. It should look like a yellow star with a dragon ball in the center.</li>
108
- <li>Tap on the icon to open the game. You may see a loading screen with some tips and information about the game.</li>
109
- <li>You may also see a pop-up that asks you to agree to the terms of service and privacy policy of the game. Tap on Agree or Accept (depending on your device) to continue.</li>
110
- <li>You may also see a pop-up that asks you to choose your preferred language for the game. Tap on English or any other language you want to use.</li>
111
- <li>You may also see a pop-up that asks you to download some additional data for the game. Tap on Download or OK (depending on your device) to start the download. You can also choose to skip this step and download later, but it is recommended to download now for a better gaming experience.</li>
112
- <li>Wait for the download to finish. You can check the progress in the bottom right corner of the screen.</li>
113
- <li>Once the download is complete, you will see a message that says "Download complete". Tap on OK or Continue (depending on your device) to proceed.</li>
114
- <li>You will then see an introduction video that shows some scenes from the game and its story. You can watch it or skip it by tapping on Skip in the top right corner of the screen.</li>
115
- <li>You will then see a tutorial that explains how to play the game and its basic controls. You can follow it or skip it by tapping on Skip in the top right corner of the screen.</li>
116
- <li>You will then see a screen that asks you to choose your name and appearance for your character. You can use the default name and appearance or customize them by tapping on Edit in the bottom right corner of the screen.</li>
117
- <li>Once you are done, tap on Confirm in the bottom right corner of the screen.</li>
118
- <li>You will then see a screen that shows your character and some information about him/her. Tap on Start in the bottom right corner of the screen to begin your adventure.</li>
119
- </ol>
120
- <h2>How to Play Dragon Ball Legends</h2>
121
- <p>Now that you have downloaded and installed Dragon Ball Legends, you might be wondering how to play it and what are some tips and tricks for beginners. Here are some basic controls and gameplay elements that you should know:</p>
122
- <h3>Basic Controls and Gameplay</h3>
123
- <p>The game uses a card-based combat system that is easy to learn but hard to master. You can use various skills, abilities, and combos to defeat your opponents in real-time battles. Here are some basic controls and gameplay elements:</p>
124
- <ul>
125
- <li>To move your character, swipe left or right on the screen. To dash towards or away from your enemy, swipe up or down on the screen.</li>
126
- <li>To attack your enemy, tap on one of the cards at the bottom of the screen. Each card has a different color and effect: red cards are melee attacks, yellow cards are ranged attacks, green cards are special abilities, and blue cards are ultimate attacks.</li>
127
- <li>To use a combo, tap on multiple cards in succession. The more cards you use, the more damage you deal. However, each card also consumes some energy from your ki gauge, which is shown at the top of the screen. You need to manage your ki wisely and avoid running out of it.</li>
128
- <li>To dodge an enemy attack, swipe left or right on the screen. You can also use a vanish gauge, which is shown at the bottom of the screen, to perform a vanish step and teleport behind your enemy. However, each vanish step also consumes some energy from your vanish gauge, which recharges over time.</li>
129
- <li>To use a Rising Rush attack, tap on the dragon ball icon at the top of the screen when you have collected all seven dragon balls. You can collect dragon balls by using certain cards in battle. A Rising Rush attack is a team-based attack that unleashes a powerful blow on your enemy. However, you can only use it once per battle.</li>
130
- <li>To switch your character, tap on one of the portraits at the top left corner of the screen. You can have up to three characters in your team, and each character has a different element, type, and role. You need to choose your team wisely and switch your character strategically to gain an advantage in battle.</li>
131
- <li>To use a main ability, tap on the portrait of your active character when it glows. Each character has a unique main ability that can provide various benefits, such as healing, boosting, or debuffing. However, you can only use it once per battle.</li>
132
- <li>To use a Z ability, tap on the Z icon at the top right corner of the screen when it glows. Each character has a unique Z ability that can enhance your team's performance, such as increasing damage, defense, or ki recovery. However, you can only use it once per battle.</li>
133
- </ul>
134
- <h3>Tips and Tricks for Beginners</h3>
135
- <p>Here are some tips and tricks that can help you improve your skills and enjoy the game more:</p>
136
- <ul>
137
- <li>Complete the story mode to unlock new characters, items, and rewards. You can also replay the story mode chapters to earn more stars and crystals.</li>
138
- <li>Complete the missions and events to get more rewards and challenges. You can also join co-op missions and events with other players to get more fun and rewards.</li>
139
- <li>Upgrade your characters by using souls, zeni, and training items. You can also limit break your characters by using z power to increase their stats and stars.</li>
140
- <li>Equip your characters with equipment items that match their element, type, and role. You can also upgrade your equipment items by using zeni and erasers.</li>
141
- <li>Customize your team by choosing the best combination of characters, equipment, and abilities. You can also create different teams for different game modes and situations.</li>
142
- <li>Learn the strengths and weaknesses of each element, type, and role. You can also check the details of each character by tapping on them in the character list or in battle.</li>
143
- <li>Practice your combat skills by playing against the AI or other players in PvP mode. You can also watch replays of your battles or other players' battles to learn from them.</li>
144
- <li>Join a guild and chat with other players who share your passion for Dragon Ball. You can also participate in guild activities and events to get more rewards and fun.</li>
145
- </ul>
146
- <h2>Conclusion</h2>
147
- <p>Dragon Ball Legends is an amazing game that lets you experience the thrill of Dragon Ball on your mobile device. You can download and play it for free by following the steps above. You can also enjoy an original story with a new character designed by Akira Toriyama, the creator of Dragon Ball. You can also collect and train hundreds of characters from the anime series and fight with them in real-time battles against other players from around the world.</p>
148
- <p>If you are looking for a fun and exciting RPG game that is based on one of the most popular anime series of all time, you should definitely try out Dragon Ball Legends. It is a game that will keep you entertained for hours with its stunning graphics, voice acting, story, gameplay, and features. Download it now and join the adventure!</p>
149
- <h2>FAQs</h2>
150
- <p>Here are some frequently asked questions about Dragon Ball Legends:</p>
151
- <ol>
152
- <li><b>How do I get more crystals?</b><br>Crystals are the premium currency of the game that you can use to summon new characters or buy items. You can get more crystals by completing missions, events, achievements, story mode chapters, PvP matches, login bonuses, or buying them with real money.</li>
153
- <li><b>How do I get more z power?</b><br>Z power is the item that you need to limit break your characters and increase their stats and stars. You can get more z power by summoning new characters or duplicates of existing characters, completing missions, events, co-op mode matches, exchange shops, or buying them with real money.</li>
154
- <li><b>How do I get more souls?</b><br>Souls are the items that you need to upgrade your characters' panels and boost their stats. You can get more souls by completing missions, events, soul boost stages, exchange shops, or buying them with real money.</li>
155
- <li><b>How do I get more equipment?</b><br>Equipment are the items that you can equip to your characters to enhance their performance. You can get more equipment by completing missions, events, equipment stages, PvP mode matches, co-op mode matches, exchange shops, or buying them with real money.</li>
156
- <li><b>How do I get more characters?</b><br>Characters are the main attraction of the game that you can summon and fight with. You can get more characters by using crystals to summon them from various banners, using tickets to summon them from special banners, completing missions, events, story mode chapters, co-op mode matches, exchange shops, or buying them with real money.</li>
157
- </ol></p> 197e85843d<br />
158
- <br />
159
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Bloody Vampire Season 2 A Novel by Zanoor Writes - PDF Download or Online Reading.md DELETED
@@ -1,139 +0,0 @@
1
- <br />
2
- <h1>Bloody Vampire Novel Season 2: A Review of the Horror Romance Series by Zanoor Writes</h1>
3
- <p>If you're looking for a thrilling and passionate read that will keep you on the edge of your seat, you might want to check out Bloody Vampire Novel Season 2 by Zanoor Writes. This novel series is a sequel to the popular Bloody Vampire Novel Season 1, which introduced us to a world where vampires and humans coexist in a fragile balance.</p>
4
- <p>In this article, we'll give you a brief overview of what Bloody Vampire Novel Season 2 is about, who is Zanoor Writes, and why you should read it. We'll also show you how to download Bloody Vampire Novel Season 2 PDF for free from various sources, as well as some tips and tricks for reading PDF files on different devices. Finally, we'll give you a sneak peek of what to expect from Bloody Vampire Novel Season 3, which is currently in progress.</p>
5
- <h2>bloody vampire novel season 2 pdf download</h2><br /><p><b><b>Download Zip</b> &#9733;&#9733;&#9733;&#9733;&#9733; <a href="https://jinyurl.com/2uNUho">https://jinyurl.com/2uNUho</a></b></p><br /><br />
6
- <h2>What is Bloody Vampire Novel Season 2?</h2>
7
- <p>Bloody Vampire Novel Season 2 is a horror romance novel series written by Zanoor Writes, a Pakistani writer who specializes in vampire-based books. The novel series consists of 144 pages and was published online on Urdu Novels Hub in July 2021.</p>
8
- <p>The novel series follows the story of Zara Khan, a young woman who falls in love with a mysterious vampire named Zain Ali. Their relationship is complicated by their different backgrounds, beliefs, and enemies. Zara has to deal with her family's disapproval, her ex-boyfriend's jealousy, and her own fears and doubts. Zain has to protect Zara from his rival vampires, his dark past, and his inner demons.</p>
9
- <p>bloody vampire season 2 zanoor writes pdf<br />
10
- download bloody vampire season 2 urdu novel<br />
11
- bloody vampire novel season 2 free pdf online<br />
12
- bloody vampire season 2 by zanoor writes download<br />
13
- urdu novels hub bloody vampire season 2 pdf<br />
14
- bloody vampire novel season 2 complete pdf<br />
15
- bloody vampire season 2 romantic novel pdf<br />
16
- bloody vampire novel season 2 drive link download<br />
17
- bloody vampire season 2 urdu novalists pdf<br />
18
- bloody vampire novel season 2 category most romantic<br />
19
- zanoor writes bloody vampire season 2 pdf file<br />
20
- bloody vampire novel season 2 status complete<br />
21
- bloody vampire season 2 source drive free link<br />
22
- read online bloody vampire novel season 2 pdf<br />
23
- bloody vampire season 2 urdu pdf novel by zanoor writes<br />
24
- zanoor writes novels bloody vampire season 2 pdf<br />
25
- bloody vampire novel season 2 social issues based<br />
26
- download in pdf file bloody vampire season 2 novel<br />
27
- bloody vampire season 2 latest urdu novel pdf<br />
28
- urdu novels hub zanoor writes bloody vampire season 2<br />
29
- urdu novalists zanoor writes bloody vampire season 2 pdf<br />
30
- download for free bloody vampire novel season 2 pdf<br />
31
- save it for later bloody vampire season 2 pdf download<br />
32
- share with friends bloody vampire novel season 2 pdf<br />
33
- comment your views on bloody vampire season 2 pdf novel<br />
34
- subscribe to our newsletter for more bloody vampire season 2 pdf updates<br />
35
- like our facebook page for more bloody vampire novel season 2 pdf news<br />
36
- follow us on twitter for more bloody vampire season 2 pdf alerts<br />
37
- join our telegram channel for more bloody vampire novel season 2 pdf links<br />
38
- watch our youtube video for more bloody vampire season 2 pdf reviews</p>
39
- <p>The novel series combines elements of horror, romance, drama, and mystery. It explores themes such as love, trust, loyalty, betrayal, sacrifice, revenge, and redemption. It also features a unique vampire lore that blends Eastern and Western mythology.</p>
40
- <h3>Who is Zanoor Writes?</h3>
41
- <p>Zanoor Writes is <p>Zanoor Writes is the pen name of Zainab Noor, a 25-year-old writer from Lahore, Pakistan. She started writing at the age of 15 and has published several novels and short stories online. She is best known for her vampire-based books, such as Bloody Vampire Novel Season 1 and 2, The Vampire King, and The Vampire's Bride. She is also a fan of Twilight, The Vampire Diaries, and Dracula.</p>
42
- <p>Zanoor Writes has a loyal fan base who appreciate her creative and captivating stories. She interacts with her readers through her social media accounts, such as Facebook, Instagram, and Twitter. She also has a website where she posts updates, news, and previews of her upcoming works.</p>
43
- <h2>Why You Should Read Bloody Vampire Novel Season 2?</h2>
44
- <p>Bloody Vampire Novel Season 2 is a novel series that will appeal to anyone who loves horror and romance. Here are some reasons why you should read it:</p>
45
- <ul>
46
- <li>It has a suspenseful and intriguing storyline that will keep you hooked from the first page to the last. You'll never know what will happen next as Zara and Zain face various challenges and dangers in their relationship.</li>
47
- <li>It has a captivating and passionate romance that will make you swoon and root for the main couple. You'll feel their emotions and chemistry as they overcome their differences and grow closer together.</li>
48
- <li>It has a unique and original vampire lore that will fascinate you with its details and diversity. You'll learn about the history, culture, and rules of the vampire world, as well as the different types and powers of vampires.</li>
49
- <li>It has a talented and engaging author who knows how to write well and entertain her readers. You'll enjoy her style, language, and humor as she tells the story in a captivating way.</li>
50
- </ul>
51
- <h3>How to Download Bloody Vampire Novel Season 2 PDF for Free?</h3>
52
- <p>If you want to read Bloody Vampire Novel Season 2 in PDF format, you have several options to download it for free. Here are some steps you can follow:</p>
53
- <ol>
54
- <li>Go to Urdu Novels Hub, the official website where Zanoor Writes publishes her novel series online. You can find the link to the website here: .</li>
55
- <li>On the website, look for the category "Zanoor Writes" on the menu bar. Click on it and you'll see a list of her novel series.</li>
56
- <li>Find Bloody Vampire Novel Season 2 on the list and click on it. You'll be directed to a page where you can read the novel series online or download it in PDF format.</li>
57
- <li>To download it in PDF format, scroll down to the bottom of the page where you'll see a button that says "Download PDF". Click on it and you'll be asked to enter your email address.</li>
58
- <li>Enter your email address and click on "Submit". You'll receive an email with a link to download the PDF file of Bloody Vampire Novel Season 2.</li>
59
- <li>Click on the link in the email and you'll be able to download the PDF file to your device.</li>
60
- </ol> <h4>Pros and Cons of Downloading PDF Files</h4>
61
- <p>Downloading PDF files of Bloody Vampire Novel Season 2 has its pros and cons. Here are some of them:</p>
62
- <table>
63
- <tr>
64
- <th>Pros</th>
65
- <th>Cons</th>
66
- </tr>
67
- <tr>
68
- <td>You can read the novel series offline without an internet connection.</td>
69
- <td>You need to have a PDF reader software or app installed on your device.</td>
70
- </tr>
71
- <tr>
72
- <td>You can save the novel series on your device or cloud storage for future reference.</td>
73
- <td>You might encounter some formatting or compatibility issues depending on your device or PDF reader.</td>
74
- </tr>
75
- <tr>
76
- <td>You can print the novel series if you prefer reading on paper.</td>
77
- <td>You might use up a lot of ink and paper, which can be costly and wasteful.</td>
78
- </tr>
79
- <tr>
80
- <td>You can share the novel series with your friends or family who are also interested in reading it.</td>
81
- <td>You might violate the author's rights or terms of service if you distribute the novel series without permission.</td>
82
- </tr>
83
- </table>
84
- <h4>Tips and Tricks for Reading PDF Files on Different Devices</h4>
85
- <p>If you want to read PDF files of Bloody Vampire Novel Season 2 on different devices, such as laptops, tablets, or smartphones, here are some tips and tricks you can use to optimize your reading experience:</p>
86
- <ul>
87
- <li>Choose a PDF reader software or app that suits your preferences and needs. There are many options available, such as Adobe Acrobat Reader, Foxit Reader, Google PDF Viewer, etc. Some of them are free, while others require a subscription or a one-time payment. Compare their features, functions, and reviews before downloading them.</li>
88
- <li>Adjust the settings of your PDF reader to enhance the readability and accessibility of the novel series. For example, you can change the font size, color, brightness, contrast, orientation, zoom level, etc. You can also enable features such as text-to-speech, night mode, bookmarks, annotations, etc.</li>
89
- <li>Use keyboard shortcuts or gestures to navigate and control the PDF reader. For example, you can use the arrow keys or swipe left and right to move between pages. You can also use the spacebar or tap to scroll up and down. You can also use the Ctrl+F or search icon to find specific words or phrases in the novel series.</li>
90
- <li>Be mindful of your battery life and data usage when reading PDF files. If you're reading online, make sure you have a stable and secure internet connection. If you're reading offline, make sure you have enough battery power or plug in your charger. You can also turn on airplane mode or disable notifications to avoid interruptions.</li>
91
- <li>Take breaks and rest your eyes when reading PDF files for a long time. Reading on a screen can cause eye strain, fatigue, headache, or blurred vision. To prevent this, you should follow the 20-20-20 rule: every 20 minutes, look at something 20 feet away for 20 seconds. You should also blink often and drink water to stay hydrated.</li>
92
- </ul>
93
- <h4>Alternative Ways to Read Bloody Vampire Novel Season 2 Online or Offline</h4>
94
- <p>If you don't want to read PDF files of Bloody Vampire Novel Season 2, you have other options to read the novel series online or offline. Here are some of them:</p>
95
- <ul>
96
- <li>You can read the novel series online on Urdu Novels Hub's website using your browser. You don't need to download anything or enter your email address. You just need to have an internet connection and a compatible browser.</li>
97
- <li>You can read the novel series online on other platforms that host Urdu novels, such as Urdu Novels Online, Urdu Novels Collection, Urdu Novels Library, etc. However, you should be careful about the quality and authenticity of these platforms. Some of them might have incomplete, inaccurate, or pirated versions of the novel series.</li>
98
- <li>You can read the novel series offline on an e-reader device, such as Kindle, Nook, Kobo, etc. You just need to download the novel series in a compatible format (such as EPUB or MOBI) from Urdu Novels Hub's website or other sources. Then, you need to transfer the file to your e-reader device using a USB cable or Wi-Fi.</li>
99
- <li>You can read the novel series offline on a printed book. You can either buy the book from a bookstore or online retailer that sells Urdu novels (such as Amazon), or print it yourself using a printer and paper. However, this option might be more expensive and less convenient than reading online or on an e-reader device.</li>
100
- </ul> <h2>What to Expect from Bloody Vampire Novel Season 3?</h2>
101
- <p>If you've finished reading Bloody Vampire Novel Season 2, you might be wondering what will happen next in the novel series. Well, you're not alone. Many fans are eagerly waiting for Bloody Vampire Novel Season 3, which is expected to be the final installment of the trilogy.</p>
102
- <p>While the author has not revealed much about the plot of Bloody Vampire Novel Season 3, she has dropped some hints and teasers on her social media accounts and website. Based on these clues and fan theories, here are some things you can expect from Bloody Vampire Novel Season 3:</p>
103
- <ul>
104
- <li>A shocking revelation about Zain's past that will change everything.</li>
105
- <li>A new enemy that will threaten Zara and Zain's relationship and lives.</li>
106
- <li>A major twist that will test Zara and Zain's love and loyalty.</li>
107
- <li>A heartbreaking sacrifice that will determine the fate of the vampire world.</li>
108
- <li>A satisfying and surprising ending that will wrap up the story and answer all the questions.</li>
109
- </ul>
110
- <h3>When Will Bloody Vampire Novel Season 3 Be Released?</h3>
111
- <p>The release date of Bloody Vampire Novel Season 3 is not yet confirmed by the author. However, based on her previous schedule and updates, we can estimate that it will be released sometime in late 2023 or early 2024.</p>
112
- <p>The author usually publishes one chapter per week on Urdu Novels Hub's website, which means that it takes about three to four months to complete one season. Since Bloody Vampire Novel Season 2 was completed in July 2021, we can assume that the author is currently working on Bloody Vampire Novel Season 3 and will publish it soon.</p>
113
- <p>Of course, this is just a rough estimation and the actual release date might vary depending on the author's availability, progress, and other factors. The best way to know the exact release date is to follow the author's updates and announcements.</p>
114
- <h3>How to Stay Updated on Bloody Vampire Novel Season 3 News and Updates?</h3>
115
- <p>If you want to stay updated on Bloody Vampire Novel Season 3 news and updates, you have several ways to follow the author and her novel series. Here are some of them:</p>
116
- <ul>
117
- <li>Follow Zanoor Writes on her social media accounts, such as Facebook, Instagram, and Twitter. She often posts previews, snippets, covers, and other information about her novel series on these platforms. You can also interact with her and other fans through comments, messages, and likes.</li>
118
- <li>Visit Zanoor Writes' website, where she posts news, updates, blogs, and other content related to her novel series. You can also subscribe to her newsletter to receive email notifications whenever she publishes a new chapter or post.</li>
119
- <li>Bookmark Urdu Novels Hub's website, where Zanoor Writes publishes her novel series online. You can also turn on notifications to get alerts whenever a new chapter is available.</li>
120
- <li>Join online communities and forums dedicated to Zanoor Writes and her novel series, such as Reddit, Quora, Goodreads, etc. You can discuss your opinions, theories, questions, and feedback with other fans and readers.</li>
121
- </ul> <h2>Conclusion</h2>
122
- <p>Bloody Vampire Novel Season 2 is a novel series that you don't want to miss if you're a fan of horror and romance. It has a captivating plot, a passionate romance, a unique vampire lore, and a talented author. You can download it in PDF format for free from various sources, or read it online or offline on different platforms. You can also look forward to Bloody Vampire Novel Season 3, which is coming soon.</p>
123
- <p>So, what are you waiting for? Download Bloody Vampire Novel Season 2 PDF now and enjoy the thrilling and passionate story of Zara and Zain. You won't regret it!</p>
124
- <h3>FAQs About Bloody Vampire Novel Season 2 PDF Download</h3>
125
- <p>Here are some frequently asked questions that readers might have about Bloody Vampire Novel Season 2 PDF download:</p>
126
- <ol>
127
- <li>Is Bloody Vampire Novel Season 2 PDF download safe and legal?</li>
128
- <p>Yes, downloading Bloody Vampire Novel Season 2 PDF from Urdu Novels Hub's website is safe and legal. The website is the official and authorized source of Zanoor Writes' novel series. The website uses encryption and security measures to protect your data and privacy. The website also respects the author's rights and terms of service, and does not distribute the novel series without permission.</p>
129
- <li>How long does it take to download Bloody Vampire Novel Season 2 PDF?</li>
130
- <p>The time it takes to download Bloody Vampire Novel Season 2 PDF depends on your internet speed and the size of the file. The file size of Bloody Vampire Novel Season 2 PDF is about 1.5 MB, which means that it should take less than a minute to download on a fast internet connection. However, if your internet connection is slow or unstable, it might take longer to download the file.</p>
131
- <li>Can I read Bloody Vampire Novel Season 2 PDF on my phone?</li>
132
- <p>Yes, you can read Bloody Vampire Novel Season 2 PDF on your phone, as long as you have a PDF reader app installed on your phone. There are many PDF reader apps available for both Android and iOS devices, such as Adobe Acrobat Reader, Foxit Reader, Google PDF Viewer, etc. You can download them from the Google Play Store or the App Store for free or for a fee.</p>
133
- <li>Can I convert Bloody Vampire Novel Season 2 PDF to other formats?</li>
134
- <p>Yes, you can convert Bloody Vampire Novel Season 2 PDF to other formats, such as EPUB or MOBI, if you prefer reading on an e-reader device or app. There are many online tools and software that can help you convert PDF files to other formats, such as Zamzar, Online-Convert, Calibre, etc. However, you should be careful about the quality and accuracy of the conversion process. Some tools or software might not preserve the original formatting or layout of the novel series.</p>
135
- <li>Can I request a hard copy of Bloody Vampire Novel Season 2?</li>
136
- <p>Yes, you can request a hard copy of Bloody Vampire Novel Season 2 from Zanoor Writes directly. You can contact her through her social media accounts or email address and ask her if she can provide you with a printed version of the novel series. However, you might have to pay for the printing and shipping costs, which can vary depending on your location and preferences.</p>
137
- </ol></p> 401be4b1e0<br />
138
- <br />
139
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/FIFA 19 APK Download Latest Version 2023 for Android.md DELETED
@@ -1,124 +0,0 @@
1
- <br />
2
- <h1>FIFA APK 19: How to Download and Install the Best Soccer Game on Android</h1>
3
- <h2>Introduction</h2>
4
- <p>If you are a fan of soccer, you probably have heard of FIFA, the most popular and realistic soccer game series in the world. FIFA is developed by EA Sports, a leading company in the gaming industry. FIFA has been releasing new versions of its game every year, with improved graphics, gameplay, and features.</p>
5
- <h2>fifa apk 19</h2><br /><p><b><b>Download</b> &rarr;&rarr;&rarr; <a href="https://jinyurl.com/2uNPLs">https://jinyurl.com/2uNPLs</a></b></p><br /><br />
6
- <p>One of the latest versions of FIFA is FIFA 19, which was released in 2018 for various platforms, including PC, PlayStation, Xbox, Nintendo Switch, and mobile devices. However, if you want to play FIFA 19 on your Android phone or tablet, you might encounter some difficulties. That's because the official version of FIFA 19 for Android is not available on the Google Play Store. Instead, you have to download and install an unofficial version of FIFA 19, which is called FIFA APK 19.</p>
7
- <p>In this article, we will show you how to download and install FIFA APK 19 on your Android device, and how to enjoy the best soccer game on your mobile screen. We will also tell you why you should play FIFA APK 19, and what features and tips you can expect from this game.</p>
8
- <h2>How to download FIFA APK 19</h2>
9
- <h3>Requirements for FIFA APK 19</h3>
10
- <p>Before you download FIFA APK 19, you need to make sure that your Android device meets the minimum requirements for this game. Here are the requirements:</p>
11
- <ul>
12
- <li>Android version: 4.4 or higher</li>
13
- <li>RAM: 2 GB or more</li>
14
- <li>Storage space: At least 4 GB of free space</li>
15
- <li>Internet connection: Required for online features</li>
16
- </ul>
17
- <p>If your device meets these requirements, you can proceed to download FIFA APK 19. However, if your device does not meet these requirements, you might experience some issues with the game, such as lagging, crashing, or errors.</p>
18
- <p>fifa 19 apk download android<br />
19
- fifa 19 apk mod offline<br />
20
- fifa 19 apk data obb<br />
21
- fifa 19 apk obb download<br />
22
- fifa 19 apk offline mode<br />
23
- fifa 19 apk latest version<br />
24
- fifa 19 apk and obb file<br />
25
- fifa 19 apk free download full version<br />
26
- fifa 19 apk unlimited money<br />
27
- fifa 19 apk highly compressed<br />
28
- fifa 19 apk mobile game<br />
29
- fifa 19 apk android game<br />
30
- fifa 19 apk full unlocked<br />
31
- fifa 19 apk no verification<br />
32
- fifa 19 apk update patch<br />
33
- fifa 19 apk real faces<br />
34
- fifa 19 apk best graphics<br />
35
- fifa 19 apk original game<br />
36
- fifa 19 apk online multiplayer<br />
37
- fifa 19 apk ultimate team<br />
38
- fifa 19 apk career mode<br />
39
- fifa 19 apk champions league<br />
40
- fifa 19 apk world cup mode<br />
41
- fifa 19 apk commentary download<br />
42
- fifa 19 apk english language<br />
43
- fifa 19 apk new kits and transfers<br />
44
- fifa 19 apk new features and gameplay<br />
45
- fifa 19 apk new stadiums and teams<br />
46
- fifa 19 apk new skills and tricks<br />
47
- fifa 19 apk new celebrations and animations<br />
48
- fifa 19 apk requirements and compatibility<br />
49
- fifa 19 apk size and installation guide<br />
50
- fifa 19 apk review and rating<br />
51
- fifa 19 apk download link and password<br />
52
- fifa 19 apk how to play and tips<br />
53
- fifa 19 apk cheats and hacks<br />
54
- fifa 19 apk mod menu and coins generator<br />
55
- fifa 19 apk comparison and difference with other versions<br />
56
- fifa 19 apk problems and solutions<br />
57
- fifa 19 apk questions and answers</p>
58
- <h3>Steps to download FIFA APK 19</h3>
59
- <p>To download FIFA APK 19, you need to follow these steps:</p>
60
- <ol>
61
- <li>Go to a trusted website that provides the download link for FIFA APK 19. For example, you can use [this website](^1^), [this website](^2^), or [this website](^3^).</li>
62
- <li>On the website, look for the download button or link for FIFA APK 19. You might have to scroll down or click on some tabs to find it.</li>
63
- <li>Click on the download button or link. You will be redirected to another page where you have to wait for a few seconds before the download starts.</li>
64
- <li>Once the download starts, you will see a pop-up window asking you to confirm the download. Tap on OK or Download.</li>
65
- <li>Wait for the download to finish. You will need to download two files: an APK file and an OBB file. The APK file is about 30 MB in size, while the OBB file is about 1 GB in size.</li>
66
- <li>After downloading both files, locate them in your device's file manager. They are usually stored in the Downloads folder.</li>
67
- </ol>
68
- <p>Congratulations! You have successfully downloaded FIFA APK 19 on your Android device. Now, you need to install it.</p>
69
- <h2>How to install FIFA APK 19</h2>
70
- <h3>How to install the APK file</h3>
71
- <p>To install the APK file of FIFA APK 19, you need to follow these steps:</ <p>- Before you install the APK file, you need to enable the installation of unknown sources on your device. To do this, go to Settings > Security > Unknown Sources and toggle it on.</p>
72
- <p>- Next, go to your file manager and tap on the APK file of FIFA APK 19. You will see a pop-up window asking you to install the app. Tap on Install.</p>
73
- <p>- Wait for the installation to finish. You will see a message saying that the app has been installed. Tap on Open or Done.</p>
74
- <p>- You have successfully installed the APK file of FIFA APK 19. However, you are not done yet. You still need to install the OBB file.</p>
75
- <h3>How to install the OBB file</h3>
76
- <p>To install the OBB file of FIFA APK 19, you need to follow these steps:</p>
77
- <ol>
78
- <li>Go to your file manager and locate the OBB file of FIFA APK 19. It is usually named as com.ea.game.fifa14_row.obb.</li>
79
- <li>Long press on the OBB file and select Copy or Move.</li>
80
- <li>Navigate to the folder Android > obb > com.ea.game.fifa14_row and paste the OBB file there. If you don't see this folder, you can create it manually.</li>
81
- <li>Wait for the copying or moving process to finish. You have successfully installed the OBB file of FIFA APK 19.</li>
82
- </ol>
83
- <p>Now, you are ready to play FIFA APK 19 on your Android device.</p>
84
- <h2>How to play FIFA APK 19</h2>
85
- <h3>Features of FIFA APK 19</h3>
86
- <p>FIFA APK 19 is an amazing soccer game that offers you many features and modes to enjoy. Here are some of the features of FIFA APK 19:</p>
87
- <ul>
88
- <li>Realistic graphics and animations that make you feel like you are watching a real soccer match.</li>
89
- <li>Smooth and responsive controls that let you perform various actions, such as passing, shooting, dribbling, tackling, and more.</li>
90
- <li>A variety of game modes, such as Career Mode, Tournament Mode, Manager Mode, Online Mode, and more.</li>
91
- <li>A huge database of players, teams, leagues, and stadiums from around the world. You can choose your favorite team and players, or create your own custom team and players.</li>
92
- <li>A dynamic commentary system that provides you with insightful and exciting commentary during the game.</li>
93
- <li>An online feature that lets you play with or against other players from around the world. You can also join leagues and tournaments and compete for glory and rewards.</li>
94
- </ul>
95
- <p>FIFA APK 19 is a game that will keep you entertained for hours with its amazing gameplay and features.</p>
96
- <h3>Tips and tricks for FIFA APK 19</h3>
97
- <p>If you want to improve your skills and performance in FIFA APK 19, here are some tips and tricks that you can use:</p>
98
- <ul>
99
- <li>Practice your skills in the Training Mode. You can learn how to perform various actions, such as passing, shooting, dribbling, tackling, and more.</li>
100
- <li>Adjust your settings according to your preference and device. You can change the difficulty level, camera angle, control scheme, sound effects, and more.</li>
101
- <li>Use the right players for the right positions. Each player has different attributes, such as speed, strength, stamina, shooting, passing, dribbling, defending, and more. You should use the players that suit your playing style and strategy.</li>
102
- <li>Use different tactics and formations depending on your opponent and situation. You can change your tactics and formations during the game by tapping on the menu button on the top right corner of the screen.</li>
103
- <li>Use your coins wisely. You can earn coins by playing games, completing achievements, or watching ads. You can use coins to buy new players, upgrade your existing players, or unlock new items and features.</li>
104
- </ul>
105
- <p>With these tips and tricks, you can become a master of FIFA APK 19 in no time.</p>
106
- <h2>Conclusion</h2>
107
- <h3>Summary of the article</h3>
108
- <p>In this article, we have shown you how to download and install FIFA APK 19 on your Android device. We have also told you why you should play FIFA APK 19, and what features and tips you can expect from this game. FIFA APK 19 is an amazing soccer game that will give you hours of fun and excitement. If you love soccer, you should definitely try FIFA APK 19 on your Android device.</p>
109
- <h3>FAQs</h3>
110
- <p>Here are some frequently asked questions about FIFA APK 19:</p>
111
- <ol>
112
- <li><b>Is FIFA APK 19 safe to download and install?</b <p>- Yes, FIFA APK 19 is safe to download and install, as long as you use a trusted website that provides the download link. However, you should always be careful when downloading and installing any app from unknown sources, as they might contain malware or viruses. You should also scan your device with an antivirus app after installing FIFA APK 19.</p>
113
- <li><b>Is FIFA APK 19 legal to play?</b></li>
114
- <p>- FIFA APK 19 is not an official version of FIFA 19, and it is not authorized by EA Sports or any other entity. Therefore, playing FIFA APK 19 might be considered illegal in some countries or regions. You should check your local laws and regulations before playing FIFA APK 19. You should also be aware that playing FIFA APK 19 might violate the terms and conditions of EA Sports or Google Play Store, and you might face some consequences or penalties.</p>
115
- <li><b>Is FIFA APK 19 compatible with all Android devices?</b></li>
116
- <p>- FIFA APK 19 is compatible with most Android devices that meet the minimum requirements for this game. However, some devices might not be able to run FIFA APK 19 smoothly or properly, due to different hardware specifications or software versions. You should try FIFA APK 19 on your device and see if it works well for you.</p>
117
- <li><b>How can I update FIFA APK 19?</b></li>
118
- <p>- FIFA APK 19 does not have an automatic update feature, unlike the official version of FIFA 19. Therefore, if you want to update FIFA APK 19, you have to download and install the latest version of FIFA APK 19 from a trusted website. You might also have to delete the previous version of FIFA APK 19 from your device before installing the new one.</p>
119
- <li><b>How can I contact the developer of FIFA APK 19?</b></li>
120
- <p>- FIFA APK 19 is developed by an unknown developer or group of developers, who are not affiliated with EA Sports or any other entity. Therefore, there is no official way to contact the developer of FIFA APK 19. However, you might be able to find some information or feedback from other users of FIFA APK 19 on the website where you downloaded the game, or on some online forums or social media platforms.</p>
121
- </ol>
122
- <p>I hope this article has helped you learn more about FIFA APK 19 and how to download and install it on your Android device. If you have any questions or comments, please feel free to leave them below. Thank you for reading!</p> 197e85843d<br />
123
- <br />
124
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1toTree/lora_test/ppdiffusers/pipelines/stochastic_karras_ve/__init__.py DELETED
@@ -1,17 +0,0 @@
1
- # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
- # Copyright 2022 The HuggingFace Team. All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- # flake8: noqa
17
- from .pipeline_stochastic_karras_ve import KarrasVePipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AI-Hobbyist/Hoyo-RVC/docs/training_tips_ja.md DELETED
@@ -1,64 +0,0 @@
1
- RVCの訓練における説明、およびTIPS
2
- ===============================
3
- 本TIPSではどのようにデータの訓練が行われているかを説明します。
4
-
5
- # 訓練の流れ
6
- GUIの訓練タブのstepに沿って説明します。
7
-
8
- ## step1
9
- 実験名の設定を行います。
10
-
11
- また、モデルに音高ガイド(ピッチ)を考慮させるかもここで設定できます。考慮させない場合はモデルは軽量になりますが、歌唱には向かなくなります。
12
-
13
- 各実験のデータは`/logs/実験名/`に配置されます。
14
-
15
- ## step2a
16
- 音声の読み込みと前処理を行います。
17
-
18
- ### load audio
19
- 音声のあるフォルダを指定すると、そのフォルダ内にある音声ファイルを自動で読み込みます。
20
- 例えば`C:Users\hoge\voices`を指定した場合、`C:Users\hoge\voices\voice.mp3`は読み込まれますが、`C:Users\hoge\voices\dir\voice.mp3`は読み込まれません。
21
-
22
- 音声の読み込みには内部でffmpegを利用しているので、ffmpegで対応している拡張子であれば自動的に読み込まれます。
23
- ffmpegでint16に変換した後、float32に変換し、-1 ~ 1の間に正規化されます。
24
-
25
- ### denoising
26
- 音声についてscipyのfiltfiltによる平滑化を行います。
27
-
28
- ### 音声の分割
29
- 入力した音声はまず、一定期間(max_sil_kept=5秒?)より長く無音が続く部分を検知して音声を分割します。無音で音声を分割した後は、0.3秒のoverlapを含む4秒ごとに音声を分割します。4秒以内に区切られた音声は、音量の正規化を行った後wavファイルを`/logs/実験名/0_gt_wavs`に、そこから16kのサンプリングレートに変換して`/logs/実験名/1_16k_wavs`にwavファイルで保存します。
30
-
31
- ## step2b
32
- ### ピッチの抽出
33
- wavファイルからピッチ(音の高低)の情報を抽出します。parselmouthやpyworldに内蔵されている手法でピッチ情報(=f0)を抽出し、`/logs/実験名/2a_f0`に保存します。その後、ピッチ情報を対数で変換して1~255の整数に変換し、`/logs/実験名/2b-f0nsf`に保存します。
34
-
35
- ### feature_printの抽出
36
- HuBERTを用いてwavファイルを事前にembeddingに変換します。`/logs/実験名/1_16k_wavs`に保存したwavファイルを読み込み、HuBERTでwavファイルを256次元の特徴量に変換し、npy形式で`/logs/実験名/3_feature256`に保存します。
37
-
38
- ## step3
39
- モデルのトレーニングを行います。
40
- ### 初心者向け用語解説
41
- 深層学習ではデータセットを分割し、少しずつ学習を進めていきます。一回のモデルの更新(step)では、batch_size個のデータを取り出し予測と誤差の修正を行います。これをデータセットに対して一通り行うと一epochと数えます。
42
-
43
- そのため、学習時間は 1step当たりの学習時間 x (データセット内のデータ数 ÷ バッチサイズ) x epoch数 かかります。一般にバッチサイズを大きくするほど学習は安定し、(1step当たりの学習時間÷バッチサイズ)は小さくなりますが、その分GPUのメモリを多く使用します。GPUのRAMはnvidia-smiコマンド等で確認できます。実行環境のマシンに合わせてバッチサイズをできるだけ大きくするとより短時間で学習が可能です。
44
-
45
- ### pretrained modelの指定
46
- RVCではモデルの訓練を0からではなく、事前学習済みの重みから開始するため、少ないデータセットで学習を行えます。
47
-
48
- デフォルトでは
49
-
50
- - 音高ガイドを考慮する場合、`RVCのある場所/pretrained/f0G40k.pth`と`RVCのある場所/pretrained/f0D40k.pth`を読み込みます。
51
- - 音高ガイドを考慮しない場合、`RVCのある場所/pretrained/G40k.pth`と`RVCのある場所/pretrained/D40k.pth`を読み込みます。
52
-
53
- 学習時はsave_every_epochごとにモデルのパラメータが`logs/実験名/G_{}.pth`と`logs/実験名/D_{}.pth`に保存されますが、このパスを指定することで学習を再開したり、もしくは違う実験で学習したモデルの重みから学習を開始できます。
54
-
55
- ### indexの学習
56
- RVCでは学習時に使われたHuBERTの特徴量を保存し、推論時は学習時の特徴量から近い特徴量を探してきて推論を行います。この検索を高速に行うために事前にindexの学習を行います。
57
- indexの学習には近似近傍探索ライブラリのfaissを用います。`/logs/実験名/3_feature256`の特徴量を読み込み、それを用いて学習したindexを`/logs/実験名/add_XXX.index`として保存します。
58
- (20230428updateよりtotal_fea.npyはindexから読み込むので不要になりました。)
59
-
60
- ### ボタンの説明
61
- - モデルのトレーニング: step2bまでを実行した後、このボタンを押すとモデルの学習を行います。
62
- - 特徴インデックスのトレーニング: モデルのトレーニング後、indexの学習を行います。
63
- - ワンクリックトレーニング: step2bまでとモデルのトレーニング、特徴インデックスのトレーニングを一括で行います。
64
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/StyleGANEX/models/stylegan2/op/conv2d_gradfix.py DELETED
@@ -1,227 +0,0 @@
1
- import contextlib
2
- import warnings
3
-
4
- import torch
5
- from torch import autograd
6
- from torch.nn import functional as F
7
-
8
- enabled = True
9
- weight_gradients_disabled = False
10
-
11
-
12
- @contextlib.contextmanager
13
- def no_weight_gradients():
14
- global weight_gradients_disabled
15
-
16
- old = weight_gradients_disabled
17
- weight_gradients_disabled = True
18
- yield
19
- weight_gradients_disabled = old
20
-
21
-
22
- def conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
23
- if could_use_op(input):
24
- return conv2d_gradfix(
25
- transpose=False,
26
- weight_shape=weight.shape,
27
- stride=stride,
28
- padding=padding,
29
- output_padding=0,
30
- dilation=dilation,
31
- groups=groups,
32
- ).apply(input, weight, bias)
33
-
34
- return F.conv2d(
35
- input=input,
36
- weight=weight,
37
- bias=bias,
38
- stride=stride,
39
- padding=padding,
40
- dilation=dilation,
41
- groups=groups,
42
- )
43
-
44
-
45
- def conv_transpose2d(
46
- input,
47
- weight,
48
- bias=None,
49
- stride=1,
50
- padding=0,
51
- output_padding=0,
52
- groups=1,
53
- dilation=1,
54
- ):
55
- if could_use_op(input):
56
- return conv2d_gradfix(
57
- transpose=True,
58
- weight_shape=weight.shape,
59
- stride=stride,
60
- padding=padding,
61
- output_padding=output_padding,
62
- groups=groups,
63
- dilation=dilation,
64
- ).apply(input, weight, bias)
65
-
66
- return F.conv_transpose2d(
67
- input=input,
68
- weight=weight,
69
- bias=bias,
70
- stride=stride,
71
- padding=padding,
72
- output_padding=output_padding,
73
- dilation=dilation,
74
- groups=groups,
75
- )
76
-
77
-
78
- def could_use_op(input):
79
- if (not enabled) or (not torch.backends.cudnn.enabled):
80
- return False
81
-
82
- if input.device.type != "cuda":
83
- return False
84
-
85
- if any(torch.__version__.startswith(x) for x in ["1.7.", "1.8."]):
86
- return True
87
-
88
- warnings.warn(
89
- f"conv2d_gradfix not supported on PyTorch {torch.__version__}. Falling back to torch.nn.functional.conv2d()."
90
- )
91
-
92
- return False
93
-
94
-
95
- def ensure_tuple(xs, ndim):
96
- xs = tuple(xs) if isinstance(xs, (tuple, list)) else (xs,) * ndim
97
-
98
- return xs
99
-
100
-
101
- conv2d_gradfix_cache = dict()
102
-
103
-
104
- def conv2d_gradfix(
105
- transpose, weight_shape, stride, padding, output_padding, dilation, groups
106
- ):
107
- ndim = 2
108
- weight_shape = tuple(weight_shape)
109
- stride = ensure_tuple(stride, ndim)
110
- padding = ensure_tuple(padding, ndim)
111
- output_padding = ensure_tuple(output_padding, ndim)
112
- dilation = ensure_tuple(dilation, ndim)
113
-
114
- key = (transpose, weight_shape, stride, padding, output_padding, dilation, groups)
115
- if key in conv2d_gradfix_cache:
116
- return conv2d_gradfix_cache[key]
117
-
118
- common_kwargs = dict(
119
- stride=stride, padding=padding, dilation=dilation, groups=groups
120
- )
121
-
122
- def calc_output_padding(input_shape, output_shape):
123
- if transpose:
124
- return [0, 0]
125
-
126
- return [
127
- input_shape[i + 2]
128
- - (output_shape[i + 2] - 1) * stride[i]
129
- - (1 - 2 * padding[i])
130
- - dilation[i] * (weight_shape[i + 2] - 1)
131
- for i in range(ndim)
132
- ]
133
-
134
- class Conv2d(autograd.Function):
135
- @staticmethod
136
- def forward(ctx, input, weight, bias):
137
- if not transpose:
138
- out = F.conv2d(input=input, weight=weight, bias=bias, **common_kwargs)
139
-
140
- else:
141
- out = F.conv_transpose2d(
142
- input=input,
143
- weight=weight,
144
- bias=bias,
145
- output_padding=output_padding,
146
- **common_kwargs,
147
- )
148
-
149
- ctx.save_for_backward(input, weight)
150
-
151
- return out
152
-
153
- @staticmethod
154
- def backward(ctx, grad_output):
155
- input, weight = ctx.saved_tensors
156
- grad_input, grad_weight, grad_bias = None, None, None
157
-
158
- if ctx.needs_input_grad[0]:
159
- p = calc_output_padding(
160
- input_shape=input.shape, output_shape=grad_output.shape
161
- )
162
- grad_input = conv2d_gradfix(
163
- transpose=(not transpose),
164
- weight_shape=weight_shape,
165
- output_padding=p,
166
- **common_kwargs,
167
- ).apply(grad_output, weight, None)
168
-
169
- if ctx.needs_input_grad[1] and not weight_gradients_disabled:
170
- grad_weight = Conv2dGradWeight.apply(grad_output, input)
171
-
172
- if ctx.needs_input_grad[2]:
173
- grad_bias = grad_output.sum((0, 2, 3))
174
-
175
- return grad_input, grad_weight, grad_bias
176
-
177
- class Conv2dGradWeight(autograd.Function):
178
- @staticmethod
179
- def forward(ctx, grad_output, input):
180
- op = torch._C._jit_get_operation(
181
- "aten::cudnn_convolution_backward_weight"
182
- if not transpose
183
- else "aten::cudnn_convolution_transpose_backward_weight"
184
- )
185
- flags = [
186
- torch.backends.cudnn.benchmark,
187
- torch.backends.cudnn.deterministic,
188
- torch.backends.cudnn.allow_tf32,
189
- ]
190
- grad_weight = op(
191
- weight_shape,
192
- grad_output,
193
- input,
194
- padding,
195
- stride,
196
- dilation,
197
- groups,
198
- *flags,
199
- )
200
- ctx.save_for_backward(grad_output, input)
201
-
202
- return grad_weight
203
-
204
- @staticmethod
205
- def backward(ctx, grad_grad_weight):
206
- grad_output, input = ctx.saved_tensors
207
- grad_grad_output, grad_grad_input = None, None
208
-
209
- if ctx.needs_input_grad[0]:
210
- grad_grad_output = Conv2d.apply(input, grad_grad_weight, None)
211
-
212
- if ctx.needs_input_grad[1]:
213
- p = calc_output_padding(
214
- input_shape=input.shape, output_shape=grad_output.shape
215
- )
216
- grad_grad_input = conv2d_gradfix(
217
- transpose=(not transpose),
218
- weight_shape=weight_shape,
219
- output_padding=p,
220
- **common_kwargs,
221
- ).apply(grad_output, grad_grad_weight, None)
222
-
223
- return grad_grad_output, grad_grad_input
224
-
225
- conv2d_gradfix_cache[key] = Conv2d
226
-
227
- return Conv2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/NeuralSeq/tasks/tts/pe.py DELETED
@@ -1,155 +0,0 @@
1
- import matplotlib
2
- matplotlib.use('Agg')
3
-
4
- import torch
5
- import numpy as np
6
- import os
7
-
8
- from tasks.base_task import BaseDataset
9
- from tasks.tts.fs2 import FastSpeech2Task
10
- from modules.fastspeech.pe import PitchExtractor
11
- import utils
12
- from utils.indexed_datasets import IndexedDataset
13
- from utils.hparams import hparams
14
- from utils.plot import f0_to_figure
15
- from utils.pitch_utils import norm_interp_f0, denorm_f0
16
-
17
-
18
- class PeDataset(BaseDataset):
19
- def __init__(self, prefix, shuffle=False):
20
- super().__init__(shuffle)
21
- self.data_dir = hparams['binary_data_dir']
22
- self.prefix = prefix
23
- self.hparams = hparams
24
- self.sizes = np.load(f'{self.data_dir}/{self.prefix}_lengths.npy')
25
- self.indexed_ds = None
26
-
27
- # pitch stats
28
- f0_stats_fn = f'{self.data_dir}/train_f0s_mean_std.npy'
29
- if os.path.exists(f0_stats_fn):
30
- hparams['f0_mean'], hparams['f0_std'] = self.f0_mean, self.f0_std = np.load(f0_stats_fn)
31
- hparams['f0_mean'] = float(hparams['f0_mean'])
32
- hparams['f0_std'] = float(hparams['f0_std'])
33
- else:
34
- hparams['f0_mean'], hparams['f0_std'] = self.f0_mean, self.f0_std = None, None
35
-
36
- if prefix == 'test':
37
- if hparams['num_test_samples'] > 0:
38
- self.avail_idxs = list(range(hparams['num_test_samples'])) + hparams['test_ids']
39
- self.sizes = [self.sizes[i] for i in self.avail_idxs]
40
-
41
- def _get_item(self, index):
42
- if hasattr(self, 'avail_idxs') and self.avail_idxs is not None:
43
- index = self.avail_idxs[index]
44
- if self.indexed_ds is None:
45
- self.indexed_ds = IndexedDataset(f'{self.data_dir}/{self.prefix}')
46
- return self.indexed_ds[index]
47
-
48
- def __getitem__(self, index):
49
- hparams = self.hparams
50
- item = self._get_item(index)
51
- max_frames = hparams['max_frames']
52
- spec = torch.Tensor(item['mel'])[:max_frames]
53
- # mel2ph = torch.LongTensor(item['mel2ph'])[:max_frames] if 'mel2ph' in item else None
54
- f0, uv = norm_interp_f0(item["f0"][:max_frames], hparams)
55
- pitch = torch.LongTensor(item.get("pitch"))[:max_frames]
56
- # print(item.keys(), item['mel'].shape, spec.shape)
57
- sample = {
58
- "id": index,
59
- "item_name": item['item_name'],
60
- "text": item['txt'],
61
- "mel": spec,
62
- "pitch": pitch,
63
- "f0": f0,
64
- "uv": uv,
65
- # "mel2ph": mel2ph,
66
- # "mel_nonpadding": spec.abs().sum(-1) > 0,
67
- }
68
- return sample
69
-
70
- def collater(self, samples):
71
- if len(samples) == 0:
72
- return {}
73
- id = torch.LongTensor([s['id'] for s in samples])
74
- item_names = [s['item_name'] for s in samples]
75
- text = [s['text'] for s in samples]
76
- f0 = utils.collate_1d([s['f0'] for s in samples], 0.0)
77
- pitch = utils.collate_1d([s['pitch'] for s in samples])
78
- uv = utils.collate_1d([s['uv'] for s in samples])
79
- mels = utils.collate_2d([s['mel'] for s in samples], 0.0)
80
- mel_lengths = torch.LongTensor([s['mel'].shape[0] for s in samples])
81
- # mel2ph = utils.collate_1d([s['mel2ph'] for s in samples], 0.0) \
82
- # if samples[0]['mel2ph'] is not None else None
83
- # mel_nonpaddings = utils.collate_1d([s['mel_nonpadding'].float() for s in samples], 0.0)
84
-
85
- batch = {
86
- 'id': id,
87
- 'item_name': item_names,
88
- 'nsamples': len(samples),
89
- 'text': text,
90
- 'mels': mels,
91
- 'mel_lengths': mel_lengths,
92
- 'pitch': pitch,
93
- # 'mel2ph': mel2ph,
94
- # 'mel_nonpaddings': mel_nonpaddings,
95
- 'f0': f0,
96
- 'uv': uv,
97
- }
98
- return batch
99
-
100
-
101
- class PitchExtractionTask(FastSpeech2Task):
102
- def __init__(self):
103
- super().__init__()
104
- self.dataset_cls = PeDataset
105
-
106
- def build_tts_model(self):
107
- self.model = PitchExtractor(conv_layers=hparams['pitch_extractor_conv_layers'])
108
-
109
- # def build_scheduler(self, optimizer):
110
- # return torch.optim.lr_scheduler.StepLR(optimizer, hparams['decay_steps'], gamma=0.5)
111
- def _training_step(self, sample, batch_idx, _):
112
- loss_output = self.run_model(self.model, sample)
113
- total_loss = sum([v for v in loss_output.values() if isinstance(v, torch.Tensor) and v.requires_grad])
114
- loss_output['batch_size'] = sample['mels'].size()[0]
115
- return total_loss, loss_output
116
-
117
- def validation_step(self, sample, batch_idx):
118
- outputs = {}
119
- outputs['losses'] = {}
120
- outputs['losses'], model_out = self.run_model(self.model, sample, return_output=True, infer=True)
121
- outputs['total_loss'] = sum(outputs['losses'].values())
122
- outputs['nsamples'] = sample['nsamples']
123
- outputs = utils.tensors_to_scalars(outputs)
124
- if batch_idx < hparams['num_valid_plots']:
125
- self.plot_pitch(batch_idx, model_out, sample)
126
- return outputs
127
-
128
- def run_model(self, model, sample, return_output=False, infer=False):
129
- f0 = sample['f0']
130
- uv = sample['uv']
131
- output = model(sample['mels'])
132
- losses = {}
133
- self.add_pitch_loss(output, sample, losses)
134
- if not return_output:
135
- return losses
136
- else:
137
- return losses, output
138
-
139
- def plot_pitch(self, batch_idx, model_out, sample):
140
- gt_f0 = denorm_f0(sample['f0'], sample['uv'], hparams)
141
- self.logger.experiment.add_figure(
142
- f'f0_{batch_idx}',
143
- f0_to_figure(gt_f0[0], None, model_out['f0_denorm_pred'][0]),
144
- self.global_step)
145
-
146
- def add_pitch_loss(self, output, sample, losses):
147
- # mel2ph = sample['mel2ph'] # [B, T_s]
148
- mel = sample['mels']
149
- f0 = sample['f0']
150
- uv = sample['uv']
151
- # nonpadding = (mel2ph != 0).float() if hparams['pitch_type'] == 'frame' \
152
- # else (sample['txt_tokens'] != 0).float()
153
- nonpadding = (mel.abs().sum(-1) > 0).float() # sample['mel_nonpaddings']
154
- # print(nonpadding[0][-8:], nonpadding.shape)
155
- self.add_f0_loss(output['pitch_pred'], f0, uv, losses, nonpadding=nonpadding)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIWaves/Debate/app.py DELETED
@@ -1,365 +0,0 @@
1
- import sys
2
- sys.path.append("../../Gradio_Config")
3
-
4
- from gradio_base import UIHelper, WebUI
5
- import os
6
- from gradio_base import WebUI, UIHelper, PORT, HOST, Client
7
- from gradio_config import GradioConfig as gc
8
- from typing import List, Tuple, Any
9
- import gradio as gr
10
- import time
11
-
12
-
13
- class DebateUI(WebUI):
14
- FORMAT = "{}\n<debate topic>\n{}\nAffirmative viewpoint:{}\nNegative viewpoint:{}\n<debate topic>{}"
15
- AUDIENCE = "Audience"
16
- cache = {}
17
- all_agents_name = []
18
- receive_server = None
19
-
20
- @classmethod
21
- def extract(cls, content):
22
- topic = content.split("<debate topic>")[1].split("Affirmative viewpoint:")[0]
23
- positive = content.split("<debate topic>")[1].split("Affirmative viewpoint:")[1].split("negative viewpoint:")[0]
24
- negative = content.split("<debate topic>")[1].split("Affirmative viewpoint:")[1].split("negative viewpoint:")[1]
25
- return topic.strip(), positive.strip(), negative.strip()
26
-
27
- @classmethod
28
- def merge(cls, theme, positive, negative, origin_content) -> str:
29
- return cls.FORMAT.format(
30
- origin_content.split("<debate topic>")[0],
31
- theme, positive, negative,
32
- origin_content.split("<debate topic>")[-1]
33
- )
34
-
35
- @classmethod
36
- def convert2list4agentname(cls, sop):
37
- only_name = []
38
- agent_name = []
39
- roles_to_names = sop.roles_to_names
40
- for state_name,roles_names in roles_to_names.items():
41
- for role,name in roles_names.items():
42
- agent_name.append(f"{name}({role})")
43
- only_name.append(name)
44
- agent_name.append(cls.AUDIENCE)
45
- agent_name = list(set(agent_name))
46
- agent_name.sort()
47
- return agent_name, only_name
48
-
49
- def render_and_register_ui(self):
50
- gc.add_agent(self.cache["only_name"])
51
-
52
- def __init__(
53
- self,
54
- client_cmd: list,
55
- socket_host: str = HOST,
56
- socket_port: int = PORT,
57
- bufsize: int = 1024,
58
- ui_name: str = "DebateUI"
59
- ):
60
- super(DebateUI, self).__init__(client_cmd, socket_host, socket_port, bufsize, ui_name)
61
- self.first_recieve_from_client()
62
- self.data_history = list()
63
- self.caller = 0
64
-
65
- def handle_message(self, history:list,
66
- state, agent_name, token, node_name):
67
- if state % 10 == 0:
68
- self.data_history.append({agent_name: token})
69
- elif state % 10 == 1:
70
- # Same state. Need to add new bubble in same bubble.
71
- if len(self.data_history) == 0:
72
- self.data_history.append({agent_name:""})
73
- self.data_history[-1][agent_name] += token
74
- elif state % 10 == 2:
75
- # New state. Need to add new bubble.
76
- history.append([None, ""])
77
- self.data_history.clear()
78
- self.data_history.append({agent_name: token})
79
- else:
80
- assert False, "Invalid state."
81
- render_data = self.render_bubble(history, self.data_history, node_name, render_node_name= True or state % 10 == 2)
82
- return render_data
83
-
84
- def start_button_when_click(self, theme, positive, negative, choose, mode, api_key):
85
- """
86
- inputs=[self.text_theme, self.text_positive, self.text_negative, self.radio_choose],
87
- outputs=[self.chatbot, self.btn_send]
88
- """
89
- cosplay = None if choose == self.AUDIENCE else choose.split("(")[0]
90
- message = dict(theme=theme, positive=positive, negative=negative, cosplay=cosplay, mode=mode, api_key=api_key)
91
- self.send_start_cmd(message=message)
92
- return gr.Chatbot.update(
93
- visible=True
94
- ), gr.Button.update(visible=False)
95
-
96
- def start_button_after_click(self, history):
97
- """
98
- inputs=[self.chatbot],
99
- outputs=[self.chatbot, self.text_user, self.btn_send, self.btn_reset, self.btn_next]
100
- """
101
- if self.caller == 0:
102
- # not single mode
103
- self.data_history = list()
104
- self.caller = 0
105
- receive_server = self.receive_server
106
- while True:
107
- data_list: List = receive_server.send(None)
108
- for item in data_list:
109
- data = eval(item)
110
- assert isinstance(data, list)
111
- state, agent_name, token, node_name = data
112
- assert isinstance(state, int)
113
- if state == 30:
114
- # user input
115
- yield history,\
116
- gr.Textbox.update(visible=True, interactive=True), \
117
- gr.Button.update(visible=True, interactive=True),\
118
- gr.Button.update(visible=True, interactive=True),\
119
- gr.Button.update(visible=False)
120
- return
121
- elif state == 99:
122
- # finish
123
- yield history, gr.Textbox.update(visible=True, interactive=False, value="finish!"), \
124
- gr.Button.update(visible=True, interactive=False, value="finish!"), gr.Button.update(visible=True, interactive=True),\
125
- gr.Button.update(visible=False)
126
- elif state == 98:
127
- yield history, \
128
- gr.Textbox.update(visible=False, interactive=False), \
129
- gr.Button.update(visible=False, interactive=False),\
130
- gr.Button.update(visible=False, interactive=False),\
131
- gr.Button.update(visible=True, value=f"Next Agent: 🤖{agent_name} | Next Node: ⭕{node_name}")
132
- return
133
- else:
134
- history = self.handle_message(history, state, agent_name, token, node_name)
135
- yield history, \
136
- gr.Textbox.update(visible=False, interactive=False), \
137
- gr.Button.update(visible=False, interactive=False),\
138
- gr.Button.update(visible=False, interactive=False),\
139
- gr.Button.update(visible=False)
140
-
141
- def send_button_when_click(self, text_user, history:list):
142
- """
143
- inputs=[self.text_user, self.chatbot],
144
- outputs=[self.text_user, self.btn_send, self.chatbot]
145
- """
146
- history.append(
147
- [UIHelper.wrap_css(text_user, "User"), None]
148
- )
149
- # print(f"server: send {text_user} to client")
150
- self.send_message("<USER>"+text_user+self.SIGN["SPLIT"])
151
- return gr.Textbox.update(value="", visible=False),\
152
- gr.Button.update(visible=False), \
153
- history,\
154
- gr.Button.update(visible=False)
155
-
156
- def reset_button_when_click(self, history, text_positive, text_negative, text_theme, text_user, btn_send, btn_start, btn_reset):
157
- """
158
- self.chatbot,
159
- self.text_positive,
160
- self.text_negative,
161
- self.text_theme,
162
- self.text_user,
163
- self.btn_send,
164
- self.btn_start,
165
- self.btn_reset
166
- self.btn_next
167
- """
168
- self.caller = 0
169
- return None, \
170
- "", \
171
- "", \
172
- "", \
173
- "", \
174
- gr.Button.update(value="Restarting...", interactive=False, visible=True),\
175
- gr.Button.update(value="Restarting...", interactive=False, visible=True),\
176
- gr.Button.update(value="Restarting...", interactive=False, visible=True),\
177
- gr.Button.update(value="Restarting...", interactive=False, visible=False)
178
-
179
- def reset_button_after_click(self, history, text_positive, text_negative, text_theme, text_user, btn_send, btn_start, btn_reset):
180
- self.reset()
181
- self.first_recieve_from_client(reset_mode=True)
182
- return gr.Chatbot.update(value=None, visible=False),\
183
- gr.Textbox.update(value=f"{self.cache['positive']}", interactive=True, visible=True),\
184
- gr.Textbox.update(value=f"{self.cache['negative']}", interactive=True, visible=True),\
185
- gr.Textbox.update(value=f"{self.cache['theme']}", interactive=True, visible=True),\
186
- gr.Textbox.update(value=f"", interactive=True, visible=False),\
187
- gr.Button.update(interactive=True, visible=False, value="Send"),\
188
- gr.Button.update(interactive=True, visible=True, value="Start"),\
189
- gr.Button.update(interactive=False, visible=False, value="Restart"),\
190
- gr.Button.update(interactive=True, visible=False, value="Next Agent")
191
-
192
- def btn_next_when_click(self):
193
- yield gr.Button.update(visible=False)
194
- self.send_message("nothing")
195
- self.caller = 1 # will note clear the self.data_history
196
- time.sleep(0.5)
197
- return
198
-
199
- def construct_ui(
200
- self,
201
- theme:str=None,
202
- positive:str=None,
203
- negative:str=None,
204
- agents_name:List=None,
205
- default_cos_play_id:int=None
206
- ):
207
- theme = self.cache["theme"] if theme is None else theme
208
- positive = self.cache["positive"] if positive is None else positive
209
- negative = self.cache["negative"] if negative is None else negative
210
- agents_name = self.cache["agents_name"] if agents_name is None else agents_name
211
- default_cos_play_id = self.cache["default_cos_play_id"] if default_cos_play_id is None else default_cos_play_id
212
-
213
- with gr.Blocks(css=gc.CSS) as demo:
214
- gr.Markdown("""# Agents""")
215
- gr.Markdown("""**Agents** is an open-source library/framework for building autonomous language agents.if you want to know more about **Agents**, please check our<a href="https://arxiv.org/pdf/2309.07870.pdf">📄 Paper</a> and<a href="http://www.aiwaves-agents.com/">📦 Github</a>. Here is a demo of **Agents**.""")
216
- gr.Markdown("""<font size=5>If an error occurs or the queue is too long, please create your own demo by clicking <font color=red>Duplicate This Space</font> in the upper right corner.</font>""")
217
- with gr.Row():
218
- with gr.Column():
219
- self.text_api = gr.Textbox(
220
- value = self.cache["api_key"],
221
- placeholder="openai key",
222
- label="Please input valid openai key for gpt-3.5-turbo-16k."
223
- )
224
- self.radio_mode = gr.Radio(
225
- [Client.SINGLE_MODE],
226
- value=Client.SINGLE_MODE,
227
- interactive=True,
228
- label = Client.MODE_LABEL,
229
- info = Client.MODE_INFO
230
- )
231
- self.text_theme = gr.Textbox(
232
- label="Debate Topic:",
233
- value=theme,
234
- placeholder="Please input the Debate Topic"
235
- )
236
- self.text_positive = gr.Textbox(
237
- label="Affirmative viewpoint:",
238
- value=positive,
239
- placeholder="Please input the Affirmative viewpoint"
240
- )
241
- self.text_negative = gr.Textbox(
242
- label="Negative viewpoint:",
243
- value=negative,
244
- placeholder="Please input the Negative viewpoint"
245
- )
246
- self.radio_choose = gr.Radio(
247
- agents_name,
248
- value=agents_name[default_cos_play_id],
249
- label="User'agent",
250
- interactive=True
251
- )
252
- self.btn_start = gr.Button(
253
- value="run"
254
- )
255
- VISIBLE = False
256
- with gr.Column():
257
- self.chatbot = gr.Chatbot(
258
- height= 650,
259
- elem_id="chatbot1",
260
- label="Dialog",
261
- visible=VISIBLE
262
- )
263
- self.btn_next = gr.Button(
264
- value="Next Agent Start",
265
- visible=False
266
- )
267
- self.text_user = gr.Textbox(
268
- label="Input",
269
- placeholder="Input here",
270
- visible=VISIBLE
271
- )
272
- self.btn_send = gr.Button(
273
- value="Send",
274
- visible=VISIBLE
275
- )
276
- self.btn_reset = gr.Button(
277
- value="Restart",
278
- visible=VISIBLE
279
- )
280
-
281
- self.btn_start.click(
282
- fn=self.start_button_when_click,
283
- inputs=[self.text_theme, self.text_positive, self.text_negative, self.radio_choose, self.radio_mode, self.text_api],
284
- outputs=[self.chatbot, self.btn_start]
285
- ).then(
286
- fn=self.start_button_after_click,
287
- inputs=[self.chatbot],
288
- outputs=[self.chatbot, self.text_user, self.btn_send, self.btn_reset, self.btn_next]
289
- )
290
-
291
- self.btn_send.click(
292
- fn=self.send_button_when_click,
293
- inputs=[self.text_user, self.chatbot],
294
- outputs=[self.text_user, self.btn_send, self.chatbot, self.btn_reset]
295
- ).then(
296
- fn=self.start_button_after_click,
297
- inputs=[self.chatbot],
298
- outputs=[self.chatbot, self.text_user, self.btn_send, self.btn_reset, self.btn_next]
299
- )
300
-
301
- self.btn_reset.click(
302
- fn=self.reset_button_when_click,
303
- inputs=[
304
- self.chatbot,
305
- self.text_positive,
306
- self.text_negative,
307
- self.text_theme,
308
- self.text_user,
309
- self.btn_send,
310
- self.btn_start,
311
- self.btn_reset
312
- ],
313
- outputs=[
314
- self.chatbot,
315
- self.text_positive,
316
- self.text_negative,
317
- self.text_theme,
318
- self.text_user,
319
- self.btn_send,
320
- self.btn_start,
321
- self.btn_reset,
322
- self.btn_next
323
- ]
324
- ).then(
325
- fn=self.reset_button_after_click,
326
- inputs=[
327
- self.chatbot,
328
- self.text_positive,
329
- self.text_negative,
330
- self.text_theme,
331
- self.text_user,
332
- self.btn_send,
333
- self.btn_start,
334
- self.btn_reset
335
- ],
336
- outputs=[
337
- self.chatbot,
338
- self.text_positive,
339
- self.text_negative,
340
- self.text_theme,
341
- self.text_user,
342
- self.btn_send,
343
- self.btn_start,
344
- self.btn_reset,
345
- self.btn_next
346
- ]
347
- )
348
-
349
- self.btn_next.click(
350
- fn=self.btn_next_when_click,
351
- inputs=[],
352
- outputs=[self.btn_next]
353
- ).then(
354
- fn=self.start_button_after_click,
355
- inputs=[self.chatbot],
356
- outputs=[self.chatbot, self.text_user, self.btn_send, self.btn_reset, self.btn_next]
357
- )
358
-
359
- self.demo = demo
360
-
361
-
362
- if __name__ == '__main__':
363
- ui = DebateUI(client_cmd=["python","gradio_backend.py"])
364
- ui.construct_ui()
365
- ui.run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Adapter/CoAdapter/ldm/modules/extra_condition/midas/midas/vit.py DELETED
@@ -1,491 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import timm
4
- import types
5
- import math
6
- import torch.nn.functional as F
7
-
8
-
9
- class Slice(nn.Module):
10
- def __init__(self, start_index=1):
11
- super(Slice, self).__init__()
12
- self.start_index = start_index
13
-
14
- def forward(self, x):
15
- return x[:, self.start_index :]
16
-
17
-
18
- class AddReadout(nn.Module):
19
- def __init__(self, start_index=1):
20
- super(AddReadout, self).__init__()
21
- self.start_index = start_index
22
-
23
- def forward(self, x):
24
- if self.start_index == 2:
25
- readout = (x[:, 0] + x[:, 1]) / 2
26
- else:
27
- readout = x[:, 0]
28
- return x[:, self.start_index :] + readout.unsqueeze(1)
29
-
30
-
31
- class ProjectReadout(nn.Module):
32
- def __init__(self, in_features, start_index=1):
33
- super(ProjectReadout, self).__init__()
34
- self.start_index = start_index
35
-
36
- self.project = nn.Sequential(nn.Linear(2 * in_features, in_features), nn.GELU())
37
-
38
- def forward(self, x):
39
- readout = x[:, 0].unsqueeze(1).expand_as(x[:, self.start_index :])
40
- features = torch.cat((x[:, self.start_index :], readout), -1)
41
-
42
- return self.project(features)
43
-
44
-
45
- class Transpose(nn.Module):
46
- def __init__(self, dim0, dim1):
47
- super(Transpose, self).__init__()
48
- self.dim0 = dim0
49
- self.dim1 = dim1
50
-
51
- def forward(self, x):
52
- x = x.transpose(self.dim0, self.dim1)
53
- return x
54
-
55
-
56
- def forward_vit(pretrained, x):
57
- b, c, h, w = x.shape
58
-
59
- glob = pretrained.model.forward_flex(x)
60
-
61
- layer_1 = pretrained.activations["1"]
62
- layer_2 = pretrained.activations["2"]
63
- layer_3 = pretrained.activations["3"]
64
- layer_4 = pretrained.activations["4"]
65
-
66
- layer_1 = pretrained.act_postprocess1[0:2](layer_1)
67
- layer_2 = pretrained.act_postprocess2[0:2](layer_2)
68
- layer_3 = pretrained.act_postprocess3[0:2](layer_3)
69
- layer_4 = pretrained.act_postprocess4[0:2](layer_4)
70
-
71
- unflatten = nn.Sequential(
72
- nn.Unflatten(
73
- 2,
74
- torch.Size(
75
- [
76
- h // pretrained.model.patch_size[1],
77
- w // pretrained.model.patch_size[0],
78
- ]
79
- ),
80
- )
81
- )
82
-
83
- if layer_1.ndim == 3:
84
- layer_1 = unflatten(layer_1)
85
- if layer_2.ndim == 3:
86
- layer_2 = unflatten(layer_2)
87
- if layer_3.ndim == 3:
88
- layer_3 = unflatten(layer_3)
89
- if layer_4.ndim == 3:
90
- layer_4 = unflatten(layer_4)
91
-
92
- layer_1 = pretrained.act_postprocess1[3 : len(pretrained.act_postprocess1)](layer_1)
93
- layer_2 = pretrained.act_postprocess2[3 : len(pretrained.act_postprocess2)](layer_2)
94
- layer_3 = pretrained.act_postprocess3[3 : len(pretrained.act_postprocess3)](layer_3)
95
- layer_4 = pretrained.act_postprocess4[3 : len(pretrained.act_postprocess4)](layer_4)
96
-
97
- return layer_1, layer_2, layer_3, layer_4
98
-
99
-
100
- def _resize_pos_embed(self, posemb, gs_h, gs_w):
101
- posemb_tok, posemb_grid = (
102
- posemb[:, : self.start_index],
103
- posemb[0, self.start_index :],
104
- )
105
-
106
- gs_old = int(math.sqrt(len(posemb_grid)))
107
-
108
- posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)
109
- posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear")
110
- posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1)
111
-
112
- posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
113
-
114
- return posemb
115
-
116
-
117
- def forward_flex(self, x):
118
- b, c, h, w = x.shape
119
-
120
- pos_embed = self._resize_pos_embed(
121
- self.pos_embed, h // self.patch_size[1], w // self.patch_size[0]
122
- )
123
-
124
- B = x.shape[0]
125
-
126
- if hasattr(self.patch_embed, "backbone"):
127
- x = self.patch_embed.backbone(x)
128
- if isinstance(x, (list, tuple)):
129
- x = x[-1] # last feature if backbone outputs list/tuple of features
130
-
131
- x = self.patch_embed.proj(x).flatten(2).transpose(1, 2)
132
-
133
- if getattr(self, "dist_token", None) is not None:
134
- cls_tokens = self.cls_token.expand(
135
- B, -1, -1
136
- ) # stole cls_tokens impl from Phil Wang, thanks
137
- dist_token = self.dist_token.expand(B, -1, -1)
138
- x = torch.cat((cls_tokens, dist_token, x), dim=1)
139
- else:
140
- cls_tokens = self.cls_token.expand(
141
- B, -1, -1
142
- ) # stole cls_tokens impl from Phil Wang, thanks
143
- x = torch.cat((cls_tokens, x), dim=1)
144
-
145
- x = x + pos_embed
146
- x = self.pos_drop(x)
147
-
148
- for blk in self.blocks:
149
- x = blk(x)
150
-
151
- x = self.norm(x)
152
-
153
- return x
154
-
155
-
156
- activations = {}
157
-
158
-
159
- def get_activation(name):
160
- def hook(model, input, output):
161
- activations[name] = output
162
-
163
- return hook
164
-
165
-
166
- def get_readout_oper(vit_features, features, use_readout, start_index=1):
167
- if use_readout == "ignore":
168
- readout_oper = [Slice(start_index)] * len(features)
169
- elif use_readout == "add":
170
- readout_oper = [AddReadout(start_index)] * len(features)
171
- elif use_readout == "project":
172
- readout_oper = [
173
- ProjectReadout(vit_features, start_index) for out_feat in features
174
- ]
175
- else:
176
- assert (
177
- False
178
- ), "wrong operation for readout token, use_readout can be 'ignore', 'add', or 'project'"
179
-
180
- return readout_oper
181
-
182
-
183
- def _make_vit_b16_backbone(
184
- model,
185
- features=[96, 192, 384, 768],
186
- size=[384, 384],
187
- hooks=[2, 5, 8, 11],
188
- vit_features=768,
189
- use_readout="ignore",
190
- start_index=1,
191
- ):
192
- pretrained = nn.Module()
193
-
194
- pretrained.model = model
195
- pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
196
- pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
197
- pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
198
- pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))
199
-
200
- pretrained.activations = activations
201
-
202
- readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)
203
-
204
- # 32, 48, 136, 384
205
- pretrained.act_postprocess1 = nn.Sequential(
206
- readout_oper[0],
207
- Transpose(1, 2),
208
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
209
- nn.Conv2d(
210
- in_channels=vit_features,
211
- out_channels=features[0],
212
- kernel_size=1,
213
- stride=1,
214
- padding=0,
215
- ),
216
- nn.ConvTranspose2d(
217
- in_channels=features[0],
218
- out_channels=features[0],
219
- kernel_size=4,
220
- stride=4,
221
- padding=0,
222
- bias=True,
223
- dilation=1,
224
- groups=1,
225
- ),
226
- )
227
-
228
- pretrained.act_postprocess2 = nn.Sequential(
229
- readout_oper[1],
230
- Transpose(1, 2),
231
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
232
- nn.Conv2d(
233
- in_channels=vit_features,
234
- out_channels=features[1],
235
- kernel_size=1,
236
- stride=1,
237
- padding=0,
238
- ),
239
- nn.ConvTranspose2d(
240
- in_channels=features[1],
241
- out_channels=features[1],
242
- kernel_size=2,
243
- stride=2,
244
- padding=0,
245
- bias=True,
246
- dilation=1,
247
- groups=1,
248
- ),
249
- )
250
-
251
- pretrained.act_postprocess3 = nn.Sequential(
252
- readout_oper[2],
253
- Transpose(1, 2),
254
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
255
- nn.Conv2d(
256
- in_channels=vit_features,
257
- out_channels=features[2],
258
- kernel_size=1,
259
- stride=1,
260
- padding=0,
261
- ),
262
- )
263
-
264
- pretrained.act_postprocess4 = nn.Sequential(
265
- readout_oper[3],
266
- Transpose(1, 2),
267
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
268
- nn.Conv2d(
269
- in_channels=vit_features,
270
- out_channels=features[3],
271
- kernel_size=1,
272
- stride=1,
273
- padding=0,
274
- ),
275
- nn.Conv2d(
276
- in_channels=features[3],
277
- out_channels=features[3],
278
- kernel_size=3,
279
- stride=2,
280
- padding=1,
281
- ),
282
- )
283
-
284
- pretrained.model.start_index = start_index
285
- pretrained.model.patch_size = [16, 16]
286
-
287
- # We inject this function into the VisionTransformer instances so that
288
- # we can use it with interpolated position embeddings without modifying the library source.
289
- pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
290
- pretrained.model._resize_pos_embed = types.MethodType(
291
- _resize_pos_embed, pretrained.model
292
- )
293
-
294
- return pretrained
295
-
296
-
297
- def _make_pretrained_vitl16_384(pretrained, use_readout="ignore", hooks=None):
298
- model = timm.create_model("vit_large_patch16_384", pretrained=pretrained)
299
-
300
- hooks = [5, 11, 17, 23] if hooks == None else hooks
301
- return _make_vit_b16_backbone(
302
- model,
303
- features=[256, 512, 1024, 1024],
304
- hooks=hooks,
305
- vit_features=1024,
306
- use_readout=use_readout,
307
- )
308
-
309
-
310
- def _make_pretrained_vitb16_384(pretrained, use_readout="ignore", hooks=None):
311
- model = timm.create_model("vit_base_patch16_384", pretrained=pretrained)
312
-
313
- hooks = [2, 5, 8, 11] if hooks == None else hooks
314
- return _make_vit_b16_backbone(
315
- model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout
316
- )
317
-
318
-
319
- def _make_pretrained_deitb16_384(pretrained, use_readout="ignore", hooks=None):
320
- model = timm.create_model("vit_deit_base_patch16_384", pretrained=pretrained)
321
-
322
- hooks = [2, 5, 8, 11] if hooks == None else hooks
323
- return _make_vit_b16_backbone(
324
- model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout
325
- )
326
-
327
-
328
- def _make_pretrained_deitb16_distil_384(pretrained, use_readout="ignore", hooks=None):
329
- model = timm.create_model(
330
- "vit_deit_base_distilled_patch16_384", pretrained=pretrained
331
- )
332
-
333
- hooks = [2, 5, 8, 11] if hooks == None else hooks
334
- return _make_vit_b16_backbone(
335
- model,
336
- features=[96, 192, 384, 768],
337
- hooks=hooks,
338
- use_readout=use_readout,
339
- start_index=2,
340
- )
341
-
342
-
343
- def _make_vit_b_rn50_backbone(
344
- model,
345
- features=[256, 512, 768, 768],
346
- size=[384, 384],
347
- hooks=[0, 1, 8, 11],
348
- vit_features=768,
349
- use_vit_only=False,
350
- use_readout="ignore",
351
- start_index=1,
352
- ):
353
- pretrained = nn.Module()
354
-
355
- pretrained.model = model
356
-
357
- if use_vit_only == True:
358
- pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
359
- pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
360
- else:
361
- pretrained.model.patch_embed.backbone.stages[0].register_forward_hook(
362
- get_activation("1")
363
- )
364
- pretrained.model.patch_embed.backbone.stages[1].register_forward_hook(
365
- get_activation("2")
366
- )
367
-
368
- pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
369
- pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))
370
-
371
- pretrained.activations = activations
372
-
373
- readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)
374
-
375
- if use_vit_only == True:
376
- pretrained.act_postprocess1 = nn.Sequential(
377
- readout_oper[0],
378
- Transpose(1, 2),
379
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
380
- nn.Conv2d(
381
- in_channels=vit_features,
382
- out_channels=features[0],
383
- kernel_size=1,
384
- stride=1,
385
- padding=0,
386
- ),
387
- nn.ConvTranspose2d(
388
- in_channels=features[0],
389
- out_channels=features[0],
390
- kernel_size=4,
391
- stride=4,
392
- padding=0,
393
- bias=True,
394
- dilation=1,
395
- groups=1,
396
- ),
397
- )
398
-
399
- pretrained.act_postprocess2 = nn.Sequential(
400
- readout_oper[1],
401
- Transpose(1, 2),
402
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
403
- nn.Conv2d(
404
- in_channels=vit_features,
405
- out_channels=features[1],
406
- kernel_size=1,
407
- stride=1,
408
- padding=0,
409
- ),
410
- nn.ConvTranspose2d(
411
- in_channels=features[1],
412
- out_channels=features[1],
413
- kernel_size=2,
414
- stride=2,
415
- padding=0,
416
- bias=True,
417
- dilation=1,
418
- groups=1,
419
- ),
420
- )
421
- else:
422
- pretrained.act_postprocess1 = nn.Sequential(
423
- nn.Identity(), nn.Identity(), nn.Identity()
424
- )
425
- pretrained.act_postprocess2 = nn.Sequential(
426
- nn.Identity(), nn.Identity(), nn.Identity()
427
- )
428
-
429
- pretrained.act_postprocess3 = nn.Sequential(
430
- readout_oper[2],
431
- Transpose(1, 2),
432
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
433
- nn.Conv2d(
434
- in_channels=vit_features,
435
- out_channels=features[2],
436
- kernel_size=1,
437
- stride=1,
438
- padding=0,
439
- ),
440
- )
441
-
442
- pretrained.act_postprocess4 = nn.Sequential(
443
- readout_oper[3],
444
- Transpose(1, 2),
445
- nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
446
- nn.Conv2d(
447
- in_channels=vit_features,
448
- out_channels=features[3],
449
- kernel_size=1,
450
- stride=1,
451
- padding=0,
452
- ),
453
- nn.Conv2d(
454
- in_channels=features[3],
455
- out_channels=features[3],
456
- kernel_size=3,
457
- stride=2,
458
- padding=1,
459
- ),
460
- )
461
-
462
- pretrained.model.start_index = start_index
463
- pretrained.model.patch_size = [16, 16]
464
-
465
- # We inject this function into the VisionTransformer instances so that
466
- # we can use it with interpolated position embeddings without modifying the library source.
467
- pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
468
-
469
- # We inject this function into the VisionTransformer instances so that
470
- # we can use it with interpolated position embeddings without modifying the library source.
471
- pretrained.model._resize_pos_embed = types.MethodType(
472
- _resize_pos_embed, pretrained.model
473
- )
474
-
475
- return pretrained
476
-
477
-
478
- def _make_pretrained_vitb_rn50_384(
479
- pretrained, use_readout="ignore", hooks=None, use_vit_only=False
480
- ):
481
- model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained)
482
-
483
- hooks = [0, 1, 8, 11] if hooks == None else hooks
484
- return _make_vit_b_rn50_backbone(
485
- model,
486
- features=[256, 512, 768, 768],
487
- size=[384, 384],
488
- hooks=hooks,
489
- use_vit_only=use_vit_only,
490
- use_readout=use_readout,
491
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Aditya9790/yolo7-object-tracking/utils/metrics.py DELETED
@@ -1,227 +0,0 @@
1
- # Model validation metrics
2
-
3
- from pathlib import Path
4
-
5
- import matplotlib.pyplot as plt
6
- import numpy as np
7
- import torch
8
-
9
- from . import general
10
-
11
-
12
- def fitness(x):
13
- # Model fitness as a weighted combination of metrics
14
- w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, [email protected], [email protected]:0.95]
15
- return (x[:, :4] * w).sum(1)
16
-
17
-
18
- def ap_per_class(tp, conf, pred_cls, target_cls, v5_metric=False, plot=False, save_dir='.', names=()):
19
- """ Compute the average precision, given the recall and precision curves.
20
- Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
21
- # Arguments
22
- tp: True positives (nparray, nx1 or nx10).
23
- conf: Objectness value from 0-1 (nparray).
24
- pred_cls: Predicted object classes (nparray).
25
- target_cls: True object classes (nparray).
26
- plot: Plot precision-recall curve at [email protected]
27
- save_dir: Plot save directory
28
- # Returns
29
- The average precision as computed in py-faster-rcnn.
30
- """
31
-
32
- # Sort by objectness
33
- i = np.argsort(-conf)
34
- tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
35
-
36
- # Find unique classes
37
- unique_classes = np.unique(target_cls)
38
- nc = unique_classes.shape[0] # number of classes, number of detections
39
-
40
- # Create Precision-Recall curve and compute AP for each class
41
- px, py = np.linspace(0, 1, 1000), [] # for plotting
42
- ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
43
- for ci, c in enumerate(unique_classes):
44
- i = pred_cls == c
45
- n_l = (target_cls == c).sum() # number of labels
46
- n_p = i.sum() # number of predictions
47
-
48
- if n_p == 0 or n_l == 0:
49
- continue
50
- else:
51
- # Accumulate FPs and TPs
52
- fpc = (1 - tp[i]).cumsum(0)
53
- tpc = tp[i].cumsum(0)
54
-
55
- # Recall
56
- recall = tpc / (n_l + 1e-16) # recall curve
57
- r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
58
-
59
- # Precision
60
- precision = tpc / (tpc + fpc) # precision curve
61
- p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
62
-
63
- # AP from recall-precision curve
64
- for j in range(tp.shape[1]):
65
- ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j], v5_metric=v5_metric)
66
- if plot and j == 0:
67
- py.append(np.interp(px, mrec, mpre)) # precision at [email protected]
68
-
69
- # Compute F1 (harmonic mean of precision and recall)
70
- f1 = 2 * p * r / (p + r + 1e-16)
71
- if plot:
72
- plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
73
- plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
74
- plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
75
- plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
76
-
77
- i = f1.mean(0).argmax() # max F1 index
78
- return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
79
-
80
-
81
- def compute_ap(recall, precision, v5_metric=False):
82
- """ Compute the average precision, given the recall and precision curves
83
- # Arguments
84
- recall: The recall curve (list)
85
- precision: The precision curve (list)
86
- v5_metric: Assume maximum recall to be 1.0, as in YOLOv5, MMDetetion etc.
87
- # Returns
88
- Average precision, precision curve, recall curve
89
- """
90
-
91
- # Append sentinel values to beginning and end
92
- if v5_metric: # New YOLOv5 metric, same as MMDetection and Detectron2 repositories
93
- mrec = np.concatenate(([0.], recall, [1.0]))
94
- else: # Old YOLOv5 metric, i.e. default YOLOv7 metric
95
- mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
96
- mpre = np.concatenate(([1.], precision, [0.]))
97
-
98
- # Compute the precision envelope
99
- mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
100
-
101
- # Integrate area under curve
102
- method = 'interp' # methods: 'continuous', 'interp'
103
- if method == 'interp':
104
- x = np.linspace(0, 1, 101) # 101-point interp (COCO)
105
- ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
106
- else: # 'continuous'
107
- i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
108
- ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
109
-
110
- return ap, mpre, mrec
111
-
112
-
113
- class ConfusionMatrix:
114
- # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
115
- def __init__(self, nc, conf=0.25, iou_thres=0.45):
116
- self.matrix = np.zeros((nc + 1, nc + 1))
117
- self.nc = nc # number of classes
118
- self.conf = conf
119
- self.iou_thres = iou_thres
120
-
121
- def process_batch(self, detections, labels):
122
- """
123
- Return intersection-over-union (Jaccard index) of boxes.
124
- Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
125
- Arguments:
126
- detections (Array[N, 6]), x1, y1, x2, y2, conf, class
127
- labels (Array[M, 5]), class, x1, y1, x2, y2
128
- Returns:
129
- None, updates confusion matrix accordingly
130
- """
131
- detections = detections[detections[:, 4] > self.conf]
132
- gt_classes = labels[:, 0].int()
133
- detection_classes = detections[:, 5].int()
134
- iou = general.box_iou(labels[:, 1:], detections[:, :4])
135
-
136
- x = torch.where(iou > self.iou_thres)
137
- if x[0].shape[0]:
138
- matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
139
- if x[0].shape[0] > 1:
140
- matches = matches[matches[:, 2].argsort()[::-1]]
141
- matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
142
- matches = matches[matches[:, 2].argsort()[::-1]]
143
- matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
144
- else:
145
- matches = np.zeros((0, 3))
146
-
147
- n = matches.shape[0] > 0
148
- m0, m1, _ = matches.transpose().astype(np.int16)
149
- for i, gc in enumerate(gt_classes):
150
- j = m0 == i
151
- if n and sum(j) == 1:
152
- self.matrix[gc, detection_classes[m1[j]]] += 1 # correct
153
- else:
154
- self.matrix[self.nc, gc] += 1 # background FP
155
-
156
- if n:
157
- for i, dc in enumerate(detection_classes):
158
- if not any(m1 == i):
159
- self.matrix[dc, self.nc] += 1 # background FN
160
-
161
- def matrix(self):
162
- return self.matrix
163
-
164
- def plot(self, save_dir='', names=()):
165
- try:
166
- import seaborn as sn
167
-
168
- array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
169
- array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
170
-
171
- fig = plt.figure(figsize=(12, 9), tight_layout=True)
172
- sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
173
- labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
174
- sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
175
- xticklabels=names + ['background FP'] if labels else "auto",
176
- yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
177
- fig.axes[0].set_xlabel('True')
178
- fig.axes[0].set_ylabel('Predicted')
179
- fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
180
- except Exception as e:
181
- pass
182
-
183
- def print(self):
184
- for i in range(self.nc + 1):
185
- print(' '.join(map(str, self.matrix[i])))
186
-
187
-
188
- # Plots ----------------------------------------------------------------------------------------------------------------
189
-
190
- def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
191
- # Precision-recall curve
192
- fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
193
- py = np.stack(py, axis=1)
194
-
195
- if 0 < len(names) < 21: # display per-class legend if < 21 classes
196
- for i, y in enumerate(py.T):
197
- ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
198
- else:
199
- ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
200
-
201
- ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f [email protected]' % ap[:, 0].mean())
202
- ax.set_xlabel('Recall')
203
- ax.set_ylabel('Precision')
204
- ax.set_xlim(0, 1)
205
- ax.set_ylim(0, 1)
206
- plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
207
- fig.savefig(Path(save_dir), dpi=250)
208
-
209
-
210
- def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
211
- # Metric-confidence curve
212
- fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
213
-
214
- if 0 < len(names) < 21: # display per-class legend if < 21 classes
215
- for i, y in enumerate(py):
216
- ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
217
- else:
218
- ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
219
-
220
- y = py.mean(0)
221
- ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
222
- ax.set_xlabel(xlabel)
223
- ax.set_ylabel(ylabel)
224
- ax.set_xlim(0, 1)
225
- ax.set_ylim(0, 1)
226
- plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
227
- fig.savefig(Path(save_dir), dpi=250)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/sde_team_given_tests.py DELETED
@@ -1,128 +0,0 @@
1
- import asyncio
2
- import logging
3
- from typing import Any, Dict, List
4
- import json
5
-
6
- from agentverse.agents.simulation_agent.conversation import BaseAgent
7
-
8
- # from agentverse.environments.simulation_env.rules.base import Rule
9
- from agentverse.environments.simulation_env.rules.base import SimulationRule as Rule
10
- from agentverse.message import Message
11
-
12
- from .. import env_registry as EnvironmentRegistry
13
- from ..base import BaseEnvironment
14
-
15
- from agentverse.initialization import load_tools
16
-
17
-
18
- @EnvironmentRegistry.register("sde_team_given_tests")
19
- class SdeTeamGivenTestsEnvironment(BaseEnvironment):
20
- """
21
- A basic environment implementing the logic of conversation to craft code.
22
-
23
- Args:
24
- agents: List of agents
25
- rule: Rule for the environment
26
- max_turns: Maximum number of turns
27
- cnt_turn: Current turn number
28
- last_messages: Messages from last turn
29
- rule_params: Variables set by the rule
30
- """
31
-
32
- agents: List[BaseAgent]
33
- rule: Rule
34
- max_turns: int = 10
35
- cnt_turn: int = 0
36
- last_messages: List[Message] = []
37
- rule_params: Dict = {}
38
- unit_tests: str = ""
39
- # # variables for experiment
40
- # task_name: str = "test"
41
- # experiment_name: str = ""
42
-
43
- def __init__(self, rule, **kwargs):
44
- rule_config = rule
45
- order_config = rule_config.get("order", {"type": "sde_team_given_tests"})
46
- visibility_config = rule_config.get("visibility", {"type": "base"})
47
- selector_config = rule_config.get("selector", {"type": "sde_team_given_tests"})
48
- updater_config = rule_config.get("updater", {"type": "sde_team"})
49
- describer_config = rule_config.get("describer", {"type": "base"})
50
- rule = Rule(
51
- order_config,
52
- visibility_config,
53
- selector_config,
54
- updater_config,
55
- describer_config,
56
- )
57
- super().__init__(rule=rule, **kwargs)
58
- self.rule_params["first_round"] = True
59
- self.rule_params["end_flag"] = False
60
-
61
- # # Set up logging for experiment
62
- # filename = self.task_name.replace("/", "_")
63
- # import os
64
- # import os.path
65
- # if not os.path.exists(f"human_eval_experiments/{self.experiment_name}/log"):
66
- # os.makedirs(f"human_eval_experiments/{self.experiment_name}/log")
67
- # file_handler = logging.FileHandler(f"human_eval_experiments/{self.experiment_name}/log/{filename}.txt")
68
- # logging.getLogger().addHandler(file_handler)
69
-
70
- async def step(self) -> List[Message]:
71
- """Run one step of the environment"""
72
-
73
- # Get the next agent index
74
- agent_ids = self.rule.get_next_agent_idx(self) # order
75
-
76
- # Generate current environment description
77
- # env_descriptions = self.rule.get_env_description(self) # describer
78
-
79
- # # Generate the next message
80
- # messages = await asyncio.gather(
81
- # *[self.agents[i].astep(env_descriptions[i]) for i in agent_ids]
82
- # ) # call chatgpt api
83
-
84
- messages = await asyncio.gather(*[self.agents[i].astep("") for i in agent_ids])
85
-
86
- # Track the messages to get the role of the sender
87
- self.last_messages = messages
88
-
89
- # Some rules will select certain messages from all the messages
90
- selected_messages = self.rule.select_message(self, messages) # selector
91
- self.last_messages = selected_messages
92
- self.print_messages(selected_messages)
93
-
94
- # Update the memory of the agents
95
- self.rule.update_memory(self) # updater: update memory
96
-
97
- # Update the set of visible agents for each agent
98
- self.rule.update_visible_agents(self) # change receiver
99
-
100
- self.cnt_turn += 1
101
-
102
- return selected_messages
103
-
104
- def print_messages(self, messages: List[Message]) -> None:
105
- for message in messages:
106
- if message is not None:
107
- logging.info(f"{message.sender}: {message.content}")
108
-
109
- def reset(self) -> None:
110
- """Reset the environment"""
111
- self.cnt_turn = 0
112
- self.rule.reset()
113
- for agent in self.agents:
114
- agent.reset()
115
-
116
- def is_done(self) -> bool:
117
- """Check if the environment is done"""
118
- if self.cnt_turn >= self.max_turns or self.rule_params["end_flag"]:
119
- # # Write to file for experiment
120
- # with open(f"human_eval_experiments/{self.experiment_name}/record_human_eval_prediction.jsonl", "a") as f:
121
- # wd = dict()
122
- # wd['task_id'] = self.task_name
123
- # wd['code'] = self.rule_params['code']
124
- # # print(wd)
125
- # f.write(json.dumps(wd) + "\n")
126
- # logging.getLogger().handlers.pop()
127
- return True
128
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/agentverse/output_parser/output_parser.py DELETED
@@ -1,621 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- from abc import abstractmethod
5
- import json
6
- from typing import Union, List, Tuple, NamedTuple, TYPE_CHECKING
7
-
8
- from . import output_parser_registry
9
-
10
- from agentverse.utils import AgentAction, AgentFinish, AgentCriticism
11
-
12
- from agentverse.llms import LLMResult
13
- from agentverse.logging import logger
14
-
15
- from pydantic import BaseModel
16
-
17
- if TYPE_CHECKING:
18
- from agentverse.agents.base import BaseAgent
19
- from agentverse.environments.base import BaseEnvironment
20
-
21
- class OutputParserError(Exception):
22
- """Exception raised when parsing output from a command fails."""
23
-
24
- def __init__(self, message):
25
- self.message = message
26
-
27
- def __str__(self):
28
- return "Failed to parse output of the model:%s\n " % self.message
29
-
30
-
31
- class OutputParser(BaseModel):
32
- """Base class for output parsers."""
33
-
34
- @abstractmethod
35
- def parse(self, output: LLMResult) -> NamedTuple:
36
- pass
37
-
38
-
39
- @output_parser_registry.register("alice_home")
40
- class AliceHomeParser(OutputParser):
41
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
42
- text = output.content
43
- cleaned_output = text.strip()
44
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
45
- cleaned_output = cleaned_output.split("\n")
46
- if not (
47
- len(cleaned_output) == 2
48
- and cleaned_output[0].startswith("Thought:")
49
- and cleaned_output[1].startswith("Action:")
50
- ):
51
- raise OutputParserError(text)
52
-
53
- action = cleaned_output[1][len("Action:") :].strip()
54
-
55
- return AgentFinish({"output": action}, text)
56
-
57
-
58
- @output_parser_registry.register("db_diag")
59
- @output_parser_registry.register("nlp_classroom_3players_withtool")
60
- class CommonParser1(OutputParser):
61
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
62
- text = output.content
63
- cleaned_output = text.strip()
64
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
65
- cleaned_output = cleaned_output.split("\n")
66
- if not (
67
- len(cleaned_output) == 3
68
- and cleaned_output[0].startswith("Thought:")
69
- and cleaned_output[1].startswith("Action:")
70
- and cleaned_output[2].startswith("Action Input:")
71
- ):
72
- raise OutputParserError(text)
73
- action = cleaned_output[1][len("Action:") :].strip()
74
- action_input = cleaned_output[2][len("Action Input:") :].strip()
75
- if action in ["Speak"]:
76
- return AgentFinish({"output": action_input}, text)
77
- elif action == "CallOn":
78
- return AgentFinish({"output": "[CallOn] " + action_input}, text)
79
- elif action == "RaiseHand":
80
- return AgentFinish({"output": "[RaiseHand] " + action_input}, text)
81
- elif action == "Listen":
82
- return AgentFinish({"output": ""}, text)
83
- else:
84
- return AgentAction(action.lower(), action_input, text)
85
-
86
-
87
- @output_parser_registry.register("math_problem_2players_tools")
88
- class MathProblem2PlayersToolsParser(OutputParser):
89
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
90
- text = output.content
91
- cleaned_output = text.strip()
92
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
93
- cleaned_output = cleaned_output.split("\n")
94
- if not (
95
- len(cleaned_output) == 2
96
- and cleaned_output[0].startswith("Action:")
97
- and cleaned_output[1].startswith("Action Input:")
98
- ):
99
- raise OutputParserError(text)
100
- action = cleaned_output[0][len("Action:") :].strip()
101
- action_input = cleaned_output[1][len("Action Input:") :].strip()
102
- if action == "Speak":
103
- return AgentFinish({"output": action_input}, text)
104
- else:
105
- return AgentAction(action, action_input, text)
106
-
107
-
108
- @output_parser_registry.register("nlp_classroom_3players")
109
- class NlpClassroom3PlayersParser(OutputParser):
110
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
111
- text = output.content
112
- cleaned_output = text.strip()
113
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
114
- cleaned_output = cleaned_output.split("\n")
115
- if not (
116
- len(cleaned_output) == 2
117
- and cleaned_output[0].startswith("Action:")
118
- and cleaned_output[1].startswith("Action Input:")
119
- ):
120
- raise OutputParserError(text)
121
- action = cleaned_output[0][len("Action:") :].strip()
122
- action_input = cleaned_output[1][len("Action Input:") :].strip()
123
- if action == "Speak":
124
- return AgentFinish({"output": action_input}, text)
125
- else:
126
- raise OutputParserError(text)
127
-
128
-
129
- @output_parser_registry.register("nlp_classroom_9players")
130
- class NlpClassroom9PlayersParser(OutputParser):
131
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
132
- text = output.content
133
- cleaned_output = text.strip()
134
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
135
- cleaned_output = cleaned_output.split("\n")
136
- if not (
137
- len(cleaned_output) == 2
138
- and cleaned_output[0].startswith("Action:")
139
- and cleaned_output[1].startswith("Action Input:")
140
- ):
141
- raise OutputParserError(text)
142
- action = cleaned_output[0][len("Action:") :].strip()
143
- action_input = cleaned_output[1][len("Action Input:") :].strip()
144
- if action == "Speak":
145
- return AgentFinish({"output": action_input}, text)
146
- elif action == "CallOn":
147
- return AgentFinish({"output": "[CallOn] " + action_input}, text)
148
- elif action == "RaiseHand":
149
- return AgentFinish({"output": "[RaiseHand] " + action_input}, text)
150
- elif action == "Listen":
151
- return AgentFinish({"output": ""}, text)
152
- else:
153
- return AgentAction(action, action_input, text)
154
-
155
-
156
- @output_parser_registry.register("nlp_classroom_9players_group")
157
- class NlpClassroom9PlayersGroupParser(OutputParser):
158
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
159
- text = output.content
160
- cleaned_output = text.strip()
161
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
162
- cleaned_output = cleaned_output.split("\n")
163
- if not (
164
- len(cleaned_output) == 2
165
- and cleaned_output[0].startswith("Action:")
166
- and cleaned_output[1].startswith("Action Input:")
167
- ):
168
- raise OutputParserError(text)
169
- action = cleaned_output[0][len("Action:") :].strip()
170
- action_input = cleaned_output[1][len("Action Input:") :].strip()
171
- if action == "Speak":
172
- return AgentFinish({"output": action_input}, text)
173
- elif action in ["CallOn", "RaiseHand", "GroupDiscuss"]:
174
- return AgentFinish({"output": f"[{action}] {action_input}"}, text)
175
- elif action == "Listen":
176
- return AgentFinish({"output": ""}, text)
177
- else:
178
- return AgentAction(action, action_input, text)
179
-
180
-
181
- @output_parser_registry.register("pokemon")
182
- class PokemonParser(OutputParser):
183
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
184
- text = output.content
185
- cleaned_output = text.strip()
186
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
187
- cleaned_output = cleaned_output.split("\n")
188
- if not (
189
- len(cleaned_output) == 3
190
- and cleaned_output[0].startswith("Thought:")
191
- and cleaned_output[1].startswith("Action:")
192
- and cleaned_output[2].startswith("Action Input:")
193
- ):
194
- raise OutputParserError(text)
195
- action = cleaned_output[1][len("Action:") :].strip()
196
- action_input = cleaned_output[2][len("Action Input:") :].strip()
197
- try:
198
- action_input = json.loads(action_input)
199
- except json.JSONDecodeError:
200
- raise OutputParserError(text)
201
- action_input["action"] = action
202
- return AgentFinish({"output": json.dumps(action_input)}, text)
203
-
204
-
205
- @output_parser_registry.register("prisoner_dilemma")
206
- class PrisonerDilemmaParser(OutputParser):
207
- # make sure 1 1 2 2 3 3
208
- cur_round: int = 1
209
- encounter_cur_round: bool = False
210
-
211
- def parse(
212
- self, agent: "BaseAgent", environment: "BaseEnvironment", output: LLMResult
213
- ) -> Union[AgentAction, AgentFinish]:
214
- text = output.content
215
- cleaned_output = text.strip()
216
- cleaned_output = re.sub(r"\n+", "\n", cleaned_output)
217
- cleaned_output = cleaned_output.split("\n")
218
- if not (
219
- len(cleaned_output) == 2
220
- and cleaned_output[0].startswith("Action:")
221
- and cleaned_output[1].startswith("Action Input:")
222
- ):
223
- raise OutputParserError(text)
224
- action = cleaned_output[0][len("Action:") :].strip()
225
- action_input = cleaned_output[1][len("Action Input:") :].strip()
226
-
227
- if action == "Speak":
228
- # make sure the police count the round right
229
- # if agent.name == "Police":
230
- # action_input = re.sub(r'Round (\d+)', f'Round {self.cur_round}', action_input)
231
- # self.cur_round += 1
232
- # if self.encounter_cur_round:
233
- # self.encounter_cur_round = False
234
- # self.cur_round += 1
235
- # else:
236
- # self.encounter_cur_round = True
237
-
238
- # each time police speak is a new round
239
- if agent.name == "Police":
240
- if environment.cnt_turn == (environment.max_turns - 4):
241
- action_input = (
242
- "Attention! You are now required to made your final decision and I will made the "
243
- "final judgement to both of you based on this time, Please Answer now !"
244
- )
245
-
246
- elif environment.cnt_turn == (environment.max_turns - 2):
247
- action_input = "Attention! Suspect2, it's now your time to make your final decision, Please Answer now !"
248
-
249
- # elif self.cur_round == 1:
250
- # action_input = "Hey Listen! You are both arrested, and I am going to give you both a chance to walk out of here," \
251
- # "But you should comply with the following rules:" \
252
- # "- If one of you are willing to testifies against the other and the other one remains silent, then the one who testifies will be released IMMEDIATELY, while the silent one will be sentenced to TEN years in prison." \
253
- # "- If both of you remain silent, you will each receive a sentence of ONE year in prison." \
254
- # "- It seems that always testifying is a goog strategy, So! if you both choose to testify against each other, you will each receive a sentence of FIVE years in prison." \
255
- # "Now, it's your time to consider testifying or remaining silent. Remember this is a best chance you might ever have to walk out of here without guilty." \
256
- # "I will noticed both of you WHEN you have to make your final decision! Before that, try to make your best!" \
257
-
258
- self.cur_round += 1
259
-
260
- return AgentFinish({"output": action_input}, text)
261
- else:
262
- raise OutputParserError(text)
263
-
264
-
265
- @output_parser_registry.register("sde_team/sde_team_2players")
266
- @output_parser_registry.register("sde_team/sde_team_3players")
267
- @output_parser_registry.register("commongen")
268
- @output_parser_registry.register("humaneval-manager")
269
- @output_parser_registry.register("mgsm")
270
- @output_parser_registry.register("dummy")
271
- @output_parser_registry.register("responsegen")
272
- class CommonParser2(OutputParser):
273
- # def parse(self, agent, env, output: LLMResult) -> Union[AgentAction, AgentFinish]:
274
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
275
- return AgentFinish({"output": output.content}, output.content)
276
-
277
-
278
- @output_parser_registry.register("role_assigner")
279
- class RoleAssignerParser(OutputParser):
280
- cnt_critic_agents: int = 0
281
-
282
- def parse(self, output: LLMResult) -> List[str]:
283
- text = output.content
284
- pattern = re.compile(r"\d\.\s*(.+)")
285
- roles = pattern.findall(text)
286
- if len(roles) < self.cnt_critic_agents:
287
- logger.error(
288
- f"Role assigner failed to assign roles to {self.cnt_critic_agents} critics!"
289
- )
290
- raise OutputParserError(text)
291
- return roles
292
-
293
-
294
- @output_parser_registry.register("evaluator")
295
- class EvaluatorParser(OutputParser):
296
- dimensions: List[str] = None
297
-
298
- def parse(self, output: LLMResult) -> Tuple[List[int], str]:
299
- text = output.content
300
- cleaned_output = re.sub(r"\n+", "\n", text.strip())
301
- checks = cleaned_output.split("\n")
302
- patterns = [
303
- re.compile(r"(?:\d\.\s*)?" + dimension + r":\s*(\d)")
304
- for dimension in self.dimensions
305
- ]
306
- try:
307
- # find score and advice
308
- score = [
309
- int(pattern.findall(checks[i])[0]) for i, pattern in enumerate(patterns)
310
- ]
311
- advice_text = "".join(checks[len(self.dimensions) :])
312
- advice = re.findall(r"(?:\d\.\s*)?Advice:\s*(.+)", advice_text)[0]
313
- # logger.info("Evaluator give the following advice:\n" + advice)
314
- except (IndexError, ValueError):
315
- # logger.error("Bad response from evaluator!")
316
- raise OutputParserError(text)
317
- return score, advice
318
-
319
-
320
- @output_parser_registry.register("humaneval-solver")
321
- class HumanevalSolverParser(OutputParser):
322
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
323
- text = output.content
324
- # start_pos = text.find("```")
325
- # end_pos = text.rfind("```")
326
- # if end_pos == -1:
327
- # raise OutputParserError(text)
328
- # text = text[start_pos:end_pos]
329
- # cleaned_output = text.strip().strip("```").strip()
330
- # if cleaned_output.startswith("python"):
331
- # cleaned_output = cleaned_output[6:].strip()
332
- # elif cleaned_output.startswith("python3"):
333
- # cleaned_output = cleaned_output[7:].strip()
334
- code = re.findall(r"```.*?\n(.+?)```", text, re.DOTALL)[-1]
335
-
336
- return AgentFinish({"output": code}, text)
337
-
338
-
339
- @output_parser_registry.register("humaneval-executor")
340
- class HumanevalSolverParser(OutputParser):
341
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
342
- text = output.content
343
- try:
344
- parsed_result = re.findall(
345
- r"Thought:(.+?)Reasoning:(.+?)Criticism:(.+?)File Path:(.+?)Code:(.+?)Command:(.+)",
346
- text,
347
- re.DOTALL,
348
- )[0]
349
- cleaned_output = {
350
- "thought": parsed_result[0].strip(),
351
- "reasoning": parsed_result[1].strip(),
352
- "criticism": parsed_result[2].strip(),
353
- "file_path": parsed_result[3].strip().strip("`"),
354
- "code": parsed_result[4]
355
- .strip()
356
- .strip("```")
357
- .strip("python")
358
- .strip("python3"),
359
- "command": parsed_result[5].strip().strip("`"),
360
- }
361
- except BaseException as e:
362
- raise OutputParserError(text)
363
-
364
- return AgentFinish({"output": cleaned_output}, text)
365
-
366
-
367
- @output_parser_registry.register("humaneval-evaluator")
368
- class HumanevalEvaluatorParser(OutputParser):
369
- dimensions: List[str] = None
370
-
371
- def parse(self, output: LLMResult) -> Tuple[List[int], str]:
372
- text = output.content
373
- cleaned_output = re.sub(r"\n+", "\n", text.strip())
374
- checks = cleaned_output.split("\n")
375
-
376
- patterns = [
377
- re.compile(r"(?:\d.\s*)?" + dimension + r":\s*(\d)")
378
- for dimension in self.dimensions
379
- ]
380
-
381
- advice = ""
382
- for check in reversed(checks):
383
- advice = check + advice
384
- if check.startswith("Advice:"):
385
- break
386
- checks[-1] = advice
387
- try:
388
- # find score and advice
389
- score = []
390
- for pattern in patterns:
391
- for check in checks[:-1]:
392
- if pattern.findall(check):
393
- score.append(bool(int(pattern.findall(check)[0])))
394
- break
395
- advice = re.findall(r"(?:\d.\s*)?Advice:\s*(.+)", checks[-1])[0]
396
- # logger.info("Evaluator give the following advice:\n" + advice)
397
- except (IndexError, ValueError):
398
- # logger.error("Bad response from evaluator!")
399
- raise OutputParserError(text)
400
- return score[0], advice
401
-
402
-
403
- @output_parser_registry.register("humaneval-critic-agree")
404
- class HumanevalyCriticParser(OutputParser):
405
- def parse(self, output: LLMResult) -> AgentCriticism:
406
- text = output.content
407
- if "[Agree]" in text:
408
- return AgentCriticism(True, "")
409
- else:
410
- return AgentCriticism(False, text)
411
-
412
-
413
- @output_parser_registry.register("mgsm-evaluator")
414
- class MGSMEvaluatorParser(OutputParser):
415
- dimensions: List[str] = None
416
-
417
- def parse(self, output: LLMResult) -> Tuple[List[int], str]:
418
- text = output.content
419
- cleaned_output = re.sub(r"\n+", "\n", text.strip())
420
- # checks = cleaned_output.split("\n")
421
-
422
- patterns = [
423
- re.compile(r"(?:\d.\s*)?" + dimension + r":\s*(\d)")
424
- for dimension in self.dimensions
425
- ]
426
- try:
427
- # find score and advice
428
- score_num = [
429
- int(pattern.findall(cleaned_output)[0])
430
- for i, pattern in enumerate(patterns)
431
- ][0]
432
- if score_num == 0:
433
- score = False
434
- elif score_num == 1:
435
- score = True
436
- else:
437
- raise ValueError("Bad score!")
438
- pat = re.compile(r"(?:\d.\s*)?Response:\s*(.+)", re.DOTALL)
439
- advice = pat.findall(cleaned_output)[0]
440
- # logger.info("Evaluator give the following advice:\n" + advice)
441
- except (IndexError, ValueError):
442
- # logger.error("Bad response from evaluator!")
443
- raise OutputParserError(text)
444
- return score, advice
445
-
446
-
447
- @output_parser_registry.register("mgsm-critic-agree")
448
- class MGSMCriticAgreeParser(OutputParser):
449
- def parse(self, output: LLMResult) -> AgentCriticism:
450
- text = output.content
451
- text = re.sub(r"\n+", "\n", text.strip())
452
- # checks = text.split("\n")
453
- # if not text.startswith("Thought:"):
454
- # raise OutputParserError(text)
455
- # if not (checks[0].startswith("Action:")):
456
- # raise OutputParserError(text)
457
- # if checks[0].strip(". ") == "Action: Agree":
458
- # return AgentCriticism(True, "")
459
- if "[Agree]" in text:
460
- return AgentCriticism(True, "")
461
- else:
462
- # pattern = re.compile(r"Action Input: ([\S\n ]+)")
463
- # try:
464
- # criticism = pattern.findall(text)[0].strip()
465
- # criticism = (
466
- # re.findall(r"Output:\S?(.+)", text)[0].replace("[Wrong]", "")
467
- # ).strip()
468
- criticism = text.replace("[Disagree]", "").strip()
469
- # except IndexError:
470
- # logger.error("Bad response from critic!")
471
- # raise OutputParserError(text)
472
- # criticism = "I think the solution is not correct. Please think carefully and correct it."
473
- return AgentCriticism(False, criticism)
474
- # else:
475
- # raise OutputParserError(text)
476
-
477
-
478
- @output_parser_registry.register("responsegen-evaluator")
479
- class ResponseGenEvaluatorParser(OutputParser):
480
- dimensions: List[str] = None
481
-
482
- def parse(self, output: LLMResult) -> Tuple[List[int], str]:
483
- text = output.content
484
- cleaned_output = re.sub(r"\n+", "\n", text.strip())
485
- checks = cleaned_output.split("\n")
486
-
487
- patterns = [
488
- re.compile(r"(?:\d.\s*)?" + dimension + r":\s*(\d+)")
489
- for dimension in self.dimensions
490
- ]
491
-
492
- advice = ""
493
- for check in reversed(checks):
494
- advice = check + advice
495
- if check.startswith("Advice:"):
496
- break
497
- checks[-1] = advice
498
- try:
499
- # find score and advice
500
- score = [
501
- int(pattern.findall(checks[i])[0]) for i, pattern in enumerate(patterns)
502
- ]
503
- advice = re.findall(r"(?:\d.\s*)?Advice:\s*(.+)", checks[-1])[0]
504
- # logger.info("Evaluator give the following advice:\n" + advice)
505
- except (IndexError, ValueError):
506
- # logger.error("Bad response from evaluator!")
507
- raise OutputParserError(text)
508
- return score, advice
509
-
510
-
511
- @output_parser_registry.register("responsegen-critic")
512
- @output_parser_registry.register("critic")
513
- class CommonParser3(OutputParser):
514
- def parse(self, output: LLMResult) -> AgentCriticism:
515
- text = output.content
516
- text = re.sub(r"\n+", "\n", text.strip())
517
- checks = text.split("\n")
518
- if not (checks[0].startswith("Action:")):
519
- raise OutputParserError(text)
520
- if checks[0].strip(". ") == "Action: Agree":
521
- return AgentCriticism(True, "")
522
- elif checks[0].strip(". ") == "Action: Disagree":
523
- pattern = re.compile(r"Action Input: ([\S\n ]+)")
524
- try:
525
- criticism = pattern.findall(text)[0].strip()
526
- except IndexError:
527
- criticism = (
528
- "I think it is not correct. Please think carefully and improve it."
529
- )
530
- # raise OutputParserError(text)
531
- return AgentCriticism(False, criticism)
532
- else:
533
- raise OutputParserError(text)
534
-
535
-
536
- @output_parser_registry.register("responsegen-critic-2")
537
- class ResponseGenCriticParser(OutputParser):
538
- def parse(self, output: LLMResult) -> AgentCriticism:
539
- text = output.content
540
- # text = re.sub(r"\n+", "\n", text.strip())
541
- # checks = text.split("\n")
542
- # if not (checks[0].startswith("Action:")):
543
- # raise OutputParserError(text)
544
- # if checks[0].strip(". ") == "Action: Agree":
545
- # return AgentCriticism(True, "")
546
- # elif checks[0].strip(". ") == "Action: Disagree":
547
- # pattern = re.compile(r"Action Input: ([\S\n ]+)")
548
- # try:
549
- # criticism = pattern.findall(text)[0].strip()
550
- # except IndexError:
551
- # # criticism = "I think the solution is not correct. Please think carefully and correct it."
552
- # raise OutputParserError(text)
553
- # return AgentCriticism(False, criticism)
554
- # else:
555
- # raise OutputParserError(text)
556
- result = re.findall(r"Decision:(.+?)Response:(.+)", text, re.DOTALL)
557
- if len(result) == 0:
558
- result = ["Disagree", "I think the response can be further improved."]
559
- else:
560
- result = result[0]
561
- if "Agree" in result[0]:
562
- return AgentCriticism(True, "")
563
- else:
564
- return AgentCriticism(False, result[1].strip())
565
-
566
-
567
- @output_parser_registry.register("role-description-name-assigner")
568
- class RoleAssignerParser(OutputParser):
569
- cnt_critic_agents: int = 0
570
-
571
- def parse(self, output: LLMResult) -> List[str]:
572
- text = output.content
573
- pattern = re.compile(r"\d+?\.\s*(.+?) - (.+)")
574
- roles = pattern.findall(text)
575
- if len(roles) < self.cnt_critic_agents:
576
- logger.error(
577
- f"Role assigner failed to assign roles to {self.cnt_critic_agents} critics!"
578
- )
579
- raise OutputParserError(text)
580
- res = []
581
- for role in roles:
582
- res.append({"name": role[0], "description": role[1]})
583
- return res
584
-
585
-
586
- @output_parser_registry.register("tool-using-solver")
587
- class SolverParser(OutputParser):
588
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
589
- text = output.content
590
- pattern = re.compile(r"\d+?\.\s*(.+?) - (.+)")
591
- tasks = pattern.findall(text)
592
- if len(tasks) == 0:
593
- raise OutputParserError(text)
594
- return AgentFinish({"output": tasks}, text)
595
-
596
-
597
- @output_parser_registry.register("tool-using-executor")
598
- class ToolUsingSolverParser(OutputParser):
599
- def parse(self, output: LLMResult) -> Union[AgentAction, AgentFinish]:
600
- if output.function_name != "":
601
- return AgentAction(
602
- tool=output.function_name,
603
- tool_input=output.function_arguments,
604
- log=output.content,
605
- )
606
- else:
607
- return AgentFinish({"output": output.content}, output.content)
608
-
609
-
610
- @output_parser_registry.register("tool-using-evaluator")
611
- class HumanevalEvaluatorParser(OutputParser):
612
- def parse(self, output: LLMResult) -> Tuple[List[int], str]:
613
- text = output.content
614
- try:
615
- result = re.findall(r"Status:(.+?)Speak:(.+)", text, re.DOTALL)[0]
616
- score = bool(int(result[0]))
617
- words = result[1].strip()
618
- except (IndexError, ValueError):
619
- # logger.error("Bad response from evaluator!")
620
- raise OutputParserError(text)
621
- return score, words
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AlanMars/QYL-AI-Space/modules/llama_func.py DELETED
@@ -1,166 +0,0 @@
1
- import os
2
- import logging
3
-
4
- from llama_index import download_loader
5
- from llama_index import (
6
- Document,
7
- LLMPredictor,
8
- PromptHelper,
9
- QuestionAnswerPrompt,
10
- RefinePrompt,
11
- )
12
- import colorama
13
- import PyPDF2
14
- from tqdm import tqdm
15
-
16
- from modules.presets import *
17
- from modules.utils import *
18
- from modules.config import local_embedding
19
-
20
-
21
- def get_index_name(file_src):
22
- file_paths = [x.name for x in file_src]
23
- file_paths.sort(key=lambda x: os.path.basename(x))
24
-
25
- md5_hash = hashlib.md5()
26
- for file_path in file_paths:
27
- with open(file_path, "rb") as f:
28
- while chunk := f.read(8192):
29
- md5_hash.update(chunk)
30
-
31
- return md5_hash.hexdigest()
32
-
33
-
34
- def block_split(text):
35
- blocks = []
36
- while len(text) > 0:
37
- blocks.append(Document(text[:1000]))
38
- text = text[1000:]
39
- return blocks
40
-
41
-
42
- def get_documents(file_src):
43
- documents = []
44
- logging.debug("Loading documents...")
45
- logging.debug(f"file_src: {file_src}")
46
- for file in file_src:
47
- filepath = file.name
48
- filename = os.path.basename(filepath)
49
- file_type = os.path.splitext(filepath)[1]
50
- logging.info(f"loading file: {filename}")
51
- try:
52
- if file_type == ".pdf":
53
- logging.debug("Loading PDF...")
54
- try:
55
- from modules.pdf_func import parse_pdf
56
- from modules.config import advance_docs
57
-
58
- two_column = advance_docs["pdf"].get("two_column", False)
59
- pdftext = parse_pdf(filepath, two_column).text
60
- except:
61
- pdftext = ""
62
- with open(filepath, "rb") as pdfFileObj:
63
- pdfReader = PyPDF2.PdfReader(pdfFileObj)
64
- for page in tqdm(pdfReader.pages):
65
- pdftext += page.extract_text()
66
- text_raw = pdftext
67
- elif file_type == ".docx":
68
- logging.debug("Loading Word...")
69
- DocxReader = download_loader("DocxReader")
70
- loader = DocxReader()
71
- text_raw = loader.load_data(file=filepath)[0].text
72
- elif file_type == ".epub":
73
- logging.debug("Loading EPUB...")
74
- EpubReader = download_loader("EpubReader")
75
- loader = EpubReader()
76
- text_raw = loader.load_data(file=filepath)[0].text
77
- elif file_type == ".xlsx":
78
- logging.debug("Loading Excel...")
79
- text_list = excel_to_string(filepath)
80
- for elem in text_list:
81
- documents.append(Document(elem))
82
- continue
83
- else:
84
- logging.debug("Loading text file...")
85
- with open(filepath, "r", encoding="utf-8") as f:
86
- text_raw = f.read()
87
- except Exception as e:
88
- logging.error(f"Error loading file: {filename}")
89
- pass
90
- text = add_space(text_raw)
91
- # text = block_split(text)
92
- # documents += text
93
- documents += [Document(text)]
94
- logging.debug("Documents loaded.")
95
- return documents
96
-
97
-
98
- def construct_index(
99
- api_key,
100
- file_src,
101
- max_input_size=4096,
102
- num_outputs=5,
103
- max_chunk_overlap=20,
104
- chunk_size_limit=600,
105
- embedding_limit=None,
106
- separator=" ",
107
- ):
108
- from langchain.chat_models import ChatOpenAI
109
- from langchain.embeddings.huggingface import HuggingFaceEmbeddings
110
- from llama_index import GPTSimpleVectorIndex, ServiceContext, LangchainEmbedding, OpenAIEmbedding
111
-
112
- if api_key:
113
- os.environ["OPENAI_API_KEY"] = api_key
114
- else:
115
- # 由于一个依赖的愚蠢的设计,这里必须要有一个API KEY
116
- os.environ["OPENAI_API_KEY"] = "sk-xxxxxxx"
117
- chunk_size_limit = None if chunk_size_limit == 0 else chunk_size_limit
118
- embedding_limit = None if embedding_limit == 0 else embedding_limit
119
- separator = " " if separator == "" else separator
120
-
121
- prompt_helper = PromptHelper(
122
- max_input_size=max_input_size,
123
- num_output=num_outputs,
124
- max_chunk_overlap=max_chunk_overlap,
125
- embedding_limit=embedding_limit,
126
- chunk_size_limit=600,
127
- separator=separator,
128
- )
129
- index_name = get_index_name(file_src)
130
- if os.path.exists(f"./index/{index_name}.json"):
131
- logging.info("找到了缓存的索引文件,加载中……")
132
- return GPTSimpleVectorIndex.load_from_disk(f"./index/{index_name}.json")
133
- else:
134
- try:
135
- documents = get_documents(file_src)
136
- if local_embedding:
137
- embed_model = LangchainEmbedding(HuggingFaceEmbeddings(model_name = "sentence-transformers/distiluse-base-multilingual-cased-v2"))
138
- else:
139
- embed_model = OpenAIEmbedding()
140
- logging.info("构建索引中……")
141
- with retrieve_proxy():
142
- service_context = ServiceContext.from_defaults(
143
- prompt_helper=prompt_helper,
144
- chunk_size_limit=chunk_size_limit,
145
- embed_model=embed_model,
146
- )
147
- index = GPTSimpleVectorIndex.from_documents(
148
- documents, service_context=service_context
149
- )
150
- logging.debug("索引构建完成!")
151
- os.makedirs("./index", exist_ok=True)
152
- index.save_to_disk(f"./index/{index_name}.json")
153
- logging.debug("索引已保存至本地!")
154
- return index
155
-
156
- except Exception as e:
157
- logging.error("索引构建失败!", e)
158
- print(e)
159
- return None
160
-
161
-
162
- def add_space(text):
163
- punctuations = {",": ", ", "。": "。 ", "?": "? ", "!": "! ", ":": ": ", ";": "; "}
164
- for cn_punc, en_punc in punctuations.items():
165
- text = text.replace(cn_punc, en_punc)
166
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alycer/VITS-Umamusume-voice-synthesizer/text/cantonese.py DELETED
@@ -1,59 +0,0 @@
1
- import re
2
- import cn2an
3
- import opencc
4
-
5
-
6
- converter = opencc.OpenCC('jyutjyu')
7
-
8
- # List of (Latin alphabet, ipa) pairs:
9
- _latin_to_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
10
- ('A', 'ei˥'),
11
- ('B', 'biː˥'),
12
- ('C', 'siː˥'),
13
- ('D', 'tiː˥'),
14
- ('E', 'iː˥'),
15
- ('F', 'e˥fuː˨˩'),
16
- ('G', 'tsiː˥'),
17
- ('H', 'ɪk̚˥tsʰyː˨˩'),
18
- ('I', 'ɐi˥'),
19
- ('J', 'tsei˥'),
20
- ('K', 'kʰei˥'),
21
- ('L', 'e˥llou˨˩'),
22
- ('M', 'ɛːm˥'),
23
- ('N', 'ɛːn˥'),
24
- ('O', 'ou˥'),
25
- ('P', 'pʰiː˥'),
26
- ('Q', 'kʰiːu˥'),
27
- ('R', 'aː˥lou˨˩'),
28
- ('S', 'ɛː˥siː˨˩'),
29
- ('T', 'tʰiː˥'),
30
- ('U', 'juː˥'),
31
- ('V', 'wiː˥'),
32
- ('W', 'tʊk̚˥piː˥juː˥'),
33
- ('X', 'ɪk̚˥siː˨˩'),
34
- ('Y', 'waːi˥'),
35
- ('Z', 'iː˨sɛːt̚˥')
36
- ]]
37
-
38
-
39
- def number_to_cantonese(text):
40
- return re.sub(r'\d+(?:\.?\d+)?', lambda x: cn2an.an2cn(x.group()), text)
41
-
42
-
43
- def latin_to_ipa(text):
44
- for regex, replacement in _latin_to_ipa:
45
- text = re.sub(regex, replacement, text)
46
- return text
47
-
48
-
49
- def cantonese_to_ipa(text):
50
- text = number_to_cantonese(text.upper())
51
- text = converter.convert(text).replace('-','').replace('$',' ')
52
- text = re.sub(r'[A-Z]', lambda x: latin_to_ipa(x.group())+' ', text)
53
- text = re.sub(r'[、;:]', ',', text)
54
- text = re.sub(r'\s*,\s*', ', ', text)
55
- text = re.sub(r'\s*。\s*', '. ', text)
56
- text = re.sub(r'\s*?\s*', '? ', text)
57
- text = re.sub(r'\s*!\s*', '! ', text)
58
- text = re.sub(r'\s*$', '', text)
59
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_detection/configs/cascade_rcnn/cascade_rcnn_r101_fpn_20e_coco.py DELETED
@@ -1,2 +0,0 @@
1
- _base_ = './cascade_rcnn_r50_fpn_20e_coco.py'
2
- model = dict(pretrained='torchvision://resnet101', backbone=dict(depth=101))
 
 
 
spaces/Andy1621/uniformer_image_detection/mmdet/models/necks/nasfcos_fpn.py DELETED
@@ -1,161 +0,0 @@
1
- import torch.nn as nn
2
- import torch.nn.functional as F
3
- from mmcv.cnn import ConvModule, caffe2_xavier_init
4
- from mmcv.ops.merge_cells import ConcatCell
5
-
6
- from ..builder import NECKS
7
-
8
-
9
- @NECKS.register_module()
10
- class NASFCOS_FPN(nn.Module):
11
- """FPN structure in NASFPN.
12
-
13
- Implementation of paper `NAS-FCOS: Fast Neural Architecture Search for
14
- Object Detection <https://arxiv.org/abs/1906.04423>`_
15
-
16
- Args:
17
- in_channels (List[int]): Number of input channels per scale.
18
- out_channels (int): Number of output channels (used at each scale)
19
- num_outs (int): Number of output scales.
20
- start_level (int): Index of the start input backbone level used to
21
- build the feature pyramid. Default: 0.
22
- end_level (int): Index of the end input backbone level (exclusive) to
23
- build the feature pyramid. Default: -1, which means the last level.
24
- add_extra_convs (bool): It decides whether to add conv
25
- layers on top of the original feature maps. Default to False.
26
- If True, its actual mode is specified by `extra_convs_on_inputs`.
27
- conv_cfg (dict): dictionary to construct and config conv layer.
28
- norm_cfg (dict): dictionary to construct and config norm layer.
29
- """
30
-
31
- def __init__(self,
32
- in_channels,
33
- out_channels,
34
- num_outs,
35
- start_level=1,
36
- end_level=-1,
37
- add_extra_convs=False,
38
- conv_cfg=None,
39
- norm_cfg=None):
40
- super(NASFCOS_FPN, self).__init__()
41
- assert isinstance(in_channels, list)
42
- self.in_channels = in_channels
43
- self.out_channels = out_channels
44
- self.num_ins = len(in_channels)
45
- self.num_outs = num_outs
46
- self.norm_cfg = norm_cfg
47
- self.conv_cfg = conv_cfg
48
-
49
- if end_level == -1:
50
- self.backbone_end_level = self.num_ins
51
- assert num_outs >= self.num_ins - start_level
52
- else:
53
- self.backbone_end_level = end_level
54
- assert end_level <= len(in_channels)
55
- assert num_outs == end_level - start_level
56
- self.start_level = start_level
57
- self.end_level = end_level
58
- self.add_extra_convs = add_extra_convs
59
-
60
- self.adapt_convs = nn.ModuleList()
61
- for i in range(self.start_level, self.backbone_end_level):
62
- adapt_conv = ConvModule(
63
- in_channels[i],
64
- out_channels,
65
- 1,
66
- stride=1,
67
- padding=0,
68
- bias=False,
69
- norm_cfg=dict(type='BN'),
70
- act_cfg=dict(type='ReLU', inplace=False))
71
- self.adapt_convs.append(adapt_conv)
72
-
73
- # C2 is omitted according to the paper
74
- extra_levels = num_outs - self.backbone_end_level + self.start_level
75
-
76
- def build_concat_cell(with_input1_conv, with_input2_conv):
77
- cell_conv_cfg = dict(
78
- kernel_size=1, padding=0, bias=False, groups=out_channels)
79
- return ConcatCell(
80
- in_channels=out_channels,
81
- out_channels=out_channels,
82
- with_out_conv=True,
83
- out_conv_cfg=cell_conv_cfg,
84
- out_norm_cfg=dict(type='BN'),
85
- out_conv_order=('norm', 'act', 'conv'),
86
- with_input1_conv=with_input1_conv,
87
- with_input2_conv=with_input2_conv,
88
- input_conv_cfg=conv_cfg,
89
- input_norm_cfg=norm_cfg,
90
- upsample_mode='nearest')
91
-
92
- # Denote c3=f0, c4=f1, c5=f2 for convince
93
- self.fpn = nn.ModuleDict()
94
- self.fpn['c22_1'] = build_concat_cell(True, True)
95
- self.fpn['c22_2'] = build_concat_cell(True, True)
96
- self.fpn['c32'] = build_concat_cell(True, False)
97
- self.fpn['c02'] = build_concat_cell(True, False)
98
- self.fpn['c42'] = build_concat_cell(True, True)
99
- self.fpn['c36'] = build_concat_cell(True, True)
100
- self.fpn['c61'] = build_concat_cell(True, True) # f9
101
- self.extra_downsamples = nn.ModuleList()
102
- for i in range(extra_levels):
103
- extra_act_cfg = None if i == 0 \
104
- else dict(type='ReLU', inplace=False)
105
- self.extra_downsamples.append(
106
- ConvModule(
107
- out_channels,
108
- out_channels,
109
- 3,
110
- stride=2,
111
- padding=1,
112
- act_cfg=extra_act_cfg,
113
- order=('act', 'norm', 'conv')))
114
-
115
- def forward(self, inputs):
116
- """Forward function."""
117
- feats = [
118
- adapt_conv(inputs[i + self.start_level])
119
- for i, adapt_conv in enumerate(self.adapt_convs)
120
- ]
121
-
122
- for (i, module_name) in enumerate(self.fpn):
123
- idx_1, idx_2 = int(module_name[1]), int(module_name[2])
124
- res = self.fpn[module_name](feats[idx_1], feats[idx_2])
125
- feats.append(res)
126
-
127
- ret = []
128
- for (idx, input_idx) in zip([9, 8, 7], [1, 2, 3]): # add P3, P4, P5
129
- feats1, feats2 = feats[idx], feats[5]
130
- feats2_resize = F.interpolate(
131
- feats2,
132
- size=feats1.size()[2:],
133
- mode='bilinear',
134
- align_corners=False)
135
-
136
- feats_sum = feats1 + feats2_resize
137
- ret.append(
138
- F.interpolate(
139
- feats_sum,
140
- size=inputs[input_idx].size()[2:],
141
- mode='bilinear',
142
- align_corners=False))
143
-
144
- for submodule in self.extra_downsamples:
145
- ret.append(submodule(ret[-1]))
146
-
147
- return tuple(ret)
148
-
149
- def init_weights(self):
150
- """Initialize the weights of module."""
151
- for module in self.fpn.values():
152
- if hasattr(module, 'conv_out'):
153
- caffe2_xavier_init(module.out_conv.conv)
154
-
155
- for modules in [
156
- self.adapt_convs.modules(),
157
- self.extra_downsamples.modules()
158
- ]:
159
- for module in modules:
160
- if isinstance(module, nn.Conv2d):
161
- caffe2_xavier_init(module)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_segmentation/configs/ocrnet/ocrnet_hr48_512x512_40k_voc12aug.py DELETED
@@ -1,39 +0,0 @@
1
- _base_ = './ocrnet_hr18_512x512_40k_voc12aug.py'
2
- norm_cfg = dict(type='SyncBN', requires_grad=True)
3
- model = dict(
4
- pretrained='open-mmlab://msra/hrnetv2_w48',
5
- backbone=dict(
6
- extra=dict(
7
- stage2=dict(num_channels=(48, 96)),
8
- stage3=dict(num_channels=(48, 96, 192)),
9
- stage4=dict(num_channels=(48, 96, 192, 384)))),
10
- decode_head=[
11
- dict(
12
- type='FCNHead',
13
- in_channels=[48, 96, 192, 384],
14
- channels=sum([48, 96, 192, 384]),
15
- input_transform='resize_concat',
16
- in_index=(0, 1, 2, 3),
17
- kernel_size=1,
18
- num_convs=1,
19
- norm_cfg=norm_cfg,
20
- concat_input=False,
21
- dropout_ratio=-1,
22
- num_classes=21,
23
- align_corners=False,
24
- loss_decode=dict(
25
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),
26
- dict(
27
- type='OCRHead',
28
- in_channels=[48, 96, 192, 384],
29
- channels=512,
30
- ocr_channels=256,
31
- input_transform='resize_concat',
32
- in_index=(0, 1, 2, 3),
33
- norm_cfg=norm_cfg,
34
- dropout_ratio=-1,
35
- num_classes=21,
36
- align_corners=False,
37
- loss_decode=dict(
38
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0))
39
- ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/cnn/bricks/conv.py DELETED
@@ -1,44 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
- from torch import nn
3
-
4
- from .registry import CONV_LAYERS
5
-
6
- CONV_LAYERS.register_module('Conv1d', module=nn.Conv1d)
7
- CONV_LAYERS.register_module('Conv2d', module=nn.Conv2d)
8
- CONV_LAYERS.register_module('Conv3d', module=nn.Conv3d)
9
- CONV_LAYERS.register_module('Conv', module=nn.Conv2d)
10
-
11
-
12
- def build_conv_layer(cfg, *args, **kwargs):
13
- """Build convolution layer.
14
-
15
- Args:
16
- cfg (None or dict): The conv layer config, which should contain:
17
- - type (str): Layer type.
18
- - layer args: Args needed to instantiate an conv layer.
19
- args (argument list): Arguments passed to the `__init__`
20
- method of the corresponding conv layer.
21
- kwargs (keyword arguments): Keyword arguments passed to the `__init__`
22
- method of the corresponding conv layer.
23
-
24
- Returns:
25
- nn.Module: Created conv layer.
26
- """
27
- if cfg is None:
28
- cfg_ = dict(type='Conv2d')
29
- else:
30
- if not isinstance(cfg, dict):
31
- raise TypeError('cfg must be a dict')
32
- if 'type' not in cfg:
33
- raise KeyError('the cfg dict must contain the key "type"')
34
- cfg_ = cfg.copy()
35
-
36
- layer_type = cfg_.pop('type')
37
- if layer_type not in CONV_LAYERS:
38
- raise KeyError(f'Unrecognized norm type {layer_type}')
39
- else:
40
- conv_layer = CONV_LAYERS.get(layer_type)
41
-
42
- layer = conv_layer(*args, **kwargs, **cfg_)
43
-
44
- return layer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/ops/nms.py DELETED
@@ -1,417 +0,0 @@
1
- import os
2
-
3
- import numpy as np
4
- import torch
5
-
6
- from annotator.uniformer.mmcv.utils import deprecated_api_warning
7
- from ..utils import ext_loader
8
-
9
- ext_module = ext_loader.load_ext(
10
- '_ext', ['nms', 'softnms', 'nms_match', 'nms_rotated'])
11
-
12
-
13
- # This function is modified from: https://github.com/pytorch/vision/
14
- class NMSop(torch.autograd.Function):
15
-
16
- @staticmethod
17
- def forward(ctx, bboxes, scores, iou_threshold, offset, score_threshold,
18
- max_num):
19
- is_filtering_by_score = score_threshold > 0
20
- if is_filtering_by_score:
21
- valid_mask = scores > score_threshold
22
- bboxes, scores = bboxes[valid_mask], scores[valid_mask]
23
- valid_inds = torch.nonzero(
24
- valid_mask, as_tuple=False).squeeze(dim=1)
25
-
26
- inds = ext_module.nms(
27
- bboxes, scores, iou_threshold=float(iou_threshold), offset=offset)
28
-
29
- if max_num > 0:
30
- inds = inds[:max_num]
31
- if is_filtering_by_score:
32
- inds = valid_inds[inds]
33
- return inds
34
-
35
- @staticmethod
36
- def symbolic(g, bboxes, scores, iou_threshold, offset, score_threshold,
37
- max_num):
38
- from ..onnx import is_custom_op_loaded
39
- has_custom_op = is_custom_op_loaded()
40
- # TensorRT nms plugin is aligned with original nms in ONNXRuntime
41
- is_trt_backend = os.environ.get('ONNX_BACKEND') == 'MMCVTensorRT'
42
- if has_custom_op and (not is_trt_backend):
43
- return g.op(
44
- 'mmcv::NonMaxSuppression',
45
- bboxes,
46
- scores,
47
- iou_threshold_f=float(iou_threshold),
48
- offset_i=int(offset))
49
- else:
50
- from torch.onnx.symbolic_opset9 import select, squeeze, unsqueeze
51
- from ..onnx.onnx_utils.symbolic_helper import _size_helper
52
-
53
- boxes = unsqueeze(g, bboxes, 0)
54
- scores = unsqueeze(g, unsqueeze(g, scores, 0), 0)
55
-
56
- if max_num > 0:
57
- max_num = g.op(
58
- 'Constant',
59
- value_t=torch.tensor(max_num, dtype=torch.long))
60
- else:
61
- dim = g.op('Constant', value_t=torch.tensor(0))
62
- max_num = _size_helper(g, bboxes, dim)
63
- max_output_per_class = max_num
64
- iou_threshold = g.op(
65
- 'Constant',
66
- value_t=torch.tensor([iou_threshold], dtype=torch.float))
67
- score_threshold = g.op(
68
- 'Constant',
69
- value_t=torch.tensor([score_threshold], dtype=torch.float))
70
- nms_out = g.op('NonMaxSuppression', boxes, scores,
71
- max_output_per_class, iou_threshold,
72
- score_threshold)
73
- return squeeze(
74
- g,
75
- select(
76
- g, nms_out, 1,
77
- g.op(
78
- 'Constant',
79
- value_t=torch.tensor([2], dtype=torch.long))), 1)
80
-
81
-
82
- class SoftNMSop(torch.autograd.Function):
83
-
84
- @staticmethod
85
- def forward(ctx, boxes, scores, iou_threshold, sigma, min_score, method,
86
- offset):
87
- dets = boxes.new_empty((boxes.size(0), 5), device='cpu')
88
- inds = ext_module.softnms(
89
- boxes.cpu(),
90
- scores.cpu(),
91
- dets.cpu(),
92
- iou_threshold=float(iou_threshold),
93
- sigma=float(sigma),
94
- min_score=float(min_score),
95
- method=int(method),
96
- offset=int(offset))
97
- return dets, inds
98
-
99
- @staticmethod
100
- def symbolic(g, boxes, scores, iou_threshold, sigma, min_score, method,
101
- offset):
102
- from packaging import version
103
- assert version.parse(torch.__version__) >= version.parse('1.7.0')
104
- nms_out = g.op(
105
- 'mmcv::SoftNonMaxSuppression',
106
- boxes,
107
- scores,
108
- iou_threshold_f=float(iou_threshold),
109
- sigma_f=float(sigma),
110
- min_score_f=float(min_score),
111
- method_i=int(method),
112
- offset_i=int(offset),
113
- outputs=2)
114
- return nms_out
115
-
116
-
117
- @deprecated_api_warning({'iou_thr': 'iou_threshold'})
118
- def nms(boxes, scores, iou_threshold, offset=0, score_threshold=0, max_num=-1):
119
- """Dispatch to either CPU or GPU NMS implementations.
120
-
121
- The input can be either torch tensor or numpy array. GPU NMS will be used
122
- if the input is gpu tensor, otherwise CPU NMS
123
- will be used. The returned type will always be the same as inputs.
124
-
125
- Arguments:
126
- boxes (torch.Tensor or np.ndarray): boxes in shape (N, 4).
127
- scores (torch.Tensor or np.ndarray): scores in shape (N, ).
128
- iou_threshold (float): IoU threshold for NMS.
129
- offset (int, 0 or 1): boxes' width or height is (x2 - x1 + offset).
130
- score_threshold (float): score threshold for NMS.
131
- max_num (int): maximum number of boxes after NMS.
132
-
133
- Returns:
134
- tuple: kept dets(boxes and scores) and indice, which is always the \
135
- same data type as the input.
136
-
137
- Example:
138
- >>> boxes = np.array([[49.1, 32.4, 51.0, 35.9],
139
- >>> [49.3, 32.9, 51.0, 35.3],
140
- >>> [49.2, 31.8, 51.0, 35.4],
141
- >>> [35.1, 11.5, 39.1, 15.7],
142
- >>> [35.6, 11.8, 39.3, 14.2],
143
- >>> [35.3, 11.5, 39.9, 14.5],
144
- >>> [35.2, 11.7, 39.7, 15.7]], dtype=np.float32)
145
- >>> scores = np.array([0.9, 0.9, 0.5, 0.5, 0.5, 0.4, 0.3],\
146
- dtype=np.float32)
147
- >>> iou_threshold = 0.6
148
- >>> dets, inds = nms(boxes, scores, iou_threshold)
149
- >>> assert len(inds) == len(dets) == 3
150
- """
151
- assert isinstance(boxes, (torch.Tensor, np.ndarray))
152
- assert isinstance(scores, (torch.Tensor, np.ndarray))
153
- is_numpy = False
154
- if isinstance(boxes, np.ndarray):
155
- is_numpy = True
156
- boxes = torch.from_numpy(boxes)
157
- if isinstance(scores, np.ndarray):
158
- scores = torch.from_numpy(scores)
159
- assert boxes.size(1) == 4
160
- assert boxes.size(0) == scores.size(0)
161
- assert offset in (0, 1)
162
-
163
- if torch.__version__ == 'parrots':
164
- indata_list = [boxes, scores]
165
- indata_dict = {
166
- 'iou_threshold': float(iou_threshold),
167
- 'offset': int(offset)
168
- }
169
- inds = ext_module.nms(*indata_list, **indata_dict)
170
- else:
171
- inds = NMSop.apply(boxes, scores, iou_threshold, offset,
172
- score_threshold, max_num)
173
- dets = torch.cat((boxes[inds], scores[inds].reshape(-1, 1)), dim=1)
174
- if is_numpy:
175
- dets = dets.cpu().numpy()
176
- inds = inds.cpu().numpy()
177
- return dets, inds
178
-
179
-
180
- @deprecated_api_warning({'iou_thr': 'iou_threshold'})
181
- def soft_nms(boxes,
182
- scores,
183
- iou_threshold=0.3,
184
- sigma=0.5,
185
- min_score=1e-3,
186
- method='linear',
187
- offset=0):
188
- """Dispatch to only CPU Soft NMS implementations.
189
-
190
- The input can be either a torch tensor or numpy array.
191
- The returned type will always be the same as inputs.
192
-
193
- Arguments:
194
- boxes (torch.Tensor or np.ndarray): boxes in shape (N, 4).
195
- scores (torch.Tensor or np.ndarray): scores in shape (N, ).
196
- iou_threshold (float): IoU threshold for NMS.
197
- sigma (float): hyperparameter for gaussian method
198
- min_score (float): score filter threshold
199
- method (str): either 'linear' or 'gaussian'
200
- offset (int, 0 or 1): boxes' width or height is (x2 - x1 + offset).
201
-
202
- Returns:
203
- tuple: kept dets(boxes and scores) and indice, which is always the \
204
- same data type as the input.
205
-
206
- Example:
207
- >>> boxes = np.array([[4., 3., 5., 3.],
208
- >>> [4., 3., 5., 4.],
209
- >>> [3., 1., 3., 1.],
210
- >>> [3., 1., 3., 1.],
211
- >>> [3., 1., 3., 1.],
212
- >>> [3., 1., 3., 1.]], dtype=np.float32)
213
- >>> scores = np.array([0.9, 0.9, 0.5, 0.5, 0.4, 0.0], dtype=np.float32)
214
- >>> iou_threshold = 0.6
215
- >>> dets, inds = soft_nms(boxes, scores, iou_threshold, sigma=0.5)
216
- >>> assert len(inds) == len(dets) == 5
217
- """
218
-
219
- assert isinstance(boxes, (torch.Tensor, np.ndarray))
220
- assert isinstance(scores, (torch.Tensor, np.ndarray))
221
- is_numpy = False
222
- if isinstance(boxes, np.ndarray):
223
- is_numpy = True
224
- boxes = torch.from_numpy(boxes)
225
- if isinstance(scores, np.ndarray):
226
- scores = torch.from_numpy(scores)
227
- assert boxes.size(1) == 4
228
- assert boxes.size(0) == scores.size(0)
229
- assert offset in (0, 1)
230
- method_dict = {'naive': 0, 'linear': 1, 'gaussian': 2}
231
- assert method in method_dict.keys()
232
-
233
- if torch.__version__ == 'parrots':
234
- dets = boxes.new_empty((boxes.size(0), 5), device='cpu')
235
- indata_list = [boxes.cpu(), scores.cpu(), dets.cpu()]
236
- indata_dict = {
237
- 'iou_threshold': float(iou_threshold),
238
- 'sigma': float(sigma),
239
- 'min_score': min_score,
240
- 'method': method_dict[method],
241
- 'offset': int(offset)
242
- }
243
- inds = ext_module.softnms(*indata_list, **indata_dict)
244
- else:
245
- dets, inds = SoftNMSop.apply(boxes.cpu(), scores.cpu(),
246
- float(iou_threshold), float(sigma),
247
- float(min_score), method_dict[method],
248
- int(offset))
249
-
250
- dets = dets[:inds.size(0)]
251
-
252
- if is_numpy:
253
- dets = dets.cpu().numpy()
254
- inds = inds.cpu().numpy()
255
- return dets, inds
256
- else:
257
- return dets.to(device=boxes.device), inds.to(device=boxes.device)
258
-
259
-
260
- def batched_nms(boxes, scores, idxs, nms_cfg, class_agnostic=False):
261
- """Performs non-maximum suppression in a batched fashion.
262
-
263
- Modified from https://github.com/pytorch/vision/blob
264
- /505cd6957711af790211896d32b40291bea1bc21/torchvision/ops/boxes.py#L39.
265
- In order to perform NMS independently per class, we add an offset to all
266
- the boxes. The offset is dependent only on the class idx, and is large
267
- enough so that boxes from different classes do not overlap.
268
-
269
- Arguments:
270
- boxes (torch.Tensor): boxes in shape (N, 4).
271
- scores (torch.Tensor): scores in shape (N, ).
272
- idxs (torch.Tensor): each index value correspond to a bbox cluster,
273
- and NMS will not be applied between elements of different idxs,
274
- shape (N, ).
275
- nms_cfg (dict): specify nms type and other parameters like iou_thr.
276
- Possible keys includes the following.
277
-
278
- - iou_thr (float): IoU threshold used for NMS.
279
- - split_thr (float): threshold number of boxes. In some cases the
280
- number of boxes is large (e.g., 200k). To avoid OOM during
281
- training, the users could set `split_thr` to a small value.
282
- If the number of boxes is greater than the threshold, it will
283
- perform NMS on each group of boxes separately and sequentially.
284
- Defaults to 10000.
285
- class_agnostic (bool): if true, nms is class agnostic,
286
- i.e. IoU thresholding happens over all boxes,
287
- regardless of the predicted class.
288
-
289
- Returns:
290
- tuple: kept dets and indice.
291
- """
292
- nms_cfg_ = nms_cfg.copy()
293
- class_agnostic = nms_cfg_.pop('class_agnostic', class_agnostic)
294
- if class_agnostic:
295
- boxes_for_nms = boxes
296
- else:
297
- max_coordinate = boxes.max()
298
- offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))
299
- boxes_for_nms = boxes + offsets[:, None]
300
-
301
- nms_type = nms_cfg_.pop('type', 'nms')
302
- nms_op = eval(nms_type)
303
-
304
- split_thr = nms_cfg_.pop('split_thr', 10000)
305
- # Won't split to multiple nms nodes when exporting to onnx
306
- if boxes_for_nms.shape[0] < split_thr or torch.onnx.is_in_onnx_export():
307
- dets, keep = nms_op(boxes_for_nms, scores, **nms_cfg_)
308
- boxes = boxes[keep]
309
- # -1 indexing works abnormal in TensorRT
310
- # This assumes `dets` has 5 dimensions where
311
- # the last dimension is score.
312
- # TODO: more elegant way to handle the dimension issue.
313
- # Some type of nms would reweight the score, such as SoftNMS
314
- scores = dets[:, 4]
315
- else:
316
- max_num = nms_cfg_.pop('max_num', -1)
317
- total_mask = scores.new_zeros(scores.size(), dtype=torch.bool)
318
- # Some type of nms would reweight the score, such as SoftNMS
319
- scores_after_nms = scores.new_zeros(scores.size())
320
- for id in torch.unique(idxs):
321
- mask = (idxs == id).nonzero(as_tuple=False).view(-1)
322
- dets, keep = nms_op(boxes_for_nms[mask], scores[mask], **nms_cfg_)
323
- total_mask[mask[keep]] = True
324
- scores_after_nms[mask[keep]] = dets[:, -1]
325
- keep = total_mask.nonzero(as_tuple=False).view(-1)
326
-
327
- scores, inds = scores_after_nms[keep].sort(descending=True)
328
- keep = keep[inds]
329
- boxes = boxes[keep]
330
-
331
- if max_num > 0:
332
- keep = keep[:max_num]
333
- boxes = boxes[:max_num]
334
- scores = scores[:max_num]
335
-
336
- return torch.cat([boxes, scores[:, None]], -1), keep
337
-
338
-
339
- def nms_match(dets, iou_threshold):
340
- """Matched dets into different groups by NMS.
341
-
342
- NMS match is Similar to NMS but when a bbox is suppressed, nms match will
343
- record the indice of suppressed bbox and form a group with the indice of
344
- kept bbox. In each group, indice is sorted as score order.
345
-
346
- Arguments:
347
- dets (torch.Tensor | np.ndarray): Det boxes with scores, shape (N, 5).
348
- iou_thr (float): IoU thresh for NMS.
349
-
350
- Returns:
351
- List[torch.Tensor | np.ndarray]: The outer list corresponds different
352
- matched group, the inner Tensor corresponds the indices for a group
353
- in score order.
354
- """
355
- if dets.shape[0] == 0:
356
- matched = []
357
- else:
358
- assert dets.shape[-1] == 5, 'inputs dets.shape should be (N, 5), ' \
359
- f'but get {dets.shape}'
360
- if isinstance(dets, torch.Tensor):
361
- dets_t = dets.detach().cpu()
362
- else:
363
- dets_t = torch.from_numpy(dets)
364
- indata_list = [dets_t]
365
- indata_dict = {'iou_threshold': float(iou_threshold)}
366
- matched = ext_module.nms_match(*indata_list, **indata_dict)
367
- if torch.__version__ == 'parrots':
368
- matched = matched.tolist()
369
-
370
- if isinstance(dets, torch.Tensor):
371
- return [dets.new_tensor(m, dtype=torch.long) for m in matched]
372
- else:
373
- return [np.array(m, dtype=np.int) for m in matched]
374
-
375
-
376
- def nms_rotated(dets, scores, iou_threshold, labels=None):
377
- """Performs non-maximum suppression (NMS) on the rotated boxes according to
378
- their intersection-over-union (IoU).
379
-
380
- Rotated NMS iteratively removes lower scoring rotated boxes which have an
381
- IoU greater than iou_threshold with another (higher scoring) rotated box.
382
-
383
- Args:
384
- boxes (Tensor): Rotated boxes in shape (N, 5). They are expected to \
385
- be in (x_ctr, y_ctr, width, height, angle_radian) format.
386
- scores (Tensor): scores in shape (N, ).
387
- iou_threshold (float): IoU thresh for NMS.
388
- labels (Tensor): boxes' label in shape (N,).
389
-
390
- Returns:
391
- tuple: kept dets(boxes and scores) and indice, which is always the \
392
- same data type as the input.
393
- """
394
- if dets.shape[0] == 0:
395
- return dets, None
396
- multi_label = labels is not None
397
- if multi_label:
398
- dets_wl = torch.cat((dets, labels.unsqueeze(1)), 1)
399
- else:
400
- dets_wl = dets
401
- _, order = scores.sort(0, descending=True)
402
- dets_sorted = dets_wl.index_select(0, order)
403
-
404
- if torch.__version__ == 'parrots':
405
- keep_inds = ext_module.nms_rotated(
406
- dets_wl,
407
- scores,
408
- order,
409
- dets_sorted,
410
- iou_threshold=iou_threshold,
411
- multi_label=multi_label)
412
- else:
413
- keep_inds = ext_module.nms_rotated(dets_wl, scores, order, dets_sorted,
414
- iou_threshold, multi_label)
415
- dets = torch.cat((dets[keep_inds], scores[keep_inds].reshape(-1, 1)),
416
- dim=1)
417
- return dets, keep_inds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/parallel/distributed_deprecated.py DELETED
@@ -1,70 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
- import torch
3
- import torch.distributed as dist
4
- import torch.nn as nn
5
- from torch._utils import (_flatten_dense_tensors, _take_tensors,
6
- _unflatten_dense_tensors)
7
-
8
- from annotator.uniformer.mmcv.utils import TORCH_VERSION, digit_version
9
- from .registry import MODULE_WRAPPERS
10
- from .scatter_gather import scatter_kwargs
11
-
12
-
13
- @MODULE_WRAPPERS.register_module()
14
- class MMDistributedDataParallel(nn.Module):
15
-
16
- def __init__(self,
17
- module,
18
- dim=0,
19
- broadcast_buffers=True,
20
- bucket_cap_mb=25):
21
- super(MMDistributedDataParallel, self).__init__()
22
- self.module = module
23
- self.dim = dim
24
- self.broadcast_buffers = broadcast_buffers
25
-
26
- self.broadcast_bucket_size = bucket_cap_mb * 1024 * 1024
27
- self._sync_params()
28
-
29
- def _dist_broadcast_coalesced(self, tensors, buffer_size):
30
- for tensors in _take_tensors(tensors, buffer_size):
31
- flat_tensors = _flatten_dense_tensors(tensors)
32
- dist.broadcast(flat_tensors, 0)
33
- for tensor, synced in zip(
34
- tensors, _unflatten_dense_tensors(flat_tensors, tensors)):
35
- tensor.copy_(synced)
36
-
37
- def _sync_params(self):
38
- module_states = list(self.module.state_dict().values())
39
- if len(module_states) > 0:
40
- self._dist_broadcast_coalesced(module_states,
41
- self.broadcast_bucket_size)
42
- if self.broadcast_buffers:
43
- if (TORCH_VERSION != 'parrots'
44
- and digit_version(TORCH_VERSION) < digit_version('1.0')):
45
- buffers = [b.data for b in self.module._all_buffers()]
46
- else:
47
- buffers = [b.data for b in self.module.buffers()]
48
- if len(buffers) > 0:
49
- self._dist_broadcast_coalesced(buffers,
50
- self.broadcast_bucket_size)
51
-
52
- def scatter(self, inputs, kwargs, device_ids):
53
- return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
54
-
55
- def forward(self, *inputs, **kwargs):
56
- inputs, kwargs = self.scatter(inputs, kwargs,
57
- [torch.cuda.current_device()])
58
- return self.module(*inputs[0], **kwargs[0])
59
-
60
- def train_step(self, *inputs, **kwargs):
61
- inputs, kwargs = self.scatter(inputs, kwargs,
62
- [torch.cuda.current_device()])
63
- output = self.module.train_step(*inputs[0], **kwargs[0])
64
- return output
65
-
66
- def val_step(self, *inputs, **kwargs):
67
- inputs, kwargs = self.scatter(inputs, kwargs,
68
- [torch.cuda.current_device()])
69
- output = self.module.val_step(*inputs[0], **kwargs[0])
70
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/packages/__init__.py DELETED
File without changes
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/rotate.py DELETED
@@ -1,64 +0,0 @@
1
- from distutils.util import convert_path
2
- from distutils import log
3
- from distutils.errors import DistutilsOptionError
4
- import os
5
- import shutil
6
-
7
- from setuptools import Command
8
-
9
-
10
- class rotate(Command):
11
- """Delete older distributions"""
12
-
13
- description = "delete older distributions, keeping N newest files"
14
- user_options = [
15
- ('match=', 'm', "patterns to match (required)"),
16
- ('dist-dir=', 'd', "directory where the distributions are"),
17
- ('keep=', 'k', "number of matching distributions to keep"),
18
- ]
19
-
20
- boolean_options = []
21
-
22
- def initialize_options(self):
23
- self.match = None
24
- self.dist_dir = None
25
- self.keep = None
26
-
27
- def finalize_options(self):
28
- if self.match is None:
29
- raise DistutilsOptionError(
30
- "Must specify one or more (comma-separated) match patterns "
31
- "(e.g. '.zip' or '.egg')"
32
- )
33
- if self.keep is None:
34
- raise DistutilsOptionError("Must specify number of files to keep")
35
- try:
36
- self.keep = int(self.keep)
37
- except ValueError as e:
38
- raise DistutilsOptionError("--keep must be an integer") from e
39
- if isinstance(self.match, str):
40
- self.match = [
41
- convert_path(p.strip()) for p in self.match.split(',')
42
- ]
43
- self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
44
-
45
- def run(self):
46
- self.run_command("egg_info")
47
- from glob import glob
48
-
49
- for pattern in self.match:
50
- pattern = self.distribution.get_name() + '*' + pattern
51
- files = glob(os.path.join(self.dist_dir, pattern))
52
- files = [(os.path.getmtime(f), f) for f in files]
53
- files.sort()
54
- files.reverse()
55
-
56
- log.info("%d file(s) matching %s", len(files), pattern)
57
- files = files[self.keep:]
58
- for (t, f) in files:
59
- log.info("Deleting %s", f)
60
- if not self.dry_run:
61
- if os.path.isdir(f):
62
- shutil.rmtree(f)
63
- else:
64
- os.unlink(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Baptlem/UCDR-Net/app.py DELETED
@@ -1,360 +0,0 @@
1
- # This file is adapted from https://huggingface.co/spaces/diffusers/controlnet-canny/blob/main/app.py
2
- # The original license file is LICENSE.ControlNet in this repo.
3
- from diffusers import FlaxStableDiffusionControlNetPipeline, FlaxControlNetModel, FlaxDPMSolverMultistepScheduler
4
- from transformers import CLIPTokenizer, FlaxCLIPTextModel, set_seed
5
- from flax.training.common_utils import shard
6
- from flax.jax_utils import replicate
7
- from diffusers.utils import load_image
8
- import jax.numpy as jnp
9
- import jax
10
- import cv2
11
- from PIL import Image
12
- import numpy as np
13
- import gradio as gr
14
- import os
15
-
16
-
17
- if gr.__version__ != "3.28.3": #doesn't work...
18
- os.system("pip uninstall -y gradio")
19
- os.system("pip install gradio==3.28.3")
20
-
21
- title_description = """
22
- # Unlimited Controlled Domain Randomization Network for Bridging the Sim2Real Gap in Robotics
23
-
24
- """
25
-
26
- description = """
27
- While existing ControlNet and public diffusion models are predominantly geared towards high-resolution images (512x512 or above) and intricate artistic detail generation, there's an untapped potential of these models in Automatic Data Augmentation (ADA).
28
- By harnessing the inherent variance in prompt-conditioned generated images, we can significantly boost the visual diversity of training samples for computer vision pipelines.
29
- This is particularly relevant in the field of robotics, where deep learning is increasingly playing a pivotal role in training policies for robotic manipulation from images.
30
-
31
- In this HuggingFace sprint, we present UCDR-Net (Unlimited Controlled Domain Randomization Network), a novel CannyEdge mini-ControlNet trained on Stable Diffusion 1.5 with mixed datasets.
32
- Our model generates photorealistic and varied renderings from simplistic robotic simulation images, enabling real-time data augmentation for robotic vision training.
33
-
34
- We specifically designed UCDR-Net to be fast and composition preserving, with an emphasis on lower resolution images (128x128) for online data augmentation in typical preprocessing pipelines.
35
- Our choice of Canny Edge version of ControlNet ensures shape and structure preservation in the image, which is crucial for visuomotor policy learning.
36
-
37
- We trained ControlNet from scratch using only 128x128 images, preprocessing the training datasets and extracting Canny Edge maps.
38
- We then trained four Control-Nets with different mixtures of 2 datasets (Coyo-700M and Bridge Data) and showcased the results.
39
- * [Coyo-700M](https://github.com/kakaobrain/coyo-dataset)
40
- * [Bridge](https://sites.google.com/view/bridgedata)
41
-
42
- Model Description and Training Process: Please refer to the readme file attached to the model repository.
43
-
44
- Model Repository: [ControlNet repo](https://huggingface.co/Baptlem/UCDR-Net_models)
45
-
46
- """
47
-
48
- traj_description = """
49
- To demonstrate UCDR-Net's capabilities, we generated a trajectory of our simulated robotic environment and presented the resulting videos for each model.
50
- We batched the frames for each video and performed independent inference for each frame, which explains the "wobbling" effect.
51
- Prompt used for every video: "A robotic arm with a gripper and a small cube on a table, super realistic, industrial background"
52
-
53
- """
54
-
55
- perfo_description = """
56
- Our model has been benchmarked on a node of 8 A100 80Go GPUs, achieving an impressive 170 FPS image generation rate!
57
-
58
- To make the benchmark, we loaded one of our model on every GPUs of the node. We then retrieve an episode of our simulation.
59
- For every frame of the episode, we preprocess the image (resize, canny, …) and process the Canny image on the GPUs.
60
- We repeated this procedure for different Batch Size (BS).
61
-
62
- We can see that the greater the BS the greater the FPS. By increazing the BS, we take advantage of the parallelization of the GPUs.
63
- """
64
-
65
- conclusion_description = """
66
- UCDR-Net stands as a natural development in bridging the Sim2Real gap in robotics by providing real-time data augmentation for training visual policies.
67
- We are excited to share our work with the HuggingFace community and contribute to the advancement of robotic vision training techniques.
68
-
69
- """
70
-
71
- def create_key(seed=0):
72
- return jax.random.PRNGKey(seed)
73
-
74
- def load_controlnet(controlnet_version):
75
- controlnet, controlnet_params = FlaxControlNetModel.from_pretrained(
76
- "Baptlem/UCDR-Net_models",
77
- subfolder=controlnet_version,
78
- from_flax=True,
79
- dtype=jnp.float32,
80
- )
81
- return controlnet, controlnet_params
82
-
83
-
84
- def load_sb_pipe(controlnet_version, sb_path="runwayml/stable-diffusion-v1-5"):
85
- controlnet, controlnet_params = load_controlnet(controlnet_version)
86
-
87
- scheduler, scheduler_params = FlaxDPMSolverMultistepScheduler.from_pretrained(
88
- sb_path,
89
- subfolder="scheduler"
90
- )
91
-
92
- pipe, params = FlaxStableDiffusionControlNetPipeline.from_pretrained(
93
- sb_path,
94
- controlnet=controlnet,
95
- revision="flax",
96
- dtype=jnp.bfloat16
97
- )
98
-
99
- pipe.scheduler = scheduler
100
- params["controlnet"] = controlnet_params
101
- params["scheduler"] = scheduler_params
102
- return pipe, params
103
-
104
-
105
-
106
- controlnet_path = "Baptlem/UCDR-Net_models"
107
- controlnet_version = "coyo-500k"
108
-
109
- # Constants
110
- low_threshold = 100
111
- high_threshold = 200
112
-
113
- print(os.path.abspath('.'))
114
- print(os.listdir("."))
115
- print("Gradio version:", gr.__version__)
116
- # pipe.enable_xformers_memory_efficient_attention()
117
- # pipe.enable_model_cpu_offload()
118
- # pipe.enable_attention_slicing()
119
- print("Loaded models...")
120
- def pipe_inference(
121
- image,
122
- prompt,
123
- is_canny=False,
124
- num_samples=4,
125
- resolution=128,
126
- num_inference_steps=50,
127
- guidance_scale=7.5,
128
- model="coyo-500k",
129
- seed=0,
130
- negative_prompt="",
131
- ):
132
- print("Loading pipe")
133
- pipe, params = load_sb_pipe(model)
134
-
135
- if not isinstance(image, np.ndarray):
136
- image = np.array(image)
137
-
138
- processed_image = resize_image(image, resolution) #-> PIL
139
-
140
- if not is_canny:
141
- resized_image, processed_image = preprocess_canny(processed_image, resolution)
142
-
143
- rng = create_key(seed)
144
- rng = jax.random.split(rng, jax.device_count())
145
-
146
- prompt_ids = pipe.prepare_text_inputs([prompt] * num_samples)
147
- negative_prompt_ids = pipe.prepare_text_inputs([negative_prompt] * num_samples)
148
- processed_image = pipe.prepare_image_inputs([processed_image] * num_samples)
149
-
150
- p_params = replicate(params)
151
- prompt_ids = shard(prompt_ids)
152
- negative_prompt_ids = shard(negative_prompt_ids)
153
- processed_image = shard(processed_image)
154
- print("Inference...")
155
- output = pipe(
156
- prompt_ids=prompt_ids,
157
- image=processed_image,
158
- params=p_params,
159
- prng_seed=rng,
160
- num_inference_steps=num_inference_steps,
161
- guidance_scale=guidance_scale,
162
- neg_prompt_ids=negative_prompt_ids,
163
- jit=True,
164
- ).images
165
- print("Finished inference...")
166
- # all_outputs = []
167
- # all_outputs.append(image)
168
- # if not is_canny:
169
- # all_outputs.append(resized_image)
170
-
171
- # for image in output.images:
172
- # all_outputs.append(image)
173
-
174
- all_outputs = pipe.numpy_to_pil(np.asarray(output.reshape((num_samples,) + output.shape[-3:])))
175
- return all_outputs
176
-
177
- def resize_image(image, resolution):
178
- if not isinstance(image, np.ndarray):
179
- image = np.array(image)
180
- h, w = image.shape[:2]
181
- ratio = w/h
182
- if ratio > 1 :
183
- resized_image = cv2.resize(image, (int(resolution*ratio), resolution), interpolation=cv2.INTER_NEAREST)
184
- elif ratio < 1 :
185
- resized_image = cv2.resize(image, (resolution, int(resolution/ratio)), interpolation=cv2.INTER_NEAREST)
186
- else:
187
- resized_image = cv2.resize(image, (resolution, resolution), interpolation=cv2.INTER_NEAREST)
188
-
189
- return Image.fromarray(resized_image)
190
-
191
-
192
- def preprocess_canny(image, resolution=128):
193
- if not isinstance(image, np.ndarray):
194
- image = np.array(image)
195
-
196
- processed_image = cv2.Canny(image, low_threshold, high_threshold)
197
- processed_image = processed_image[:, :, None]
198
- processed_image = np.concatenate([processed_image, processed_image, processed_image], axis=2)
199
-
200
- resized_image = Image.fromarray(image)
201
- processed_image = Image.fromarray(processed_image)
202
- return resized_image, processed_image
203
-
204
-
205
- def create_demo(process, max_images=12, default_num_images=4):
206
- with gr.Blocks() as demo:
207
- with gr.Row():
208
- gr.Markdown(title_description)
209
- with gr.Row():
210
- with gr.Column():
211
- input_image = gr.Image(source='upload', type='numpy')
212
- prompt = gr.Textbox(label='Prompt')
213
- run_button = gr.Button(label='Run')
214
- with gr.Accordion('Advanced options', open=False):
215
- is_canny = gr.Checkbox(
216
- label='Is canny', value=False)
217
- num_samples = gr.Slider(label='Images',
218
- minimum=1,
219
- maximum=max_images,
220
- value=default_num_images,
221
- step=1)
222
- """
223
- canny_low_threshold = gr.Slider(
224
- label='Canny low threshold',
225
- minimum=1,
226
- maximum=255,
227
- value=100,
228
- step=1)
229
- canny_high_threshold = gr.Slider(
230
- label='Canny high threshold',
231
- minimum=1,
232
- maximum=255,
233
- value=200,
234
- step=1)
235
- """
236
- resolution = gr.Slider(label='Resolution',
237
- minimum=128,
238
- maximum=128,
239
- value=128,
240
- step=1)
241
- num_steps = gr.Slider(label='Steps',
242
- minimum=1,
243
- maximum=100,
244
- value=20,
245
- step=1)
246
- guidance_scale = gr.Slider(label='Guidance Scale',
247
- minimum=0.1,
248
- maximum=30.0,
249
- value=7.5,
250
- step=0.1)
251
- model = gr.Dropdown(choices=["coyo-500k", "bridge-2M", "coyo1M-bridge2M", "coyo2M-bridge325k"],
252
- value="coyo-500k",
253
- label="Model used for inference",
254
- info="Find every models at https://huggingface.co/Baptlem/UCDR-Net_models")
255
- seed = gr.Slider(label='Seed',
256
- minimum=-1,
257
- maximum=2147483647,
258
- step=1,
259
- randomize=True)
260
- n_prompt = gr.Textbox(
261
- label='Negative Prompt',
262
- value=
263
- 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
264
- )
265
- with gr.Column():
266
- result = gr.Gallery(label='Output',
267
- show_label=False,
268
- elem_id='gallery').style(grid=2,
269
- height='auto')
270
-
271
- with gr.Row():
272
- gr.Video("./trajectory_hf/trajectory_coyo2M-bridge325k_64.avi",
273
- format="avi",
274
- interactive=False).style(height=512,
275
- width=512)
276
-
277
- with gr.Row():
278
- gr.Markdown(description)
279
-
280
- with gr.Row():
281
- with gr.Column():
282
- gr.Markdown(traj_description)
283
- with gr.Column():
284
- gr.Video("./trajectory_hf/trajectory.avi",
285
- format="avi",
286
- interactive=False)
287
-
288
- with gr.Row():
289
- with gr.Column():
290
- gr.Markdown("Trajectory processed with coyo-500k model :")
291
- with gr.Column():
292
- gr.Video("./trajectory_hf/trajectory_coyo-500k.avi",
293
- format="avi",
294
- interactive=False)
295
-
296
- with gr.Row():
297
- with gr.Column():
298
- gr.Markdown("Trajectory processed with bridge-2M model :")
299
- with gr.Column():
300
- gr.Video("./trajectory_hf/trajectory_bridge-2M.avi",
301
- format="avi",
302
- interactive=False)
303
-
304
- with gr.Row():
305
- with gr.Column():
306
- gr.Markdown("Trajectory processed with coyo1M-bridge2M model :")
307
- with gr.Column():
308
- gr.Video("./trajectory_hf/trajectory_coyo1M-bridge2M.avi",
309
- format="avi",
310
- interactive=False)
311
-
312
- with gr.Row():
313
- with gr.Column():
314
- gr.Markdown("Trajectory processed with coyo2M-bridge325k model :")
315
- with gr.Column():
316
- gr.Video("./trajectory_hf/trajectory_coyo2M-bridge325k.avi",
317
- format="avi",
318
- interactive=False)
319
-
320
- with gr.Row():
321
- with gr.Column():
322
- gr.Markdown(perfo_description)
323
- with gr.Column():
324
- gr.Image("./perfo_rtx.png",
325
- interactive=False)
326
-
327
- with gr.Row():
328
- gr.Markdown(conclusion_description)
329
-
330
-
331
-
332
- inputs = [
333
- input_image,
334
- prompt,
335
- is_canny,
336
- num_samples,
337
- resolution,
338
- #canny_low_threshold,
339
- #canny_high_threshold,
340
- num_steps,
341
- guidance_scale,
342
- model,
343
- seed,
344
- n_prompt,
345
- ]
346
- prompt.submit(fn=process, inputs=inputs, outputs=result)
347
- run_button.click(fn=process,
348
- inputs=inputs,
349
- outputs=result,
350
- api_name='canny')
351
-
352
- return demo
353
-
354
- if __name__ == '__main__':
355
-
356
- pipe_inference
357
- demo = create_demo(pipe_inference)
358
- demo.queue().launch()
359
- # gr.Interface(create_demo).launch()
360
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Descargar Archivo Zip Brawlhalla.md DELETED
@@ -1,88 +0,0 @@
1
- <br />
2
- <h1>Cómo descargar Naruto x Boruto Ninja Voltage desde Play Store</h1>
3
- <p>Si eres fan de las series de anime Naruto y Boruto, quizás quieras probar Naruto x Boruto Ninja Voltage, un popular juego móvil que combina acción, estrategia y elementos de rol. En este juego, puede recoger sus personajes shinobi favoritos, construir su propia fortaleza ninja, y la batalla contra otros jugadores o jefes gigantes. En este artículo, le mostraremos cómo descargar e instalar Naruto x Boruto Ninja Voltage de Play Store, así como cómo jugar y disfrutar del juego. </p>
4
- <h2>¿Qué es Naruto x Boruto Ninja Voltage? </h2>
5
- <h3>Una breve introducción al juego y sus características</h3>
6
- <p>Naruto x Boruto Ninja Voltage es un juego gratuito desarrollado por Bandai Namco Entertainment Inc. Se basa en la popular serie de manga y anime Naruto y su secuela Boruto. El juego cuenta con personajes de ambas series, como Naruto Uzumaki, Sasuke Uchiha, Boruto Uzumaki, Sarada Uchiha, y muchos más. Puedes mejorar y evolucionar a tus ninjas para convertirte en el clan más fuerte. </p>
7
- <h2>descargar archivo zip brawlhalla</h2><br /><p><b><b>Download File</b> <a href="https://bltlly.com/2v6JSW">https://bltlly.com/2v6JSW</a></b></p><br /><br />
8
- <p>El juego tiene dos modos principales: modo fortaleza y modo misión. En el modo fortaleza, puedes diseñar tu propia fortaleza ninja con trampas, shinobi y sistemas de defensa. También puedes atacar fortalezas de otros jugadores y competir por posiciones de batalla. En el modo misión, puedes unirte a un gremio shinobi e ir a misiones con hasta cuatro jugadores. También puedes luchar contra jefes gigantes sin sellar en misiones de ataque sorpresa. </p>
9
- <p>El juego también tiene acción shinobi de ritmo rápido con controles simples y hermosos gráficos de anime en 3D. Puedes realizar combos ninja y terminar a tus enemigos con poderosos ataques de ninjutsu, como Rasengan de Naruto o Chidori de Sasuke. También puedes ganar recompensas completando varias misiones ninja. </p>
10
- <h2>Cómo descargar e instalar el juego desde Play Store</h2>
11
- <h3>Instrucciones paso a paso con capturas de pantalla</h3>
12
-
13
- <ol>
14
- <li>Abra la aplicación Play Store en su dispositivo Android. </li>
15
- <li>Buscar "Naruto x Boruto Ninja Voltage" en la barra de búsqueda. </li>
16
- <li>Toque en el icono del juego que aparece en los resultados. </li>
17
- <li>Toque en el botón "Instalar" para comenzar a descargar el juego. </li>
18
- <li>Espera a que termine la descarga y luego toca "Abrir" para iniciar el juego. </li>
19
- <li>Acepta los términos de servicio y la política de privacidad del juego. </li>
20
- <li>Elija su idioma y servidor preferido. </li>
21
- <li>¡Disfruta del juego! </li>
22
- </ol>
23
- <img src="( 1 )" alt="Play Store screenshot" width="300" height="600">
24
- <img src="( 2 )" alt="Imagen del icono del juego" width="300" height="600">
25
- <img src="( 3 )" alt="Install button screenshot" width="300" height="600">
26
- <img src="( 4 )" alt="Abrir la captura de pantalla del botón" width="300" height="600">
27
- <img src="( 5 )" alt="Términos de la captura de pantalla del servicio" width="300" height="600">
28
- <img src="( 6 )" alt="Captura de pantalla de selección de idioma" width="300" height="600">
29
- <h2>Cómo jugar y disfrutar del juego</h2>
30
- <h3>Algunos consejos y trucos para principiantes</h3>
31
- <p>Si eres nuevo en Naruto x Boruto Ninja Voltage, aquí hay algunos consejos y trucos que pueden ayudarte a empezar:</p>
32
- <ul>
33
- <li>Completa las misiones de tutorial para aprender los fundamentos del juego. </li>
34
- <li>Recoger fragmentos de héroe de las misiones para desbloquear más personajes. </li>
35
- <li>Invoca tarjetas ninja desde banners para equipar a tus personajes con jutsu y potenciadores de estadísticas. </li>
36
- <li>Limite la ruptura de sus tarjetas con ranas o duplicados para aumentar su nivel y poder. </li>
37
- <li>Mejora tus instalaciones de fortaleza con ryo y chakra para mejorar tu defensa y ofensiva. </li>
38
- <li>Únete a un gremio y coopera con otros jugadores para ganar medallas y recompensas. </li>
39
- <li>Participa en eventos y misiones especiales para obtener artículos y personajes exclusivos. </li>
40
- <li>Diviértete y experimenta con diferentes combinaciones y estrategias de equipo. </li>
41
- </ul>
42
- <h3>Algunas fuentes para más información y comentarios</h3>
43
-
44
- <tabla>
45
- <tr>
46
- <th>Fuente</th>
47
- <th>Descripción</th>
48
- </tr>
49
- <tr>
50
- <td>[Sitio web oficial]</td>
51
- <td>El sitio web oficial del juego, donde puedes encontrar las últimas noticias, actualizaciones y anuncios. </td>
52
- </tr>
53
- <tr>
54
- <td>[Página oficial de Facebook]</td>
55
- <td>La página oficial de Facebook del juego, donde puedes interactuar con otros fans, obtener consejos y unirse a eventos. </td>
56
- </tr>
57
- <tr>
58
- <td>[Comunidad de Reddit]</td>
59
- <td>Un subreddit dedicado al juego, donde puedes discutir, compartir y hacer preguntas sobre el juego. </td>
60
- </tr>
61
- <tr>
62
- <td>[canal de YouTube]</td>
63
- <td>Un canal de YouTube que incluye vídeos, guías, reseñas y más sobre el juego. </td>
64
- </tr>
65
- <tr>
66
- <td>[Google Play Store]</td>
67
- <td>La página de Google Play Store del juego, donde puedes descargar el juego, leer los comentarios de los usuarios y calificar el juego. </td>
68
- </tr>
69
- </tabla>
70
- <h2>Conclusión</h2>
71
- <h3>Un resumen de los puntos principales y una llamada a la acción</h3>
72
- <p>Naruto x Boruto Ninja Voltage es un juego divertido y emocionante que te permite experimentar el mundo de Naruto y Boruto en tu dispositivo móvil. Puedes recoger y personalizar tus personajes shinobi favoritos, construir y defender tu fortaleza ninja, y formar equipo con otros jugadores para completar misiones y jefes de lucha. El juego es fácil de descargar e instalar desde Play Store, y puedes seguir nuestros consejos y trucos para empezar. Si eres fan de las series de anime Naruto y Boruto, definitivamente deberías probar este juego. ¡Descarga Naruto x Boruto Ninja Voltage de Play Store hoy y libera tu potencial ninja! </p>
73
- <h4>Preguntas frecuentes</h4>
74
- <p>Aquí hay algunas preguntas comunes que la gente tiene sobre Naruto x Boruto Ninja Voltage:</p>
75
- <ol type="a">
76
- <li> ¿Es Naruto x Boruto Ninja Voltage gratis para jugar? </li>
77
- <p>Sí, Naruto x Boruto Ninja Voltage es gratis para jugar. Sin embargo, hay algunas compras opcionales en la aplicación que pueden mejorar su experiencia de juego. </p>
78
- <p></p>
79
- <li> ¿Cuáles son los requisitos del sistema para Naruto x Boruto Ninja Voltage? </li>
80
-
81
- <li> ¿Cómo puedo obtener más caracteres shinobi en Naruto x Boruto Ninja Voltage? </li>
82
- <p>Puedes conseguir más personajes shinobi recogiendo fragmentos de héroes de misiones o invocando cartas ninja desde banners. También puedes obtener algunos personajes como recompensas de eventos o misiones especiales. </p>
83
- <li> ¿Cómo puedo mejorar mis personajes shinobi en Naruto x Boruto Ninja Voltage? </li>
84
- <p>Puedes mejorar a tus personajes shinobi mejorando y evolucionando sus cartas ninja, limitando el romper sus cartas con ranas o duplicados, despertando sus habilidades con materiales y aumentando su rango con pergaminos. </p>
85
- <li>¿Cómo puedo contactar al equipo de soporte de Naruto x Boruto Ninja Voltage? </li>
86
- <p>Puede ponerse en contacto con el equipo de soporte de Naruto x Boruto Ninja Voltage tocando el botón "Soporte" en la pantalla de título o el botón "Contáctenos" en el menú de configuración. También puede enviar un correo electrónico a [email protected]. </p> 64aa2da5cf<br />
87
- <br />
88
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Descargar Genshin Impacto En El Ordenador Porttil.md DELETED
@@ -1,106 +0,0 @@
1
- <br />
2
- <h1>Cómo descargar Genshin impacto en el ordenador portátil</h1>
3
- <p>Genshin Impact es un juego de rol de acción de mundo abierto que ha tomado el mundo del juego por asalto. En este juego, puedes explorar un vasto y hermoso mundo llamado Teyvat, donde puedes conocer a un diverso elenco de personajes, luchar contra poderosos enemigos y descubrir los secretos de los siete elementos. También puedes hacer equipo con tus amigos en diferentes plataformas, ya que Genshin Impact admite el juego cruzado entre dispositivos PC, PS4, iOS y Android. </p>
4
- <p>Si usted está buscando una manera de jugar este increíble juego en su computadora portátil, usted ha venido al lugar correcto. En este artículo, le mostraremos cómo descargar Genshin Impact en una computadora portátil desde diferentes fuentes, cómo instalarlo y lanzarlo, cómo optimizarlo para un mejor rendimiento y cómo disfrutar de sus funciones de juego. ¡Vamos a empezar! </p>
5
- <h2>descargar genshin impacto en el ordenador portátil</h2><br /><p><b><b>Download</b> &#11088; <a href="https://bltlly.com/2v6IOn">https://bltlly.com/2v6IOn</a></b></p><br /><br />
6
- <h2>Lo que necesita para jugar Genshin impacto en el ordenador portátil</h2>
7
- <p>Antes de descargar Genshin Impact en la computadora portátil, debe asegurarse de que su dispositivo cumple con los requisitos mínimos del sistema para el juego. Según el sitio web oficial, estos son:</p>
8
- <ul>
9
- <li>Sistema operativo: Windows 7 SP1 64-bit, Windows 8.1 64-bit, o Windows 10 64-bit</li>
10
- <li>Procesador: Intel Core i5 o equivalente</li>
11
- <li>RAM: 8 GB</li>
12
- <li>Tarjeta gráfica: NVIDIA GeForce GT 1030 o mejor</li>
13
- <li>Versión de DirectX: 11</li>
14
- <li>Espacio de almacenamiento: 30 GB o más</li>
15
- </ul>
16
- <p>Si su computadora portátil cumple con estos requisitos, puede jugar Genshin Impact en la computadora portátil sin ningún problema importante. Sin embargo, si quieres disfrutar del juego con ajustes de gráficos más altos y velocidades de fotogramas más suaves, es posible que quieras actualizar tu computadora portátil o usar una GPU externa.</p>
17
- <p>Otra cosa que necesita para jugar Genshin impacto en el ordenador portátil es una plataforma donde se puede descargar el juego. Hay dos opciones principales para esto: el sitio web oficial de Genshin Impact o la Epic Games Store. Explicaremos cómo descargar Genshin Impact de ambas fuentes en las próximas secciones. </p>
18
-
19
- <p>El sitio web oficial de Genshin Impact es una de las formas más fáciles de descargar el juego en su computadora portátil. Estos son los pasos que debe seguir:</p>
20
- <ol>
21
- <li>Ir a [el sitio web oficial de Genshin Impact]( 5 ) y haga clic en "Descargar ahora". </li>
22
- <li>Seleccione "Windows" de la lista de plataformas disponibles y haga clic en "Descargar". </li>
23
- <li>Espere al archivo llamado "GenshinImpact_install_" para terminar de descargar. </li>
24
- <li>Haga doble clic en el archivo y siga las instrucciones para instalar el lanzador de juegos. </li>
25
- <li>Inicie el lanzador de juegos e inicie sesión con su cuenta miHoYo o cree uno si no tiene uno. </li>
26
- <li>Haga clic en "Obtener juego" y esperar a que los archivos del juego para descargar. </li>
27
- <li>Haga clic en "Lanzamiento" y disfrutar jugando Genshin impacto en el ordenador portátil! </li>
28
- </ol>
29
- <p>Aquí hay algunas capturas de pantalla del proceso:</p>
30
- <p></p>
31
- <img src=" 21 " alt="Captura de pantalla de la descarga de Genshin Impact desde el sitio web oficial" width="600">
32
- <img src=" <h3>Cómo descargar Genshin Impact desde el Epic Games Store</h3>
33
- <p>Si prefieres usar la Epic Games Store como plataforma para descargar juegos, también puedes obtener Genshin Impact desde allí. Estos son los pasos que debes seguir:</p>
34
- <ol>
35
- <li>Vaya a [el sitio web de Epic Games Store]( 1 ) e inicie sesión con su cuenta de Epic o cree una si no tiene una. </li>
36
- <li>Buscar "Genshin Impact" en la barra de búsqueda y haga clic en el icono del juego. </li>
37
- <li>Haga clic en "Obtener" para agregar el juego a su biblioteca de forma gratuita. </li>
38
- <li>Haga clic en "Instalar" para comenzar a descargar los archivos del juego. </li>
39
- <li>Espere a que la descarga termine y lance el juego desde el Lanzador de Juegos Épicos.</li>
40
- <li>Inicia sesión con tu cuenta miHoYo o crea una si no tienes una. </li>
41
- <li>Disfruta jugando Genshin impacto en el ordenador portátil! </li>
42
- </ol>
43
- <p>Aquí hay algunas capturas de pantalla del proceso:</p>
44
- <img src=" 22 " alt="Captura de pantalla de la descarga de Genshin Impact de Epic Games Store" width="600">
45
- <img src=" 23 " alt="Captura de pantalla de instalación de Genshin Impact desde Epic Games Store" width="600">
46
-
47
- <p>Si no desea utilizar el sitio web oficial o la Epic Games Store, es posible que se pregunte si hay otras fuentes donde se puede descargar Genshin Impact en el ordenador portátil. La respuesta es sí, pero hay que tener cuidado. Algunos sitios web pueden ofrecer réplicas no oficiales o archivos editados que podrían contener malware o virus. Por lo tanto, no recomendamos descargar Genshin Impact desde ninguna otra fuente que no sea el sitio web oficial o la Epic Games Store.</p>
48
- <p>Sin embargo, si tienes curiosidad, aquí hay algunos ejemplos de otras fuentes donde puedes encontrar Genshin Impact:</p>
49
- <ul>
50
- <li>[Reddit]( 5 ): Algunos usuarios en Reddit han compartido enlaces de descarga directa para Genshin Impact desde el servidor oficial de Hoyoverse. Estos son los mismos archivos que el lanzador utiliza para descargar e instalar el juego o actualizaciones. Sin embargo, es posible que estos enlaces no se actualicen regularmente o que expiren después de algún tiempo. También necesita extraer y actualizar manualmente los archivos, lo que podría causar problemas o errores. </li>
51
- <li>[YouTube]( 12 ): Algunos videos de YouTube han proporcionado tutoriales sobre cómo impulsar FPS y aumentar el rendimiento en Genshin Impact en el ordenador portátil. Estos videos también pueden incluir enlaces para descargar el juego o algunas herramientas de optimización. Sin embargo, estos enlaces pueden no ser confiables o seguros, y algunos de los consejos de optimización pueden no funcionar para todos. </li>
52
- <li>[Otros sitios web]( 9 ) : Algunos otros sitios web han proporcionado guías sobre cómo descargar, instalar, iniciar u optimizar Genshin Impact en el ordenador portátil. Estos sitios web también pueden incluir enlaces para descargar el juego o algún software. Sin embargo, estos enlaces pueden no ser verificados o seguros, y algunos de los programas pueden no ser compatibles o eficaces. </li>
53
- </ul>
54
-
55
- <p>Después de haber descargado Genshin Impact en la computadora portátil desde el sitio web oficial o la Epic Games Store, debe instalar y lanzar el juego. Este es un proceso simple y directo, pero lo guiaremos de todos modos. Estos son los pasos que debe seguir:</p>
56
- <ol>
57
- <li>Localice la carpeta donde ha descargado los archivos del juego. Si ha utilizado el sitio web oficial, debe estar en la carpeta Descargas. Si has usado la Epic Games Store, debería estar en tu carpeta Epic Games. </li>
58
- <li>Haga doble clic en el archivo llamado "GenshinImpact.exe" para iniciar el proceso de instalación. </li>
59
- <li> Seleccione el idioma y la carpeta de destino del juego. También puede crear un acceso directo del escritorio si lo desea. </li>
60
- <li>Haga clic en "Instalar" y espere a que termine la instalación. </li>
61
- <li>Haga clic en "Finalizar" y lanzar el juego desde el acceso directo del escritorio o el menú de inicio. </li>
62
- <li>Inicia sesión con tu cuenta miHoYo o crea una si no tienes una. </li>
63
- <li>Seleccione una región del servidor y acepte los términos del servicio. </li>
64
- <li>Crea tu personaje y empezar a jugar Genshin impacto en el ordenador portátil! </li>
65
- </ol>
66
- <p>Aquí hay algunas capturas de pantalla del proceso:</p>
67
- <img src=" 24 " alt="Captura de pantalla de la instalación de Genshin Impacto en el ordenador portátil" ancho="600">
68
- <img src=" 25 " alt="Captura de pantalla del lanzamiento de Genshin Impact en la computadora portátil" width="600">
69
- <h2>Cómo optimizar el impacto de Genshin para el rendimiento del ordenador portátil</h2>
70
- <p>Genshin Impact es un juego visualmente impresionante que requiere una gran cantidad de recursos para funcionar sin problemas. Si usted tiene un ordenador portátil de gran alcance, es posible que no tenga ningún problema para jugar el juego en la configuración de gráficos de alta y resolución. Sin embargo, si tiene una computadora portátil de gama baja o media, puede experimentar algunos problemas de retraso, tartamudez o sobrecalentamiento. Afortunadamente, hay algunas maneras de optimizar Genshin Impact para el rendimiento de la computadora portátil y hacer que funcione mejor. Aquí hay algunos consejos y trucos que puedes probar:</p>
71
- <ul>
72
-
73
- <li>Optimizar la configuración de su ordenador portátil: También puede ajustar algunos ajustes en su ordenador portátil para mejorar su rendimiento. Por ejemplo, puede cambiar al modo de alto rendimiento en sus opciones de alimentación, actualizar sus controladores, cerrar cualquier programa de fondo o aplicaciones que no sean necesarios, desactivar cualquier programa de inicio innecesario y limpiar el espacio en disco. </li>
74
- <li>Utilice una almohadilla de enfriamiento externa o ventilador: Una de las principales causas de mal rendimiento en los ordenadores portátiles es el sobrecalentamiento. Si su computadora portátil se calienta demasiado, puede acelerar su velocidad o apagarse por completo. Para evitar esto, puede usar una almohadilla de enfriamiento externa o un ventilador para mantener su computadora portátil fresca y ventilada. También puede limpiar los ventiladores y rejillas de ventilación de su computadora portátil regularmente para eliminar cualquier polvo o escombros que puedan bloquear el flujo de aire. </li>
75
- <li>Utilice un teclado y un ratón externos: Otro problema que puede afectar su experiencia de juego es la comodidad y la precisión de sus dispositivos de entrada. Si está usando el teclado y el panel táctil de su computadora portátil, es posible que se sientan incómodos o no respondan al tocar Genshin Impact. Para resolver esto, puede usar un teclado y un ratón externos que sean más ergonómicos y precisos. También puede ajustar la sensibilidad y las combinaciones de teclas en la configuración del juego para adaptarse a sus preferencias. </li>
76
- </ul>
77
- <p>Siguiendo estos consejos y trucos, puede optimizar Genshin Impact para el rendimiento del ordenador portátil y disfrutar de un juego más suave y más inmersiva. </p> <h2>Cómo disfrutar de Genshin impacto en el ordenador portátil</h2>
78
- <p>Ahora que ha descargado, instalado y optimizado Genshin Impact en el ordenador portátil, usted está listo para disfrutar del juego y sus características. Genshin Impact es un juego que ofrece mucho contenido y variedad para jugadores de diferentes gustos y preferencias. Estas son algunas de las cosas que puedes hacer en Genshin Impact:</p>
79
- <ul>
80
-
81
- <li>Recoge y actualiza personajes: Genshin Impact tiene una lista de más de 40 personajes que puedes recopilar y usar en tu grupo. Cada personaje tiene una personalidad única, historia de fondo, elemento, tipo de arma y habilidades. Puedes subir de nivel, ascender y equipar a tus personajes con diferentes artefactos y armas para mejorar sus estadísticas y habilidades. También puedes desbloquear sus constelaciones y talentos para obtener más beneficios y efectos. </li>
82
- <li>Construye tu equipo y estrategia de combate: Genshin Impact tiene un sistema de combate dinámico que te permite cambiar entre cuatro personajes en tu grupo en cualquier momento. También puede combinar diferentes elementos para crear reacciones poderosas que pueden causar más daño, infligir efectos de estado o proporcionar beneficios. Puedes personalizar la composición de tu equipo y la estrategia de combate de acuerdo a los enemigos que enfrentas y los desafíos que encuentras. </li>
83
- <li>Completar misiones y eventos: Genshin Impact tiene una historia rica y atractiva que se desarrolla a través de varias misiones y escenas. Puedes seguir la historia principal del viaje de tu personaje en Teyvat, o ramificarte en diferentes misiones secundarias y misiones mundiales que involucran a otros personajes y facciones. También puede participar en varios eventos que ofrecen recompensas y actividades especiales. </li>
84
- <li>Juega con tus amigos: Genshin Impact soporta el juego cruzado entre dispositivos PC, PS4, iOS y Android. Puede invitar a sus amigos a unirse a su mundo o unirse a los de ellos, independientemente de su plataforma. Puedes cooperar con hasta otros tres jugadores para explorar el mundo, completar dominios y jefes o enfrentarse al Abismo Espiral. También puedes chatear con tus amigos usando mensajes de texto o de voz. </li>
85
- </ul>
86
- <p>Genshin Impact es un juego que te mantendrá entretenido durante horas con sus impresionantes gráficos, banda sonora inmersiva, historia cautivadora, jugabilidad diversa y actualizaciones constantes. Ya sea que juegues solo o con amigos, seguramente tendrás una explosión jugando Genshin Impact en la computadora portátil. </p>
87
- <h1>Conclusión</h1>
88
-
89
- <p>Si quieres jugar este increíble juego en tu computadora portátil, necesitas descargarlo desde el sitio web oficial o la Epic Games Store. También necesita instalarlo y lanzarlo correctamente, y optimizarlo para un mejor rendimiento. Siguiendo los pasos y consejos que hemos proporcionado en este artículo, puede descargar fácilmente Genshin Impact en la computadora portátil y disfrutar de sus características. </p>
90
- <p>¿Qué estás esperando? Descargar Genshin impacto en el ordenador portátil hoy y embarcarse en una aventura épica en Teyvat! </p>
91
- <h2>Preguntas frecuentes</h2>
92
- <p>Aquí están algunas de las preguntas más comunes que la gente pregunta acerca de la descarga de Genshin Impact en la computadora portátil:</p>
93
- <ol>
94
- <li><b>¿Genshin Impact es libre de jugar? </b></li>
95
- <p>Sí, Genshin Impact es gratis. Puedes descargarlo desde el sitio web oficial o la Epic Games Store sin pagar nada. Sin embargo, el juego tiene algunas microtransacciones opcionales que te permiten comprar moneda o artículos en el juego. </p>
96
- <li><b>¿Puedo jugar Genshin Impact sin conexión? </b></li>
97
- <p>No, Genshin Impact requiere una conexión a Internet para jugar. Debes iniciar sesión con tu cuenta miHoYo cada vez que inicies el juego. También necesitas descargar actualizaciones o parches periódicamente para mantener el juego funcionando sin problemas. </p>
98
- <li><b>¿Puedo transferir mi progreso de una plataforma a otra? </b></li>
99
- <p>Sí, Genshin Impact admite cross-save entre dispositivos PC, iOS y Android. Puedes iniciar sesión con la misma cuenta miHoYo en cualquiera de estas plataformas y acceder a tu progreso y datos. Sin embargo, PS4 no soporta cross-save en este momento. </p>
100
- <li><b>¿Puedo jugar a Genshin Impact con un controlador? </b></li>
101
- <p>Sí, Genshin Impact admite la entrada del controlador en PC y PS4. Puede conectar un controlador compatible a su ordenador portátil o PS4 y jugar el juego con él. También puedes ajustar la configuración del controlador en las opciones del juego para personalizar tus botones y sensibilidad. </li>
102
- <li><b>¿Con qué frecuencia se actualiza Genshin Impact? </b></li>
103
-
104
- </ol></p> 64aa2da5cf<br />
105
- <br />
106
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/botocore/waiter.py DELETED
@@ -1,393 +0,0 @@
1
- # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License"). You
4
- # may not use this file except in compliance with the License. A copy of
5
- # the License is located at
6
- #
7
- # http://aws.amazon.com/apache2.0/
8
- #
9
- # or in the "license" file accompanying this file. This file is
10
- # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
- # ANY KIND, either express or implied. See the License for the specific
12
- # language governing permissions and limitations under the License.
13
- import logging
14
- import time
15
-
16
- import jmespath
17
-
18
- from botocore.docs.docstring import WaiterDocstring
19
- from botocore.utils import get_service_module_name
20
-
21
- from . import xform_name
22
- from .exceptions import ClientError, WaiterConfigError, WaiterError
23
-
24
- logger = logging.getLogger(__name__)
25
-
26
-
27
- def create_waiter_with_client(waiter_name, waiter_model, client):
28
- """
29
-
30
- :type waiter_name: str
31
- :param waiter_name: The name of the waiter. The name should match
32
- the name (including the casing) of the key name in the waiter
33
- model file (typically this is CamelCasing).
34
-
35
- :type waiter_model: botocore.waiter.WaiterModel
36
- :param waiter_model: The model for the waiter configuration.
37
-
38
- :type client: botocore.client.BaseClient
39
- :param client: The botocore client associated with the service.
40
-
41
- :rtype: botocore.waiter.Waiter
42
- :return: The waiter object.
43
-
44
- """
45
- single_waiter_config = waiter_model.get_waiter(waiter_name)
46
- operation_name = xform_name(single_waiter_config.operation)
47
- operation_method = NormalizedOperationMethod(
48
- getattr(client, operation_name)
49
- )
50
-
51
- # Create a new wait method that will serve as a proxy to the underlying
52
- # Waiter.wait method. This is needed to attach a docstring to the
53
- # method.
54
- def wait(self, **kwargs):
55
- Waiter.wait(self, **kwargs)
56
-
57
- wait.__doc__ = WaiterDocstring(
58
- waiter_name=waiter_name,
59
- event_emitter=client.meta.events,
60
- service_model=client.meta.service_model,
61
- service_waiter_model=waiter_model,
62
- include_signature=False,
63
- )
64
-
65
- # Rename the waiter class based on the type of waiter.
66
- waiter_class_name = str(
67
- '%s.Waiter.%s'
68
- % (get_service_module_name(client.meta.service_model), waiter_name)
69
- )
70
-
71
- # Create the new waiter class
72
- documented_waiter_cls = type(waiter_class_name, (Waiter,), {'wait': wait})
73
-
74
- # Return an instance of the new waiter class.
75
- return documented_waiter_cls(
76
- waiter_name, single_waiter_config, operation_method
77
- )
78
-
79
-
80
- def is_valid_waiter_error(response):
81
- error = response.get('Error')
82
- if isinstance(error, dict) and 'Code' in error:
83
- return True
84
- return False
85
-
86
-
87
- class NormalizedOperationMethod:
88
- def __init__(self, client_method):
89
- self._client_method = client_method
90
-
91
- def __call__(self, **kwargs):
92
- try:
93
- return self._client_method(**kwargs)
94
- except ClientError as e:
95
- return e.response
96
-
97
-
98
- class WaiterModel:
99
- SUPPORTED_VERSION = 2
100
-
101
- def __init__(self, waiter_config):
102
- """
103
-
104
- Note that the WaiterModel takes ownership of the waiter_config.
105
- It may or may not mutate the waiter_config. If this is a concern,
106
- it is best to make a copy of the waiter config before passing it to
107
- the WaiterModel.
108
-
109
- :type waiter_config: dict
110
- :param waiter_config: The loaded waiter config
111
- from the <service>*.waiters.json file. This can be
112
- obtained from a botocore Loader object as well.
113
-
114
- """
115
- self._waiter_config = waiter_config['waiters']
116
-
117
- # These are part of the public API. Changing these
118
- # will result in having to update the consuming code,
119
- # so don't change unless you really need to.
120
- version = waiter_config.get('version', 'unknown')
121
- self._verify_supported_version(version)
122
- self.version = version
123
- self.waiter_names = list(sorted(waiter_config['waiters'].keys()))
124
-
125
- def _verify_supported_version(self, version):
126
- if version != self.SUPPORTED_VERSION:
127
- raise WaiterConfigError(
128
- error_msg=(
129
- "Unsupported waiter version, supported version "
130
- "must be: %s, but version of waiter config "
131
- "is: %s" % (self.SUPPORTED_VERSION, version)
132
- )
133
- )
134
-
135
- def get_waiter(self, waiter_name):
136
- try:
137
- single_waiter_config = self._waiter_config[waiter_name]
138
- except KeyError:
139
- raise ValueError("Waiter does not exist: %s" % waiter_name)
140
- return SingleWaiterConfig(single_waiter_config)
141
-
142
-
143
- class SingleWaiterConfig:
144
- """Represents the waiter configuration for a single waiter.
145
-
146
- A single waiter is considered the configuration for a single
147
- value associated with a named waiter (i.e TableExists).
148
-
149
- """
150
-
151
- def __init__(self, single_waiter_config):
152
- self._config = single_waiter_config
153
-
154
- # These attributes are part of the public API.
155
- self.description = single_waiter_config.get('description', '')
156
- # Per the spec, these three fields are required.
157
- self.operation = single_waiter_config['operation']
158
- self.delay = single_waiter_config['delay']
159
- self.max_attempts = single_waiter_config['maxAttempts']
160
-
161
- @property
162
- def acceptors(self):
163
- acceptors = []
164
- for acceptor_config in self._config['acceptors']:
165
- acceptor = AcceptorConfig(acceptor_config)
166
- acceptors.append(acceptor)
167
- return acceptors
168
-
169
-
170
- class AcceptorConfig:
171
- def __init__(self, config):
172
- self.state = config['state']
173
- self.matcher = config['matcher']
174
- self.expected = config['expected']
175
- self.argument = config.get('argument')
176
- self.matcher_func = self._create_matcher_func()
177
-
178
- @property
179
- def explanation(self):
180
- if self.matcher == 'path':
181
- return 'For expression "{}" we matched expected path: "{}"'.format(
182
- self.argument,
183
- self.expected,
184
- )
185
- elif self.matcher == 'pathAll':
186
- return (
187
- 'For expression "%s" all members matched excepted path: "%s"'
188
- % (self.argument, self.expected)
189
- )
190
- elif self.matcher == 'pathAny':
191
- return (
192
- 'For expression "%s" we matched expected path: "%s" at least once'
193
- % (self.argument, self.expected)
194
- )
195
- elif self.matcher == 'status':
196
- return 'Matched expected HTTP status code: %s' % self.expected
197
- elif self.matcher == 'error':
198
- return 'Matched expected service error code: %s' % self.expected
199
- else:
200
- return (
201
- 'No explanation for unknown waiter type: "%s"' % self.matcher
202
- )
203
-
204
- def _create_matcher_func(self):
205
- # An acceptor function is a callable that takes a single value. The
206
- # parsed AWS response. Note that the parsed error response is also
207
- # provided in the case of errors, so it's entirely possible to
208
- # handle all the available matcher capabilities in the future.
209
- # There's only three supported matchers, so for now, this is all
210
- # contained to a single method. If this grows, we can expand this
211
- # out to separate methods or even objects.
212
-
213
- if self.matcher == 'path':
214
- return self._create_path_matcher()
215
- elif self.matcher == 'pathAll':
216
- return self._create_path_all_matcher()
217
- elif self.matcher == 'pathAny':
218
- return self._create_path_any_matcher()
219
- elif self.matcher == 'status':
220
- return self._create_status_matcher()
221
- elif self.matcher == 'error':
222
- return self._create_error_matcher()
223
- else:
224
- raise WaiterConfigError(
225
- error_msg="Unknown acceptor: %s" % self.matcher
226
- )
227
-
228
- def _create_path_matcher(self):
229
- expression = jmespath.compile(self.argument)
230
- expected = self.expected
231
-
232
- def acceptor_matches(response):
233
- if is_valid_waiter_error(response):
234
- return
235
- return expression.search(response) == expected
236
-
237
- return acceptor_matches
238
-
239
- def _create_path_all_matcher(self):
240
- expression = jmespath.compile(self.argument)
241
- expected = self.expected
242
-
243
- def acceptor_matches(response):
244
- if is_valid_waiter_error(response):
245
- return
246
- result = expression.search(response)
247
- if not isinstance(result, list) or not result:
248
- # pathAll matcher must result in a list.
249
- # Also we require at least one element in the list,
250
- # that is, an empty list should not result in this
251
- # acceptor match.
252
- return False
253
- for element in result:
254
- if element != expected:
255
- return False
256
- return True
257
-
258
- return acceptor_matches
259
-
260
- def _create_path_any_matcher(self):
261
- expression = jmespath.compile(self.argument)
262
- expected = self.expected
263
-
264
- def acceptor_matches(response):
265
- if is_valid_waiter_error(response):
266
- return
267
- result = expression.search(response)
268
- if not isinstance(result, list) or not result:
269
- # pathAny matcher must result in a list.
270
- # Also we require at least one element in the list,
271
- # that is, an empty list should not result in this
272
- # acceptor match.
273
- return False
274
- for element in result:
275
- if element == expected:
276
- return True
277
- return False
278
-
279
- return acceptor_matches
280
-
281
- def _create_status_matcher(self):
282
- expected = self.expected
283
-
284
- def acceptor_matches(response):
285
- # We don't have any requirements on the expected incoming data
286
- # other than it is a dict, so we don't assume there's
287
- # a ResponseMetadata.HTTPStatusCode.
288
- status_code = response.get('ResponseMetadata', {}).get(
289
- 'HTTPStatusCode'
290
- )
291
- return status_code == expected
292
-
293
- return acceptor_matches
294
-
295
- def _create_error_matcher(self):
296
- expected = self.expected
297
-
298
- def acceptor_matches(response):
299
- # When the client encounters an error, it will normally raise
300
- # an exception. However, the waiter implementation will catch
301
- # this exception, and instead send us the parsed error
302
- # response. So response is still a dictionary, and in the case
303
- # of an error response will contain the "Error" and
304
- # "ResponseMetadata" key.
305
- return response.get("Error", {}).get("Code", "") == expected
306
-
307
- return acceptor_matches
308
-
309
-
310
- class Waiter:
311
- def __init__(self, name, config, operation_method):
312
- """
313
-
314
- :type name: string
315
- :param name: The name of the waiter
316
-
317
- :type config: botocore.waiter.SingleWaiterConfig
318
- :param config: The configuration for the waiter.
319
-
320
- :type operation_method: callable
321
- :param operation_method: A callable that accepts **kwargs
322
- and returns a response. For example, this can be
323
- a method from a botocore client.
324
-
325
- """
326
- self._operation_method = operation_method
327
- # The two attributes are exposed to allow for introspection
328
- # and documentation.
329
- self.name = name
330
- self.config = config
331
-
332
- def wait(self, **kwargs):
333
- acceptors = list(self.config.acceptors)
334
- current_state = 'waiting'
335
- # pop the invocation specific config
336
- config = kwargs.pop('WaiterConfig', {})
337
- sleep_amount = config.get('Delay', self.config.delay)
338
- max_attempts = config.get('MaxAttempts', self.config.max_attempts)
339
- last_matched_acceptor = None
340
- num_attempts = 0
341
-
342
- while True:
343
- response = self._operation_method(**kwargs)
344
- num_attempts += 1
345
- for acceptor in acceptors:
346
- if acceptor.matcher_func(response):
347
- last_matched_acceptor = acceptor
348
- current_state = acceptor.state
349
- break
350
- else:
351
- # If none of the acceptors matched, we should
352
- # transition to the failure state if an error
353
- # response was received.
354
- if is_valid_waiter_error(response):
355
- # Transition to a failure state, which we
356
- # can just handle here by raising an exception.
357
- raise WaiterError(
358
- name=self.name,
359
- reason='An error occurred (%s): %s'
360
- % (
361
- response['Error'].get('Code', 'Unknown'),
362
- response['Error'].get('Message', 'Unknown'),
363
- ),
364
- last_response=response,
365
- )
366
- if current_state == 'success':
367
- logger.debug(
368
- "Waiting complete, waiter matched the " "success state."
369
- )
370
- return
371
- if current_state == 'failure':
372
- reason = 'Waiter encountered a terminal failure state: %s' % (
373
- acceptor.explanation
374
- )
375
- raise WaiterError(
376
- name=self.name,
377
- reason=reason,
378
- last_response=response,
379
- )
380
- if num_attempts >= max_attempts:
381
- if last_matched_acceptor is None:
382
- reason = 'Max attempts exceeded'
383
- else:
384
- reason = (
385
- 'Max attempts exceeded. Previously accepted state: %s'
386
- % (acceptor.explanation)
387
- )
388
- raise WaiterError(
389
- name=self.name,
390
- reason=reason,
391
- last_response=response,
392
- )
393
- time.sleep(sleep_amount)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/urllib3/util/ssl_.py DELETED
@@ -1,495 +0,0 @@
1
- from __future__ import absolute_import
2
-
3
- import hmac
4
- import os
5
- import sys
6
- import warnings
7
- from binascii import hexlify, unhexlify
8
- from hashlib import md5, sha1, sha256
9
-
10
- from ..exceptions import (
11
- InsecurePlatformWarning,
12
- ProxySchemeUnsupported,
13
- SNIMissingWarning,
14
- SSLError,
15
- )
16
- from ..packages import six
17
- from .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE
18
-
19
- SSLContext = None
20
- SSLTransport = None
21
- HAS_SNI = False
22
- IS_PYOPENSSL = False
23
- IS_SECURETRANSPORT = False
24
- ALPN_PROTOCOLS = ["http/1.1"]
25
-
26
- # Maps the length of a digest to a possible hash function producing this digest
27
- HASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256}
28
-
29
-
30
- def _const_compare_digest_backport(a, b):
31
- """
32
- Compare two digests of equal length in constant time.
33
-
34
- The digests must be of type str/bytes.
35
- Returns True if the digests match, and False otherwise.
36
- """
37
- result = abs(len(a) - len(b))
38
- for left, right in zip(bytearray(a), bytearray(b)):
39
- result |= left ^ right
40
- return result == 0
41
-
42
-
43
- _const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport)
44
-
45
- try: # Test for SSL features
46
- import ssl
47
- from ssl import CERT_REQUIRED, wrap_socket
48
- except ImportError:
49
- pass
50
-
51
- try:
52
- from ssl import HAS_SNI # Has SNI?
53
- except ImportError:
54
- pass
55
-
56
- try:
57
- from .ssltransport import SSLTransport
58
- except ImportError:
59
- pass
60
-
61
-
62
- try: # Platform-specific: Python 3.6
63
- from ssl import PROTOCOL_TLS
64
-
65
- PROTOCOL_SSLv23 = PROTOCOL_TLS
66
- except ImportError:
67
- try:
68
- from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS
69
-
70
- PROTOCOL_SSLv23 = PROTOCOL_TLS
71
- except ImportError:
72
- PROTOCOL_SSLv23 = PROTOCOL_TLS = 2
73
-
74
- try:
75
- from ssl import PROTOCOL_TLS_CLIENT
76
- except ImportError:
77
- PROTOCOL_TLS_CLIENT = PROTOCOL_TLS
78
-
79
-
80
- try:
81
- from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3
82
- except ImportError:
83
- OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000
84
- OP_NO_COMPRESSION = 0x20000
85
-
86
-
87
- try: # OP_NO_TICKET was added in Python 3.6
88
- from ssl import OP_NO_TICKET
89
- except ImportError:
90
- OP_NO_TICKET = 0x4000
91
-
92
-
93
- # A secure default.
94
- # Sources for more information on TLS ciphers:
95
- #
96
- # - https://wiki.mozilla.org/Security/Server_Side_TLS
97
- # - https://www.ssllabs.com/projects/best-practices/index.html
98
- # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
99
- #
100
- # The general intent is:
101
- # - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
102
- # - prefer ECDHE over DHE for better performance,
103
- # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
104
- # security,
105
- # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,
106
- # - disable NULL authentication, MD5 MACs, DSS, and other
107
- # insecure ciphers for security reasons.
108
- # - NOTE: TLS 1.3 cipher suites are managed through a different interface
109
- # not exposed by CPython (yet!) and are enabled by default if they're available.
110
- DEFAULT_CIPHERS = ":".join(
111
- [
112
- "ECDHE+AESGCM",
113
- "ECDHE+CHACHA20",
114
- "DHE+AESGCM",
115
- "DHE+CHACHA20",
116
- "ECDH+AESGCM",
117
- "DH+AESGCM",
118
- "ECDH+AES",
119
- "DH+AES",
120
- "RSA+AESGCM",
121
- "RSA+AES",
122
- "!aNULL",
123
- "!eNULL",
124
- "!MD5",
125
- "!DSS",
126
- ]
127
- )
128
-
129
- try:
130
- from ssl import SSLContext # Modern SSL?
131
- except ImportError:
132
-
133
- class SSLContext(object): # Platform-specific: Python 2
134
- def __init__(self, protocol_version):
135
- self.protocol = protocol_version
136
- # Use default values from a real SSLContext
137
- self.check_hostname = False
138
- self.verify_mode = ssl.CERT_NONE
139
- self.ca_certs = None
140
- self.options = 0
141
- self.certfile = None
142
- self.keyfile = None
143
- self.ciphers = None
144
-
145
- def load_cert_chain(self, certfile, keyfile):
146
- self.certfile = certfile
147
- self.keyfile = keyfile
148
-
149
- def load_verify_locations(self, cafile=None, capath=None, cadata=None):
150
- self.ca_certs = cafile
151
-
152
- if capath is not None:
153
- raise SSLError("CA directories not supported in older Pythons")
154
-
155
- if cadata is not None:
156
- raise SSLError("CA data not supported in older Pythons")
157
-
158
- def set_ciphers(self, cipher_suite):
159
- self.ciphers = cipher_suite
160
-
161
- def wrap_socket(self, socket, server_hostname=None, server_side=False):
162
- warnings.warn(
163
- "A true SSLContext object is not available. This prevents "
164
- "urllib3 from configuring SSL appropriately and may cause "
165
- "certain SSL connections to fail. You can upgrade to a newer "
166
- "version of Python to solve this. For more information, see "
167
- "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
168
- "#ssl-warnings",
169
- InsecurePlatformWarning,
170
- )
171
- kwargs = {
172
- "keyfile": self.keyfile,
173
- "certfile": self.certfile,
174
- "ca_certs": self.ca_certs,
175
- "cert_reqs": self.verify_mode,
176
- "ssl_version": self.protocol,
177
- "server_side": server_side,
178
- }
179
- return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
180
-
181
-
182
- def assert_fingerprint(cert, fingerprint):
183
- """
184
- Checks if given fingerprint matches the supplied certificate.
185
-
186
- :param cert:
187
- Certificate as bytes object.
188
- :param fingerprint:
189
- Fingerprint as string of hexdigits, can be interspersed by colons.
190
- """
191
-
192
- fingerprint = fingerprint.replace(":", "").lower()
193
- digest_length = len(fingerprint)
194
- hashfunc = HASHFUNC_MAP.get(digest_length)
195
- if not hashfunc:
196
- raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint))
197
-
198
- # We need encode() here for py32; works on py2 and p33.
199
- fingerprint_bytes = unhexlify(fingerprint.encode())
200
-
201
- cert_digest = hashfunc(cert).digest()
202
-
203
- if not _const_compare_digest(cert_digest, fingerprint_bytes):
204
- raise SSLError(
205
- 'Fingerprints did not match. Expected "{0}", got "{1}".'.format(
206
- fingerprint, hexlify(cert_digest)
207
- )
208
- )
209
-
210
-
211
- def resolve_cert_reqs(candidate):
212
- """
213
- Resolves the argument to a numeric constant, which can be passed to
214
- the wrap_socket function/method from the ssl module.
215
- Defaults to :data:`ssl.CERT_REQUIRED`.
216
- If given a string it is assumed to be the name of the constant in the
217
- :mod:`ssl` module or its abbreviation.
218
- (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
219
- If it's neither `None` nor a string we assume it is already the numeric
220
- constant which can directly be passed to wrap_socket.
221
- """
222
- if candidate is None:
223
- return CERT_REQUIRED
224
-
225
- if isinstance(candidate, str):
226
- res = getattr(ssl, candidate, None)
227
- if res is None:
228
- res = getattr(ssl, "CERT_" + candidate)
229
- return res
230
-
231
- return candidate
232
-
233
-
234
- def resolve_ssl_version(candidate):
235
- """
236
- like resolve_cert_reqs
237
- """
238
- if candidate is None:
239
- return PROTOCOL_TLS
240
-
241
- if isinstance(candidate, str):
242
- res = getattr(ssl, candidate, None)
243
- if res is None:
244
- res = getattr(ssl, "PROTOCOL_" + candidate)
245
- return res
246
-
247
- return candidate
248
-
249
-
250
- def create_urllib3_context(
251
- ssl_version=None, cert_reqs=None, options=None, ciphers=None
252
- ):
253
- """All arguments have the same meaning as ``ssl_wrap_socket``.
254
-
255
- By default, this function does a lot of the same work that
256
- ``ssl.create_default_context`` does on Python 3.4+. It:
257
-
258
- - Disables SSLv2, SSLv3, and compression
259
- - Sets a restricted set of server ciphers
260
-
261
- If you wish to enable SSLv3, you can do::
262
-
263
- from pip._vendor.urllib3.util import ssl_
264
- context = ssl_.create_urllib3_context()
265
- context.options &= ~ssl_.OP_NO_SSLv3
266
-
267
- You can do the same to enable compression (substituting ``COMPRESSION``
268
- for ``SSLv3`` in the last line above).
269
-
270
- :param ssl_version:
271
- The desired protocol version to use. This will default to
272
- PROTOCOL_SSLv23 which will negotiate the highest protocol that both
273
- the server and your installation of OpenSSL support.
274
- :param cert_reqs:
275
- Whether to require the certificate verification. This defaults to
276
- ``ssl.CERT_REQUIRED``.
277
- :param options:
278
- Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
279
- ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.
280
- :param ciphers:
281
- Which cipher suites to allow the server to select.
282
- :returns:
283
- Constructed SSLContext object with specified options
284
- :rtype: SSLContext
285
- """
286
- # PROTOCOL_TLS is deprecated in Python 3.10
287
- if not ssl_version or ssl_version == PROTOCOL_TLS:
288
- ssl_version = PROTOCOL_TLS_CLIENT
289
-
290
- context = SSLContext(ssl_version)
291
-
292
- context.set_ciphers(ciphers or DEFAULT_CIPHERS)
293
-
294
- # Setting the default here, as we may have no ssl module on import
295
- cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
296
-
297
- if options is None:
298
- options = 0
299
- # SSLv2 is easily broken and is considered harmful and dangerous
300
- options |= OP_NO_SSLv2
301
- # SSLv3 has several problems and is now dangerous
302
- options |= OP_NO_SSLv3
303
- # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
304
- # (issue #309)
305
- options |= OP_NO_COMPRESSION
306
- # TLSv1.2 only. Unless set explicitly, do not request tickets.
307
- # This may save some bandwidth on wire, and although the ticket is encrypted,
308
- # there is a risk associated with it being on wire,
309
- # if the server is not rotating its ticketing keys properly.
310
- options |= OP_NO_TICKET
311
-
312
- context.options |= options
313
-
314
- # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
315
- # necessary for conditional client cert authentication with TLS 1.3.
316
- # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older
317
- # versions of Python. We only enable on Python 3.7.4+ or if certificate
318
- # verification is enabled to work around Python issue #37428
319
- # See: https://bugs.python.org/issue37428
320
- if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr(
321
- context, "post_handshake_auth", None
322
- ) is not None:
323
- context.post_handshake_auth = True
324
-
325
- def disable_check_hostname():
326
- if (
327
- getattr(context, "check_hostname", None) is not None
328
- ): # Platform-specific: Python 3.2
329
- # We do our own verification, including fingerprints and alternative
330
- # hostnames. So disable it here
331
- context.check_hostname = False
332
-
333
- # The order of the below lines setting verify_mode and check_hostname
334
- # matter due to safe-guards SSLContext has to prevent an SSLContext with
335
- # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more
336
- # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used
337
- # or not so we don't know the initial state of the freshly created SSLContext.
338
- if cert_reqs == ssl.CERT_REQUIRED:
339
- context.verify_mode = cert_reqs
340
- disable_check_hostname()
341
- else:
342
- disable_check_hostname()
343
- context.verify_mode = cert_reqs
344
-
345
- # Enable logging of TLS session keys via defacto standard environment variable
346
- # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.
347
- if hasattr(context, "keylog_filename"):
348
- sslkeylogfile = os.environ.get("SSLKEYLOGFILE")
349
- if sslkeylogfile:
350
- context.keylog_filename = sslkeylogfile
351
-
352
- return context
353
-
354
-
355
- def ssl_wrap_socket(
356
- sock,
357
- keyfile=None,
358
- certfile=None,
359
- cert_reqs=None,
360
- ca_certs=None,
361
- server_hostname=None,
362
- ssl_version=None,
363
- ciphers=None,
364
- ssl_context=None,
365
- ca_cert_dir=None,
366
- key_password=None,
367
- ca_cert_data=None,
368
- tls_in_tls=False,
369
- ):
370
- """
371
- All arguments except for server_hostname, ssl_context, and ca_cert_dir have
372
- the same meaning as they do when using :func:`ssl.wrap_socket`.
373
-
374
- :param server_hostname:
375
- When SNI is supported, the expected hostname of the certificate
376
- :param ssl_context:
377
- A pre-made :class:`SSLContext` object. If none is provided, one will
378
- be created using :func:`create_urllib3_context`.
379
- :param ciphers:
380
- A string of ciphers we wish the client to support.
381
- :param ca_cert_dir:
382
- A directory containing CA certificates in multiple separate files, as
383
- supported by OpenSSL's -CApath flag or the capath argument to
384
- SSLContext.load_verify_locations().
385
- :param key_password:
386
- Optional password if the keyfile is encrypted.
387
- :param ca_cert_data:
388
- Optional string containing CA certificates in PEM format suitable for
389
- passing as the cadata parameter to SSLContext.load_verify_locations()
390
- :param tls_in_tls:
391
- Use SSLTransport to wrap the existing socket.
392
- """
393
- context = ssl_context
394
- if context is None:
395
- # Note: This branch of code and all the variables in it are no longer
396
- # used by urllib3 itself. We should consider deprecating and removing
397
- # this code.
398
- context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)
399
-
400
- if ca_certs or ca_cert_dir or ca_cert_data:
401
- try:
402
- context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)
403
- except (IOError, OSError) as e:
404
- raise SSLError(e)
405
-
406
- elif ssl_context is None and hasattr(context, "load_default_certs"):
407
- # try to load OS default certs; works well on Windows (require Python3.4+)
408
- context.load_default_certs()
409
-
410
- # Attempt to detect if we get the goofy behavior of the
411
- # keyfile being encrypted and OpenSSL asking for the
412
- # passphrase via the terminal and instead error out.
413
- if keyfile and key_password is None and _is_key_file_encrypted(keyfile):
414
- raise SSLError("Client private key is encrypted, password is required")
415
-
416
- if certfile:
417
- if key_password is None:
418
- context.load_cert_chain(certfile, keyfile)
419
- else:
420
- context.load_cert_chain(certfile, keyfile, key_password)
421
-
422
- try:
423
- if hasattr(context, "set_alpn_protocols"):
424
- context.set_alpn_protocols(ALPN_PROTOCOLS)
425
- except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols
426
- pass
427
-
428
- # If we detect server_hostname is an IP address then the SNI
429
- # extension should not be used according to RFC3546 Section 3.1
430
- use_sni_hostname = server_hostname and not is_ipaddress(server_hostname)
431
- # SecureTransport uses server_hostname in certificate verification.
432
- send_sni = (use_sni_hostname and HAS_SNI) or (
433
- IS_SECURETRANSPORT and server_hostname
434
- )
435
- # Do not warn the user if server_hostname is an invalid SNI hostname.
436
- if not HAS_SNI and use_sni_hostname:
437
- warnings.warn(
438
- "An HTTPS request has been made, but the SNI (Server Name "
439
- "Indication) extension to TLS is not available on this platform. "
440
- "This may cause the server to present an incorrect TLS "
441
- "certificate, which can cause validation failures. You can upgrade to "
442
- "a newer version of Python to solve this. For more information, see "
443
- "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
444
- "#ssl-warnings",
445
- SNIMissingWarning,
446
- )
447
-
448
- if send_sni:
449
- ssl_sock = _ssl_wrap_socket_impl(
450
- sock, context, tls_in_tls, server_hostname=server_hostname
451
- )
452
- else:
453
- ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
454
- return ssl_sock
455
-
456
-
457
- def is_ipaddress(hostname):
458
- """Detects whether the hostname given is an IPv4 or IPv6 address.
459
- Also detects IPv6 addresses with Zone IDs.
460
-
461
- :param str hostname: Hostname to examine.
462
- :return: True if the hostname is an IP address, False otherwise.
463
- """
464
- if not six.PY2 and isinstance(hostname, bytes):
465
- # IDN A-label bytes are ASCII compatible.
466
- hostname = hostname.decode("ascii")
467
- return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))
468
-
469
-
470
- def _is_key_file_encrypted(key_file):
471
- """Detects if a key file is encrypted or not."""
472
- with open(key_file, "r") as f:
473
- for line in f:
474
- # Look for Proc-Type: 4,ENCRYPTED
475
- if "ENCRYPTED" in line:
476
- return True
477
-
478
- return False
479
-
480
-
481
- def _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None):
482
- if tls_in_tls:
483
- if not SSLTransport:
484
- # Import error, ssl is not available.
485
- raise ProxySchemeUnsupported(
486
- "TLS in TLS requires support for the 'ssl' module"
487
- )
488
-
489
- SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)
490
- return SSLTransport(sock, ssl_context, server_hostname)
491
-
492
- if server_hostname:
493
- return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
494
- else:
495
- return ssl_context.wrap_socket(sock)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/command/check.py DELETED
@@ -1,151 +0,0 @@
1
- """distutils.command.check
2
-
3
- Implements the Distutils 'check' command.
4
- """
5
- import contextlib
6
-
7
- from distutils.core import Command
8
- from distutils.errors import DistutilsSetupError
9
-
10
- with contextlib.suppress(ImportError):
11
- import docutils.utils
12
- import docutils.parsers.rst
13
- import docutils.frontend
14
- import docutils.nodes
15
-
16
- class SilentReporter(docutils.utils.Reporter):
17
- def __init__(
18
- self,
19
- source,
20
- report_level,
21
- halt_level,
22
- stream=None,
23
- debug=0,
24
- encoding='ascii',
25
- error_handler='replace',
26
- ):
27
- self.messages = []
28
- super().__init__(
29
- source, report_level, halt_level, stream, debug, encoding, error_handler
30
- )
31
-
32
- def system_message(self, level, message, *children, **kwargs):
33
- self.messages.append((level, message, children, kwargs))
34
- return docutils.nodes.system_message(
35
- message, level=level, type=self.levels[level], *children, **kwargs
36
- )
37
-
38
-
39
- class check(Command):
40
- """This command checks the meta-data of the package."""
41
-
42
- description = "perform some checks on the package"
43
- user_options = [
44
- ('metadata', 'm', 'Verify meta-data'),
45
- (
46
- 'restructuredtext',
47
- 'r',
48
- (
49
- 'Checks if long string meta-data syntax '
50
- 'are reStructuredText-compliant'
51
- ),
52
- ),
53
- ('strict', 's', 'Will exit with an error if a check fails'),
54
- ]
55
-
56
- boolean_options = ['metadata', 'restructuredtext', 'strict']
57
-
58
- def initialize_options(self):
59
- """Sets default values for options."""
60
- self.restructuredtext = 0
61
- self.metadata = 1
62
- self.strict = 0
63
- self._warnings = 0
64
-
65
- def finalize_options(self):
66
- pass
67
-
68
- def warn(self, msg):
69
- """Counts the number of warnings that occurs."""
70
- self._warnings += 1
71
- return Command.warn(self, msg)
72
-
73
- def run(self):
74
- """Runs the command."""
75
- # perform the various tests
76
- if self.metadata:
77
- self.check_metadata()
78
- if self.restructuredtext:
79
- if 'docutils' in globals():
80
- try:
81
- self.check_restructuredtext()
82
- except TypeError as exc:
83
- raise DistutilsSetupError(str(exc))
84
- elif self.strict:
85
- raise DistutilsSetupError('The docutils package is needed.')
86
-
87
- # let's raise an error in strict mode, if we have at least
88
- # one warning
89
- if self.strict and self._warnings > 0:
90
- raise DistutilsSetupError('Please correct your package.')
91
-
92
- def check_metadata(self):
93
- """Ensures that all required elements of meta-data are supplied.
94
-
95
- Required fields:
96
- name, version
97
-
98
- Warns if any are missing.
99
- """
100
- metadata = self.distribution.metadata
101
-
102
- missing = []
103
- for attr in 'name', 'version':
104
- if not getattr(metadata, attr, None):
105
- missing.append(attr)
106
-
107
- if missing:
108
- self.warn("missing required meta-data: %s" % ', '.join(missing))
109
-
110
- def check_restructuredtext(self):
111
- """Checks if the long string fields are reST-compliant."""
112
- data = self.distribution.get_long_description()
113
- for warning in self._check_rst_data(data):
114
- line = warning[-1].get('line')
115
- if line is None:
116
- warning = warning[1]
117
- else:
118
- warning = '{} (line {})'.format(warning[1], line)
119
- self.warn(warning)
120
-
121
- def _check_rst_data(self, data):
122
- """Returns warnings when the provided data doesn't compile."""
123
- # the include and csv_table directives need this to be a path
124
- source_path = self.distribution.script_name or 'setup.py'
125
- parser = docutils.parsers.rst.Parser()
126
- settings = docutils.frontend.OptionParser(
127
- components=(docutils.parsers.rst.Parser,)
128
- ).get_default_values()
129
- settings.tab_width = 4
130
- settings.pep_references = None
131
- settings.rfc_references = None
132
- reporter = SilentReporter(
133
- source_path,
134
- settings.report_level,
135
- settings.halt_level,
136
- stream=settings.warning_stream,
137
- debug=settings.debug,
138
- encoding=settings.error_encoding,
139
- error_handler=settings.error_encoding_error_handler,
140
- )
141
-
142
- document = docutils.nodes.document(settings, reporter, source=source_path)
143
- document.note_source(source_path, -1)
144
- try:
145
- parser.parse(data, document)
146
- except AttributeError as e:
147
- reporter.messages.append(
148
- (-1, 'Could not finish the parsing: %s.' % e, '', {})
149
- )
150
-
151
- return reporter.messages
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BramVanroy/spacey_conll/README.md DELETED
@@ -1,11 +0,0 @@
1
- ---
2
- title: Parsing to CoNLL-U with spaCy
3
- emoji: 📝
4
- colorFrom: indigo
5
- colorTo: green
6
- sdk: docker
7
- app_port: 8501
8
- app_file: app.py
9
- pinned: false
10
- license: gpl-3.0
11
- ---
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/pybind11/tests/test_modules.cpp DELETED
@@ -1,98 +0,0 @@
1
- /*
2
- tests/test_modules.cpp -- nested modules, importing modules, and
3
- internal references
4
-
5
- Copyright (c) 2016 Wenzel Jakob <[email protected]>
6
-
7
- All rights reserved. Use of this source code is governed by a
8
- BSD-style license that can be found in the LICENSE file.
9
- */
10
-
11
- #include "pybind11_tests.h"
12
- #include "constructor_stats.h"
13
-
14
- TEST_SUBMODULE(modules, m) {
15
- // test_nested_modules
16
- py::module m_sub = m.def_submodule("subsubmodule");
17
- m_sub.def("submodule_func", []() { return "submodule_func()"; });
18
-
19
- // test_reference_internal
20
- class A {
21
- public:
22
- A(int v) : v(v) { print_created(this, v); }
23
- ~A() { print_destroyed(this); }
24
- A(const A&) { print_copy_created(this); }
25
- A& operator=(const A &copy) { print_copy_assigned(this); v = copy.v; return *this; }
26
- std::string toString() { return "A[" + std::to_string(v) + "]"; }
27
- private:
28
- int v;
29
- };
30
- py::class_<A>(m_sub, "A")
31
- .def(py::init<int>())
32
- .def("__repr__", &A::toString);
33
-
34
- class B {
35
- public:
36
- B() { print_default_created(this); }
37
- ~B() { print_destroyed(this); }
38
- B(const B&) { print_copy_created(this); }
39
- B& operator=(const B &copy) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; }
40
- A &get_a1() { return a1; }
41
- A &get_a2() { return a2; }
42
-
43
- A a1{1};
44
- A a2{2};
45
- };
46
- py::class_<B>(m_sub, "B")
47
- .def(py::init<>())
48
- .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal)
49
- .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal)
50
- .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default
51
- .def_readwrite("a2", &B::a2);
52
-
53
- m.attr("OD") = py::module::import("collections").attr("OrderedDict");
54
-
55
- // test_duplicate_registration
56
- // Registering two things with the same name
57
- m.def("duplicate_registration", []() {
58
- class Dupe1 { };
59
- class Dupe2 { };
60
- class Dupe3 { };
61
- class DupeException { };
62
-
63
- auto dm = py::module("dummy");
64
- auto failures = py::list();
65
-
66
- py::class_<Dupe1>(dm, "Dupe1");
67
- py::class_<Dupe2>(dm, "Dupe2");
68
- dm.def("dupe1_factory", []() { return Dupe1(); });
69
- py::exception<DupeException>(dm, "DupeException");
70
-
71
- try {
72
- py::class_<Dupe1>(dm, "Dupe1");
73
- failures.append("Dupe1 class");
74
- } catch (std::runtime_error &) {}
75
- try {
76
- dm.def("Dupe1", []() { return Dupe1(); });
77
- failures.append("Dupe1 function");
78
- } catch (std::runtime_error &) {}
79
- try {
80
- py::class_<Dupe3>(dm, "dupe1_factory");
81
- failures.append("dupe1_factory");
82
- } catch (std::runtime_error &) {}
83
- try {
84
- py::exception<Dupe3>(dm, "Dupe2");
85
- failures.append("Dupe2");
86
- } catch (std::runtime_error &) {}
87
- try {
88
- dm.def("DupeException", []() { return 30; });
89
- failures.append("DupeException1");
90
- } catch (std::runtime_error &) {}
91
- try {
92
- py::class_<DupeException>(dm, "DupeException");
93
- failures.append("DupeException2");
94
- } catch (std::runtime_error &) {}
95
-
96
- return failures;
97
- });
98
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/system/detail/adl/transform.h DELETED
@@ -1,44 +0,0 @@
1
- /*
2
- * Copyright 2008-2013 NVIDIA Corporation
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a fill of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- #pragma once
18
-
19
- #include <thrust/detail/config.h>
20
-
21
- // the purpose of this header is to #include the transform.h header
22
- // of the sequential, host, and device systems. It should be #included in any
23
- // code which uses adl to dispatch transform
24
-
25
- #include <thrust/system/detail/sequential/transform.h>
26
-
27
- // SCons can't see through the #defines below to figure out what this header
28
- // includes, so we fake it out by specifying all possible files we might end up
29
- // including inside an #if 0.
30
- #if 0
31
- #include <thrust/system/cpp/detail/transform.h>
32
- #include <thrust/system/cuda/detail/transform.h>
33
- #include <thrust/system/omp/detail/transform.h>
34
- #include <thrust/system/tbb/detail/transform.h>
35
- #endif
36
-
37
- #define __THRUST_HOST_SYSTEM_TRANSFORM_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/transform.h>
38
- #include __THRUST_HOST_SYSTEM_TRANSFORM_HEADER
39
- #undef __THRUST_HOST_SYSTEM_TRANSFORM_HEADER
40
-
41
- #define __THRUST_DEVICE_SYSTEM_TRANSFORM_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/transform.h>
42
- #include __THRUST_DEVICE_SYSTEM_TRANSFORM_HEADER
43
- #undef __THRUST_DEVICE_SYSTEM_TRANSFORM_HEADER
44
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/WALT/mmdet/models/roi_heads/mask_heads/fused_semantic_head.py DELETED
@@ -1,107 +0,0 @@
1
- import torch.nn as nn
2
- import torch.nn.functional as F
3
- from mmcv.cnn import ConvModule, kaiming_init
4
- from mmcv.runner import auto_fp16, force_fp32
5
-
6
- from mmdet.models.builder import HEADS
7
-
8
-
9
- @HEADS.register_module()
10
- class FusedSemanticHead(nn.Module):
11
- r"""Multi-level fused semantic segmentation head.
12
-
13
- .. code-block:: none
14
-
15
- in_1 -> 1x1 conv ---
16
- |
17
- in_2 -> 1x1 conv -- |
18
- ||
19
- in_3 -> 1x1 conv - ||
20
- ||| /-> 1x1 conv (mask prediction)
21
- in_4 -> 1x1 conv -----> 3x3 convs (*4)
22
- | \-> 1x1 conv (feature)
23
- in_5 -> 1x1 conv ---
24
- """ # noqa: W605
25
-
26
- def __init__(self,
27
- num_ins,
28
- fusion_level,
29
- num_convs=4,
30
- in_channels=256,
31
- conv_out_channels=256,
32
- num_classes=183,
33
- ignore_label=255,
34
- loss_weight=0.2,
35
- conv_cfg=None,
36
- norm_cfg=None):
37
- super(FusedSemanticHead, self).__init__()
38
- self.num_ins = num_ins
39
- self.fusion_level = fusion_level
40
- self.num_convs = num_convs
41
- self.in_channels = in_channels
42
- self.conv_out_channels = conv_out_channels
43
- self.num_classes = num_classes
44
- self.ignore_label = ignore_label
45
- self.loss_weight = loss_weight
46
- self.conv_cfg = conv_cfg
47
- self.norm_cfg = norm_cfg
48
- self.fp16_enabled = False
49
-
50
- self.lateral_convs = nn.ModuleList()
51
- for i in range(self.num_ins):
52
- self.lateral_convs.append(
53
- ConvModule(
54
- self.in_channels,
55
- self.in_channels,
56
- 1,
57
- conv_cfg=self.conv_cfg,
58
- norm_cfg=self.norm_cfg,
59
- inplace=False))
60
-
61
- self.convs = nn.ModuleList()
62
- for i in range(self.num_convs):
63
- in_channels = self.in_channels if i == 0 else conv_out_channels
64
- self.convs.append(
65
- ConvModule(
66
- in_channels,
67
- conv_out_channels,
68
- 3,
69
- padding=1,
70
- conv_cfg=self.conv_cfg,
71
- norm_cfg=self.norm_cfg))
72
- self.conv_embedding = ConvModule(
73
- conv_out_channels,
74
- conv_out_channels,
75
- 1,
76
- conv_cfg=self.conv_cfg,
77
- norm_cfg=self.norm_cfg)
78
- self.conv_logits = nn.Conv2d(conv_out_channels, self.num_classes, 1)
79
-
80
- self.criterion = nn.CrossEntropyLoss(ignore_index=ignore_label)
81
-
82
- def init_weights(self):
83
- kaiming_init(self.conv_logits)
84
-
85
- @auto_fp16()
86
- def forward(self, feats):
87
- x = self.lateral_convs[self.fusion_level](feats[self.fusion_level])
88
- fused_size = tuple(x.shape[-2:])
89
- for i, feat in enumerate(feats):
90
- if i != self.fusion_level:
91
- feat = F.interpolate(
92
- feat, size=fused_size, mode='bilinear', align_corners=True)
93
- x += self.lateral_convs[i](feat)
94
-
95
- for i in range(self.num_convs):
96
- x = self.convs[i](x)
97
-
98
- mask_pred = self.conv_logits(x)
99
- x = self.conv_embedding(x)
100
- return mask_pred, x
101
-
102
- @force_fp32(apply_to=('mask_pred', ))
103
- def loss(self, mask_pred, labels):
104
- labels = labels.squeeze(1).long()
105
- loss_semantic_seg = self.criterion(mask_pred, labels)
106
- loss_semantic_seg *= self.loss_weight
107
- return loss_semantic_seg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChallengeHub/Chinese-LangChain/app_modules/presets.py DELETED
@@ -1,82 +0,0 @@
1
- # -*- coding:utf-8 -*-
2
- import gradio as gr
3
-
4
-
5
- title = """<h1 align="left" style="min-width:200px; margin-top:0;"> <img src="https://raw.githubusercontent.com/twitter/twemoji/master/assets/svg/1f432.svg" width="32px" style="display: inline"> Baize-7B </h1>"""
6
- description_top = """\
7
- <div align="left">
8
- <p>
9
- Disclaimer: The LLaMA model is a third-party version available on Hugging Face model hub. This demo should be used for research purposes only. Commercial use is strictly prohibited. The model output is not censored and the authors do not endorse the opinions in the generated content. Use at your own risk.
10
- </p >
11
- </div>
12
- """
13
- description = """\
14
- <div align="center" style="margin:16px 0">
15
- The demo is built on <a href="https://github.com/GaiZhenbiao/ChuanhuChatGPT">ChuanhuChatGPT</a>.
16
- </div>
17
- """
18
- CONCURRENT_COUNT = 100
19
-
20
-
21
- ALREADY_CONVERTED_MARK = "<!-- ALREADY CONVERTED BY PARSER. -->"
22
-
23
- small_and_beautiful_theme = gr.themes.Soft(
24
- primary_hue=gr.themes.Color(
25
- c50="#02C160",
26
- c100="rgba(2, 193, 96, 0.2)",
27
- c200="#02C160",
28
- c300="rgba(2, 193, 96, 0.32)",
29
- c400="rgba(2, 193, 96, 0.32)",
30
- c500="rgba(2, 193, 96, 1.0)",
31
- c600="rgba(2, 193, 96, 1.0)",
32
- c700="rgba(2, 193, 96, 0.32)",
33
- c800="rgba(2, 193, 96, 0.32)",
34
- c900="#02C160",
35
- c950="#02C160",
36
- ),
37
- secondary_hue=gr.themes.Color(
38
- c50="#576b95",
39
- c100="#576b95",
40
- c200="#576b95",
41
- c300="#576b95",
42
- c400="#576b95",
43
- c500="#576b95",
44
- c600="#576b95",
45
- c700="#576b95",
46
- c800="#576b95",
47
- c900="#576b95",
48
- c950="#576b95",
49
- ),
50
- neutral_hue=gr.themes.Color(
51
- name="gray",
52
- c50="#f9fafb",
53
- c100="#f3f4f6",
54
- c200="#e5e7eb",
55
- c300="#d1d5db",
56
- c400="#B2B2B2",
57
- c500="#808080",
58
- c600="#636363",
59
- c700="#515151",
60
- c800="#393939",
61
- c900="#272727",
62
- c950="#171717",
63
- ),
64
- radius_size=gr.themes.sizes.radius_sm,
65
- ).set(
66
- button_primary_background_fill="#06AE56",
67
- button_primary_background_fill_dark="#06AE56",
68
- button_primary_background_fill_hover="#07C863",
69
- button_primary_border_color="#06AE56",
70
- button_primary_border_color_dark="#06AE56",
71
- button_primary_text_color="#FFFFFF",
72
- button_primary_text_color_dark="#FFFFFF",
73
- button_secondary_background_fill="#F2F2F2",
74
- button_secondary_background_fill_dark="#2B2B2B",
75
- button_secondary_text_color="#393939",
76
- button_secondary_text_color_dark="#FFFFFF",
77
- # background_fill_primary="#F7F7F7",
78
- # background_fill_primary_dark="#1F1F1F",
79
- block_title_text_color="*primary_500",
80
- block_title_background_fill="*primary_100",
81
- input_background_fill="#F6F6F6",
82
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChandraMohanNayal/AutoGPT/tests/milvus_memory_test.py DELETED
@@ -1,72 +0,0 @@
1
- # sourcery skip: snake-case-functions
2
- """Tests for the MilvusMemory class."""
3
- import os
4
- import sys
5
- import unittest
6
-
7
- try:
8
- from autogpt.memory.milvus import MilvusMemory
9
-
10
- def mock_config() -> dict:
11
- """Mock the Config class"""
12
- return type(
13
- "MockConfig",
14
- (object,),
15
- {
16
- "debug_mode": False,
17
- "continuous_mode": False,
18
- "speak_mode": False,
19
- "milvus_collection": "autogpt",
20
- "milvus_addr": "localhost:19530",
21
- },
22
- )
23
-
24
- class TestMilvusMemory(unittest.TestCase):
25
- """Tests for the MilvusMemory class."""
26
-
27
- def setUp(self) -> None:
28
- """Set up the test environment"""
29
- self.cfg = mock_config()
30
- self.memory = MilvusMemory(self.cfg)
31
-
32
- def test_add(self) -> None:
33
- """Test adding a text to the cache"""
34
- text = "Sample text"
35
- self.memory.clear()
36
- self.memory.add(text)
37
- result = self.memory.get(text)
38
- self.assertEqual([text], result)
39
-
40
- def test_clear(self) -> None:
41
- """Test clearing the cache"""
42
- self.memory.clear()
43
- self.assertEqual(self.memory.collection.num_entities, 0)
44
-
45
- def test_get(self) -> None:
46
- """Test getting a text from the cache"""
47
- text = "Sample text"
48
- self.memory.clear()
49
- self.memory.add(text)
50
- result = self.memory.get(text)
51
- self.assertEqual(result, [text])
52
-
53
- def test_get_relevant(self) -> None:
54
- """Test getting relevant texts from the cache"""
55
- text1 = "Sample text 1"
56
- text2 = "Sample text 2"
57
- self.memory.clear()
58
- self.memory.add(text1)
59
- self.memory.add(text2)
60
- result = self.memory.get_relevant(text1, 1)
61
- self.assertEqual(result, [text1])
62
-
63
- def test_get_stats(self) -> None:
64
- """Test getting the cache stats"""
65
- text = "Sample text"
66
- self.memory.clear()
67
- self.memory.add(text)
68
- stats = self.memory.get_stats()
69
- self.assertEqual(15, len(stats))
70
-
71
- except:
72
- print("Milvus not installed, skipping tests")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CikeyQI/Yunzai/Yunzai/plugins/ws-plugin/components/Version.js DELETED
@@ -1,96 +0,0 @@
1
- import fs from 'fs'
2
- import lodash from 'lodash'
3
-
4
- let packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'))
5
-
6
- const getLine = function (line) {
7
- line = line.replace(/(^\s*\*|\r)/g, '')
8
- line = line.replace(/\s*`([^`]+`)/g, '<span class="cmd">$1')
9
- line = line.replace(/`\s*/g, '</span>')
10
- line = line.replace(/\s*\*\*([^\*]+\*\*)/g, '<span class="strong">$1')
11
- line = line.replace(/\*\*\s*/g, '</span>')
12
- line = line.replace(/ⁿᵉʷ/g, '<span class="new"></span>')
13
- return line
14
- }
15
-
16
- const readLogFile = function (root, versionCount = 4) {
17
- let logPath = `${root}/CHANGELOG.md`
18
- let logs = {}
19
- let changelogs = []
20
- let currentVersion
21
-
22
- try {
23
- if (fs.existsSync(logPath)) {
24
- logs = fs.readFileSync(logPath, 'utf8') || ''
25
- logs = logs.split('\n')
26
-
27
- let temp = {}
28
- let lastLine = {}
29
- lodash.forEach(logs, (line) => {
30
- if (versionCount <= -1) {
31
- return false
32
- }
33
- let versionRet = /^#\s*([0-9a-zA-Z\\.~\s]+?)\s*$/.exec(line)
34
- if (versionRet && versionRet[1]) {
35
- let v = versionRet[1].trim()
36
- if (!currentVersion) {
37
- currentVersion = v
38
- } else {
39
- changelogs.push(temp)
40
- if (/0\s*$/.test(v) && versionCount > 0) {
41
- versionCount = 0
42
- } else {
43
- versionCount--
44
- }
45
- }
46
-
47
- temp = {
48
- version: v,
49
- logs: []
50
- }
51
- } else {
52
- if (!line.trim()) {
53
- return
54
- }
55
- if (/^\*/.test(line)) {
56
- lastLine = {
57
- title: getLine(line),
58
- logs: []
59
- }
60
- temp.logs.push(lastLine)
61
- } else if (/^\s{2,}\*/.test(line)) {
62
- lastLine.logs.push(getLine(line))
63
- }
64
- }
65
- })
66
- }
67
- } catch (e) {
68
- // do nth
69
- }
70
- return { changelogs, currentVersion }
71
- }
72
-
73
- const { changelogs, currentVersion } = readLogFile(`${process.cwd()}/plugins/ws-plugin/`)
74
-
75
- const yunzaiVersion = packageJson.version
76
- const isMiao = packageJson.dependencies.sequelize ? true : false
77
- const isTrss = Array.isArray(Bot.uin) ? true : false
78
- const protocol = ['chronocat', 'ICQQ']
79
-
80
- let Version = {
81
- isMiao,
82
- isTrss,
83
- protocol,
84
- get version() {
85
- return currentVersion
86
- },
87
- get yunzai() {
88
- return yunzaiVersion
89
- },
90
- get changelogs() {
91
- return changelogs
92
- },
93
- readLogFile
94
- }
95
-
96
- export default Version
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cpp4App/Cpp4App/CDM/detect_compo/lib_ip/ip_detection.py DELETED
@@ -1,574 +0,0 @@
1
- import cv2
2
- import numpy as np
3
-
4
- import CDM.detect_compo.lib_ip.ip_draw as draw
5
- import CDM.detect_compo.lib_ip.ip_preprocessing as pre
6
- from CDM.detect_compo.lib_ip.Component import Component
7
- import CDM.detect_compo.lib_ip.Component as Compo
8
- from CDM.config.CONFIG_UIED import Config
9
- C = Config()
10
-
11
-
12
- def merge_intersected_corner(compos, org, is_merge_contained_ele, max_gap=(0, 0), max_ele_height=25):
13
- '''
14
- :param is_merge_contained_ele: if true, merge compos nested in others
15
- :param max_gap: (horizontal_distance, vertical_distance) to be merge into one line/column
16
- :param max_ele_height: if higher than it, recognize the compo as text
17
- :return:
18
- '''
19
- changed = False
20
- new_compos = []
21
- Compo.compos_update(compos, org.shape)
22
- for i in range(len(compos)):
23
- merged = False
24
- cur_compo = compos[i]
25
- for j in range(len(new_compos)):
26
- relation = cur_compo.compo_relation(new_compos[j], max_gap)
27
- # print(relation)
28
- # draw.draw_bounding_box(org, [cur_compo, new_compos[j]], name='b-merge', show=True)
29
- # merge compo[i] to compo[j] if
30
- # 1. compo[j] contains compo[i]
31
- # 2. compo[j] intersects with compo[i] with certain iou
32
- # 3. is_merge_contained_ele and compo[j] is contained in compo[i]
33
- if relation == 1 or \
34
- relation == 2 or \
35
- (is_merge_contained_ele and relation == -1):
36
- # (relation == 2 and new_compos[j].height < max_ele_height and cur_compo.height < max_ele_height) or\
37
-
38
- new_compos[j].compo_merge(cur_compo)
39
- cur_compo = new_compos[j]
40
- # draw.draw_bounding_box(org, [new_compos[j]], name='a-merge', show=True)
41
- merged = True
42
- changed = True
43
- # break
44
- if not merged:
45
- new_compos.append(compos[i])
46
-
47
- if not changed:
48
- return compos
49
- else:
50
- return merge_intersected_corner(new_compos, org, is_merge_contained_ele, max_gap, max_ele_height)
51
-
52
-
53
- def merge_intersected_compos(compos):
54
- changed = True
55
- while changed:
56
- changed = False
57
- temp_set = []
58
- for compo_a in compos:
59
- merged = False
60
- for compo_b in temp_set:
61
- if compo_a.compo_relation(compo_b) == 2:
62
- compo_b.compo_merge(compo_a)
63
- merged = True
64
- changed = True
65
- break
66
- if not merged:
67
- temp_set.append(compo_a)
68
- compos = temp_set.copy()
69
- return compos
70
-
71
-
72
- def rm_contained_compos_not_in_block(compos):
73
- '''
74
- remove all components contained by others that are not Block
75
- '''
76
- marked = np.full(len(compos), False)
77
- for i in range(len(compos) - 1):
78
- for j in range(i + 1, len(compos)):
79
- relation = compos[i].compo_relation(compos[j])
80
- if relation == -1 and compos[j].category != 'Block':
81
- marked[i] = True
82
- if relation == 1 and compos[i].category != 'Block':
83
- marked[j] = True
84
- new_compos = []
85
- for i in range(len(marked)):
86
- if not marked[i]:
87
- new_compos.append(compos[i])
88
- return new_compos
89
-
90
-
91
- def merge_text(compos, org_shape, max_word_gad=4, max_word_height=20):
92
- def is_text_line(compo_a, compo_b):
93
- (col_min_a, row_min_a, col_max_a, row_max_a) = compo_a.put_bbox()
94
- (col_min_b, row_min_b, col_max_b, row_max_b) = compo_b.put_bbox()
95
-
96
- col_min_s = max(col_min_a, col_min_b)
97
- col_max_s = min(col_max_a, col_max_b)
98
- row_min_s = max(row_min_a, row_min_b)
99
- row_max_s = min(row_max_a, row_max_b)
100
-
101
- # on the same line
102
- # if abs(row_min_a - row_min_b) < max_word_gad and abs(row_max_a - row_max_b) < max_word_gad:
103
- if row_min_s < row_max_s:
104
- # close distance
105
- if col_min_s < col_max_s or \
106
- (0 < col_min_b - col_max_a < max_word_gad) or (0 < col_min_a - col_max_b < max_word_gad):
107
- return True
108
- return False
109
-
110
- changed = False
111
- new_compos = []
112
- row, col = org_shape[:2]
113
- for i in range(len(compos)):
114
- merged = False
115
- height = compos[i].height
116
- # ignore non-text
117
- # if height / row > max_word_height_ratio\
118
- # or compos[i].category != 'Text':
119
- if height > max_word_height:
120
- new_compos.append(compos[i])
121
- continue
122
- for j in range(len(new_compos)):
123
- # if compos[j].category != 'Text':
124
- # continue
125
- if is_text_line(compos[i], new_compos[j]):
126
- new_compos[j].compo_merge(compos[i])
127
- merged = True
128
- changed = True
129
- break
130
- if not merged:
131
- new_compos.append(compos[i])
132
-
133
- if not changed:
134
- return compos
135
- else:
136
- return merge_text(new_compos, org_shape)
137
-
138
-
139
- def rm_top_or_bottom_corners(components, org_shape, top_bottom_height=C.THRESHOLD_TOP_BOTTOM_BAR):
140
- new_compos = []
141
- height, width = org_shape[:2]
142
- for compo in components:
143
- (column_min, row_min, column_max, row_max) = compo.put_bbox()
144
- # remove big ones
145
- # if (row_max - row_min) / height > 0.65 and (column_max - column_min) / width > 0.8:
146
- # continue
147
- if not (row_max < height * top_bottom_height[0] or row_min > height * top_bottom_height[1]):
148
- new_compos.append(compo)
149
- return new_compos
150
-
151
-
152
- def rm_line_v_h(binary, show=False, max_line_thickness=C.THRESHOLD_LINE_THICKNESS):
153
- def check_continuous_line(line, edge):
154
- continuous_length = 0
155
- line_start = -1
156
- for j, p in enumerate(line):
157
- if p > 0:
158
- if line_start == -1:
159
- line_start = j
160
- continuous_length += 1
161
- elif continuous_length > 0:
162
- if continuous_length / edge > 0.6:
163
- return [line_start, j]
164
- continuous_length = 0
165
- line_start = -1
166
-
167
- if continuous_length / edge > 0.6:
168
- return [line_start, len(line)]
169
- else:
170
- return None
171
-
172
- def extract_line_area(line, start_idx, flag='v'):
173
- for e, l in enumerate(line):
174
- if flag == 'v':
175
- map_line[start_idx + e, l[0]:l[1]] = binary[start_idx + e, l[0]:l[1]]
176
-
177
- map_line = np.zeros(binary.shape[:2], dtype=np.uint8)
178
- cv2.imshow('binary', binary)
179
-
180
- width = binary.shape[1]
181
- start_row = -1
182
- line_area = []
183
- for i, row in enumerate(binary):
184
- line_v = check_continuous_line(row, width)
185
- if line_v is not None:
186
- # new line
187
- if start_row == -1:
188
- start_row = i
189
- line_area = []
190
- line_area.append(line_v)
191
- else:
192
- # checking line
193
- if start_row != -1:
194
- if i - start_row < max_line_thickness:
195
- # binary[start_row: i] = 0
196
- # map_line[start_row: i] = binary[start_row: i]
197
- print(line_area, start_row, i)
198
- extract_line_area(line_area, start_row)
199
- start_row = -1
200
-
201
- height = binary.shape[0]
202
- start_col = -1
203
- for i in range(width):
204
- col = binary[:, i]
205
- line_h = check_continuous_line(col, height)
206
- if line_h is not None:
207
- # new line
208
- if start_col == -1:
209
- start_col = i
210
- else:
211
- # checking line
212
- if start_col != -1:
213
- if i - start_col < max_line_thickness:
214
- # binary[:, start_col: i] = 0
215
- map_line[:, start_col: i] = binary[:, start_col: i]
216
- start_col = -1
217
-
218
- binary -= map_line
219
-
220
- if show:
221
- cv2.imshow('no-line', binary)
222
- cv2.imshow('lines', map_line)
223
- cv2.waitKey()
224
-
225
-
226
- def rm_line(binary,
227
- max_line_thickness=C.THRESHOLD_LINE_THICKNESS,
228
- min_line_length_ratio=C.THRESHOLD_LINE_MIN_LENGTH,
229
- show=False, wait_key=0):
230
- def is_valid_line(line):
231
- line_length = 0
232
- line_gap = 0
233
- for j in line:
234
- if j > 0:
235
- if line_gap > 5:
236
- return False
237
- line_length += 1
238
- line_gap = 0
239
- elif line_length > 0:
240
- line_gap += 1
241
- if line_length / width > 0.95:
242
- return True
243
- return False
244
-
245
- height, width = binary.shape[:2]
246
- board = np.zeros(binary.shape[:2], dtype=np.uint8)
247
-
248
- start_row, end_row = -1, -1
249
- check_line = False
250
- check_gap = False
251
- for i, row in enumerate(binary):
252
- # line_ratio = (sum(row) / 255) / width
253
- # if line_ratio > 0.9:
254
- if is_valid_line(row):
255
- # new start: if it is checking a new line, mark this row as start
256
- if not check_line:
257
- start_row = i
258
- check_line = True
259
- else:
260
- # end the line
261
- if check_line:
262
- # thin enough to be a line, then start checking gap
263
- if i - start_row < max_line_thickness:
264
- end_row = i
265
- check_gap = True
266
- else:
267
- start_row, end_row = -1, -1
268
- check_line = False
269
- # check gap
270
- if check_gap and i - end_row > max_line_thickness:
271
- binary[start_row: end_row] = 0
272
- start_row, end_row = -1, -1
273
- check_line = False
274
- check_gap = False
275
-
276
- if (check_line and (height - start_row) < max_line_thickness) or check_gap:
277
- binary[start_row: end_row] = 0
278
-
279
- if show:
280
- cv2.imshow('no-line binary', binary)
281
- if wait_key is not None:
282
- cv2.waitKey(wait_key)
283
- if wait_key == 0:
284
- cv2.destroyWindow('no-line binary')
285
-
286
-
287
- def rm_noise_compos(compos):
288
- compos_new = []
289
- for compo in compos:
290
- if compo.category == 'Noise':
291
- continue
292
- compos_new.append(compo)
293
- return compos_new
294
-
295
-
296
- def rm_noise_in_large_img(compos, org,
297
- max_compo_scale=C.THRESHOLD_COMPO_MAX_SCALE):
298
- row, column = org.shape[:2]
299
- remain = np.full(len(compos), True)
300
- new_compos = []
301
- for compo in compos:
302
- if compo.category == 'Image':
303
- for i in compo.contain:
304
- remain[i] = False
305
- for i in range(len(remain)):
306
- if remain[i]:
307
- new_compos.append(compos[i])
308
- return new_compos
309
-
310
-
311
- def detect_compos_in_img(compos, binary, org, max_compo_scale=C.THRESHOLD_COMPO_MAX_SCALE, show=False):
312
- compos_new = []
313
- row, column = binary.shape[:2]
314
- for compo in compos:
315
- if compo.category == 'Image':
316
- compo.compo_update_bbox_area()
317
- # org_clip = compo.compo_clipping(org)
318
- # bin_clip = pre.binarization(org_clip, show=show)
319
- bin_clip = compo.compo_clipping(binary)
320
- bin_clip = pre.reverse_binary(bin_clip, show=show)
321
-
322
- compos_rec, compos_nonrec = component_detection(bin_clip, test=False, step_h=10, step_v=10, rec_detect=True)
323
- for compo_rec in compos_rec:
324
- compo_rec.compo_relative_position(compo.bbox.col_min, compo.bbox.row_min)
325
- if compo_rec.bbox_area / compo.bbox_area < 0.8 and compo_rec.bbox.height > 20 and compo_rec.bbox.width > 20:
326
- compos_new.append(compo_rec)
327
- # draw.draw_bounding_box(org, [compo_rec], show=True)
328
-
329
- # compos_inner = component_detection(bin_clip, rec_detect=False)
330
- # for compo_inner in compos_inner:
331
- # compo_inner.compo_relative_position(compo.bbox.col_min, compo.bbox.row_min)
332
- # draw.draw_bounding_box(org, [compo_inner], show=True)
333
- # if compo_inner.bbox_area / compo.bbox_area < 0.8:
334
- # compos_new.append(compo_inner)
335
- compos += compos_new
336
-
337
-
338
- def compo_filter(compos, min_area, img_shape):
339
- # max_height = img_shape[0] * 0.8
340
- # compos_new = []
341
- # for compo in compos:
342
- # if compo.area < min_area:
343
- # continue
344
- # if compo.height > max_height:
345
- # continue
346
- # ratio_h = compo.width / compo.height
347
- # ratio_w = compo.height / compo.width
348
- # if ratio_h > 50 or ratio_w > 40 or \
349
- # (min(compo.height, compo.width) < 8 and max(ratio_h, ratio_w) > 10):
350
- # continue
351
- # compos_new.append(compo)
352
- # return compos_new
353
-
354
- # mobile semantics filter
355
- # compos_new = []
356
- #
357
- # for compo in compos:
358
- #
359
- # if compo.area >= 0.05 * (img_shape[0] * img_shape[1]):
360
- # continue
361
- #
362
- # smaller_dimension = min(compo.width, compo.height)
363
- # larger_dimension = max(compo.width, compo.height)
364
- #
365
- # if smaller_dimension/larger_dimension <= 0.75:
366
- # continue
367
- #
368
- # compos_new.append(compo)
369
- #
370
- # return compos_new
371
-
372
- # my own filter
373
- compos_new = []
374
-
375
- for compo in compos:
376
-
377
- if compo.area >= 0.1 * (img_shape[0] * img_shape[1]):
378
- continue
379
-
380
- if compo.area <= 0.0005 * (img_shape[0] * img_shape[1]):
381
- continue
382
-
383
- smaller_dimension = min(compo.width, compo.height)
384
- larger_dimension = max(compo.width, compo.height)
385
-
386
- if smaller_dimension / larger_dimension <= 0.6:
387
- continue
388
-
389
- compos_new.append(compo)
390
-
391
- return compos_new
392
-
393
-
394
- def is_block(clip, thread=0.15):
395
- '''
396
- Block is a rectangle border enclosing a group of compos (consider it as a wireframe)
397
- Check if a compo is block by checking if the inner side of its border is blank
398
- '''
399
- side = 4 # scan 4 lines inner forward each border
400
- # top border - scan top down
401
- blank_count = 0
402
- for i in range(1, 5):
403
- if sum(clip[side + i]) / 255 > thread * clip.shape[1]:
404
- blank_count += 1
405
- if blank_count > 2: return False
406
- # left border - scan left to right
407
- blank_count = 0
408
- for i in range(1, 5):
409
- if sum(clip[:, side + i]) / 255 > thread * clip.shape[0]:
410
- blank_count += 1
411
- if blank_count > 2: return False
412
-
413
- side = -4
414
- # bottom border - scan bottom up
415
- blank_count = 0
416
- for i in range(-1, -5, -1):
417
- if sum(clip[side + i]) / 255 > thread * clip.shape[1]:
418
- blank_count += 1
419
- if blank_count > 2: return False
420
- # right border - scan right to left
421
- blank_count = 0
422
- for i in range(-1, -5, -1):
423
- if sum(clip[:, side + i]) / 255 > thread * clip.shape[0]:
424
- blank_count += 1
425
- if blank_count > 2: return False
426
- return True
427
-
428
-
429
- def compo_block_recognition(binary, compos, block_side_length=0.15):
430
- height, width = binary.shape
431
- for compo in compos:
432
- if compo.height / height > block_side_length and compo.width / width > block_side_length:
433
- clip = compo.compo_clipping(binary)
434
- if is_block(clip):
435
- compo.category = 'Block'
436
-
437
-
438
- # take the binary image as input
439
- # calculate the connected regions -> get the bounding boundaries of them -> check if those regions are rectangles
440
- # return all boundaries and boundaries of rectangles
441
- def component_detection(binary, min_obj_area,
442
- line_thickness=C.THRESHOLD_LINE_THICKNESS,
443
- min_rec_evenness=C.THRESHOLD_REC_MIN_EVENNESS,
444
- max_dent_ratio=C.THRESHOLD_REC_MAX_DENT_RATIO,
445
- step_h = 5, step_v = 2,
446
- rec_detect=False, show=False, test=False):
447
- """
448
- :param binary: Binary image from pre-processing
449
- :param min_obj_area: If not pass then ignore the small object
450
- :param min_obj_perimeter: If not pass then ignore the small object
451
- :param line_thickness: If not pass then ignore the slim object
452
- :param min_rec_evenness: If not pass then this object cannot be rectangular
453
- :param max_dent_ratio: If not pass then this object cannot be rectangular
454
- :return: boundary: [top, bottom, left, right]
455
- -> up, bottom: list of (column_index, min/max row border)
456
- -> left, right: list of (row_index, min/max column border) detect range of each row
457
- """
458
- mask = np.zeros((binary.shape[0] + 2, binary.shape[1] + 2), dtype=np.uint8)
459
- compos_all = []
460
- compos_rec = []
461
- compos_nonrec = []
462
- row, column = binary.shape[0], binary.shape[1]
463
- for i in range(0, row, step_h):
464
- for j in range(i % 2, column, step_v):
465
- if binary[i, j] == 255 and mask[i, j] == 0:
466
- # get connected area
467
- # region = util.boundary_bfs_connected_area(binary, i, j, mask)
468
-
469
- mask_copy = mask.copy()
470
- ff = cv2.floodFill(binary, mask, (j, i), None, 0, 0, cv2.FLOODFILL_MASK_ONLY)
471
- if ff[0] < min_obj_area: continue
472
- mask_copy = mask - mask_copy
473
- region = np.reshape(cv2.findNonZero(mask_copy[1:-1, 1:-1]), (-1, 2))
474
- region = [(p[1], p[0]) for p in region]
475
-
476
- # filter out some compos
477
- component = Component(region, binary.shape)
478
- # calculate the boundary of the connected area
479
- # ignore small area
480
- if component.width <= 3 or component.height <= 3:
481
- continue
482
- # check if it is line by checking the length of edges
483
- # if component.compo_is_line(line_thickness):
484
- # continue
485
-
486
- if test:
487
- print('Area:%d' % (len(region)))
488
- draw.draw_boundary([component], binary.shape, show=True)
489
-
490
- compos_all.append(component)
491
-
492
- if rec_detect:
493
- # rectangle check
494
- if component.compo_is_rectangle(min_rec_evenness, max_dent_ratio):
495
- component.rect_ = True
496
- compos_rec.append(component)
497
- else:
498
- component.rect_ = False
499
- compos_nonrec.append(component)
500
-
501
- if show:
502
- print('Area:%d' % (len(region)))
503
- draw.draw_boundary(compos_all, binary.shape, show=True)
504
-
505
- # draw.draw_boundary(compos_all, binary.shape, show=True)
506
- if rec_detect:
507
- return compos_rec, compos_nonrec
508
- else:
509
- return compos_all
510
-
511
-
512
- def nested_components_detection(grey, org, grad_thresh,
513
- show=False, write_path=None,
514
- step_h=10, step_v=10,
515
- line_thickness=C.THRESHOLD_LINE_THICKNESS,
516
- min_rec_evenness=C.THRESHOLD_REC_MIN_EVENNESS,
517
- max_dent_ratio=C.THRESHOLD_REC_MAX_DENT_RATIO):
518
- '''
519
- :param grey: grey-scale of original image
520
- :return: corners: list of [(top_left, bottom_right)]
521
- -> top_left: (column_min, row_min)
522
- -> bottom_right: (column_max, row_max)
523
- '''
524
- compos = []
525
- mask = np.zeros((grey.shape[0]+2, grey.shape[1]+2), dtype=np.uint8)
526
- broad = np.zeros((grey.shape[0], grey.shape[1], 3), dtype=np.uint8)
527
- broad_all = broad.copy()
528
-
529
- row, column = grey.shape[0], grey.shape[1]
530
- for x in range(0, row, step_h):
531
- for y in range(0, column, step_v):
532
- if mask[x, y] == 0:
533
- # region = flood_fill_bfs(grey, x, y, mask)
534
-
535
- # flood fill algorithm to get background (layout block)
536
- mask_copy = mask.copy()
537
- ff = cv2.floodFill(grey, mask, (y, x), None, grad_thresh, grad_thresh, cv2.FLOODFILL_MASK_ONLY)
538
- # ignore small regions
539
- if ff[0] < 500: continue
540
- mask_copy = mask - mask_copy
541
- region = np.reshape(cv2.findNonZero(mask_copy[1:-1, 1:-1]), (-1, 2))
542
- region = [(p[1], p[0]) for p in region]
543
-
544
- compo = Component(region, grey.shape)
545
- # draw.draw_region(region, broad_all)
546
- # if block.height < 40 and block.width < 40:
547
- # continue
548
- if compo.height < 30:
549
- continue
550
-
551
- # print(block.area / (row * column))
552
- if compo.area / (row * column) > 0.9:
553
- continue
554
- elif compo.area / (row * column) > 0.7:
555
- compo.redundant = True
556
-
557
- # get the boundary of this region
558
- # ignore lines
559
- if compo.compo_is_line(line_thickness):
560
- continue
561
- # ignore non-rectangle as blocks must be rectangular
562
- if not compo.compo_is_rectangle(min_rec_evenness, max_dent_ratio):
563
- continue
564
- # if block.height/row < min_block_height_ratio:
565
- # continue
566
- compos.append(compo)
567
- # draw.draw_region(region, broad)
568
- if show:
569
- cv2.imshow('flood-fill all', broad_all)
570
- cv2.imshow('block', broad)
571
- cv2.waitKey()
572
- if write_path is not None:
573
- cv2.imwrite(write_path, broad)
574
- return compos
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cropinky/hana_hanak_houses/realesrgan/models/realesrnet_model.py DELETED
@@ -1,188 +0,0 @@
1
- import numpy as np
2
- import random
3
- import torch
4
- from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt
5
- from basicsr.data.transforms import paired_random_crop
6
- from basicsr.models.sr_model import SRModel
7
- from basicsr.utils import DiffJPEG, USMSharp
8
- from basicsr.utils.img_process_util import filter2D
9
- from basicsr.utils.registry import MODEL_REGISTRY
10
- from torch.nn import functional as F
11
-
12
-
13
- @MODEL_REGISTRY.register()
14
- class RealESRNetModel(SRModel):
15
- """RealESRNet Model for Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.
16
-
17
- It is trained without GAN losses.
18
- It mainly performs:
19
- 1. randomly synthesize LQ images in GPU tensors
20
- 2. optimize the networks with GAN training.
21
- """
22
-
23
- def __init__(self, opt):
24
- super(RealESRNetModel, self).__init__(opt)
25
- self.jpeger = DiffJPEG(differentiable=False).cuda() # simulate JPEG compression artifacts
26
- self.usm_sharpener = USMSharp().cuda() # do usm sharpening
27
- self.queue_size = opt.get('queue_size', 180)
28
-
29
- @torch.no_grad()
30
- def _dequeue_and_enqueue(self):
31
- """It is the training pair pool for increasing the diversity in a batch.
32
-
33
- Batch processing limits the diversity of synthetic degradations in a batch. For example, samples in a
34
- batch could not have different resize scaling factors. Therefore, we employ this training pair pool
35
- to increase the degradation diversity in a batch.
36
- """
37
- # initialize
38
- b, c, h, w = self.lq.size()
39
- if not hasattr(self, 'queue_lr'):
40
- assert self.queue_size % b == 0, f'queue size {self.queue_size} should be divisible by batch size {b}'
41
- self.queue_lr = torch.zeros(self.queue_size, c, h, w).cuda()
42
- _, c, h, w = self.gt.size()
43
- self.queue_gt = torch.zeros(self.queue_size, c, h, w).cuda()
44
- self.queue_ptr = 0
45
- if self.queue_ptr == self.queue_size: # the pool is full
46
- # do dequeue and enqueue
47
- # shuffle
48
- idx = torch.randperm(self.queue_size)
49
- self.queue_lr = self.queue_lr[idx]
50
- self.queue_gt = self.queue_gt[idx]
51
- # get first b samples
52
- lq_dequeue = self.queue_lr[0:b, :, :, :].clone()
53
- gt_dequeue = self.queue_gt[0:b, :, :, :].clone()
54
- # update the queue
55
- self.queue_lr[0:b, :, :, :] = self.lq.clone()
56
- self.queue_gt[0:b, :, :, :] = self.gt.clone()
57
-
58
- self.lq = lq_dequeue
59
- self.gt = gt_dequeue
60
- else:
61
- # only do enqueue
62
- self.queue_lr[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.lq.clone()
63
- self.queue_gt[self.queue_ptr:self.queue_ptr + b, :, :, :] = self.gt.clone()
64
- self.queue_ptr = self.queue_ptr + b
65
-
66
- @torch.no_grad()
67
- def feed_data(self, data):
68
- """Accept data from dataloader, and then add two-order degradations to obtain LQ images.
69
- """
70
- if self.is_train and self.opt.get('high_order_degradation', True):
71
- # training data synthesis
72
- self.gt = data['gt'].to(self.device)
73
- # USM sharpen the GT images
74
- if self.opt['gt_usm'] is True:
75
- self.gt = self.usm_sharpener(self.gt)
76
-
77
- self.kernel1 = data['kernel1'].to(self.device)
78
- self.kernel2 = data['kernel2'].to(self.device)
79
- self.sinc_kernel = data['sinc_kernel'].to(self.device)
80
-
81
- ori_h, ori_w = self.gt.size()[2:4]
82
-
83
- # ----------------------- The first degradation process ----------------------- #
84
- # blur
85
- out = filter2D(self.gt, self.kernel1)
86
- # random resize
87
- updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob'])[0]
88
- if updown_type == 'up':
89
- scale = np.random.uniform(1, self.opt['resize_range'][1])
90
- elif updown_type == 'down':
91
- scale = np.random.uniform(self.opt['resize_range'][0], 1)
92
- else:
93
- scale = 1
94
- mode = random.choice(['area', 'bilinear', 'bicubic'])
95
- out = F.interpolate(out, scale_factor=scale, mode=mode)
96
- # add noise
97
- gray_noise_prob = self.opt['gray_noise_prob']
98
- if np.random.uniform() < self.opt['gaussian_noise_prob']:
99
- out = random_add_gaussian_noise_pt(
100
- out, sigma_range=self.opt['noise_range'], clip=True, rounds=False, gray_prob=gray_noise_prob)
101
- else:
102
- out = random_add_poisson_noise_pt(
103
- out,
104
- scale_range=self.opt['poisson_scale_range'],
105
- gray_prob=gray_noise_prob,
106
- clip=True,
107
- rounds=False)
108
- # JPEG compression
109
- jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range'])
110
- out = torch.clamp(out, 0, 1) # clamp to [0, 1], otherwise JPEGer will result in unpleasant artifacts
111
- out = self.jpeger(out, quality=jpeg_p)
112
-
113
- # ----------------------- The second degradation process ----------------------- #
114
- # blur
115
- if np.random.uniform() < self.opt['second_blur_prob']:
116
- out = filter2D(out, self.kernel2)
117
- # random resize
118
- updown_type = random.choices(['up', 'down', 'keep'], self.opt['resize_prob2'])[0]
119
- if updown_type == 'up':
120
- scale = np.random.uniform(1, self.opt['resize_range2'][1])
121
- elif updown_type == 'down':
122
- scale = np.random.uniform(self.opt['resize_range2'][0], 1)
123
- else:
124
- scale = 1
125
- mode = random.choice(['area', 'bilinear', 'bicubic'])
126
- out = F.interpolate(
127
- out, size=(int(ori_h / self.opt['scale'] * scale), int(ori_w / self.opt['scale'] * scale)), mode=mode)
128
- # add noise
129
- gray_noise_prob = self.opt['gray_noise_prob2']
130
- if np.random.uniform() < self.opt['gaussian_noise_prob2']:
131
- out = random_add_gaussian_noise_pt(
132
- out, sigma_range=self.opt['noise_range2'], clip=True, rounds=False, gray_prob=gray_noise_prob)
133
- else:
134
- out = random_add_poisson_noise_pt(
135
- out,
136
- scale_range=self.opt['poisson_scale_range2'],
137
- gray_prob=gray_noise_prob,
138
- clip=True,
139
- rounds=False)
140
-
141
- # JPEG compression + the final sinc filter
142
- # We also need to resize images to desired sizes. We group [resize back + sinc filter] together
143
- # as one operation.
144
- # We consider two orders:
145
- # 1. [resize back + sinc filter] + JPEG compression
146
- # 2. JPEG compression + [resize back + sinc filter]
147
- # Empirically, we find other combinations (sinc + JPEG + Resize) will introduce twisted lines.
148
- if np.random.uniform() < 0.5:
149
- # resize back + the final sinc filter
150
- mode = random.choice(['area', 'bilinear', 'bicubic'])
151
- out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode)
152
- out = filter2D(out, self.sinc_kernel)
153
- # JPEG compression
154
- jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2'])
155
- out = torch.clamp(out, 0, 1)
156
- out = self.jpeger(out, quality=jpeg_p)
157
- else:
158
- # JPEG compression
159
- jpeg_p = out.new_zeros(out.size(0)).uniform_(*self.opt['jpeg_range2'])
160
- out = torch.clamp(out, 0, 1)
161
- out = self.jpeger(out, quality=jpeg_p)
162
- # resize back + the final sinc filter
163
- mode = random.choice(['area', 'bilinear', 'bicubic'])
164
- out = F.interpolate(out, size=(ori_h // self.opt['scale'], ori_w // self.opt['scale']), mode=mode)
165
- out = filter2D(out, self.sinc_kernel)
166
-
167
- # clamp and round
168
- self.lq = torch.clamp((out * 255.0).round(), 0, 255) / 255.
169
-
170
- # random crop
171
- gt_size = self.opt['gt_size']
172
- self.gt, self.lq = paired_random_crop(self.gt, self.lq, gt_size, self.opt['scale'])
173
-
174
- # training pair pool
175
- self._dequeue_and_enqueue()
176
- self.lq = self.lq.contiguous() # for the warning: grad and param do not obey the gradient layout contract
177
- else:
178
- # for paired training or validation
179
- self.lq = data['lq'].to(self.device)
180
- if 'gt' in data:
181
- self.gt = data['gt'].to(self.device)
182
- self.gt_usm = self.usm_sharpener(self.gt)
183
-
184
- def nondist_validation(self, dataloader, current_iter, tb_logger, save_img):
185
- # do not use the synthetic process during validation
186
- self.is_train = False
187
- super(RealESRNetModel, self).nondist_validation(dataloader, current_iter, tb_logger, save_img)
188
- self.is_train = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/data/datasets/evaluation/word/util/cmd.py DELETED
@@ -1,6 +0,0 @@
1
- #encoding = utf-8
2
-
3
- def cmd(cmd):
4
- import commands
5
- return commands.getoutput(cmd)
6
-
 
 
 
 
 
 
 
spaces/DHEIVER/Pedrita/app.py DELETED
@@ -1,101 +0,0 @@
1
- import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed, pipeline
3
-
4
-
5
- title = "Python Code Generator"
6
- description = "This is a space to convert English text to Python code using the [codeparrot-small-text-to-code](https://huggingface.co/codeparrot/codeparrot-small-text-to-code) model, a pre-trained Python code generation model trained on a dataset of docstrings and Python code extracted from Jupyter notebooks available at [github-jupyter-text](https://huggingface.co/datasets/codeparrot/github-jupyter-text)."
7
- example = [
8
- ["Utility function to calculate the precision of predictions using sklearn metrics", 65, 0.6, 42],
9
- ["Let's implement a function that calculates the size of a file called filepath", 60, 0.6, 42],
10
- ["Let's implement the Bubble Sort sorting algorithm in an auxiliary function:", 87, 0.6, 42],
11
- ["Function to calculate the nth Fibonacci number.", 65, 0.6, 42],
12
- ["Function to calculate the factorial of a number.", 65, 0.6, 42],
13
- ["Function to reverse a string.", 65, 0.6, 42],
14
- ["Function to check if a number is prime.", 65, 0.6, 42],
15
- ["Function to generate the Fibonacci sequence up to the nth term.", 65, 0.6, 42],
16
- ["Function to generate the factorial sequence up to the nth term.", 65, 0.6, 42],
17
- ]
18
-
19
-
20
- # Change the model to the pre-trained model
21
- tokenizer = AutoTokenizer.from_pretrained("codeparrot/codeparrot-small-text-to-code")
22
- model = AutoModelForCausalLM.from_pretrained("codeparrot/codeparrot-small-text-to-code")
23
-
24
- def create_docstring(gen_prompt):
25
- return "\"\"\"\n" + gen_prompt + "\n\"\"\"\n\n"
26
-
27
- def validate_inputs(gen_prompt, max_tokens, temperature, seed):
28
- # Add validation logic here
29
- if not gen_prompt:
30
- raise ValueError("English instructions cannot be empty.")
31
- if max_tokens <= 0 or max_tokens > 256:
32
- raise ValueError("Number of tokens to generate must be between 1 and 256.")
33
- if temperature < 0 or temperature > 2.5:
34
- raise ValueError("Temperature must be between 0 and 2.5.")
35
- if seed < 0 or seed > 1000:
36
- raise ValueError("Random seed must be between 0 and 1000.")
37
-
38
- def generate_code(gen_prompt, max_tokens, temperature=0.6, seed=42):
39
- validate_inputs(gen_prompt, max_tokens, temperature, seed)
40
-
41
- # Encode the input prompt
42
- input_ids = tokenizer.encode(gen_prompt, return_tensors="pt")
43
-
44
- # Set seed for reproducibility
45
- set_seed(seed)
46
-
47
- # Generate code tokens
48
- output = model.generate(
49
- input_ids,
50
- max_length=max_tokens + input_ids.shape[-1],
51
- temperature=temperature,
52
- pad_token_id=tokenizer.eos_token_id,
53
- num_return_sequences=1
54
- )
55
-
56
- # Decode the generated tokens into Python code
57
- generated_code = tokenizer.decode(output[:, input_ids.shape[-1]:][0], skip_special_tokens=True)
58
-
59
- return generated_code
60
-
61
-
62
-
63
- def save_to_text_file(output_text):
64
- with open("generated_code.txt", "w") as file:
65
- file.write(output_text)
66
-
67
- iface = gr.Interface(
68
- fn=generate_code,
69
- inputs=[
70
- gr.Textbox(label="English instructions", placeholder="Enter English instructions..."),
71
- gr.inputs.Slider(
72
- minimum=8,
73
- maximum=256,
74
- step=1,
75
- default=8,
76
- label="Number of tokens to generate",
77
- ),
78
- gr.inputs.Slider(
79
- minimum=0,
80
- maximum=2.5,
81
- step=0.1,
82
- default=0.6,
83
- label="Temperature",
84
- ),
85
- gr.inputs.Slider(
86
- minimum=0,
87
- maximum=1000,
88
- step=1,
89
- default=42,
90
- label="Random seed for generation"
91
- )
92
- ],
93
- outputs=gr.Code(label="Generated Python code", language="python", lines=10),
94
- examples=example,
95
- layout="horizontal",
96
- theme="peach",
97
- description=description,
98
- title=title
99
- )
100
- iface.launch()
101
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/aiohttp/http_websocket.py DELETED
@@ -1,701 +0,0 @@
1
- """WebSocket protocol versions 13 and 8."""
2
-
3
- import asyncio
4
- import collections
5
- import json
6
- import random
7
- import re
8
- import sys
9
- import zlib
10
- from enum import IntEnum
11
- from struct import Struct
12
- from typing import Any, Callable, List, Optional, Pattern, Set, Tuple, Union, cast
13
-
14
- from .base_protocol import BaseProtocol
15
- from .helpers import NO_EXTENSIONS
16
- from .streams import DataQueue
17
- from .typedefs import Final
18
-
19
- __all__ = (
20
- "WS_CLOSED_MESSAGE",
21
- "WS_CLOSING_MESSAGE",
22
- "WS_KEY",
23
- "WebSocketReader",
24
- "WebSocketWriter",
25
- "WSMessage",
26
- "WebSocketError",
27
- "WSMsgType",
28
- "WSCloseCode",
29
- )
30
-
31
-
32
- class WSCloseCode(IntEnum):
33
- OK = 1000
34
- GOING_AWAY = 1001
35
- PROTOCOL_ERROR = 1002
36
- UNSUPPORTED_DATA = 1003
37
- ABNORMAL_CLOSURE = 1006
38
- INVALID_TEXT = 1007
39
- POLICY_VIOLATION = 1008
40
- MESSAGE_TOO_BIG = 1009
41
- MANDATORY_EXTENSION = 1010
42
- INTERNAL_ERROR = 1011
43
- SERVICE_RESTART = 1012
44
- TRY_AGAIN_LATER = 1013
45
- BAD_GATEWAY = 1014
46
-
47
-
48
- ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode}
49
-
50
-
51
- class WSMsgType(IntEnum):
52
- # websocket spec types
53
- CONTINUATION = 0x0
54
- TEXT = 0x1
55
- BINARY = 0x2
56
- PING = 0x9
57
- PONG = 0xA
58
- CLOSE = 0x8
59
-
60
- # aiohttp specific types
61
- CLOSING = 0x100
62
- CLOSED = 0x101
63
- ERROR = 0x102
64
-
65
- text = TEXT
66
- binary = BINARY
67
- ping = PING
68
- pong = PONG
69
- close = CLOSE
70
- closing = CLOSING
71
- closed = CLOSED
72
- error = ERROR
73
-
74
-
75
- WS_KEY: Final[bytes] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
76
-
77
-
78
- UNPACK_LEN2 = Struct("!H").unpack_from
79
- UNPACK_LEN3 = Struct("!Q").unpack_from
80
- UNPACK_CLOSE_CODE = Struct("!H").unpack
81
- PACK_LEN1 = Struct("!BB").pack
82
- PACK_LEN2 = Struct("!BBH").pack
83
- PACK_LEN3 = Struct("!BBQ").pack
84
- PACK_CLOSE_CODE = Struct("!H").pack
85
- MSG_SIZE: Final[int] = 2**14
86
- DEFAULT_LIMIT: Final[int] = 2**16
87
-
88
-
89
- _WSMessageBase = collections.namedtuple("_WSMessageBase", ["type", "data", "extra"])
90
-
91
-
92
- class WSMessage(_WSMessageBase):
93
- def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any:
94
- """Return parsed JSON data.
95
-
96
- .. versionadded:: 0.22
97
- """
98
- return loads(self.data)
99
-
100
-
101
- WS_CLOSED_MESSAGE = WSMessage(WSMsgType.CLOSED, None, None)
102
- WS_CLOSING_MESSAGE = WSMessage(WSMsgType.CLOSING, None, None)
103
-
104
-
105
- class WebSocketError(Exception):
106
- """WebSocket protocol parser error."""
107
-
108
- def __init__(self, code: int, message: str) -> None:
109
- self.code = code
110
- super().__init__(code, message)
111
-
112
- def __str__(self) -> str:
113
- return cast(str, self.args[1])
114
-
115
-
116
- class WSHandshakeError(Exception):
117
- """WebSocket protocol handshake error."""
118
-
119
-
120
- native_byteorder: Final[str] = sys.byteorder
121
-
122
-
123
- # Used by _websocket_mask_python
124
- _XOR_TABLE: Final[List[bytes]] = [bytes(a ^ b for a in range(256)) for b in range(256)]
125
-
126
-
127
- def _websocket_mask_python(mask: bytes, data: bytearray) -> None:
128
- """Websocket masking function.
129
-
130
- `mask` is a `bytes` object of length 4; `data` is a `bytearray`
131
- object of any length. The contents of `data` are masked with `mask`,
132
- as specified in section 5.3 of RFC 6455.
133
-
134
- Note that this function mutates the `data` argument.
135
-
136
- This pure-python implementation may be replaced by an optimized
137
- version when available.
138
-
139
- """
140
- assert isinstance(data, bytearray), data
141
- assert len(mask) == 4, mask
142
-
143
- if data:
144
- a, b, c, d = (_XOR_TABLE[n] for n in mask)
145
- data[::4] = data[::4].translate(a)
146
- data[1::4] = data[1::4].translate(b)
147
- data[2::4] = data[2::4].translate(c)
148
- data[3::4] = data[3::4].translate(d)
149
-
150
-
151
- if NO_EXTENSIONS: # pragma: no cover
152
- _websocket_mask = _websocket_mask_python
153
- else:
154
- try:
155
- from ._websocket import _websocket_mask_cython # type: ignore[import]
156
-
157
- _websocket_mask = _websocket_mask_cython
158
- except ImportError: # pragma: no cover
159
- _websocket_mask = _websocket_mask_python
160
-
161
- _WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF])
162
-
163
-
164
- _WS_EXT_RE: Final[Pattern[str]] = re.compile(
165
- r"^(?:;\s*(?:"
166
- r"(server_no_context_takeover)|"
167
- r"(client_no_context_takeover)|"
168
- r"(server_max_window_bits(?:=(\d+))?)|"
169
- r"(client_max_window_bits(?:=(\d+))?)))*$"
170
- )
171
-
172
- _WS_EXT_RE_SPLIT: Final[Pattern[str]] = re.compile(r"permessage-deflate([^,]+)?")
173
-
174
-
175
- def ws_ext_parse(extstr: Optional[str], isserver: bool = False) -> Tuple[int, bool]:
176
- if not extstr:
177
- return 0, False
178
-
179
- compress = 0
180
- notakeover = False
181
- for ext in _WS_EXT_RE_SPLIT.finditer(extstr):
182
- defext = ext.group(1)
183
- # Return compress = 15 when get `permessage-deflate`
184
- if not defext:
185
- compress = 15
186
- break
187
- match = _WS_EXT_RE.match(defext)
188
- if match:
189
- compress = 15
190
- if isserver:
191
- # Server never fail to detect compress handshake.
192
- # Server does not need to send max wbit to client
193
- if match.group(4):
194
- compress = int(match.group(4))
195
- # Group3 must match if group4 matches
196
- # Compress wbit 8 does not support in zlib
197
- # If compress level not support,
198
- # CONTINUE to next extension
199
- if compress > 15 or compress < 9:
200
- compress = 0
201
- continue
202
- if match.group(1):
203
- notakeover = True
204
- # Ignore regex group 5 & 6 for client_max_window_bits
205
- break
206
- else:
207
- if match.group(6):
208
- compress = int(match.group(6))
209
- # Group5 must match if group6 matches
210
- # Compress wbit 8 does not support in zlib
211
- # If compress level not support,
212
- # FAIL the parse progress
213
- if compress > 15 or compress < 9:
214
- raise WSHandshakeError("Invalid window size")
215
- if match.group(2):
216
- notakeover = True
217
- # Ignore regex group 5 & 6 for client_max_window_bits
218
- break
219
- # Return Fail if client side and not match
220
- elif not isserver:
221
- raise WSHandshakeError("Extension for deflate not supported" + ext.group(1))
222
-
223
- return compress, notakeover
224
-
225
-
226
- def ws_ext_gen(
227
- compress: int = 15, isserver: bool = False, server_notakeover: bool = False
228
- ) -> str:
229
- # client_notakeover=False not used for server
230
- # compress wbit 8 does not support in zlib
231
- if compress < 9 or compress > 15:
232
- raise ValueError(
233
- "Compress wbits must between 9 and 15, " "zlib does not support wbits=8"
234
- )
235
- enabledext = ["permessage-deflate"]
236
- if not isserver:
237
- enabledext.append("client_max_window_bits")
238
-
239
- if compress < 15:
240
- enabledext.append("server_max_window_bits=" + str(compress))
241
- if server_notakeover:
242
- enabledext.append("server_no_context_takeover")
243
- # if client_notakeover:
244
- # enabledext.append('client_no_context_takeover')
245
- return "; ".join(enabledext)
246
-
247
-
248
- class WSParserState(IntEnum):
249
- READ_HEADER = 1
250
- READ_PAYLOAD_LENGTH = 2
251
- READ_PAYLOAD_MASK = 3
252
- READ_PAYLOAD = 4
253
-
254
-
255
- class WebSocketReader:
256
- def __init__(
257
- self, queue: DataQueue[WSMessage], max_msg_size: int, compress: bool = True
258
- ) -> None:
259
- self.queue = queue
260
- self._max_msg_size = max_msg_size
261
-
262
- self._exc: Optional[BaseException] = None
263
- self._partial = bytearray()
264
- self._state = WSParserState.READ_HEADER
265
-
266
- self._opcode: Optional[int] = None
267
- self._frame_fin = False
268
- self._frame_opcode: Optional[int] = None
269
- self._frame_payload = bytearray()
270
-
271
- self._tail = b""
272
- self._has_mask = False
273
- self._frame_mask: Optional[bytes] = None
274
- self._payload_length = 0
275
- self._payload_length_flag = 0
276
- self._compressed: Optional[bool] = None
277
- self._decompressobj: Any = None # zlib.decompressobj actually
278
- self._compress = compress
279
-
280
- def feed_eof(self) -> None:
281
- self.queue.feed_eof()
282
-
283
- def feed_data(self, data: bytes) -> Tuple[bool, bytes]:
284
- if self._exc:
285
- return True, data
286
-
287
- try:
288
- return self._feed_data(data)
289
- except Exception as exc:
290
- self._exc = exc
291
- self.queue.set_exception(exc)
292
- return True, b""
293
-
294
- def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
295
- for fin, opcode, payload, compressed in self.parse_frame(data):
296
- if compressed and not self._decompressobj:
297
- self._decompressobj = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
298
- if opcode == WSMsgType.CLOSE:
299
- if len(payload) >= 2:
300
- close_code = UNPACK_CLOSE_CODE(payload[:2])[0]
301
- if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES:
302
- raise WebSocketError(
303
- WSCloseCode.PROTOCOL_ERROR,
304
- f"Invalid close code: {close_code}",
305
- )
306
- try:
307
- close_message = payload[2:].decode("utf-8")
308
- except UnicodeDecodeError as exc:
309
- raise WebSocketError(
310
- WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message"
311
- ) from exc
312
- msg = WSMessage(WSMsgType.CLOSE, close_code, close_message)
313
- elif payload:
314
- raise WebSocketError(
315
- WSCloseCode.PROTOCOL_ERROR,
316
- f"Invalid close frame: {fin} {opcode} {payload!r}",
317
- )
318
- else:
319
- msg = WSMessage(WSMsgType.CLOSE, 0, "")
320
-
321
- self.queue.feed_data(msg, 0)
322
-
323
- elif opcode == WSMsgType.PING:
324
- self.queue.feed_data(
325
- WSMessage(WSMsgType.PING, payload, ""), len(payload)
326
- )
327
-
328
- elif opcode == WSMsgType.PONG:
329
- self.queue.feed_data(
330
- WSMessage(WSMsgType.PONG, payload, ""), len(payload)
331
- )
332
-
333
- elif (
334
- opcode not in (WSMsgType.TEXT, WSMsgType.BINARY)
335
- and self._opcode is None
336
- ):
337
- raise WebSocketError(
338
- WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}"
339
- )
340
- else:
341
- # load text/binary
342
- if not fin:
343
- # got partial frame payload
344
- if opcode != WSMsgType.CONTINUATION:
345
- self._opcode = opcode
346
- self._partial.extend(payload)
347
- if self._max_msg_size and len(self._partial) >= self._max_msg_size:
348
- raise WebSocketError(
349
- WSCloseCode.MESSAGE_TOO_BIG,
350
- "Message size {} exceeds limit {}".format(
351
- len(self._partial), self._max_msg_size
352
- ),
353
- )
354
- else:
355
- # previous frame was non finished
356
- # we should get continuation opcode
357
- if self._partial:
358
- if opcode != WSMsgType.CONTINUATION:
359
- raise WebSocketError(
360
- WSCloseCode.PROTOCOL_ERROR,
361
- "The opcode in non-fin frame is expected "
362
- "to be zero, got {!r}".format(opcode),
363
- )
364
-
365
- if opcode == WSMsgType.CONTINUATION:
366
- assert self._opcode is not None
367
- opcode = self._opcode
368
- self._opcode = None
369
-
370
- self._partial.extend(payload)
371
- if self._max_msg_size and len(self._partial) >= self._max_msg_size:
372
- raise WebSocketError(
373
- WSCloseCode.MESSAGE_TOO_BIG,
374
- "Message size {} exceeds limit {}".format(
375
- len(self._partial), self._max_msg_size
376
- ),
377
- )
378
-
379
- # Decompress process must to be done after all packets
380
- # received.
381
- if compressed:
382
- self._partial.extend(_WS_DEFLATE_TRAILING)
383
- payload_merged = self._decompressobj.decompress(
384
- self._partial, self._max_msg_size
385
- )
386
- if self._decompressobj.unconsumed_tail:
387
- left = len(self._decompressobj.unconsumed_tail)
388
- raise WebSocketError(
389
- WSCloseCode.MESSAGE_TOO_BIG,
390
- "Decompressed message size {} exceeds limit {}".format(
391
- self._max_msg_size + left, self._max_msg_size
392
- ),
393
- )
394
- else:
395
- payload_merged = bytes(self._partial)
396
-
397
- self._partial.clear()
398
-
399
- if opcode == WSMsgType.TEXT:
400
- try:
401
- text = payload_merged.decode("utf-8")
402
- self.queue.feed_data(
403
- WSMessage(WSMsgType.TEXT, text, ""), len(text)
404
- )
405
- except UnicodeDecodeError as exc:
406
- raise WebSocketError(
407
- WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message"
408
- ) from exc
409
- else:
410
- self.queue.feed_data(
411
- WSMessage(WSMsgType.BINARY, payload_merged, ""),
412
- len(payload_merged),
413
- )
414
-
415
- return False, b""
416
-
417
- def parse_frame(
418
- self, buf: bytes
419
- ) -> List[Tuple[bool, Optional[int], bytearray, Optional[bool]]]:
420
- """Return the next frame from the socket."""
421
- frames = []
422
- if self._tail:
423
- buf, self._tail = self._tail + buf, b""
424
-
425
- start_pos = 0
426
- buf_length = len(buf)
427
-
428
- while True:
429
- # read header
430
- if self._state == WSParserState.READ_HEADER:
431
- if buf_length - start_pos >= 2:
432
- data = buf[start_pos : start_pos + 2]
433
- start_pos += 2
434
- first_byte, second_byte = data
435
-
436
- fin = (first_byte >> 7) & 1
437
- rsv1 = (first_byte >> 6) & 1
438
- rsv2 = (first_byte >> 5) & 1
439
- rsv3 = (first_byte >> 4) & 1
440
- opcode = first_byte & 0xF
441
-
442
- # frame-fin = %x0 ; more frames of this message follow
443
- # / %x1 ; final frame of this message
444
- # frame-rsv1 = %x0 ;
445
- # 1 bit, MUST be 0 unless negotiated otherwise
446
- # frame-rsv2 = %x0 ;
447
- # 1 bit, MUST be 0 unless negotiated otherwise
448
- # frame-rsv3 = %x0 ;
449
- # 1 bit, MUST be 0 unless negotiated otherwise
450
- #
451
- # Remove rsv1 from this test for deflate development
452
- if rsv2 or rsv3 or (rsv1 and not self._compress):
453
- raise WebSocketError(
454
- WSCloseCode.PROTOCOL_ERROR,
455
- "Received frame with non-zero reserved bits",
456
- )
457
-
458
- if opcode > 0x7 and fin == 0:
459
- raise WebSocketError(
460
- WSCloseCode.PROTOCOL_ERROR,
461
- "Received fragmented control frame",
462
- )
463
-
464
- has_mask = (second_byte >> 7) & 1
465
- length = second_byte & 0x7F
466
-
467
- # Control frames MUST have a payload
468
- # length of 125 bytes or less
469
- if opcode > 0x7 and length > 125:
470
- raise WebSocketError(
471
- WSCloseCode.PROTOCOL_ERROR,
472
- "Control frame payload cannot be " "larger than 125 bytes",
473
- )
474
-
475
- # Set compress status if last package is FIN
476
- # OR set compress status if this is first fragment
477
- # Raise error if not first fragment with rsv1 = 0x1
478
- if self._frame_fin or self._compressed is None:
479
- self._compressed = True if rsv1 else False
480
- elif rsv1:
481
- raise WebSocketError(
482
- WSCloseCode.PROTOCOL_ERROR,
483
- "Received frame with non-zero reserved bits",
484
- )
485
-
486
- self._frame_fin = bool(fin)
487
- self._frame_opcode = opcode
488
- self._has_mask = bool(has_mask)
489
- self._payload_length_flag = length
490
- self._state = WSParserState.READ_PAYLOAD_LENGTH
491
- else:
492
- break
493
-
494
- # read payload length
495
- if self._state == WSParserState.READ_PAYLOAD_LENGTH:
496
- length = self._payload_length_flag
497
- if length == 126:
498
- if buf_length - start_pos >= 2:
499
- data = buf[start_pos : start_pos + 2]
500
- start_pos += 2
501
- length = UNPACK_LEN2(data)[0]
502
- self._payload_length = length
503
- self._state = (
504
- WSParserState.READ_PAYLOAD_MASK
505
- if self._has_mask
506
- else WSParserState.READ_PAYLOAD
507
- )
508
- else:
509
- break
510
- elif length > 126:
511
- if buf_length - start_pos >= 8:
512
- data = buf[start_pos : start_pos + 8]
513
- start_pos += 8
514
- length = UNPACK_LEN3(data)[0]
515
- self._payload_length = length
516
- self._state = (
517
- WSParserState.READ_PAYLOAD_MASK
518
- if self._has_mask
519
- else WSParserState.READ_PAYLOAD
520
- )
521
- else:
522
- break
523
- else:
524
- self._payload_length = length
525
- self._state = (
526
- WSParserState.READ_PAYLOAD_MASK
527
- if self._has_mask
528
- else WSParserState.READ_PAYLOAD
529
- )
530
-
531
- # read payload mask
532
- if self._state == WSParserState.READ_PAYLOAD_MASK:
533
- if buf_length - start_pos >= 4:
534
- self._frame_mask = buf[start_pos : start_pos + 4]
535
- start_pos += 4
536
- self._state = WSParserState.READ_PAYLOAD
537
- else:
538
- break
539
-
540
- if self._state == WSParserState.READ_PAYLOAD:
541
- length = self._payload_length
542
- payload = self._frame_payload
543
-
544
- chunk_len = buf_length - start_pos
545
- if length >= chunk_len:
546
- self._payload_length = length - chunk_len
547
- payload.extend(buf[start_pos:])
548
- start_pos = buf_length
549
- else:
550
- self._payload_length = 0
551
- payload.extend(buf[start_pos : start_pos + length])
552
- start_pos = start_pos + length
553
-
554
- if self._payload_length == 0:
555
- if self._has_mask:
556
- assert self._frame_mask is not None
557
- _websocket_mask(self._frame_mask, payload)
558
-
559
- frames.append(
560
- (self._frame_fin, self._frame_opcode, payload, self._compressed)
561
- )
562
-
563
- self._frame_payload = bytearray()
564
- self._state = WSParserState.READ_HEADER
565
- else:
566
- break
567
-
568
- self._tail = buf[start_pos:]
569
-
570
- return frames
571
-
572
-
573
- class WebSocketWriter:
574
- def __init__(
575
- self,
576
- protocol: BaseProtocol,
577
- transport: asyncio.Transport,
578
- *,
579
- use_mask: bool = False,
580
- limit: int = DEFAULT_LIMIT,
581
- random: Any = random.Random(),
582
- compress: int = 0,
583
- notakeover: bool = False,
584
- ) -> None:
585
- self.protocol = protocol
586
- self.transport = transport
587
- self.use_mask = use_mask
588
- self.randrange = random.randrange
589
- self.compress = compress
590
- self.notakeover = notakeover
591
- self._closing = False
592
- self._limit = limit
593
- self._output_size = 0
594
- self._compressobj: Any = None # actually compressobj
595
-
596
- async def _send_frame(
597
- self, message: bytes, opcode: int, compress: Optional[int] = None
598
- ) -> None:
599
- """Send a frame over the websocket with message as its payload."""
600
- if self._closing and not (opcode & WSMsgType.CLOSE):
601
- raise ConnectionResetError("Cannot write to closing transport")
602
-
603
- rsv = 0
604
-
605
- # Only compress larger packets (disabled)
606
- # Does small packet needs to be compressed?
607
- # if self.compress and opcode < 8 and len(message) > 124:
608
- if (compress or self.compress) and opcode < 8:
609
- if compress:
610
- # Do not set self._compress if compressing is for this frame
611
- compressobj = zlib.compressobj(level=zlib.Z_BEST_SPEED, wbits=-compress)
612
- else: # self.compress
613
- if not self._compressobj:
614
- self._compressobj = zlib.compressobj(
615
- level=zlib.Z_BEST_SPEED, wbits=-self.compress
616
- )
617
- compressobj = self._compressobj
618
-
619
- message = compressobj.compress(message)
620
- message = message + compressobj.flush(
621
- zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH
622
- )
623
- if message.endswith(_WS_DEFLATE_TRAILING):
624
- message = message[:-4]
625
- rsv = rsv | 0x40
626
-
627
- msg_length = len(message)
628
-
629
- use_mask = self.use_mask
630
- if use_mask:
631
- mask_bit = 0x80
632
- else:
633
- mask_bit = 0
634
-
635
- if msg_length < 126:
636
- header = PACK_LEN1(0x80 | rsv | opcode, msg_length | mask_bit)
637
- elif msg_length < (1 << 16):
638
- header = PACK_LEN2(0x80 | rsv | opcode, 126 | mask_bit, msg_length)
639
- else:
640
- header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length)
641
- if use_mask:
642
- mask = self.randrange(0, 0xFFFFFFFF)
643
- mask = mask.to_bytes(4, "big")
644
- message = bytearray(message)
645
- _websocket_mask(mask, message)
646
- self._write(header + mask + message)
647
- self._output_size += len(header) + len(mask) + len(message)
648
- else:
649
- if len(message) > MSG_SIZE:
650
- self._write(header)
651
- self._write(message)
652
- else:
653
- self._write(header + message)
654
-
655
- self._output_size += len(header) + len(message)
656
-
657
- if self._output_size > self._limit:
658
- self._output_size = 0
659
- await self.protocol._drain_helper()
660
-
661
- def _write(self, data: bytes) -> None:
662
- if self.transport is None or self.transport.is_closing():
663
- raise ConnectionResetError("Cannot write to closing transport")
664
- self.transport.write(data)
665
-
666
- async def pong(self, message: bytes = b"") -> None:
667
- """Send pong message."""
668
- if isinstance(message, str):
669
- message = message.encode("utf-8")
670
- await self._send_frame(message, WSMsgType.PONG)
671
-
672
- async def ping(self, message: bytes = b"") -> None:
673
- """Send ping message."""
674
- if isinstance(message, str):
675
- message = message.encode("utf-8")
676
- await self._send_frame(message, WSMsgType.PING)
677
-
678
- async def send(
679
- self,
680
- message: Union[str, bytes],
681
- binary: bool = False,
682
- compress: Optional[int] = None,
683
- ) -> None:
684
- """Send a frame over the websocket with message as its payload."""
685
- if isinstance(message, str):
686
- message = message.encode("utf-8")
687
- if binary:
688
- await self._send_frame(message, WSMsgType.BINARY, compress)
689
- else:
690
- await self._send_frame(message, WSMsgType.TEXT, compress)
691
-
692
- async def close(self, code: int = 1000, message: bytes = b"") -> None:
693
- """Close the websocket, sending the specified code and message."""
694
- if isinstance(message, str):
695
- message = message.encode("utf-8")
696
- try:
697
- await self._send_frame(
698
- PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE
699
- )
700
- finally:
701
- self._closing = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/T_T_F_A_.py DELETED
@@ -1,5 +0,0 @@
1
- from . import asciiTable
2
-
3
-
4
- class table_T_T_F_A_(asciiTable.asciiTable):
5
- pass
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/index-e2533c7c.js DELETED
@@ -1,2 +0,0 @@
1
- import{S as j,e as B,s as H,N as L,K as o,U as d,p as g,n as T,A as v,B as S,h as q,k as h,o as b,z as k,v as w,x as M,E as z,ae as C,O as E,q as A,r as D,F}from"./index-3370be2a.js";import{B as K}from"./Button-89624748.js";function N(s){let e,a,i;return{c(){e=L("div"),o(e,"id",s[0]),o(e,"class",a="prose "+s[1].join(" ")+" svelte-1yrv54"),o(e,"data-testid","markdown"),o(e,"dir",i=s[5]?"rtl":"ltr"),d(e,"min",s[4]),d(e,"hide",!s[2])},m(t,_){g(t,e,_),e.innerHTML=s[3],s[7](e)},p(t,[_]){_&8&&(e.innerHTML=t[3]),_&1&&o(e,"id",t[0]),_&2&&a!==(a="prose "+t[1].join(" ")+" svelte-1yrv54")&&o(e,"class",a),_&32&&i!==(i=t[5]?"rtl":"ltr")&&o(e,"dir",i),_&18&&d(e,"min",t[4]),_&6&&d(e,"hide",!t[2])},i:T,o:T,d(t){t&&v(e),s[7](null)}}}function O(s,e,a){let{elem_id:i=""}=e,{elem_classes:t=[]}=e,{visible:_=!0}=e,{value:r}=e,{min_height:u=!1}=e,{rtl:l=!1}=e;const m=S();let c;function f(n){q[n?"unshift":"push"](()=>{c=n,a(6,c)})}return s.$$set=n=>{"elem_id"in n&&a(0,i=n.elem_id),"elem_classes"in n&&a(1,t=n.elem_classes),"visible"in n&&a(2,_=n.visible),"value"in n&&a(3,r=n.value),"min_height"in n&&a(4,u=n.min_height),"rtl"in n&&a(5,l=n.rtl)},s.$$.update=()=>{s.$$.dirty&8&&m("change")},[i,t,_,r,u,l,c,f]}class U extends j{constructor(e){super(),B(this,e,O,N,H,{elem_id:0,elem_classes:1,visible:2,value:3,min_height:4,rtl:5})}}function G(s){let e,a,i,t,_;const r=[s[4],{variant:"center"}];let u={};for(let l=0;l<r.length;l+=1)u=z(u,r[l]);return e=new C({props:u}),t=new U({props:{min_height:s[4]&&s[4].status!=="complete",value:s[3],elem_id:s[0],elem_classes:s[1],visible:s[2],rtl:s[5]}}),t.$on("change",s[7]),{c(){h(e.$$.fragment),a=E(),i=L("div"),h(t.$$.fragment),o(i,"class","svelte-1ed2p3z"),d(i,"pending",s[4]?.status==="pending")},m(l,m){b(e,l,m),g(l,a,m),g(l,i,m),b(t,i,null),_=!0},p(l,m){const c=m&16?A(r,[D(l[4]),r[1]]):{};e.$set(c);const f={};m&16&&(f.min_height=l[4]&&l[4].status!=="complete"),m&8&&(f.value=l[3]),m&1&&(f.elem_id=l[0]),m&2&&(f.elem_classes=l[1]),m&4&&(f.visible=l[2]),m&32&&(f.rtl=l[5]),t.$set(f),(!_||m&16)&&d(i,"pending",l[4]?.status==="pending")},i(l){_||(k(e.$$.fragment,l),k(t.$$.fragment,l),_=!0)},o(l){w(e.$$.fragment,l),w(t.$$.fragment,l),_=!1},d(l){l&&(v(a),v(i)),M(e,l),M(t)}}}function I(s){let e,a;return e=new K({props:{visible:s[2],elem_id:s[0],elem_classes:s[1],container:!1,$$slots:{default:[G]},$$scope:{ctx:s}}}),{c(){h(e.$$.fragment)},m(i,t){b(e,i,t),a=!0},p(i,[t]){const _={};t&4&&(_.visible=i[2]),t&1&&(_.elem_id=i[0]),t&2&&(_.elem_classes=i[1]),t&575&&(_.$$scope={dirty:t,ctx:i}),e.$set(_)},i(i){a||(k(e.$$.fragment,i),a=!0)},o(i){w(e.$$.fragment,i),a=!1},d(i){M(e,i)}}}function J(s,e,a){let{label:i}=e,{elem_id:t=""}=e,{elem_classes:_=[]}=e,{visible:r=!0}=e,{value:u=""}=e,{loading_status:l}=e,{rtl:m=!1}=e;const c=S();function f(n){F.call(this,s,n)}return s.$$set=n=>{"label"in n&&a(6,i=n.label),"elem_id"in n&&a(0,t=n.elem_id),"elem_classes"in n&&a(1,_=n.elem_classes),"visible"in n&&a(2,r=n.visible),"value"in n&&a(3,u=n.value),"loading_status"in n&&a(4,l=n.loading_status),"rtl"in n&&a(5,m=n.rtl)},s.$$.update=()=>{s.$$.dirty&64&&c("change")},[t,_,r,u,l,m,i,f]}class P extends j{constructor(e){super(),B(this,e,J,I,H,{label:6,elem_id:0,elem_classes:1,visible:2,value:3,loading_status:4,rtl:5})}}const V=P,W=["static"],X=s=>({type:{payload:"string"},description:{payload:"HTML rendering of markdown"}});export{V as Component,X as document,W as modes};
2
- //# sourceMappingURL=index-e2533c7c.js.map
 
 
 
spaces/DaleChen/AutoGPT/autogpt/memory/weaviate.py DELETED
@@ -1,127 +0,0 @@
1
- import uuid
2
-
3
- import weaviate
4
- from weaviate import Client
5
- from weaviate.embedded import EmbeddedOptions
6
- from weaviate.util import generate_uuid5
7
-
8
- from autogpt.config import Config
9
- from autogpt.memory.base import MemoryProviderSingleton, get_ada_embedding
10
-
11
-
12
- def default_schema(weaviate_index):
13
- return {
14
- "class": weaviate_index,
15
- "properties": [
16
- {
17
- "name": "raw_text",
18
- "dataType": ["text"],
19
- "description": "original text for the embedding",
20
- }
21
- ],
22
- }
23
-
24
-
25
- class WeaviateMemory(MemoryProviderSingleton):
26
- def __init__(self, cfg):
27
- auth_credentials = self._build_auth_credentials(cfg)
28
-
29
- url = f"{cfg.weaviate_protocol}://{cfg.weaviate_host}:{cfg.weaviate_port}"
30
-
31
- if cfg.use_weaviate_embedded:
32
- self.client = Client(
33
- embedded_options=EmbeddedOptions(
34
- hostname=cfg.weaviate_host,
35
- port=int(cfg.weaviate_port),
36
- persistence_data_path=cfg.weaviate_embedded_path,
37
- )
38
- )
39
-
40
- print(
41
- f"Weaviate Embedded running on: {url} with persistence path: {cfg.weaviate_embedded_path}"
42
- )
43
- else:
44
- self.client = Client(url, auth_client_secret=auth_credentials)
45
-
46
- self.index = WeaviateMemory.format_classname(cfg.memory_index)
47
- self._create_schema()
48
-
49
- @staticmethod
50
- def format_classname(index):
51
- # weaviate uses capitalised index names
52
- # The python client uses the following code to format
53
- # index names before the corresponding class is created
54
- if len(index) == 1:
55
- return index.capitalize()
56
- return index[0].capitalize() + index[1:]
57
-
58
- def _create_schema(self):
59
- schema = default_schema(self.index)
60
- if not self.client.schema.contains(schema):
61
- self.client.schema.create_class(schema)
62
-
63
- def _build_auth_credentials(self, cfg):
64
- if cfg.weaviate_username and cfg.weaviate_password:
65
- return weaviate.AuthClientPassword(
66
- cfg.weaviate_username, cfg.weaviate_password
67
- )
68
- if cfg.weaviate_api_key:
69
- return weaviate.AuthApiKey(api_key=cfg.weaviate_api_key)
70
- else:
71
- return None
72
-
73
- def add(self, data):
74
- vector = get_ada_embedding(data)
75
-
76
- doc_uuid = generate_uuid5(data, self.index)
77
- data_object = {"raw_text": data}
78
-
79
- with self.client.batch as batch:
80
- batch.add_data_object(
81
- uuid=doc_uuid,
82
- data_object=data_object,
83
- class_name=self.index,
84
- vector=vector,
85
- )
86
-
87
- return f"Inserting data into memory at uuid: {doc_uuid}:\n data: {data}"
88
-
89
- def get(self, data):
90
- return self.get_relevant(data, 1)
91
-
92
- def clear(self):
93
- self.client.schema.delete_all()
94
-
95
- # weaviate does not yet have a neat way to just remove the items in an index
96
- # without removing the entire schema, therefore we need to re-create it
97
- # after a call to delete_all
98
- self._create_schema()
99
-
100
- return "Obliterated"
101
-
102
- def get_relevant(self, data, num_relevant=5):
103
- query_embedding = get_ada_embedding(data)
104
- try:
105
- results = (
106
- self.client.query.get(self.index, ["raw_text"])
107
- .with_near_vector({"vector": query_embedding, "certainty": 0.7})
108
- .with_limit(num_relevant)
109
- .do()
110
- )
111
-
112
- if len(results["data"]["Get"][self.index]) > 0:
113
- return [
114
- str(item["raw_text"]) for item in results["data"]["Get"][self.index]
115
- ]
116
- else:
117
- return []
118
-
119
- except Exception as err:
120
- print(f"Unexpected error {err=}, {type(err)=}")
121
- return []
122
-
123
- def get_stats(self):
124
- result = self.client.query.aggregate(self.index).with_meta_count().do()
125
- class_data = result["data"]["Aggregate"][self.index]
126
-
127
- return class_data[0]["meta"] if class_data else {}