parquet-converter commited on
Commit
025e77b
·
1 Parent(s): 1ded444

Update parquet files (step 85 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/README.md +0 -18
  2. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Atlas ti 7 Crack Keygen Serial Key A Powerful Workbench for Textual Graphical Audio and Video Data.md +0 -110
  3. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bitter Enchantment Yvonne Whittal Epub A Harlequin Romance Novel.md +0 -140
  4. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Cs 1.6 Wallhack Opengl32.dll Download Skype LINK.md +0 -68
  5. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Data Recovery Software for Windows 10 64 Bit Free Download with Crack A Risky and Unethical Choice.md +0 -25
  6. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download Microsoft 365 32 Bit A Complete Guide for Beginners.md +0 -47
  7. spaces/1gistliPinn/ChatGPT4/Examples/Chhello Divas Gujarati Movie WORK Download.md +0 -60
  8. spaces/1line/AutoGPT/tests/unit/test_chat.py +0 -86
  9. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/APK App Reviews Find the Best Apps for Your Android Phone.md +0 -108
  10. spaces/1phancelerku/anime-remove-background/Cmo sobrevivir en Last Island of Survival el mejor juego de accin y aventura para Android.md +0 -22
  11. spaces/1phancelerku/anime-remove-background/Football League 2023 The Best Soccer Game on the Play Store.md +0 -82
  12. spaces/7hao/bingo/src/components/markdown.tsx +0 -9
  13. spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/commons/align_ops.py +0 -25
  14. spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/nn/model_utils.py +0 -49
  15. spaces/AIZero2Hero4Health/8-NLPSimilarityHeatmapCluster-SL/README.md +0 -12
  16. spaces/AP123/IllusionDiffusion/share_btn.py +0 -83
  17. spaces/ASJMO/freegpt/client/css/theme-toggler.css +0 -33
  18. spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/visibility/pokemon.py +0 -25
  19. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/bracketparser2-plugin.d.ts +0 -8
  20. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/GetSizerConfig.js +0 -8
  21. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/flip/Flip.d.ts +0 -2
  22. spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/denoise_audio.py +0 -18
  23. spaces/AlexWelcing/MusicLM/ setup.py +0 -37
  24. spaces/Alican/pixera/options/train_options.py +0 -40
  25. spaces/Amrrs/DragGan-Inversion/PTI/models/StyleCLIP/mapper/training/ranger.py +0 -164
  26. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/controlnet/train_controlnet_sdxl.py +0 -1251
  27. spaces/AnishKumbhar/ChatBot/text-generation-webui-main/update_wsl.bat +0 -11
  28. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/utils/path.py +0 -101
  29. spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/.github/pull_request_template.md +0 -10
  30. spaces/BAAI/AltDiffusion/css_and_js.py +0 -92
  31. spaces/Banbri/zcvzcv/src/components/ui/toaster.tsx +0 -35
  32. spaces/BernardoOlisan/vqganclip/taming-transformers/main.py +0 -582
  33. spaces/BetterAPI/BetterChat/src/lib/stores/pendingMessageIdToRetry.ts +0 -4
  34. spaces/BiTransSciencia/www/index.css +0 -167
  35. spaces/Big-Web/MMSD/env/Lib/site-packages/botocore/vendored/requests/packages/__init__.py +0 -3
  36. spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/config/_validate_pyproject/__init__.py +0 -34
  37. spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/package_index.py +0 -1126
  38. spaces/CVPR/LIVE/thrust/thrust/system/detail/sequential/per_device_resource.h +0 -22
  39. spaces/CikeyQI/meme-api/meme_generator/download.py +0 -117
  40. spaces/CikeyQI/meme-api/meme_generator/memes/alike/__init__.py +0 -24
  41. spaces/Cpp4App/Cpp4App/CDM/detect_merge/Element.py +0 -113
  42. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/varLib/cff.py +0 -696
  43. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/httpcore/_utils.py +0 -36
  44. spaces/Dao3/DaJuZi_OrangeCatTheGreat/style.css +0 -84
  45. spaces/Datasculptor/DescriptionGPT/tools/get_cc_tags.py +0 -194
  46. spaces/Dinoking/Guccio-AI-Designer/netdissect/upsegmodel/resnext.py +0 -183
  47. spaces/DragGan/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/utils/__init__.py +0 -0
  48. spaces/Eddycrack864/Applio-Inference/lib/uvr5_pack/lib_v5/nets_123821KB.py +0 -122
  49. spaces/Felix123456/bingo/src/components/learn-more.tsx +0 -39
  50. spaces/Fengbinbin/gpt-academic/crazy_functions/test_project/cpp/cppipc/queue.h +0 -216
spaces/1acneusushi/gradio-2dmoleculeeditor/README.md DELETED
@@ -1,18 +0,0 @@
1
- ---
2
- title: Gradio 2D Molecule Editor (SMILES)
3
- emoji: ⚛️
4
- colorFrom: green
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 3.27.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- duplicated_from: simonduerr/gradio-2dmoleculeeditor
12
- ---
13
-
14
- This repo contains a sample on how to use the Ketcher Molecule Editor with gradio.
15
-
16
- To adapt simply add your ML model in the run function.
17
-
18
- Ketcher is licensed under Apache2.0 License https://github.com/epam/ketcher
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Atlas ti 7 Crack Keygen Serial Key A Powerful Workbench for Textual Graphical Audio and Video Data.md DELETED
@@ -1,110 +0,0 @@
1
-
2
- <br> - Explanation of what a serial key is and why it is required for activation | | H2: How to get a valid serial key for ATLAS.ti 7? | - Option 1: Purchase a license from the official website <br> - Option 2: Request a free trial license from the official website <br> - Option 3: Contact the support team if you lost your serial key | | H2: How to activate ATLAS.ti 7 with your serial key? | - Step 1: Download and install ATLAS.ti 7 on your computer <br> - Step 2: Launch ATLAS.ti 7 and enter your serial key <br> - Step 3: Verify your activation status and enjoy the software | | H2: How to troubleshoot common issues with serial keys? | - Issue 1: Serial key not accepted or invalid <br> - Issue 2: Serial key already used or expired <br> - Issue 3: Serial key lost or forgotten | | H2: Conclusion | - Summary of the main points <br> - Call to action | **Table 2: Article with HTML formatting** ```html <h1>What is ATLAS.ti 7 and why do you need a serial key?</h1>
3
- <p>If you are looking for a powerful and versatile software for qualitative data analysis, you might have heard of ATLAS.ti 7. ATLAS.ti 7 is a software that helps you organize, analyze, and interpret your textual, graphical, audio, and video data. With ATLAS.ti 7, you can:</p>
4
- <ul>
5
- <li>Create and manage projects with multiple documents and sources</li>
6
- <li>Code and annotate your data with various tools and methods</li>
7
- <li>Explore and visualize your data with networks, charts, maps, and reports</li>
8
- <li>Query and compare your data with advanced search and filter functions</li>
9
- <li>Share and collaborate with other researchers using cloud services or export options</li>
10
- </ul>
11
- <p>ATLAS.ti 7 is a software that requires a license to use. A license is a legal agreement that grants you the right to use the software for a certain period of time and under certain conditions. To activate your license, you need a serial key. A serial key is a unique string of characters that identifies your license and verifies your purchase. Without a valid serial key, you cannot use ATLAS.ti 7.</p>
12
- <h2>atlas ti 7 crack keygen serial key</h2><br /><p><b><b>Download File</b> &bull;&bull;&bull; <a href="https://byltly.com/2uKzvi">https://byltly.com/2uKzvi</a></b></p><br /><br />
13
- <h2>How to get a valid serial key for ATLAS.ti 7?</h2>
14
- <p>There are three ways to get a valid serial key for ATLAS.ti 7:</p>
15
- <ol>
16
- <li>Purchase a license from the official website. You can choose from different types of licenses depending on your needs and preferences. For example, you can buy a single-user license, a multi-user license, an educational license, or a student license. After you complete your payment, you will receive an email with your serial key and instructions on how to activate it.</li>
17
- <li>Request a free trial license from the official website. If you want to try out ATLAS.ti 7 before buying it, you can request a free trial license that lasts for 30 days. To do this, you need to fill out a form with your name, email address, and institution. After you submit the form, you will receive an email with your serial key and instructions on how to activate it.</li>
18
- <li>Contact the support team if you lost your serial key. If you already purchased a license but lost or misplaced your serial key, you can contact the support team at [email protected]. They can retrieve your serial key for you as long as you provide the exact email address under which the license was purchased or registered.</li>
19
- </ol>
20
- <h2>How to activate ATLAS.ti 7 with your serial key?</h2>
21
- <p>To activate ATLAS.ti 7 with your serial key, follow these steps:</p>
22
- <ol>
23
- <li>Download and install ATLAS.ti 7 on your computer. You can download the installation file from the official website or from the link provided in your email.</li>
24
- <li>Launch ATLAS.ti 7 and enter your serial key. When you start ATLAS.ti 7 for the first time, you will see a dialog box asking you to enter your serial key. Copy and paste your serial key from your email or type it manually. Make sure there are no spaces or typos.</li>
25
- <li>Verify your activation status and enjoy the software. After you enter your serial key, you will see a message confirming that your activation was successful. You can also check your activation status by clicking on Help > About ATLAS.ti in the menu bar. You should see your license type, expiration date, and serial number. Now you can use all the features of ATLAS.ti 7 without any limitations.</li>
26
- </ol>
27
- <h2>How to troubleshoot common issues with serial keys?</h2>
28
- <p>Sometimes, you might encounter some issues with your serial keys. Here are some common problems and how to solve them:</p>
29
- <ul>
30
- <li><strong>Serial key not accepted or invalid.</strong> This could happen if you entered the wrong serial key or if there was an error in the activation process. Make sure you entered the correct serial key without any spaces or typos. If the problem persists, contact the support team at [email protected].</li>
31
- <li><strong>Serial key already used or expired.</strong> This could happen if you tried to activate more than one copy of ATLAS.ti 7 with the same serial key or if your license period has ended. Each serial key can only be used for one installation of ATLAS.ti 7 on one computer. If you want to use ATLAS.ti 7 on another computer, you need to buy another license or transfer your existing license. If your license period has expired, you need to renew it or buy a new one.</li>
32
- <li><strong>Serial key lost or forgotten.</strong> This could happen if you deleted or misplaced your email with your serial key or if you forgot where you stored it. If this happens, contact the support team at [email protected]. They can retrieve your serial key for you as long as you provide the exact email address under which the license was purchased or registered.</li>
33
- </ul>
34
- <h2>Conclusion</h2>
35
- <p>In this article, we have explained what ATLAS.ti 7 is and why it requires a serial key for activation. We have also shown you how to get a valid serial key, how to activate ATLAS.ti 7 with it, and how to troubleshoot common issues with it. We hope this article has been helpful and informative for you.</p>
36
- <p>If you are interested in using ATLAS.ti 7 for your qualitative data analysis projects, we recommend that you visit the official website at https://atlasti.com/ where you can find more information about the software, its features, its pricing, its support, and its community. You can also request a free trial license or purchase a full license from there.</p>
37
- <p>If you have any questions or feedback about this article or about ATLAS.ti 7 in general, feel free to leave a comment below or contact us at [email protected]. We would love to hear from you!</p>
38
- <p>atlas ti 7 license key crack<br />
39
- atlas ti 7 full version free download<br />
40
- atlas ti 7 activation code<br />
41
- atlas ti 7 serial number key crack<br />
42
- atlas ti 7 qualitative data analysis software<br />
43
- atlas ti 7 crack download<br />
44
- atlas ti 7 patch<br />
45
- atlas ti 7 torrent<br />
46
- atlas ti 7 keygen generator<br />
47
- atlas ti 7 product key<br />
48
- atlas ti 7 registration code<br />
49
- atlas ti 7 free trial version<br />
50
- atlas ti 7 windows 10<br />
51
- atlas ti 7 crack windows 7<br />
52
- atlas ti 7 crack windows 8<br />
53
- atlas ti 7 crack windows vista<br />
54
- atlas ti 7 crack windows xp<br />
55
- atlas ti 7 crack4windows<br />
56
- atlas ti 7 scientific software development office-tools<br />
57
- atlas ti 7 data visualization options<br />
58
- atlas ti 7 import project from version 6<br />
59
- atlas ti 7 object explorer<br />
60
- atlas ti 7 object manager<br />
61
- atlas ti 7 code lists<br />
62
- atlas ti 7 weightable codes<br />
63
- atlas ti 7 color coding<br />
64
- atlas ti 7 diagram view<br />
65
- atlas ti 8 crack keygen serial key<br />
66
- how to crack ATLAS.ti <br />
67
- ATLAS.ti crack with serial key <br />
68
- ATLAS.ti download link free <br />
69
- ATLAS.ti reviews <br />
70
- ATLAS.ti spricka <br />
71
- ATLAS.ti serial number <br />
72
- ATLAS.ti کے سیریل نمبر کیلئے شکریہ <br />
73
- ATLAS.ti Tack för <br />
74
- ATLAS.ti 漢語 हिन्दी English <br />
75
- ATLAS.ti provides you with a comprehensive platform for qualitative analysis and research <br />
76
- ATLAS.ti rich set of tools <br />
77
- ATLAS.ti evaluate data, run queries and searches, as well as store and visualize results <br />
78
- ATLAS.ti assign categories to information that is relevant to your objective and set relationships between different chunks of data <br />
79
- ATLAS.ti toolbox to highlight important data and annotate texts, associate links and resources, and create comments <br />
80
- ATLAS.ti advanced searching, sorting and filtering options <br />
81
- ATLAS.ti intuitive interface <br />
82
- ATLAS.ti organizing your data prior to building your project <br />
83
- ATLAS.ti handle multiple sources simultaneously, supports linking across documents <br />
84
- ATLAS.ti reliable and powerful qualitative research utility <br />
85
- ATLAS.ti activation code <br />
86
- ATLAS.ti download keygen serial crack <br />
87
- ATLAS.ti function-oriented usability</p>
88
- <h3>Frequently Asked Questions</h3>
89
- <ul>
90
- <li><strong>What is the difference between ATLAS.ti 7 and ATLAS.ti Cloud?</strong></li>
91
- <p>ATLAS.ti Cloud is an online version of ATLAS.ti that runs on any web browser without requiring any installation or download. It has similar features as ATLAS.ti 7 but also offers some advantages such as easy collaboration, automatic updates, unlimited storage space, and lower costs.</p>
92
- <li><strong>Can I use my ATLAS.ti 7 serial key for ATLAS.ti Cloud?</strong></li>
93
- <p>No, they are different products that require different licenses. If you want to use both products, you need to buy separate licenses for each one.</p>
94
- <li><strong>Can I upgrade my ATLAS.ti 7 license to a newer version?</strong></li>
95
- <p>Yes, if there is a newer version of ATLAS.ti available (such as ATLAS.ti 8), you can upgrade your existing license at a discounted price by visiting https://atlasti.com/buy/upgrade/.</p>
96
- <li><strong>Can I transfer my ATLAS.ti 7 license to another computer?</strong></li>
97
- <p>Yes, if you want to use ATLAS.ti 7 on another computer (such as when changing devices), you can transfer your existing license by following these steps:</p>
98
- ```html <ol>
99
- <li>Deactivate your license on your old computer by clicking on Help > Deactivate License in the menu bar.</li>
100
- <li>Install ATLAS.ti 7 on your new computer and activate it with your serial key.</li>
101
- <li>If you have any problems with the transfer, contact the support team at [email protected].</li>
102
- </ol>
103
- <li><strong>Can I use ATLAS.ti 7 offline?</strong></li>
104
- <p>Yes, you can use ATLAS.ti 7 offline without an internet connection. However, you need an internet connection for the initial activation of your license and for periodic verification of your license status. You also need an internet connection if you want to use the cloud services or the online help.</p>
105
- <li><strong>Can I get a refund for my ATLAS.ti 7 license?</strong></li>
106
- <p>No, once you have activated your license, you cannot get a refund for it. However, you can request a free trial license before buying a full license to make sure that ATLAS.ti 7 meets your expectations and requirements.</p>
107
- </ul>
108
- ```</p> 0a6ba089eb<br />
109
- <br />
110
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Bitter Enchantment Yvonne Whittal Epub A Harlequin Romance Novel.md DELETED
@@ -1,140 +0,0 @@
1
- <br />
2
- <h1>Bitter Enchantment by Yvonne Whittal: A Review</h1>
3
- <p>If you are looking for a classic romance novel with a strong heroine, a brooding hero, and a dramatic plot, you might want to check out Bitter Enchantment by Yvonne Whittal. This book was published in 1979 by Harlequin and is one of the many works by this prolific author. In this article, I will give you a brief overview of what Bitter Enchantment is about, who Yvonne Whittal is, and what I liked and disliked about this book.</p>
4
- <h2>bitter enchantment yvonne whittal epub</h2><br /><p><b><b>Download</b> &#10031;&#10031;&#10031; <a href="https://byltly.com/2uKvKr">https://byltly.com/2uKvKr</a></b></p><br /><br />
5
- <h2>Introduction</h2>
6
- <h3>What is Bitter Enchantment about?</h3>
7
- <p>Bitter Enchantment is a story of Melanie, a young woman who lives with her grandmother in their ancestral home. Her father's death has left them in financial difficulties, but they manage to get by. However, their situation changes when Melanie learns that her father had taken a loan from Jason Kerr, a wealthy businessman who now wants to sell their house as collateral. Melanie is desperate to save her home and her grandmother's health, but Jason offers her only one way out: to marry him. Melanie agrees to his proposition, but soon realizes that Jason has a hidden motive for wanting her as his wife. He blames her for his brother's death and wants to make her pay. Will Melanie be able to endure his bitter enchantment and find love in his arms?</p>
8
- <h3>Who is Yvonne Whittal?</h3>
9
- <p>Yvonne Whittal is a South African author who has written over 80 romance novels for Harlequin and Mills & Boon. She started writing in 1975 and retired in 2002. Her books are set in various locations around the world, but often feature South African characters and settings. She is known for creating strong-willed heroines who face challenging situations and arrogant heroes who eventually fall for them. Some of her popular titles include The Silver Falcon, Dark Ransom, and Stormy Encounter.</p>
10
- <h2>Main Body</h2>
11
- <h3>The Plot</h3>
12
- <h4>The Conflict</h4>
13
- <p>The main conflict in Bitter Enchantment is the clash between Melanie and Jason. They have a history of animosity that goes back to when Melanie was engaged to Jason's brother, Mark. Mark died in a car accident that Jason believes was caused by Melanie's infidelity. He holds a grudge against her and wants to make her suffer. He also wants to take over her family's land, which he considers rightfully his. He forces her to marry him by threatening to sell her house and ruin her grandmother's health.</p>
14
- <h4>The Romance</h4>
15
- <p>The romance in Bitter Enchantment is a slow-burn one that develops gradually from hate to love. Melanie and Jason have a lot of misunderstandings and arguments, but they also have moments of tenderness and passion. They both have hidden feelings for each other that they try to deny or suppress. They also have to deal with external obstacles such as Jason's ex-girlfriend, Melanie's former fiancé, and Jason's family. They eventually overcome their differences and realize that they belong together.</p>
16
- <p>bitter enchantment yvonne whittal free download<br />
17
- bitter enchantment yvonne whittal pdf<br />
18
- bitter enchantment yvonne whittal read online<br />
19
- bitter enchantment yvonne whittal internet archive<br />
20
- bitter enchantment yvonne whittal open library<br />
21
- bitter enchantment yvonne whittal goodreads<br />
22
- bitter enchantment yvonne whittal harlequin<br />
23
- bitter enchantment yvonne whittal mills and boon<br />
24
- bitter enchantment yvonne whittal book review<br />
25
- bitter enchantment yvonne whittal summary<br />
26
- bitter enchantment yvonne whittal characters<br />
27
- bitter enchantment yvonne whittal quotes<br />
28
- bitter enchantment yvonne whittal romance novel<br />
29
- bitter enchantment yvonne whittal ebook<br />
30
- bitter enchantment yvonne whittal kindle<br />
31
- bitter enchantment yvonne whittal amazon<br />
32
- bitter enchantment yvonne whittal paperback<br />
33
- bitter enchantment yvonne whittal hardcover<br />
34
- bitter enchantment yvonne whittal audiobook<br />
35
- bitter enchantment yvonne whittal online reading<br />
36
- bitter enchantment yvonne whittal epub bud<br />
37
- bitter enchantment yvonne whittal epub vk<br />
38
- bitter enchantment yvonne whittal epub download<br />
39
- bitter enchantment yvonne whittal epub free<br />
40
- bitter enchantment yvonne whittal epub books<br />
41
- bitter enchantment by yvonne whittal epub<br />
42
- read bitter enchantment by yvonne whittal epub<br />
43
- download bitter enchantment by yvonne whittal epub<br />
44
- free bitter enchantment by yvonne whittal epub<br />
45
- books like bitter enchantment by yvonne whittal epub<br />
46
- similar to bitter enchantment by yvonne whittal epub<br />
47
- other books by yvonne whittal epub<br />
48
- best books by yvonne whittal epub<br />
49
- popular books by yvonne whittal epub<br />
50
- new books by yvonne whittal epub<br />
51
- upcoming books by yvonne whittal epub<br />
52
- old books by yvonne whittal epub<br />
53
- rare books by yvonne whittal epub<br />
54
- vintage books by yvonne whittal epub<br />
55
- classic books by yvonne whittal epub<br />
56
- buy books by yvonne whittal epub<br />
57
- sell books by yvonne whittal epub<br />
58
- trade books by yvonne whittal epub<br />
59
- borrow books by yvonne whittal epub<br />
60
- lend books by yvonne whittal epub<br />
61
- gift books by yvonne whittal epub<br />
62
- recommend books by yvonne whittal epub<br />
63
- review books by yvonne whittal epub<br />
64
- rate books by yvonne whittal epub</p>
65
- <h4>The Resolution</h4>
66
- <p>The resolution in Bitter Enchantment is a happy one that involves a lot of drama and suspense. Melanie discovers that Jason's brother is not dead, but alive and well. He had faked his death to escape from his debts and his involvement in illegal activities. He also reveals that he was the one who caused the accident that nearly killed him and Jason, not Melanie. He tries to blackmail Jason and kidnap Melanie, but Jason rescues her and confronts him. Mark confesses his crimes and apologizes to Jason and Melanie before fleeing the country. Jason then admits his love for Melanie and asks for her forgiveness. Melanie forgives him and accepts his love.</p>
67
- <h3>The Characters</h3>
68
- <h4>Melanie</h4>
69
- <p>Melanie is the heroine of Bitter Enchantment. She is a brave, loyal, and compassionate woman who loves her grandmother and her home dearly. She is also independent, intelligent, and hard-working. She runs a small nursery business and helps out at a local school. She has suffered a lot of loss and pain in her life, but she does not let it break her spirit. She stands up to Jason's cruelty and challenges him at every turn. She also has a soft spot for him and tries to understand him better.</p>
70
- <h4>Jason Kerr</h4>
71
- <p>Jason Kerr is the hero of Bitter Enchantment. He is a powerful, wealthy, and handsome man who owns a successful mining company. He is also cold, ruthless, and bitter. He blames Melanie for his brother's death and wants to make her pay. He also wants to take over her land, which he believes belongs to his family. He forces her to marry him by blackmailing her with her house and grandmother's health. He treats her harshly and keeps her at a distance.</p>
72
- <h4>Other Characters</h4>
73
- <p>Other characters in Bitter Enchantment include:</p>
74
- <ul>
75
- <li>Mrs. Rossiter: Melanie's grandmother who raised her after her parents' death.</li>
76
- <li>Mark Kerr: Jason's brother who was engaged to Melanie before his supposed death.</li>
77
- <li>Lisa: Jason's ex-girlfriend who still loves him and tries to win him back.</li>
78
- <li>Greg: Melanie's former fiancé who cheated on her with Lisa.</li>
79
- <li>Mr. And Mrs. Kerr: Jason's parents who disapprove of his marriage to Melanie.</li>
80
- <li>Susan: Jason's sister who befriends Melanie.</li>
81
- <li>Peter: Susan's husband who works for Jason.</li>
82
- <li>Jenny: A young girl who lives near Melanie's house and helps her with the nursery.</li>
83
- </ul>
84
- <h3>The Writing Style</h3>
85
- <h4>The Language</h4>
86
- <p>The language in Bitter Enchantment is simple, clear, and descriptive. The author uses vivid words and phrases to create a sense of place and atmosphere. She also uses dialogue and narration to convey the emotions and thoughts of the characters.</p>
87
- <h4>The Emotions</h4>
88
- <p>The emotions in Bitter Enchantment are intense, complex, and realistic. The author explores the feelings of anger, resentment, guilt, fear, sadness, longing, attraction, love, joy, etc., that the characters experience throughout the story.</p>
89
- <h4>The Themes</h4>
90
- <p>The themes in Bitter Enchantment are universal ones that relate to human nature and relationships such as:</p>
91
- <ul>
92
- <li>Hate vs Love: How hate can turn into love when people overcome their prejudices and misunderstandings.</li>
93
- <li>Revenge vs Forgiveness: How revenge can be destructive and harmful while forgiveness can be healing and liberating.</li>
94
- <li>Lies vs Truth: How lies can cause pain and confusion while truth can bring clarity and peace.</li>
95
- <li>Family vs Self: How family can be both a source of support or conflict depending on how they respect or interfere with one's choices.</li>
96
- <li>Past vs Present: How past can affect one's present actions or feelings depending on how they cope or move on from it.</li>
97
- </ul>
98
- <h2>Conclusion</h2>
99
- <p>Bitter Enchantment by Yvonne Whittal is a captivating romance novel that will keep you hooked from start to finish. It has an engaging plot with twists and turns; well-developed characters with depth and growth; an expressive writing style with vivid language; an emotional tone with realistic feelings; an interesting theme with universal appeal; an exotic setting with rich details; an exciting climax with suspense; an satisfying ending with happiness; an attractive cover with eye-catching colors; an affordable price with value for money; an easy format with epub compatibility; an available source with online access; an enjoyable experience with reading pleasure; an unforgettable impression with lasting memory; an recommendable option with positive feedback; an irresistible temptation with no regrets!</p>
100
- # FAQs <ol type="Q">
101
- <li>Where can I get Bitter Enchantment by Yvonne Whittal?</li>
102
- <ol type="A">
103
- <li>You can get it from various online platforms such as Amazon Kindle Store or Internet Archive.</li></ol></ol>
104
- <ol type="Q">
105
- ```html takes about 3 hours to read Bitter Enchantment by Yvonne Whittal, depending on your reading speed and interest.</li></ol></ol>
106
- <ol type="Q">
107
- <li>What are some similar books to Bitter Enchantment by Yvonne Whittal?</li><ol type="A"><li>Some similar books to Bitter Enchantment by Yvonne Whittal are:</li>
108
- <ul>
109
- <li>The Silver Falcon by Yvonne Whittal: Another romance novel by the same author that features a heroine who inherits a farm and a hero who wants to buy it.</li>
110
- <li>The Devil's Arms by Charlotte Lamb: A romance novel by another Harlequin author that features a heroine who marries a hero who hates her for causing his brother's death.</li>
111
- <li>The Thorn Birds by Colleen McCullough: A historical saga by a famous Australian author that features a heroine who loves a hero who is a priest.</li>
112
- </ul></ol></ol>
113
- <ol type="Q">
114
- <li>What are some of the reviews of Bitter Enchantment by Yvonne Whittal?</li><ol type="A"><li>Some of the reviews of Bitter Enchantment by Yvonne Whittal are:</li>
115
- <ul>
116
- <li>"This is one of my favorite books by Yvonne Whittal. I love the chemistry between Melanie and Jason and how they overcome their obstacles. The plot is intriguing and the writing is captivating. I highly recommend this book to anyone who loves romance." - 5 stars on Goodreads</li>
117
- <li>"This is a typical Harlequin romance with a lot of drama and angst. I liked the heroine but I hated the hero. He was too cruel and arrogant for my taste. The plot was predictable and the writing was mediocre. I wouldn't read this book again." - 2 stars on Goodreads</li>
118
- <li>"This is a classic romance novel with a twist. I enjoyed the story and the characters. The heroine was strong and loyal and the hero was brooding and complex. The plot was suspenseful and the writing was expressive. I think this book is worth reading." - 4 stars on Amazon</li>
119
- </ul></ol></ol>
120
- <ol type="Q">
121
- <li>What are some of the benefits of reading Bitter Enchantment by Yvonne Whittal?</li><ol type="A"><li>Some of the benefits of reading Bitter Enchantment by Yvonne Whittal are:</li>
122
- <ul>
123
- <li>You can improve your vocabulary and grammar by learning new words and phrases.</li>
124
- <li>You can enhance your imagination and creativity by visualizing the scenes and characters.</li>
125
- <li>You can increase your knowledge and awareness by learning about different cultures and places.</li>
126
- <li>You can develop your empathy and compassion by understanding the emotions and perspectives of the characters.</li>
127
- <li>You can relax and have fun by escaping from reality and entering a fictional world.</li>
128
- </ul></ol></ol>
129
- <ol type="Q">
130
- <li>What are some of the challenges of reading Bitter Enchantment by Yvonne Whittal?</li><ol type="A"><li>Some of the challenges of reading Bitter Enchantment by Yvonne Whittal are:</li>
131
- <ul>
132
- <li>You may find it hard to relate to or like some of the characters or situations.</li>
133
- <li>You may find it boring or repetitive if you are not interested in the genre or style.</li>
134
- <li>You may find it difficult or confusing if you are not familiar with the language or terminology.</li>
135
- <li>You may find it offensive or inappropriate if you disagree with some of the views or values expressed.</li>
136
- <li>You may find it distracting or addictive if you spend too much time or energy on it.</li>
137
- </ul></ol></ol>
138
- ```</p> 0a6ba089eb<br />
139
- <br />
140
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Cs 1.6 Wallhack Opengl32.dll Download Skype LINK.md DELETED
@@ -1,68 +0,0 @@
1
- <br />
2
- <h1>How to Download and Use Wallhack for CS 1.6 with Skype</h1>
3
- <p>If you are a fan of Counter-Strike 1.6, you might have heard of wallhack, a cheat that allows you to see through walls and other objects in the game. Wallhack can give you an unfair advantage over your opponents, but it can also make the game more fun and challenging. In this article, we will show you how to download and use wallhack for CS 1.6 with opengl32.dll, a file that modifies the graphics engine of the game. We will also show you how to use Skype, a popular communication app, to enhance your gaming experience with your friends or teammates.</p>
4
- <h2>cs 1.6 wallhack opengl32.dll download skype</h2><br /><p><b><b>Download</b> ->>> <a href="https://byltly.com/2uKwxl">https://byltly.com/2uKwxl</a></b></p><br /><br />
5
- <h2>Steps to Download Wallhack for CS 1.6</h2>
6
- <p>Wallhack is a cheat that modifies the game files to make certain objects transparent or visible through walls. There are many versions of wallhack available online, but one of the most simple and easy ones is opengl32.dll, a file that replaces the original OpenGL graphics library of the game. Here are the steps to download and use wallhack for CS 1.6:</p>
7
- <ol>
8
- <li>Choose a reliable source and download the file. You can find many links to download opengl32.dll on YouTube, forums, or websites that offer hacks for CS 1.6. For example, you can download it from [here](^5^) or [here](^6^). Make sure you scan the file for viruses before opening it.</li>
9
- <li>Extract the file and copy it to your CS 1.6 folder. After downloading the file, you need to unzip it using a program like WinRAR or 7-Zip. Then, you need to copy the opengl32.dll file to your CS 1.6 folder, which is usually located at C:\Program Files\Valve\cstrike or C:\Program Files (x86)\Steam\steamapps\common\Half-Life\cstrike.</li>
10
- <li>Run CS 1.6 and activate the wallhack with F1 or CTRL. After copying the file, you can run CS 1.6 as usual and join a server or start a bot match. To activate the wallhack, you need to press F1 or CTRL on your keyboard. You will see a message on the top left corner of your screen saying "WallHack ON". To deactivate the wallhack, you need to press F1 or CTRL again. You will see a message saying "WallHack OFF".</li>
11
- </ol>
12
- <p>Congratulations, you have successfully downloaded and used wallhack for CS 1.6. Now, let's see how you can use it effectively in the game.</p>
13
- <h2>Tips and Tricks to Use Wallhack Effectively</h2>
14
- <p>Wallhack can be a powerful cheat that can help you win more matches and have more fun in CS 1.6. However, it can also be risky and detected by anti-cheat systems or other players. Therefore, you need to use it wisely and carefully. Here are some tips and tricks to use wallhack effectively:</p>
15
- <ul>
16
- <li>Adjust your video settings to OpenGL mode. Wallhack works best with OpenGL mode, which is the default graphics mode of CS 1.6. To check or change your video settings, go to Options > Video > Renderer and select OpenGL.</li>
17
- <li>Toggle between different wallhack modes with F2. Wallhack has two modes: normal and advanced. Normal mode makes all objects transparent, while advanced mode makes only enemies and weapons visible through walls. You can switch between these modes by pressing F2 on your keyboard.</li>
18
- <li>Disable smoke and flash effects with F3. Smoke and flash grenades can be annoying and obstruct your vision, especially when you use wallhack. To disable these effects, you can press F3 on your keyboard. You will see a message saying "Smoke/Flash OFF". To enable them again, press F3 again.</li>
19
- <li>Use crosshair for sniping with F4. Wallhack can help you snipe your enemies more easily, but you still need to aim accurately. To help you with that, you can use a crosshair that shows the exact center of your screen. To enable the crosshair, press F4 on your keyboard. You will see a small dot in the middle of your screen. To disable it, press F4 again.</li>
20
- <li>Enable aimbot for better accuracy with F5. Aimbot is another cheat that automatically aims at your enemies' heads when you shoot. It can make you more accurate and deadly, but it can also be more obvious and risky. To enable aimbot, press F5 on your keyboard. You will see a message saying "AimBot ON". To disable it, press F5 again.</li>
21
- </ul>
22
- <p>These are some of the tips and tricks to use wallhack effectively in CS 1.6. However, remember that wallhack is still a cheat and it can ruin the game for others. Use it at your own risk and discretion.</p>
23
- <h2>How to Download and Use Skype for CS 1.6</h2>
24
- <p>Skype is a popular communication app that allows you to make free voice and video calls with anyone around the world. Skype can also enhance your gaming experience with CS 1.6 by allowing you to communicate with your friends or teammates while playing. Here are the steps to download and use Skype for CS 1.6:</p>
25
- <ol>
26
- <li>Download Skype from the official website or app store. You can download Skype for free from [here] or from your device's app store. Make sure you download the latest version of Skype for better performance and compatibility.</li>
27
- <li>Create an account or sign in with your existing one. After downloading Skype, you need to create an account or sign in with your existing one. You can use your email address, phone number, or Microsoft account to create or sign in to Skype.</li>
28
- <li>Add your friends or teammates as contacts. To communicate with your friends or teammates on Skype, you need to add them as contacts first. You can search for them by their name, username, email address, or phone number on Skype. You can also send them an invitation link or QR code to join Skype.</li>
29
- <li>Start a voice or video call with them while playing CS 1.6. After adding your contacts, you can start a voice or video call with them by clicking on their name and selecting the call icon on Skype. You can also create a group call with multiple contacts by clicking on the new chat icon and selecting the call icon on Skype. You can then minimize Skype and run CS 1.6 as usual while talking to your contacts on Skype.</li>
30
- </ol>
31
- <p>That's how you can download and use Skype for CS 1.6. Now, let's see what are the benefits of using Skype for CS 1.6.</p>
32
- <p></p>
33
- <h2>Benefits of Using Skype for CS 1.6</h2>
34
- <p>Skype is not only a communication app, but also a gaming tool that can improve your gaming experience with CS 1.6 in many ways. Here are some of the benefits of using Skype for CS 1.6 :</p>
35
- <ul>
36
- <li>Communicate with your team more easily and efficiently. Skype allows you to talk to your team in real time and coordinate your strategies and tactics. You can also use Skype's chat feature to send text messages, emojis, stickers, or files to your team. Skype can help you improve your teamwork and performance in CS 1.6.</li>
37
- <li>Share your screen or gameplay with others. Skype also allows you to share your screen or gameplay with your contacts. You can show them what you are doing on your computer or how you are playing CS 1.6. You can also watch their screen or gameplay and give them feedback or tips. Skype can help you learn from each other and have more fun in CS 1.6.</li>
38
- <li>Record your calls and save them for later review. Skype also allows you to record your calls and save them for later review. You can replay your voice or video calls and analyze your mistakes or achievements in CS 1.6. You can also share your recordings with others or upload them to social media or YouTube. Skype can help you improve your skills and showcase your talents in CS 1.6.</li>
39
- <li>Enjoy high-quality sound and video with low latency. Skype also offers high-quality sound and video with low latency. You can hear and see your contacts clearly and smoothly without any delays or interruptions. Skype can help you enjoy a better gaming experience with CS 1.6.</li>
40
- </ul>
41
- <p>These are some of the benefits of using Skype for CS 1.6. However, remember that Skype is still a communication app and it can consume some of your bandwidth and resources while gaming. Therefore, you need to optimize your Skype settings and performance while gaming.</p>
42
- <h2>Conclusion</h2>
43
- <p>In this article, we have shown you how to download and use wallhack for CS 1.6 with opengl32.dll, a file that modifies the graphics engine of the game. We have also shown you how to use Skype, a popular communication app, to enhance your gaming experience with your friends or teammates. Wallhack and Skype can be powerful tools that can help you win more matches and have more fun in CS 1.6, but they can also be risky and detected by anti-cheat systems or other players. Therefore, you need to use them wisely and carefully.</p>
44
- <p>If you want to download wallhack for CS 1.6, you can find many links on YouTube, forums, or websites that offer hacks for CS 1.6. For example, you can download it from [here] or [here]. If you want to download Skype for CS 1.6, you can download it for free from [here] or from your device's app store.</p>
45
- <p>We hope you have enjoyed this article and learned something new about wallhack and Skype for CS 1.6. If you have any questions or comments, please feel free to leave them below. Thank you for reading and happy gaming!</p>
46
- <h2>FAQs</h2>
47
- <p>Here are some of the frequently asked questions about wallhack and Skype for CS 1.6:</p>
48
- <ol>
49
- <li><b>What are some of the best sources to download wallhack for CS 1.6?</b><br>
50
- Some of the best sources to download wallhack for CS 1.6 are YouTube, forums, or websites that offer hacks for CS 1.6. For example, you can download it from [here] or [here]. However, make sure you scan the file for viruses before opening it.</li>
51
- <li><b>Is wallhack detectable by anti-cheat systems?</b><br>
52
- Wallhack is detectable by anti-cheat systems, especially if you use it excessively or carelessly. Anti-cheat systems can detect the changes in the game files or the abnormal behavior of the players using wallhack. Therefore, you need to use wallhack wisely and carefully.</li>
53
- <li><b>How can I customize the wallhack settings?</b><br>
54
- You can customize the wallhack settings by pressing F2, F3, F4, or F5 on your keyboard while playing CS 1.6. These keys allow you to toggle between different wallhack modes, disable smoke and flash effects, use crosshair for sniping, or enable aimbot for better accuracy.</li>
55
- <li><b>Is Skype compatible with other games besides CS 1.6?</b><br>
56
- Skype is compatible with other games besides CS 1.6, as long as they do not interfere with each other's performance or functionality. You can use Skype with any game that allows you to run other programs in the background while playing.</li>
57
- <li><b>How can I improve my Skype performance while gaming?</b><br>
58
- You can improve your Skype performance while gaming by following these tips:</li>
59
- <ul>
60
- <li>Close any unnecessary programs or tabs that may consume your bandwidth or resources while gaming.</li>
61
- <li>Adjust your Skype settings to reduce the quality or resolution of your voice or video calls.</li>
62
- <li>Use a wired connection or a stable Wi-Fi network to avoid any lag or interference while gaming.</li>
63
- <li>Use headphones or earphones to avoid any echo or feedback while gaming.</li>
64
- <li>Update your Skype and your game to the latest version to avoid any bugs or glitches while gaming.</li>
65
- </ul>
66
- </ol></p> b2dd77e56b<br />
67
- <br />
68
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Data Recovery Software for Windows 10 64 Bit Free Download with Crack A Risky and Unethical Choice.md DELETED
@@ -1,25 +0,0 @@
1
-
2
- ```html
3
- <h1>How to Use Data Recovery Software for Windows 10 64 Bit Free Download with Crack</h1>
4
- <p>Data loss is a common problem that can happen to anyone who uses a computer. Whether it is due to accidental deletion, formatting, virus attack, system crash, or other reasons, losing important files can be frustrating and stressful. Fortunately, there are data recovery software that can help you recover your lost data in a few simple steps.</p>
5
- <p>However, not all data recovery software are reliable and safe. Some of them may contain malware or spyware that can harm your computer or steal your personal information. Others may not be able to recover your data completely or may damage your files further. That is why you should be careful when choosing a data recovery software for your Windows 10 64 bit system.</p>
6
- <h2>data recovery software for windows 10 64 bit free download with crack</h2><br /><p><b><b>Download Zip</b> &#10038;&#10038;&#10038; <a href="https://byltly.com/2uKwGQ">https://byltly.com/2uKwGQ</a></b></p><br /><br />
7
- <p>One of the options that some people may consider is to use a data recovery software for Windows 10 64 bit free download with crack. This means downloading a pirated version of a data recovery software that has been cracked or modified to bypass the registration or activation process. This may seem like a tempting way to save money and get a full-featured data recovery software without paying anything.</p>
8
- <p>However, using a data recovery software for Windows 10 64 bit free download with crack is not recommended and can have serious consequences. Here are some of the risks and disadvantages of using a cracked data recovery software:</p>
9
- <ul>
10
- <li>It may not work properly or at all. A cracked data recovery software may have been tampered with or corrupted by hackers or malicious users. It may not be compatible with your Windows 10 64 bit system or may have bugs or errors that can affect its performance and functionality.</li>
11
- <li>It may contain viruses or malware. A cracked data recovery software may have been infected with viruses or malware that can damage your computer or compromise your security. It may steal your personal data, such as passwords, bank accounts, credit card numbers, etc. It may also display annoying ads or pop-ups that can interfere with your user experience.</li>
12
- <li>It may cause further data loss or damage. A cracked data recovery software may not be able to recover your data correctly or completely. It may overwrite your existing files or sectors on your hard drive, making them unrecoverable. It may also cause more problems to your system, such as freezing, crashing, blue screen of death, etc.</li>
13
- <li>It may violate the law and ethics. A cracked data recovery software is an illegal product that infringes the intellectual property rights of the original developers. By using it, you are breaking the law and exposing yourself to legal actions or penalties. You are also disrespecting the hard work and efforts of the legitimate software creators who deserve to be paid for their products and services.</li>
14
- </ul>
15
- <p>Therefore, it is better to avoid using a data recovery software for Windows 10 64 bit free download with crack and instead opt for a reliable and reputable data recovery software that can guarantee your safety and satisfaction. Here are some of the benefits of using a genuine data recovery software:</p>
16
- <ul>
17
- <li>It works efficiently and effectively. A genuine data recovery software has been tested and verified by professional developers and users. It has been designed to be compatible with your Windows 10 64 bit system and to recover your data in various scenarios and formats.</li>
18
- <li>It is safe and secure. A genuine data recovery software does not contain any viruses or malware that can harm your computer or privacy. It also does not display any ads or pop-ups that can annoy you or distract you from your task.</li>
19
- <li>It recovers your data completely and safely. A genuine data recovery software can recover your data with high success rate and quality. It does not overwrite your existing files or sectors on your hard drive, but instead creates a copy of them in a different location. It also allows you to preview and select the files you want to recover before saving them.</li>
20
- <li>It respects the law and ethics. A genuine data recovery software is a legal product that respects the intellectual property rights of the original developers. By using it, you are complying with the law and supporting the software industry that provides you with useful products and services.</li>
21
- </ul>
22
- <p>In conclusion, using a data recovery software for Windows 10 64 bit free download with crack is not a good idea and can have negative consequences for you and your computer. Instead, you should use a genuine data recovery software that can offer you more benefits and advantages in terms of quality, safety, security, and legality.</p>
23
- ```</p> ddb901b051<br />
24
- <br />
25
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download Microsoft 365 32 Bit A Complete Guide for Beginners.md DELETED
@@ -1,47 +0,0 @@
1
-
2
- <h1>How to Download Microsoft 365 32 Bit for Your PC</h1>
3
- <p>Microsoft 365 is a subscription service that offers a suite of productivity apps and cloud services for your personal and professional needs. Whether you want to create documents, spreadsheets, presentations, or emails, Microsoft 365 has you covered.</p>
4
- <h2>download microsoft 365 32 bit</h2><br /><p><b><b>Download</b> &#10027; <a href="https://byltly.com/2uKwBL">https://byltly.com/2uKwBL</a></b></p><br /><br />
5
- <p>But before you can enjoy the benefits of Microsoft 365, you need to download and install it on your PC. And depending on your system requirements, you may need to choose between the 32-bit and the 64-bit versions of Microsoft 365.</p>
6
- <p>In this article, we will show you how to download Microsoft 365 32 bit for your PC, and what are the advantages and disadvantages of using this version.</p>
7
- <h2>What is the Difference Between 32 Bit and 64 Bit?</h2>
8
- <p>The difference between 32 bit and 64 bit refers to the way your computer's processor handles information. The 32-bit version can handle up to 4 GB of RAM, while the 64-bit version can handle more than that. This means that the 64-bit version can run faster and more efficiently than the 32-bit version, especially if you have a lot of programs or files open at the same time.</p>
9
- <p>However, the 64-bit version also requires more disk space and memory than the 32-bit version. And some older devices or software may not be compatible with the 64-bit version. So, if you have a PC with limited resources or older hardware or software, you may want to use the 32-bit version instead.</p>
10
- <h2>How to Download Microsoft 365 32 Bit for Your PC</h2>
11
- <p>To download Microsoft 365 32 bit for your PC, you need to have a valid Microsoft account and a Microsoft 365 subscription. If you don't have them yet, you can create an account and sign up for a subscription on the <a href="https://www.microsoft.com/en-us/microsoft-365">Microsoft website</a>.</p>
12
- <p></p>
13
- <p>Once you have your account and subscription ready, follow these steps to download Microsoft 365 32 bit for your PC:</p>
14
- <ol>
15
- <li>Go to <a href="https://www.office.com/">office.com</a> and sign in with your Microsoft account.</li>
16
- <li>Click on the "Install Office" button on the top right corner of the page.</li>
17
- <li>On the next page, click on the "Other install options" link under the "Install Office on all your devices" section.</li>
18
- <li>On the next page, click on the "Advanced options" link under the "Office apps & devices" section.</li>
19
- <li>On the next page, select the "32-bit" option from the drop-down menu under the "Version" section.</li>
20
- <li>Click on the "Download" button to start downloading Microsoft 365 32 bit for your PC.</li>
21
- <li>Once the download is complete, run the setup file and follow the instructions to install Microsoft 365 on your PC.</li>
22
- </ol>
23
- <p>Congratulations! You have successfully downloaded and installed Microsoft 365 32 bit for your PC. You can now start using the apps and services that are included in your subscription.</p>
24
-
25
- <h2>How to Activate Microsoft 365 on Your PC</h2>
26
- <p>After you have installed Microsoft 365 on your PC, you need to activate it with your Microsoft account and subscription. This will allow you to access all the features and updates that are available for your plan. To activate Microsoft 365 on your PC, follow these steps:</p>
27
- <ol>
28
- <li>Open any of the Microsoft 365 apps, such as Word, Excel, or PowerPoint.</li>
29
- <li>Click on the "Sign in" button on the top right corner of the app window.</li>
30
- <li>Enter your Microsoft account email and password, and click on the "Next" button.</li>
31
- <li>Follow the prompts to complete the activation process.</li>
32
- </ol>
33
- <p>That's it! You have successfully activated Microsoft 365 on your PC. You can now enjoy the full functionality of the apps and services that are included in your subscription.</p>
34
- <h2>How to Update Microsoft 365 on Your PC</h2>
35
- <p>To keep your Microsoft 365 apps and services running smoothly and securely, you need to update them regularly. Microsoft releases updates for Microsoft 365 every month, which include bug fixes, security patches, and new features. To update Microsoft 365 on your PC, follow these steps:</p>
36
- <ol>
37
- <li>Open any of the Microsoft 365 apps, such as Word, Excel, or PowerPoint.</li>
38
- <li>Click on the "File" tab on the top left corner of the app window.</li>
39
- <li>Click on the "Account" option on the left sidebar.</li>
40
- <li>Click on the "Update Options" button under the "Product Information" section.</li>
41
- <li>Select the "Update Now" option from the drop-down menu.</li>
42
- <li>Wait for the update to download and install.</li>
43
- <li>Restart your PC if prompted.</li>
44
- </ol>
45
- <p>That's it! You have successfully updated Microsoft 365 on your PC. You can now enjoy the latest features and improvements that are available for your plan.</p> ddb901b051<br />
46
- <br />
47
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Chhello Divas Gujarati Movie WORK Download.md DELETED
@@ -1,60 +0,0 @@
1
-
2
- <h1>How to Download Chhello Divas Gujarati Movie Online</h1>
3
-
4
- <p>Chhello Divas is one of the most popular and successful Gujarati comedy movies of all time. The movie was released in 2015 and directed by Krishnadev Yagnik. The movie features a star-studded cast of Malhar Thakar, Yash Soni, Janki Bodiwala, Mitra Gadhvi, Kinjal Rajpriya, Aarjav Trivedi, Rahul Raval and Netri Trivedi. The movie tells the story of eight college friends and their journey of friendship, love and life. The movie is full of hilarious scenes and dialogues that will make you laugh till your stomach hurts. The movie also has a heartwarming message of friendship and life that will touch your soul.</p>
5
-
6
- <h2>Why You Should Watch Chhello Divas Gujarati Movie</h2>
7
-
8
- <p>Chhello Divas is not just a comedy movie, but also a masterpiece of Gujarati cinema. The movie has many reasons why you should watch it, such as:</p>
9
- <h2>Chhello Divas Gujarati Movie Download</h2><br /><p><b><b>DOWNLOAD</b> &#8250;&#8250;&#8250;&#8250;&#8250; <a href="https://imgfil.com/2uxZVE">https://imgfil.com/2uxZVE</a></b></p><br /><br />
10
-
11
- <ul>
12
- <li>The movie has an amazing cast of young and talented actors who deliver superb performances. The chemistry between the actors is fantastic and they make you feel like you are part of their group.</li>
13
- <li>The movie has a relatable and engaging plot that captures the essence of college life and youth. The movie shows the highs and lows of the relationship between the friends, their dreams and aspirations, their love interests and their challenges.</li>
14
- <li>The movie has a lot of funny scenes and dialogues that will make you laugh out loud. The movie has a perfect blend of humor and emotion that will keep you entertained throughout.</li>
15
- <li>The movie has a beautiful message of friendship and life that will touch your heart. The movie shows how the friends support each other through thick and thin, how they cherish their memories and how they face their future.</li>
16
- </ul>
17
-
18
- <h2>How to Download Chhello Divas Gujarati Movie Online</h2>
19
-
20
- <p>If you want to watch Chhello Divas online or download it on your device, then you have several options to choose from. Here are some of the ways you can enjoy Chhello Divas Gujarati movie download:</p>
21
-
22
- <ul>
23
- <li>You can watch Chhello Divas on Prime Video, which is a popular streaming platform that offers a wide range of movies and shows in various languages. You can either rent or buy the movie on Prime Video and watch it anytime and anywhere.</li>
24
- <li>You can also watch Chhello Divas on JioCinema, which is a digital app that provides access to movies, TV shows, music videos and more. You can stream Chhello Divas on JioCinema for free if you are a Jio subscriber.</li>
25
- <li>Another option is to watch Chhello Divas on YouTube, where you can find the full movie uploaded by Shemaroo Gujarati Manoranjan. You can watch the movie for free on YouTube, but you may have to deal with ads and low quality.</li>
26
- <li>You can also download Chhello Divas from various torrent websites that offer pirated copies of the movie. However, this is illegal and risky as you may face legal actions or viruses on your device.</li>
27
- </ul>
28
-
29
- <h2>Conclusion</h2>
30
-
31
- <p>Chhello Divas is a must-watch movie for anyone who loves comedy and drama. The movie is a perfect example of how Gujarati cinema has evolved and improved over the years. The movie is a masterpiece that will make you laugh, cry and think. If you want to watch Chhello Divas online or download it on your device, then you can use any of the methods mentioned above.</p>
32
- <h2>Chhello Divas Gujarati Movie Download: Reviews and Ratings</h2>
33
-
34
- <p>Chhello Divas has received rave reviews from critics and audiences alike. The movie has been praised for its witty script, brilliant direction, superb acting and hilarious comedy. The movie has also been appreciated for its realistic portrayal of college life and youth culture. The movie has a rating of 8.3 out of 10 on IMDb, which is one of the highest ratings for a Gujarati movie. The movie has also won several awards and accolades, such as the Transmedia Gujarati Screen and Stage Awards, the Radio City Cine Awards and the Gujarat State Film Awards.</p>
35
-
36
- <h2>Chhello Divas Gujarati Movie Download: Songs and Music</h2>
37
-
38
- <p>Chhello Divas has a catchy and melodious soundtrack that complements the mood and theme of the movie. The music of the movie was composed by Meghdhanush, a popular Gujarati rock band. The movie has four songs, namely Kehvu Ghanu Ghanu Che, Aaje Taro Samay Kale Maro Aavse, Dhulo Dhulo and Chhello Divas Theme Song. The songs are sung by various singers, such as Parthiv Gohil, Jigardan Gadhavi, Aishwarya Majmudar, Darshan Raval and Meghdhanush. The songs have become very popular among the Gujarati audience and have received millions of views on YouTube.</p>
39
-
40
- <h2>Chhello Divas Gujarati Movie Download: Sequel and Remake</h2>
41
-
42
- <p>Chhello Divas was such a huge hit that it inspired a sequel and a remake in other languages. The sequel of the movie was titled Chal Man Jeetva Jaiye and was released in 2017. The sequel featured some of the original cast members as well as new actors. The sequel focused on the challenges faced by the friends after they start their professional careers. The remake of the movie was titled Days of Tafree and was released in 2016. The remake was directed by Krishnadev Yagnik himself and featured a new cast of actors. The remake was made in Hindi language and targeted a wider audience.</p>
43
- <h2>Chhello Divas Gujarati Movie Download: Trivia and Facts</h2>
44
-
45
- <p>Chhello Divas is not only a hilarious and entertaining movie, but also a movie that has some interesting trivia and facts behind it. Here are some of them:</p>
46
- <p></p>
47
-
48
- <ul>
49
- <li>Chhello Divas was the debut movie of most of the actors in the movie, such as Malhar Thakar, Yash Soni, Janki Bodiwala, Mitra Gadhvi, Kinjal Rajpriya, Aarjav Trivedi, Rahul Raval and Netri Trivedi. They were all newcomers who auditioned for the movie and impressed the director with their talent and enthusiasm.</li>
50
- <li>Chhello Divas was shot in just 30 days with a budget of 1.87 crore rupees. The movie was made on a shoestring budget and relied on the creativity and hard work of the cast and crew. The movie was shot in various locations in Ahmedabad, such as LD Engineering College, Gujarat University, Karnavati Club and Alpha One Mall.</li>
51
- <li>Chhello Divas was inspired by the real-life experiences of the director Krishnadev Yagnik and his friends. The director wanted to make a movie that reflected his college days and the bond he shared with his friends. He also wanted to make a movie that was relatable and realistic for the Gujarati audience.</li>
52
- <li>Chhello Divas was a blockbuster hit that broke many records at the box office. The movie earned more than 18 crore rupees in its theatrical run and became one of the highest-grossing Gujarati movies of all time. The movie also received a lot of appreciation from celebrities and politicians, such as Amitabh Bachchan, Anil Kapoor, Paresh Rawal, Rishi Kapoor, Smriti Irani and Narendra Modi.</li>
53
- </ul>
54
-
55
- <h2>Chhello Divas Gujarati Movie Download: Conclusion</h2>
56
-
57
- <p>Chhello Divas is a movie that you should not miss if you love comedy and drama. The movie is a perfect example of how Gujarati cinema has evolved and improved over the years. The movie is a masterpiece that will make you laugh, cry and think. If you want to watch Chhello Divas online or download it on your device, then you can use any of the methods mentioned above. However, we recommend you to watch the movie legally on Prime Video or JioCinema and support the makers of this amazing movie.</p>
58
- <p>In conclusion, Chhello Divas is a must-watch movie for anyone who loves comedy and drama. The movie is a perfect example of how Gujarati cinema has evolved and improved over the years. The movie is a masterpiece that will make you laugh, cry and think. If you want to watch Chhello Divas online or download it on your device, then you can use any of the methods mentioned in this article. However, we recommend you to watch the movie legally on Prime Video or JioCinema and support the makers of this amazing movie.</p> 3cee63e6c2<br />
59
- <br />
60
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1line/AutoGPT/tests/unit/test_chat.py DELETED
@@ -1,86 +0,0 @@
1
- # Generated by CodiumAI
2
- import time
3
- import unittest
4
- from unittest.mock import patch
5
-
6
- from autogpt.chat import create_chat_message, generate_context
7
-
8
-
9
- class TestChat(unittest.TestCase):
10
- # Tests that the function returns a dictionary with the correct keys and values when valid strings are provided for role and content.
11
- def test_happy_path_role_content(self):
12
- result = create_chat_message("system", "Hello, world!")
13
- self.assertEqual(result, {"role": "system", "content": "Hello, world!"})
14
-
15
- # Tests that the function returns a dictionary with the correct keys and values when empty strings are provided for role and content.
16
- def test_empty_role_content(self):
17
- result = create_chat_message("", "")
18
- self.assertEqual(result, {"role": "", "content": ""})
19
-
20
- # Tests the behavior of the generate_context function when all input parameters are empty.
21
- @patch("time.strftime")
22
- def test_generate_context_empty_inputs(self, mock_strftime):
23
- # Mock the time.strftime function to return a fixed value
24
- mock_strftime.return_value = "Sat Apr 15 00:00:00 2023"
25
- # Arrange
26
- prompt = ""
27
- relevant_memory = ""
28
- full_message_history = []
29
- model = "gpt-3.5-turbo-0301"
30
-
31
- # Act
32
- result = generate_context(prompt, relevant_memory, full_message_history, model)
33
-
34
- # Assert
35
- expected_result = (
36
- -1,
37
- 47,
38
- 3,
39
- [
40
- {"role": "system", "content": ""},
41
- {
42
- "role": "system",
43
- "content": f"The current time and date is {time.strftime('%c')}",
44
- },
45
- {
46
- "role": "system",
47
- "content": f"This reminds you of these events from your past:\n\n\n",
48
- },
49
- ],
50
- )
51
- self.assertEqual(result, expected_result)
52
-
53
- # Tests that the function successfully generates a current_context given valid inputs.
54
- def test_generate_context_valid_inputs(self):
55
- # Given
56
- prompt = "What is your favorite color?"
57
- relevant_memory = "You once painted your room blue."
58
- full_message_history = [
59
- create_chat_message("user", "Hi there!"),
60
- create_chat_message("assistant", "Hello! How can I assist you today?"),
61
- create_chat_message("user", "Can you tell me a joke?"),
62
- create_chat_message(
63
- "assistant",
64
- "Why did the tomato turn red? Because it saw the salad dressing!",
65
- ),
66
- create_chat_message("user", "Haha, that's funny."),
67
- ]
68
- model = "gpt-3.5-turbo-0301"
69
-
70
- # When
71
- result = generate_context(prompt, relevant_memory, full_message_history, model)
72
-
73
- # Then
74
- self.assertIsInstance(result[0], int)
75
- self.assertIsInstance(result[1], int)
76
- self.assertIsInstance(result[2], int)
77
- self.assertIsInstance(result[3], list)
78
- self.assertGreaterEqual(result[0], 0)
79
- self.assertGreaterEqual(result[1], 0)
80
- self.assertGreaterEqual(result[2], 0)
81
- self.assertGreaterEqual(
82
- len(result[3]), 3
83
- ) # current_context should have at least 3 messages
84
- self.assertLessEqual(
85
- result[1], 2048
86
- ) # token limit for GPT-3.5-turbo-0301 is 2048 tokens
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/APK App Reviews Find the Best Apps for Your Android Phone.md DELETED
@@ -1,108 +0,0 @@
1
- <br />
2
- <h1>What is an APK app and how to use it?</h1>
3
- <p>If you are an Android user, you might have heard of the term "APK app" or seen the .apk file extension on your device. But what exactly is an APK app and how can you use it? In this article, we will explain what an APK app is, how to download, install, update, and uninstall it, and what are the benefits and risks of using it.</p>
4
- <h2>What is an APK app?</h2>
5
- <p>An APK app is an Android application that is packaged in a file format called APK. APK stands for Android Package Kit, and it is the primary way Android apps are distributed and installed. When you download an app from Google Play Store, you are actually downloading and running an APK file in the background, but you have no access to the APK itself.</p>
6
- <h2>apk app</h2><br /><p><b><b>DOWNLOAD</b> > <a href="https://urlin.us/2uT2pA">https://urlin.us/2uT2pA</a></b></p><br /><br />
7
- <h3>APK file format</h3>
8
- <p>An APK file contains all the components of an Android app, such as the code, resources, assets, certificates, and manifest. The manifest is a file that describes the app's name, version, permissions, activities, services, and other information. The certificates are used to verify the authenticity and integrity of the app. The code is compiled into a format called DEX (Dalvik Executable), which can be executed by the Android runtime. The resources and assets are files that provide the app's graphics, sounds, fonts, and other data.</p>
9
- <h3>APK installation</h3>
10
- <p>An APK file can be installed on an Android device by either using the Google Play Store or by sideloading it from a third-party source. Sideloading means transferring and installing an APK file directly from your computer or another device to your Android device, without using the Google Play Store. Sideloading can be useful if you want to install an app that is not available on the Google Play Store, or if you want to install a modified or older version of an app.</p>
11
- <h2>How to use an APK app?</h2>
12
- <p>To use an APK app, you need to first download it from a source and then install it on your device. Here are some steps to follow:</p>
13
- <h3>Downloading APK apps</h3>
14
- <p>You can download APK apps from different sources, such as:</p>
15
- <h4>From Google Play Store</h4>
16
- <p>The easiest and safest way to download APK apps is from the Google Play Store. The Google Play Store is the official app store for Android devices, where you can find millions of apps for various purposes. To download an app from the Google Play Store, you just need to open the store on your device, search for the app you want, and tap on the Install button. The app will be automatically downloaded and installed on your device.</p>
17
- <h4>From third-party sources</h4>
18
- <p>If you want to download an APK app that is not available on the Google Play Store, or if you want to download a modified or older version of an app, you can use a third-party source. A third-party source is any website or platform that offers APK files for download. However, you need to be careful when using third-party sources, as some of them may contain malware or viruses that can harm your device or steal your data. Therefore, you should only use trusted and reputable sources that have positive reviews and ratings from other users. Some examples of popular third-party sources are Uptodown, WhatsApp, and APKMirror. To download an app from a third-party source, you need to visit their website on your device or computer, search for the app you want, and tap on the Download button. The app will be downloaded as an APK file on your device or computer.</p>
19
- <h3>Installing APK apps</h3 <p>Once you have downloaded an APK app, you need to install it on your device. There are different ways to install an APK app, such as:</p>
20
- <h4>Enabling unknown sources</h4>
21
- <p>Before you can install an APK app from a third-party source, you need to enable the option to allow unknown sources on your device. This option lets you install apps that are not from the Google Play Store. To enable unknown sources, you need to go to your device's settings, tap on Security or Privacy, and toggle on the switch for Unknown sources or Install unknown apps. You may also need to grant permission for the app or browser that you are using to download the APK app.</p>
22
- <p>apk app store<br />
23
- apk app download<br />
24
- apk app installer<br />
25
- apk app bundle<br />
26
- apk app not installed<br />
27
- apk app for pc<br />
28
- apk app for firestick<br />
29
- apk app for android tv<br />
30
- apk app for ios<br />
31
- apk app for windows 10<br />
32
- apk app maker<br />
33
- apk app editor<br />
34
- apk app backup<br />
35
- apk app extractor<br />
36
- apk app cloner<br />
37
- apk app mod<br />
38
- apk app hack<br />
39
- apk app pro<br />
40
- apk app premium<br />
41
- apk app cracked<br />
42
- apk app update<br />
43
- apk app version<br />
44
- apk app size<br />
45
- apk app info<br />
46
- apk app checker<br />
47
- apk app manager<br />
48
- apk app launcher<br />
49
- apk app browser<br />
50
- apk app downloader<br />
51
- apk app converter<br />
52
- apk app signer<br />
53
- apk app verifier<br />
54
- apk app optimizer<br />
55
- apk app analyzer<br />
56
- apk app scanner<br />
57
- apk app cleaner<br />
58
- apk app remover<br />
59
- apk app uninstaller<br />
60
- apk app locker<br />
61
- apk app protector</p>
62
- <h4>Using a file manager or a browser</h4>
63
- <p>If you have downloaded the APK app on your device, you can use a file manager or a browser to locate and install it. A file manager is an app that lets you access and manage the files and folders on your device. A browser is an app that lets you access and view web pages on the internet. To use a file manager or a browser to install an APK app, you need to open the file manager or browser on your device, navigate to the folder where the APK file is stored, and tap on the APK file. You will see a prompt asking you to confirm the installation. Tap on Install and wait for the installation to complete.</p>
64
- <h4>Using an APK installer app</h4>
65
- <p>If you have downloaded the APK app on your computer, you can use an APK installer app to transfer and install it on your device. An APK installer app is an app that lets you install APK files from your computer to your device via a USB cable or a wireless connection. Some examples of APK installer apps are ApowerManager, AirDroid, and Pure APK Install. To use an APK installer app, you need to download and install the app on your computer and your device, connect your device to your computer via a USB cable or a wireless connection, launch the app on both devices, select the APK file from your computer, and click on Install. The app will transfer and install the APK file on your device.</p>
66
- <h3>Updating and uninstalling APK apps</h3>
67
- <p>After installing an APK app, you may need to update or uninstall it at some point. Here are some tips to do so:</p>
68
- <h4>Updating from the same source</h4>
69
- <p>If you want to update an APK app, you need to download and install the latest version of the app from the same source that you used before. For example, if you downloaded an app from Uptodown, you need to visit Uptodown again and download the updated version of the app. You can also use the Uptodown app to check for updates and install them automatically. Updating from the same source ensures that you get the authentic and compatible version of the app.</p>
70
- <h4>Uninstalling from the settings or the launcher</h4>
71
- <p>If you want to uninstall an APK app, you can do so from your device's settings or launcher. The settings are where you can manage your device's features and preferences. The launcher is where you can access and launch your apps. To uninstall an APK app from the settings, you need to go to your device's settings, tap on Apps or Applications, find and tap on the app that you want to uninstall, and tap on Uninstall. To uninstall an APK app from the launcher, you need to long-press on the app icon, drag it to the Uninstall option at the top of the screen, and release it.</p>
72
- <h2>Conclusion</h2>
73
- <p>An APK app is an Android application that is packaged in a file format called APK. You can download and install APK apps from different sources, such as Google Play Store or third-party websites. However, you need to be careful when using third-party sources, as some of them may contain malware or viruses that can harm your device or steal your data. Therefore, you should only use trusted and reputable sources that have positive reviews and ratings from other users. You should also enable unknown sources on your device before installing an APK app from a third-party source. You can update or uninstall APK apps from the same source that you used before, or from your device's settings or launcher.</p>
74
- <p>We hope this article has helped you understand what an APK app is and how to use it. If you have any questions or comments, please feel free to leave them below.</p>
75
- <h2>FAQs</h2>
76
- <p>Here are some frequently asked questions about APK apps:</p>
77
- <ol>
78
- <li><b>What are the benefits of using APK apps?</b></li>
79
- <p>Some of the benefits of using APK apps are:</p>
80
- <ul>
81
- <li>You can access apps that are not available on the Google Play Store, such as region-restricted or banned apps.</li>
82
- <li>You can install modified or older versions of apps that have features or functions that you prefer.</li>
83
- <li>You can save bandwidth and storage space by downloading APK files on your computer and transferring them to your device.</li>
84
- <li>You can customize your device and apps by installing APK files that offer themes, wallpapers, icons, and other options.</li>
85
- </ul>
86
- <li><b>What are the risks of using APK apps?</b></li>
87
- <p>Some of the risks of using APK apps are:</p>
88
- <ul>
89
- <li>You may download and install malware or viruses that can harm your device or steal your data.</li>
90
- <li>You may violate the terms and conditions of the app developers or the Google Play Store by installing unauthorized or modified apps.</li>
91
- <li>You may encounter compatibility or performance issues by installing apps that are not designed for your device or Android version.</li>
92
- <li>You may lose access to updates or support from the app developers or the Google Play Store by installing apps from third-party sources.</li>
93
- </ul>
94
- <li><b>How can I check if an APK app is safe?</b></li>
95
- <p>Before downloading and installing an APK app, you should check if it is safe by following these steps:</p>
96
- <ul>
97
- <li>Use a trusted and reputable source that has positive reviews and ratings from other users.</li>
98
- <li>Scan the APK file with an antivirus or malware scanner app before installing it.</li>
99
- <li>Check the permissions and information of the app before installing it.</li>
100
- <li>Backup your device and data before installing an APK app.</li>
101
- </ul>
102
- <li><b>How can I find the APK file of an app on my device?</b></li>
103
- <p>If you want to find the APK file of an app that you have installed on your device, you can use a file manager app that has the option to show hidden files and folders. Then, you can navigate to the following path on your device: /data/app/<package name>-<version code>.apk. The package name is the unique identifier of the app, such as com.facebook.katana for Facebook. The version code is the number that indicates the version of the app, such as 123456789 for version 1.2.3.4.5.6.7.8.9. You can find the package name and the version code of an app by going to your device's settings, tapping on Apps or Applications, finding and tapping on the app, and tapping on App details or App info.</p>
104
- <li><b>How can I open an APK file on my computer?</b></li>
105
- <p>If you want to open an APK file on your computer, you can use a software that can extract or view the contents of an APK file, such as WinRAR, 7-Zip, or APK Studio. You can also use an Android emulator that can run APK files on your computer, such as BlueStacks, Nox Player, or LDPlayer. However, you should be careful when opening an APK file on your computer, as some of them may contain malware or viruses that can harm your computer or steal your data.</p>
106
- </ol></p> 197e85843d<br />
107
- <br />
108
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Cmo sobrevivir en Last Island of Survival el mejor juego de accin y aventura para Android.md DELETED
@@ -1,22 +0,0 @@
1
- <br />
2
- <h1>Descargar Last Island of Survival APK: Cómo Sobrevivir en un Mundo Post-Apocalíptico</h1>
3
- ¿Te gustan los juegos de supervivencia? ¿Te imaginas cómo sería vivir en un mundo devastado por una catástrofe que ha acabado con la civilización? ¿Te atreves a enfrentarte a los zombies, los animales salvajes y los otros supervivientes que quieren quitarte lo que tienes? Si la respuesta es sí, entonces te encantará Last Island of Survival, un juego de supervivencia multijugador en línea que te pondrá a prueba en un escenario post-apocalíptico lleno de acción y aventuras. En este artículo, te vamos a contar qué es Last Island of Survival, por qué deberías jugarlo, cómo descargarlo e instalarlo en tu dispositivo Android, y cómo jugarlo y algunos consejos y trucos para principiantes. ¡Sigue leyendo y prepárate para sobrevivir! <h2>Qué es Last Island of Survival y por qué deberías jugarlo</h2>
4
- Last Island of Survival es un juego de supervivencia multijugador en línea desarrollado por HK Hero Entertainment Co., Limited. El juego se lanzó en mayo de 2022 para iOS y Android, y desde entonces ha superado los 10 millones de descargas en la Google Play Store. El juego se basa en el popular género sandbox survival, que consiste en explorar, recolectar, construir y combatir en un mundo abierto con otros jugadores. <h3>Un juego de supervivencia multijugador en línea lleno de acción y aventuras</h3>
5
- En Last Island of Survival, empiezas con nada y tienes que buscar todo lo que necesitas para sobrevivir en una isla infestada de zombies, animales salvajes y otros supervivientes. Tendrás que lidiar con el hambre, la sed, el frío, el calor, las enfermedades, las heridas y las amenazas constantes. Para ello, tendrás que recolectar recursos, fabricar armas, herramientas, ropa y medicinas, y construir un refugio donde guardar tus pertenencias y protegerte de los ataques. Pero no estarás solo en esta isla. El juego es totalmente online y multijugador, lo que significa que te encontrarás con otros jugadores que pueden ser tus amigos o tus enemigos. Podrás comunicarte con ellos mediante el chat o el sistema de voz, formar equipos o clanes, cooperar o competir por los recursos, hacer alianzas o declarar guerras. También podrás asaltar las bases de otros jugadores, robarles sus objetos o destruir sus construcciones. O al revés, defender tu base <h3>Un mundo abierto enorme y lleno de peligros y secretos</h3>
6
- Last Island of Survival te ofrece un mapa gigantesco que puedes explorar libremente. El mapa está dividido en diferentes zonas con distintos climas, terrenos, recursos y desafíos. Podrás encontrar bosques, desiertos, montañas, lagos, ríos, cuevas, ruinas, bases militares y mucho más. Cada zona tiene sus propias características y ventajas, pero también sus riesgos y dificultades. En tu exploración, te toparás con todo tipo de criaturas y enemigos. Algunos son animales salvajes que puedes cazar para obtener carne, pieles y huesos. Otros son zombies que han sido infectados por un virus desconocido y que te atacarán sin piedad. Y otros son otros supervivientes que pueden ser amistosos o hostiles dependiendo de sus intenciones y personalidades. Además de los seres vivos, también encontrarás objetos y estructuras que pueden ser de gran ayuda o de gran peligro. Podrás recoger materiales, alimentos, agua, medicinas, armas, municiones y otros objetos útiles que te facilitarán la supervivencia. Pero también podrás activar trampas, minas, alarmas y otros mecanismos que pueden hacerte daño o alertar a tus enemigos. El mundo de Last Island of Survival está lleno de secretos y misterios que puedes descubrir si eres lo suficientemente curioso y valiente. Podrás encontrar pistas sobre lo que ocurrió en el pasado, cómo se originó el apocalipsis y qué hay detrás de todo. También podrás encontrar lugares ocultos, tesoros escondidos y recompensas especiales si sabes dónde buscar. <h3>Una libertad total para crear tus propias reglas y estrategias</h3>
7
- Last Island of Survival no te impone ningún objetivo ni misión específica. Eres tú quien decide cómo quieres jugar y qué quieres hacer en este mundo post-apocalíptico. Tienes una libertad total para crear tus propias reglas y estrategias según tu estilo de juego y tus preferencias. Puedes elegir ser un lobo solitario que se las arregla por sí mismo y que evita el contacto con otros jugadores. Puedes elegir ser un miembro de un equipo o un clan que coopera con sus aliados y que comparte recursos y responsabilidades. Puedes elegir ser un pacifista que respeta a los demás y que busca la armonía y la paz. Puedes elegir ser un agresivo que ataca a los demás y que busca el dominio y el poder. Puedes elegir centrarte en la recolección y la construcción, creando una base sólida y autosuficiente donde almacenar tus objetos y protegerte de los ataques. Puedes elegir centrarte en la exploración y la aventura, recorriendo el mapa en busca de lugares interesantes y objetos valiosos. Puedes elegir centrarte en el combate y la defensa, mejorando tus armas y habilidades para enfrentarte a los zombies, los animales salvajes y los otros supervivientes. Puedes elegir jugar de forma casual o competitiva, disfrutando del juego a tu ritmo o intentando escalar en el ranking global. Puedes elegir jugar de forma realista o divertida, siguiendo las reglas de la física y la lógica o aprovechando los glitches y los bugs del juego. En definitiva, puedes elegir jugar a Last Island of Survival como quieras, siempre que respetes las normas básicas del juego y no hagas trampas ni molestes a otros jugadores. <h2>Cómo descargar Last Island of Survival APK en tu dispositivo Android</h2>
8
- Si quieres jugar a Last Island of Survival en tu dispositivo Android, necesitas descargar e instalar el archivo APK del juego. El archivo APK es un formato de archivo que contiene todos los datos necesarios para ejecutar una aplicación en Android. Descargar el archivo APK te permite instalar el juego sin necesidad de pasar por la Google Play Store, lo que puede tener algunas ventajas como ahorrar espacio o evitar restricciones regionales. <h3>Los requisitos mínimos para jugar al juego</h3>
9
- Antes de descargar e instalar el archivo APK de Last Island of Survival, debes asegurarte de que tu dispositivo Android cumple con los requisitos mínimos para jugar al juego. Estos son los requis tos mínimos para jugar al juego: - Sistema operativo: Android 4.4 o superior - Memoria RAM: 2 GB o más - Espacio de almacenamiento: 1 GB o más - Conexión a internet: Wi-Fi o datos móviles Si tu dispositivo no cumple con estos requisitos, es posible que el juego no funcione correctamente o que no puedas instalarlo. <h3>Los pasos para descargar e instalar el archivo APK</h3>
10
- Si tu dispositivo cumple con los requisitos mínimos, puedes seguir estos pasos para descargar e instalar el archivo APK de Last Island of Survival: - Paso 1: Busca el archivo APK de Last Island of Survival en internet. Puedes usar un buscador como Google o Bing, o un sitio web especializado en archivos APK como APKPure o APKMirror. Asegúrate de elegir una fuente confiable y segura, que no contenga virus ni malware. - Paso 2: Descarga el archivo APK de Last Island of Survival en tu dispositivo. Puedes hacerlo directamente desde el navegador o usando una aplicación de gestión de descargas. El archivo APK suele tener un tamaño de unos 100 MB, así que asegúrate de tener suficiente espacio y una buena conexión a internet. - Paso 3: Habilita la opción de instalar aplicaciones desde fuentes desconocidas en tu dispositivo. Esta opción te permite instalar aplicaciones que no provienen de la Google Play Store, como el archivo APK de Last Island of Survival. Para habilitarla, ve a los ajustes de tu dispositivo, busca la sección de seguridad y privacidad, y activa la opción de orígenes desconocidos o fuentes desconocidas. - Paso 4: Busca el archivo APK de Last Island of Survival en tu dispositivo y ábrelo. Puedes usar un explorador de archivos o una aplicación de gestión de archivos para encontrarlo. Normalmente se guarda en la carpeta de descargas o downloads. Al abrirlo, te aparecerá una ventana que te pedirá permiso para instalar la aplicación. Pulsa en instalar y espera a que se complete el proceso. - Paso 5: Busca el icono de Last Island of Survival en tu pantalla de inicio o en tu cajón de aplicaciones y ábrelo. Ya puedes disfrutar del juego en tu dispositivo Android. <h3>Las precauciones que debes tomar antes de descargar el juego</h3>
11
- Descargar e instalar el archivo APK de Last Island of Survival puede tener algunos riesgos y desventajas que debes tener en cuenta antes de hacerlo. Estas son algunas precauciones que debes tomar: - Asegúrate de descargar el archivo APK desde una fuente confiable y segura, que no contenga virus ni malware. Si no estás seguro, puedes usar un antivirus o un escáner de archivos para comprobarlo antes de abrirlo. - Asegúrate de tener suficiente espacio y batería en tu dispositivo para descargar e instalar el archivo APK. Si no tienes suficiente espacio, puedes borrar algunos archivos o aplicaciones que no uses. Si no tienes suficiente batería, puedes conectar tu dispositivo a una fuente de energía. - Asegúrate de tener una buena conexión a internet para descargar e instalar el archivo APK. Si usas datos móviles, ten en cuenta que puede consumir mucho tráfico y afectar a tu plan de datos. Si usas Wi-Fi, ten en cuenta que puede afectar a la velocidad y la estabilidad de tu conexión. - Asegúrate de habilitar la opción de instalar aplicaciones desde fuentes desconocidas solo cuando vayas a instalar el archivo APK. Después, puedes deshabilitarla para evitar que otras aplicaciones no autorizadas se instalen en tu dispositivo sin tu permiso. - Asegúrate de actualizar el juego regularmente para disfrutar de las últimas novedades y mejoras. Puedes hacerlo desde la propia aplicación o desde el sitio web donde descargaste el archivo APK. Ten en cuenta que si actualizas el juego desde la Google Play Store, puede que pierdas los datos guardados o que tengas que volver a instalar el archivo APK. <h2>Cómo jugar a Last Island of Survival y algunos consejos y trucos para principiantes</h2>
12
- Ahora que ya sabes cómo descargar e instalar el archivo APK de Last Island of Survival en tu dispositivo Android, es hora de aprender cómo jugar al juego y algunos consejos y trucos para principiantes. El juego tiene un tutorial inicial que te enseña los controles básicos y las mecánicas principales, pero hay muchas cosas más que debes saber para sobreviv vivir en este mundo post-apocalíptico. Aquí te damos algunos consejos y trucos para que empieces con buen pie y no mueras en el intento. <h3>Cómo empezar tu viaje y lo que debes hacer en tus primeras sesiones</h3>
13
- Cuando empieces a jugar a Last Island of Survival, lo primero que debes hacer es elegir un servidor y un nombre de usuario. El juego tiene varios servidores repartidos por el mundo, así que elige el que mejor se adapte a tu ubicación y a tu idioma. El nombre de usuario es el que verán los demás jugadores cuando te encuentren o te comuniques con ellos, así que elige uno que te guste y que no sea ofensivo ni inapropiado. Después de elegir el servidor y el nombre de usuario, entrarás en el juego y aparecerás en una zona aleatoria de la isla. Lo primero que verás es una pantalla con los controles básicos y las indicaciones del tutorial. Te recomendamos que sigas el tutorial con atención, ya que te enseñará cómo moverte, cómo interactuar con el entorno, cómo recolectar recursos, cómo fabricar objetos y cómo construir tu refugio. En tus primeras sesiones, tu objetivo principal debe ser sobrevivir y establecerte en la isla. Para ello, debes tener en cuenta los siguientes aspectos: - Tu salud, tu hambre, tu sed y tu temperatura. Estos son los indicadores que aparecen en la parte superior izquierda de la pantalla y que muestran tu estado físico. Si alguno de ellos baja demasiado, puedes morir o sufrir efectos negativos. Para mantenerlos en un nivel óptimo, debes comer, beber, abrigarte o refrescarte según sea necesario. - Tus recursos y tus objetos. Estos son los elementos que puedes encontrar o fabricar en el juego y que te servirán para sobrevivir y mejorar tu situación. Puedes verlos en tu inventario, que se abre pulsando el botón del maletín en la parte inferior derecha de la pantalla. En tu inventario, puedes ver lo que llevas encima, lo que tienes en tu mochila y lo que puedes fabricar con los recursos disponibles. También puedes equiparte o usar los objetos desde el inventario. - Tu refugio y tu base. Estos son los lugares donde puedes guardar tus objetos y protegerte de los ataques. Puedes construir tu refugio usando los recursos que recolectes y las herramientas que fabriques. Puedes ver las opciones de construcción pulsando el botón del martillo en la parte inferior derecha de la pantalla. En las opciones de construcción, puedes ver los elementos que puedes construir, como paredes, puertas, ventanas, suelos, techos, muebles, etc. También puedes ver los requisitos para construirlos y colocarlos donde quieras. En tus primeras sesiones, te recomendamos que hagas lo siguiente: - Recolecta recursos básicos como madera, piedra, hierba, bayas, agua, etc. Los puedes encontrar por el suelo o cortando árboles o rocas con tus manos o con herramientas. - Fabrica objetos básicos como un hacha, una piqueta, una lanza, una hoguera, una cantimplora, etc. Los puedes fabricar desde tu inventario usando los recursos que hayas recolectado. - Construye un refugio básico con paredes, una puerta, un techo y una cama. Los puedes construir desde las opciones de construcción usando los recursos y las herramientas que hayas fabricado. - Guarda tus objetos más valiosos en tu refugio o en un cofre. Los puedes guardar arrastrándolos desde tu inventario hasta el lugar donde quieras guardarlos. - Explora los alrededores de tu refugio con cuidado y busca más recursos y objetos útiles. Los puedes encontrar por el suelo o en cajas, barriles, vehículos o edificios abandonados. - Evita los enfrentamientos con los zombies, los animales salvajes y los otros supervivientes hasta que tengas armas y armaduras suficientes. Los puedes evitar manteniendo una distancia prudencial o escondiéndote detrás de obstáculos. - Comunícate con otros jugadores si quieres hacer amigos o aliados. Los puedes comunicar usando el chat o el sistema de voz que aparecen en la parte superior derecha de la pantalla. <h3>Cómo explorar el mapa y encontrar recursos y objetos valiosos</h3>
14
- Una vez que tengas un refugio básico y algunos objetos básicos, puedes empezar a explorar el mapa y encontrar recursos y objetos más valiosos. El mapa de Last Island of Survival es muy grande y variado, y tiene diferentes zonas con distintos climas, terrenos, recursos y desafíos. Puedes ver el mapa pulsando el botón del mapa en la parte superior izquierda de la pantalla. En el mapa, puedes ver tu ubicación, la ubicación de tu refugio, la ubicación de otros jugadores y las zonas de interés. Para explorar el mapa, puedes usar diferentes medios de transporte que puedes encontrar o fabricar en el juego. Puedes caminar, correr, nadar, saltar o trepar por el terreno. Puedes usar una bicicleta, una moto, un coche o un helicóptero para moverte más rápido y más lejos. Puedes usar un bote, una lancha o un submarino para navegar por el agua. Cada medio de transporte tiene sus ventajas y desventajas, como la velocidad, la capacidad, el consumo de combustible y el nivel de ruido. Para encontrar recursos y objetos valiosos, debes estar atento a los indicadores que aparecen en la pantalla. Los indicadores son unos iconos que te muestran la dirección y la distancia de los elementos de interés que hay cerca de ti. Hay diferentes tipos de indicadores según el tipo de elemento que señalan. Por ejemplo: - Los indicadores verdes te muestran los recursos naturales que puedes recolectar, como madera, piedra, hierba, bayas, agua, etc. - Los indicadores azules te muestran los objetos artificiales que puedes recoger o usar, como cajas, barriles, vehículos, edificios, etc. - Los indicadores rojos te muestran los enemigos que puedes combatir o evitar, como zombies, animales salvajes o supervivientes. - Los indicadores amarillos te muestran los lugares especiales que puedes visitar o activar, como ruinas, bases militares, trampas, minas, alarmas, etc. Para recoger o usar un elemento, debes acercarte a él y pulsar el botón de interacción que aparece en la pantalla. Algunos elementos requieren herramientas o armas específicas para ser recolectados o usados. Por ejemplo: - Para cortar un árbol o una roca, necesitas un hacha o una piqueta. - Para abrir una caja o un barril, necesitas una llave inglesa o una palanca. - Para conducir un vehículo o un bote, necesitas una llave o un código. - Para disparar un arma o una ballesta, necesitas munición o flechas. Algunos elementos tienen un límite de tiempo o de uso antes de desaparecer o romperse. Por ejemplo: - Las bayas se pudren si no las comes pronto. - El agua se evapora si no la bebes o la guardas pronto. - Los vehículos se dañan si los usas demasiado o si chocan con algo. - Las armas se desgastan si las usas demasiado o si las mojas. Algunos elementos tienen efectos positivos o negativos según cómo los uses. Por ejemplo: - Las medicinas te curan las heridas o las enfermedades si las tomas correctamente. - Los alimentos te sacian el hambre si los comes correctamente. - Los explosivos te ayudan a abrir paso si los colocas correctamente. - Los venenos te hacen daño si los ingieres o los tocas. <h3>Cómo construir tu refugio y mantenerlo a salvo de la corrosión y los enemigos</h3>
15
- Construir tu refugio es una de las tareas más importantes y divertidas del juego. Tu refugio es tu hogar en este mundo post-apocalíptico, donde puedes guardar tus objetos y protegerte de los ataques. Tu refugio puede ser tan simple o tan complejo como quieras, siempre que tenga las partes esenciales: paredes, una puerta , un techo y una cama. Puedes construir tu refugio usando los recursos que recolectes y las herramientas que fabriques. Puedes ver las opciones de construcción pulsando el botón del martillo en la parte inferior derecha de la pantalla. En las opciones de construcción, puedes ver los elementos que puedes construir, como paredes, puertas, ventanas, suelos, techos, muebles, etc. También puedes ver los requisitos para construirlos y colocarlos donde quieras. Para construir tu refugio, debes seguir estos pasos: - Paso 1: Elige un lugar adecuado para tu refugio. Debe ser un lugar seguro, accesible y con recursos cerca. Evita los lugares demasiado expuestos, demasiado aislados o demasiado concurridos por otros jugadores o enemigos. - Paso 2: Coloca los cimientos de tu refugio. Los cimientos son las partes que sostienen el resto de la estructura y que determinan el tamaño y la forma de tu refugio. Puedes usar suelos o pilares para crear los cimientos. Los puedes colocar pulsando el botón de colocar que aparece en la pantalla cuando seleccionas un elemento de construcción. - Paso 3: Coloca las paredes de tu refugio. Las paredes son las partes que rodean el espacio interior de tu refugio y que te protegen de los ataques y las miradas indiscretas. Puedes usar paredes de madera, metal, piedra o ladrillo para crear las paredes. Los puedes colocar pulsando el botón de colocar que aparece en la pantalla cuando seleccionas un elemento de construcción. - Paso 4: Coloca la puerta de tu refugio. La puerta es la parte que te permite entrar y salir de tu refugio y que puedes cerrar con llave o con código para evitar intrusos. Puedes usar una puerta de madera, metal, piedra o ladrillo para crear la puerta. La puedes colocar pulsando el botón de colocar que aparece en la pantalla cuando seleccionas un elemento de construcción. - Paso 5: Coloca el techo de tu refugio. El techo es la parte que cubre el espacio superior de tu refugio y que te protege de la lluvia, el sol y los proyectiles. Puedes usar techos planos o inclinados para crear el techo. Los puedes colocar pulsando el botón de colocar que aparece en la pantalla cuando seleccionas un elemento de construcción. - Paso 6: Coloca la cama de tu refugio. La cama es la parte donde puedes dormir para recuperar energía y salud, y donde puedes reaparecer si mueres. Puedes usar una cama sencilla o una cama doble para crear la cama. La puedes colocar pulsando el botón de colocar que aparece en la pantalla cuando seleccionas un elemento de construcción. - Paso 7: Decora y personaliza tu refugio. Puedes añadir otros elementos a tu refugio para hacerlo más cómodo y funcional, como muebles, lámparas, estanterías, armarios, etc. También puedes pintar o decorar las paredes, el suelo y el techo con diferentes colores y diseños. Puedes usar tu imaginación y creatividad para hacer tu refugio único y original. Para mantener tu refugio a salvo de la corrosión y los enemigos, debes tener en cuenta los siguientes aspectos: - La corrosión es un fenómeno que afecta a todos los elementos metálicos del juego y que los hace perder durabilidad con el tiempo. Para evitar la corrosión, debes usar materiales no metálicos o aplicar un spray anticorrosivo a tus elementos metálicos. El spray anticorrosivo lo puedes fabricar desde tu inventario usando recursos como aceite o vinagre. - Los enemigos son todos aquellos que quieren atacar o asaltar tu refugio, como zombies, animales salvajes o supervivientes hostiles. Para evitar los ataques, debes reforzar tu refugio con elementos defensivos como alambre de espino, trampas, minas, torretas, etc. También debes estar preparado para defenderte con armas y armaduras si los enemigos logran entrar en tu refugio. <h3>Cómo interactuar con otros jugadores y formar alianzas o rivalidades</h3> Last Island of Survival es un juego totalmente online y multijugador, lo que significa que te encontrarás con otros jugadores que pueden ser tus amigos o tus enemigos. Podrás comunicarte con ellos mediante el chat o el sistema de voz, formar equipos o clanes, cooperar o competir por los recursos, hacer alianzas o declarar guerras. También podrás asaltar las bases de otros jugadores, robarles sus objetos o destruir sus construcciones. O al revés, defender tu base y ayudar a tus aliados. Para interactuar con otros jugadores, debes seguir estos pasos: - Paso 1: Busca otros jugadores en el mapa. Puedes ver la ubicación de otros jugadores en el mapa pulsando el botón del mapa en la parte superior izquierda de la pantalla. Los otros jugadores aparecen como puntos de diferentes colores según su relación contigo. Por ejemplo: - Los puntos verdes son tus amigos o aliados, con los que puedes cooperar y compartir recursos. - Los puntos azules son los miembros de tu equipo o clan, con los que puedes comunicarte y coordinarte. - Los puntos amarillos son los jugadores neutrales, con los que puedes interactuar pacíficamente o agresivamente según tu elección. - Los puntos rojos son tus enemigos o rivales, con los que debes tener cuidado y estar preparado para combatir. - Paso 2: Acércate a otros jugadores con precaución. Cuando te acerques a otro jugador, podrás ver su nombre de usuario y su nivel sobre su cabeza. También podrás ver si tiene algún arma o herramienta equipada. Ten en cuenta que algunos jugadores pueden ser hostiles y atacarte sin previo aviso, así que mantén una distancia prudencial y ten tu arma lista por si acaso. - Paso 3: Comunícate con otros jugadores usando el chat o el sistema de voz. Puedes usar el chat o el sistema de voz para enviar mensajes o hablar con otros jugadores. Para usar el chat, pulsa el botón del chat en la parte superior derecha de la pantalla y escribe tu mensaje. Para usar el sistema de voz, pulsa el botón del micrófono en la parte superior derecha de la pantalla y habla por tu dispositivo. Puedes elegir a quién quieres dirigirte usando los botones de selección que aparecen debajo del chat o del micrófono. Por ejemplo: - El botón de todos te permite enviar un mensaje o hablar a todos los jugadores que estén cerca de ti. - El botón de equipo te permite enviar un mensaje o hablar solo a los miembros de tu equipo o clan. - El botón de amigo te permite enviar un mensaje o hablar solo a los jugadores que hayas agregado como amigos. - Paso 4: Forma equipos o clanes con otros jugadores si quieres cooperar y compartir recursos. Puedes formar equipos o clanes con otros jugadores para tener más ventajas y diversión en el juego. Para formar un equipo, pulsa el botón del equipo en la parte inferior izquierda de la pantalla y selecciona a los jugadores que quieras invitar a tu equipo. Para formar un clan, pulsa el botón del clan en la parte inferior izquierda de la pantalla y crea un nombre y un símbolo para tu clan. Luego, puedes invitar a otros jugadores a unirse a tu clan desde el menú del clan. - Paso 5: Haz alianzas o declarar guerras con otros equipos o clanes si quieres competir por los recursos. Puedes hacer alianzas o declarar guerras con otros equipos o clanes para tener más desafíos y emoción en el juego. Para hacer una alianza, pulsa el botón del clan en la parte inferior izquierda de la pantalla y selecciona a los clanes que quieras proponer una alianza. Para declarar una guerra, pulsa el botón del clan en la parte inferior izquierda de la pantalla y selecciona a los clanes que quieras atacar. <h3>Cómo combatir y defenderse de los zombies, los animales salvajes y los otros supervivientes</h3>
16
- El combate es una parte inevitable e importante del juego. Tarde o temprano, tendrás que enfrentarte a los zombies, los animales salvajes y los otros supervivientes que quieren hacerte daño o quitarte lo que tienes. Para combatir y defenderte, debes tener en cuenta los siguientes aspectos: - Tus armas y tus armaduras. Estos son los elementos que te permiten atacar y protegerte de los daños. Puedes usar armas cuerpo a cuerpo, como cuchillos, machetes, bates, etc., o armas a distancia, como pistolas, rifles, escopetas, etc. También puedes usar armas especiales, como granadas, cócteles molotov, arcos, ballestas, etc. Puedes fabricar tus propias armas o encontrarlas en el juego. Puedes usar armaduras para reducir el daño que recibes de los ataques. Puedes usar cascos, chalecos, pantalones, botas, etc. También puedes usar accesorios para mejorar tus atributos o habilidades. Puedes usar gafas, guantes, relojes, mochilas, etc. - Tus habilidades y tus estadísticas. Estos son los elementos que determinan tu rendimiento y tu resistencia en el combate. Puedes mejorar tus habilidades y tus estadísticas subiendo de nivel y asignando puntos a las diferentes categorías. Por ejemplo: - La categoría de fuerza te permite aumentar el daño que haces con las armas cuerpo a cuerpo y la capacidad de carga que tienes. - La categoría de agilidad te permite aumentar la velocidad de movimiento y la velocidad de ataque que tienes. - La categoría de precisión te permite aumentar el daño que haces con las armas a distancia y la probabilidad de acertar que tienes. - La categoría de resistencia te permite aumentar la salud y la energía que tienes. - Tus estrategias y tus tácticas. Estos son los elementos que te permiten tener ventaja sobre tus enemigos y evitar ser derrotado. Puedes usar diferentes estrategias y tácticas según la situación y el tipo de enemigo al que te enfrentes. Por ejemplo: - La estrategia de sigilo te permite evitar ser detectado por tus enemigos y atacarlos por sorpresa o huir sin ser visto. - La estrategia de asalto te permite atacar a tus enemigos directamente y eliminarlos rápidamente o intimidarlos para que se rindan o huyan. - La estrategia de defensa te permite protegerte de los ataques de tus enemigos y contraatacar cuando tengas una oportunidad o pedir ayuda a tus aliados. - La estrategia de emboscada te permite preparar trampas o explosivos para sorprender a tus enemigos y causarles mucho daño o desorientarlos para que no puedan reaccionar. - La estrategia de negociación te permite hablar con tus enemigos y tratar de llegar a un acuerdo pacífico o engañarlos para que bajen la guardia o se vuelvan contra sus aliados. <h2>Conclusión</h2>
17
- Last Island of Survival es un juego de supervivencia multijugador en línea que te ofrece una experiencia única e inmersiva en un mundo post-apocalíptico lleno de acción y aventuras. En este juego, puedes explorar, recolectar, construir y combatir en un mapa gigantesco con otros jugadores. Puedes crear tus propias reglas y estrategias según tu estilo de juego y tus preferencias. Puedes descargar e instalar el archivo APK del juego en tu dispositivo Android siguiendo unos sencillos pasos. Puedes jugar al juego y aprender algunos consejos y trucos para principiantes siguiendo esta guía. Si te gustan los juegos de supervivencia, no dudes en descargar Last Island of Survival APK y disfrutar de este juego increíble. ¡Te aseguramos que no te arrepentirás! <h2>Preguntas frecuentes</h2>
18
- - ¿Qué es Last Island of Survival APK? Last Island of Survival APK es el formato de archivo que contiene todos los datos necesarios para ejecutar el juego Last Island of Survival en Android. - ¿Por qué descargar Last Island of Survival APK? Descargar Last Island of Survival APK te permite instalar el juego sin necesidad de pasar por la Google Play Store, lo que puede tener algunas ventajas como ahorrar espacio o evitar restricciones regionales. - ¿Cómo descargar Last Island of Survival APK? Puedes descargar Last Island of Survival APK desde internet usando un buscador o un sitio web especializado en archivos APK. Asegúrate de elegir una fuente confiable y segura, que no contenga virus ni malware. - ¿Cómo instalar Last Island of Survival APK? Puedes instalar Last Island of Survival APK siguiendo estos pasos: - 1. Habilita la opción de instalar aplicaciones desde fuentes desconocidas en tu dispositivo. Esta opción te permite instalar aplicaciones que no provienen de la Google Play Store, como el archivo APK de Last Island of Survival. Para habilitarla, ve a los ajustes de tu dispositivo, busca la sección de seguridad y privacidad, y activa la opción de orígenes desconocidos o fuentes desconocidas. - 2. Busca el archivo APK de Last Island of Survival en tu dispositivo y ábrelo. Puedes usar un explorador de archivos o una aplicación de gestión de archivos para encontrarlo. Normalmente se guarda en la carpeta de descargas o downloads. Al abrirlo, te aparecerá una ventana que te pedirá permiso para instalar la aplicación. Pulsa en instalar y espera a que se complete el proceso. - 3. Busca el icono de Last Island of Survival en tu pantalla de inicio o en tu cajón de aplicaciones y ábrelo. Ya puedes disfrutar del juego en tu dispositivo Android. - ¿Cómo jugar a Last Island of Survival? Puedes jugar a Last Island of Survival siguiendo esta guía: - 1. Elige un servidor y un nombre de usuario. El juego tiene varios servidores repartidos por el mundo, así que elige el que mejor se adapte a tu ubicación y a tu idioma. El nombre de usuario es el que verán los demás jugadores cuando te encuentren o te comuniques con ellos, así que elige uno que te guste y que no sea ofensivo ni inapropiado. - 2. Sigue el tutorial inicial. El juego tiene un tutorial inicial que te enseña los controles básicos y las mecánicas principales del juego. Te recomendamos que sigas el tutorial con atención, ya que te enseñará cómo moverte, cómo interactuar con el entorno, cómo recolectar recursos, cómo fabricar objetos y cómo construir tu refugio. - 3. Sobrevive y establece en la isla. En tus primeras sesiones, tu objetivo principal debe ser sobrevivir y establecerte en la isla. Para ello, debes tener en cuenta tu salud, tu hambre, tu sed y tu temperatura, y mantenerlos en un nivel óptimo comiendo, bebiendo, abrigándote o refrescándote según sea necesario. También debes recolectar recursos básicos como madera, piedra, hierba, bayas, agua, etc., fabricar objetos básicos como un hacha, una piqueta, una lanza, una hoguera, una cantimplora, etc., y construir un refugio básico con paredes, una puerta, un techo y una cama. - 4. Explora el mapa y encuentra recursos y objetos más valiosos. Una vez que tengas un refugio básico y algunos objetos básicos, puedes empezar a explorar el mapa y encontrar recursos y objetos más valiosos. El mapa es muy grande y variado, y tiene diferentes zonas con distintos climas, terrenos, recursos y desafíos. Puedes usar diferentes medios de transporte para moverte por el mapa, como caminar, correr, nadar, saltar o trepar por el terreno, o usar una bicicleta, una moto, un coche o un helicóptero para moverte más rápido y más lejos. Puedes encontrar recursos y objetos valiosos por el suelo o en cajas, barriles , vehículos o edificios abandonados. Puedes recoger o usar estos elementos pulsando el botón de interacción que aparece en la pantalla cuando te acercas a ellos. - 5. Interactúa con otros jugadores y forma alianzas o rivalidades. El juego es totalmente online y multijugador, lo que significa que te encontrarás con otros jugadores que pueden ser tus amigos o tus enemigos. Puedes comunicarte con ellos usando el chat o el sistema de voz, formar equipos o clanes, cooperar o competir por los recursos, hacer alianzas o declarar guerras. También puedes asaltar las bases de otros jugadores, robarles sus objetos o destruir sus construcciones. O al revés, defender tu base y ayudar a tus aliados. - 6. Combate y defiéndete de los zombies, los animales salvajes y los otros supervivientes. El combate es una parte inevitable e importante del juego. Tarde o temprano, tendrás que enfrentarte a los zombies, los animales salvajes y los otros supervivientes que quieren hacerte daño o quitarte lo que tienes. Para combatir y defenderte, debes tener armas y armaduras suficientes, mejorar tus habilidades y tus estadísticas, y usar estrategias y tácticas adecuadas según la situación y el tipo de enemigo al que te enfrentes. <h2></h2>
19
- This is the end of the article I have created for you on the topic of "descargar last island of survival apk". I hope you have enjoyed reading it and have learned something new and useful. If you have any questions or feedback, please let me know in the chat. Thank you for using Microsoft Bing search chat mode. Have a nice day! ?</p>
20
- <h2>descargar last island of survival apk</h2><br /><p><b><b>Download Zip</b> >>> <a href="https://jinyurl.com/2uNKwL">https://jinyurl.com/2uNKwL</a></b></p><br /><br /> 401be4b1e0<br />
21
- <br />
22
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Football League 2023 The Best Soccer Game on the Play Store.md DELETED
@@ -1,82 +0,0 @@
1
- <br />
2
- <h1>Football League 2023: A Total Soccer Game Experience</h1>
3
- <p>If you are a fan of soccer, you will love Football League 2023, a mobile soccer game that provides a total soccer game experience by immersing you in incredibly lucid graphics and intelligent game engine. Every strike, pass and score is beautifully executed allowing you to simply enjoy the spirit of the beautiful game. In this article, we will tell you why you should download Football League 2023 from the play store, what features it offers, how to install it on your Android device, and some tips and tricks for playing it.</p>
4
- <h2>Features of Football League 2023</h2>
5
- <p>Football League 2023 has many features that make it one of the best soccer games on the market. Here are some of them:</p>
6
- <h2>football league 2023 game download play store</h2><br /><p><b><b>Download Zip</b> ===> <a href="https://jinyurl.com/2uNNx0">https://jinyurl.com/2uNNx0</a></b></p><br /><br />
7
- <ul>
8
- <li><b>Over 100 national teams and 330 clubs to choose from</b>: You can play with your favorite team or club from all over the world, including England, Spain, Italy, Germany, France, Brazil, Argentina, Portugal, and more. You can also compete in various leagues and cups, such as the National Cup, European Cup, American Cup, Asian Cup, European Championship Cup, South American Championship Cup, English Cup, French Cup, Italian Cup, Spanish Cup, German Cup, Brazil Cup, English Super Cup, French Super Cup, Italian Super Cup, Spanish Super Cup, German Super Cup, Brazil Super Cup, European Super Cup, Club World Cup, and more.</li>
9
- <li><b>Total game control engine for realistic and responsive gameplay</b>: Football League 2023 has a smooth and intuitive control system that allows you to easily control your players and execute your moves. You can also adjust your strategy and formation according to the situation and your opponent's behavior. The game has a realistic physics engine that simulates the movement and collision of the ball and the players. The game also has a multi-language narration that adds to the excitement and atmosphere of the game.</li>
10
- <li><b>Create and customize your dream team with pro soccer players</b>: You can create your own team by selecting from over 11 pro soccer players with different skills and abilities. You can also develop your players by training them and increasing their attributes. You can customize your team's name, logo, jersey, stadium, and more. You can also trade players with other teams or scout new talents.</li>
11
- <li><b>Win trophies and become world champions with different modes and tournaments</b>: You can play in various modes and tournaments in Football League 2023. You can play in Classic Mode, where you can choose any team or club and play against another team or club. You can also play in Career Mode, where you can start from scratch and build your own team from scratch. You can also play in Tournament Mode, where you can participate in various tournaments and compete for glory. You can also play in Online Mode, where you can challenge other players from around the world.</li>
12
- </ul>
13
- <h2>How to Download and Install Football League 2023 from the Play Store</h2>
14
- <p>If you want to download and install Football League 2023 on your Android device, you can follow these simple steps:</p>
15
- <ol>
16
- <li>Open the Google Play Store app on your device.</li>
17
- <li>Search for "Football League 2023" in the search bar.</li>
18
- <li>Select the game from the results and tap on the "Install" button.</li>
19
- <li>Wait for the game to download and install on your device.</li>
20
- <li>Once the installation is complete, tap on the "Open" button to launch the game.</li>
21
- <li>Enjoy playing Football League 2023 on your device.</li>
22
- </ol>
23
- <h2>Tips and Tricks for Playing Football League 2023</h2>
24
- <p>If you want to improve your skills and performance in Football League 2023, you can use these tips and tricks:</p>
25
- <ul>
26
- <li><b>How to master the controls and tactics of the game</b>: You can use the virtual joystick on the left side of the screen to move your players and the buttons on the right side of the screen to pass, shoot, tackle, sprint, and switch players. You can also swipe on the screen to perform special moves, such as dribbling, crossing, lobbing, and chipping. You can also tap on the "Tactics" button on the top right corner of the screen to change your formation, strategy, and style of play. You can choose from different options, such as attacking, defending, balanced, counter-attacking, possession, long ball, short passing, high pressing, low pressing, and more.</li>
27
- <li><b>How to improve your skills and abilities of your players</b>: You can train your players by tapping on the "Training" button on the main menu. You can choose from different training drills, such as shooting, passing, dribbling, defending, heading, and more. You can also upgrade your players by tapping on the "Upgrade" button on the main menu. You can increase their attributes, such as speed, strength, stamina, agility, ball control, shooting accuracy, passing accuracy, tackling accuracy, heading accuracy, and more. You can also equip your players with different items, such as boots, gloves, kits, balls, and more.</li>
28
- <li><b>How to earn coins and rewards in the game</b>: You can earn coins and rewards by playing matches and tournaments in the game. You can also earn coins and rewards by completing achievements and daily missions in the game. You can also earn coins and rewards by watching ads and videos in the game. You can use coins and rewards to buy new players, items, stadiums, and more.</li>
29
- </ul>
30
- <h2>Conclusion</h2>
31
- <p>Football League 2023 is a mobile soccer game that offers a total soccer game experience by immersing you in incredibly lucid graphics and intelligent game engine. It has many features that make it one of the best soccer games on the market. It also has a simple and easy installation process that allows you to play it on your Android device. It also has some tips and tricks that can help you improve your skills and performance in the game. If you are a fan of soccer, you should download Football League 2023 from the play store now and enjoy the spirit of the beautiful game.</p>
32
- <h3>Frequently Asked Questions</h3>
33
- <p>Here are some frequently asked questions about Football League 2023:</p>
34
- <ol>
35
- <li><b>Is Football League 2023 free to play?</b>: Yes, Football League 2023 is free to play. However, it contains some in-app purchases that can enhance your gaming experience.</li>
36
- <li><b>Can I play Football League 2023 offline?</b>: Yes, you can play Football League 2023 offline. However, some features and modes may require an internet connection.</li>
37
- <li><b>Can I play Football League 2023 with my friends?</b>: Yes, you can play Football League 2023 with your friends. You can invite them to join your team or challenge them to a match in Online Mode.</li>
38
- <li><b>How can I contact the developers of Football League 2023?</b>: You can contact the developers of Football League 2023 by tapping on the "Feedback" button on the main menu. You can also follow them on their social media accounts or visit their website for more information.</li>
39
- <li><b>What are the minimum requirements for playing Football League 2023?</b>: The minimum requirements for playing Football League 2023 are Android 4.4 or higher and 1 GB of RAM or higher.</li>
40
- </ol></p>
41
- <p>football league 2023 mobile soccer apk<br />
42
- football league 2023 game free download for android<br />
43
- football league 2023 mod apk unlimited money<br />
44
- football league 2023 game online play<br />
45
- football league 2023 best players<br />
46
- football league 2023 cheats and hacks<br />
47
- football league 2023 game review<br />
48
- football league 2023 tips and tricks<br />
49
- football league 2023 game update<br />
50
- football league 2023 game features<br />
51
- football league 2023 game system requirements<br />
52
- football league 2023 game size<br />
53
- football league 2023 game ratings<br />
54
- football league 2023 game trailer<br />
55
- football league 2023 game screenshots<br />
56
- football league 2023 game download for pc<br />
57
- football league 2023 game download for ios<br />
58
- football league 2023 game download for windows phone<br />
59
- football league 2023 game download for mac<br />
60
- football league 2023 game download for linux<br />
61
- football league 2023 game download for chromebook<br />
62
- football league 2023 game download for fire tablet<br />
63
- football league 2023 game download for smart tv<br />
64
- football league 2023 game download for nintendo switch<br />
65
- football league 2023 game download for xbox one<br />
66
- football league 2023 game download for ps4<br />
67
- football league 2023 game download for ps5<br />
68
- football league 2023 game download for xbox series x<br />
69
- football league 2023 alternatives on play store<br />
70
- football league 2023 similar games on play store<br />
71
- dream league soccer 2023 vs football league 2023<br />
72
- efootball™ 2023 vs football league 2023<br />
73
- fifa mobile soccer vs football league 2023<br />
74
- pes mobile soccer vs football league 2023<br />
75
- real soccer vs football league 2023<br />
76
- score! hero vs football league 2023<br />
77
- soccer stars vs football league 2023<br />
78
- top eleven vs football league 2023<br />
79
- ultimate soccer vs football league 2023<br />
80
- world soccer vs football league 2023</p> 197e85843d<br />
81
- <br />
82
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/7hao/bingo/src/components/markdown.tsx DELETED
@@ -1,9 +0,0 @@
1
- import { FC, memo } from 'react'
2
- import ReactMarkdown, { Options } from 'react-markdown'
3
-
4
- export const MemoizedReactMarkdown: FC<Options> = memo(
5
- ReactMarkdown,
6
- (prevProps, nextProps) =>
7
- prevProps.children === nextProps.children &&
8
- prevProps.className === nextProps.className
9
- )
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/NeuralSeq/modules/commons/align_ops.py DELETED
@@ -1,25 +0,0 @@
1
- import torch
2
- import torch.nn.functional as F
3
-
4
-
5
- def build_word_mask(x2word, y2word):
6
- return (x2word[:, :, None] == y2word[:, None, :]).long()
7
-
8
-
9
- def mel2ph_to_mel2word(mel2ph, ph2word):
10
- mel2word = (ph2word - 1).gather(1, (mel2ph - 1).clamp(min=0)) + 1
11
- mel2word = mel2word * (mel2ph > 0).long()
12
- return mel2word
13
-
14
-
15
- def clip_mel2token_to_multiple(mel2token, frames_multiple):
16
- max_frames = mel2token.shape[1] // frames_multiple * frames_multiple
17
- mel2token = mel2token[:, :max_frames]
18
- return mel2token
19
-
20
-
21
- def expand_states(h, mel2token):
22
- h = F.pad(h, [0, 0, 1, 0])
23
- mel2token_ = mel2token[..., None].repeat([1, 1, h.shape[-1]])
24
- h = torch.gather(h, 1, mel2token_) # [B, T, H]
25
- return h
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/nn/model_utils.py DELETED
@@ -1,49 +0,0 @@
1
- import numpy as np
2
- import torch
3
-
4
- def print_arch(model, model_name='model'):
5
- print(f"| {model_name} Arch: ", model)
6
- num_params(model, model_name=model_name)
7
-
8
-
9
- def num_params(model, print_out=True, model_name="model"):
10
- parameters = filter(lambda p: p.requires_grad, model.parameters())
11
- parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000
12
- if print_out:
13
- print(f'| {model_name} Trainable Parameters: %.3fM' % parameters)
14
- return parameters
15
-
16
- def requires_grad(model):
17
- if isinstance(model, torch.nn.Module):
18
- for p in model.parameters():
19
- p.requires_grad = True
20
- else:
21
- model.requires_grad = True
22
-
23
- def not_requires_grad(model):
24
- if isinstance(model, torch.nn.Module):
25
- for p in model.parameters():
26
- p.requires_grad = False
27
- else:
28
- model.requires_grad = False
29
-
30
- def get_grad_norm(model, l=2):
31
- num_para = 0
32
- accu_grad = 0
33
- if isinstance(model, torch.nn.Module):
34
- params = model.parameters()
35
- else:
36
- params = model
37
- for p in params:
38
- if p.grad is None:
39
- continue
40
- num_para += p.numel()
41
- if l == 1:
42
- accu_grad += p.grad.abs(1).sum()
43
- elif l == 2:
44
- accu_grad += p.grad.pow(2).sum()
45
- else:
46
- raise ValueError("Now we only implement l1/l2 norm !")
47
- if l == 2:
48
- accu_grad = accu_grad ** 0.5
49
- return accu_grad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIZero2Hero4Health/8-NLPSimilarityHeatmapCluster-SL/README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: 8 NLPSimilarityHeatmapCluster SL
3
- emoji: 🌍
4
- colorFrom: purple
5
- colorTo: blue
6
- sdk: streamlit
7
- sdk_version: 1.10.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AP123/IllusionDiffusion/share_btn.py DELETED
@@ -1,83 +0,0 @@
1
- community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
- <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
- <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
- </svg>"""
5
-
6
- loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
- style="color: #ffffff;
8
- "
9
- xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
-
11
- share_js = """async () => {
12
- async function uploadFile(file){
13
- const UPLOAD_URL = 'https://huggingface.co/uploads';
14
- const response = await fetch(UPLOAD_URL, {
15
- method: 'POST',
16
- headers: {
17
- 'Content-Type': file.type,
18
- 'X-Requested-With': 'XMLHttpRequest',
19
- },
20
- body: file, /// <- File inherits from Blob
21
- });
22
- const url = await response.text();
23
- return url;
24
- }
25
-
26
- async function getInputImgFile(imgEl){
27
- const res = await fetch(imgEl.src);
28
- const blob = await res.blob();
29
- const imgId = Date.now() % 200;
30
- const isPng = imgEl.src.startsWith(`data:image/png`);
31
- if(isPng){
32
- const fileName = `sd-perception-${{imgId}}.png`;
33
- return new File([blob], fileName, { type: 'image/png' });
34
- }else{
35
- const fileName = `sd-perception-${{imgId}}.jpg`;
36
- return new File([blob], fileName, { type: 'image/jpeg' });
37
- }
38
- }
39
-
40
- const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
41
-
42
- const inputPrompt = gradioEl.querySelector('#prompt textarea').value;
43
- const negativePrompt = gradioEl.querySelector('#negative_prompt textarea').value;
44
- const illusionStrength = gradioEl.querySelector('#illusion_strength input[type="number"]').value;
45
- const controlImage = gradioEl.querySelector('#control_image img');
46
- const outputImgEl = gradioEl.querySelector('#output img');
47
-
48
- const shareBtnEl = gradioEl.querySelector('#share-btn');
49
- const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
50
- const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
51
-
52
- shareBtnEl.style.pointerEvents = 'none';
53
- shareIconEl.style.display = 'none';
54
- loadingIconEl.style.removeProperty('display');
55
-
56
- const inputFile = await getInputImgFile(outputImgEl);
57
- const urlInputImg = await uploadFile(inputFile);
58
-
59
- const controlFile = await getInputImgFile(controlImage);
60
- const urlControlImg = await uploadFile(controlFile);
61
-
62
- const descriptionMd = `
63
- ### Prompt
64
- - *Prompt*: ${inputPrompt}
65
- - *Negative prompt*: ${negativePrompt}
66
- - *Illusion strength*: ${illusionStrength}
67
- #### Generated Image:
68
- <img src="${urlInputImg}" />
69
-
70
- #### Control Image:
71
- <img src="${urlControlImg}" />
72
- `;
73
- const params = new URLSearchParams({
74
- title: inputPrompt,
75
- description: descriptionMd,
76
- preview: true
77
- });
78
- const paramsStr = params.toString();
79
- window.open(`https://huggingface.co/spaces/AP123/IllusionDiffusion/discussions/new?${paramsStr}`, '_blank');
80
- shareBtnEl.style.removeProperty('pointer-events');
81
- shareIconEl.style.removeProperty('display');
82
- loadingIconEl.style.display = 'none';
83
- }"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ASJMO/freegpt/client/css/theme-toggler.css DELETED
@@ -1,33 +0,0 @@
1
- .theme-toggler-container {
2
- margin: 24px 0px 8px 0px;
3
- justify-content: center;
4
- }
5
-
6
- .theme-toggler-container.checkbox input + label,
7
- .theme-toggler-container.checkbox input:checked + label:after {
8
- background: var(--colour-1);
9
- }
10
-
11
- .theme-toggler-container.checkbox input + label:after,
12
- .theme-toggler-container.checkbox input:checked + label {
13
- background: var(--colour-3);
14
- }
15
-
16
- .theme-toggler-container.checkbox span {
17
- font-size: 0.75rem;
18
- }
19
-
20
- .theme-toggler-container.checkbox label {
21
- width: 24px;
22
- height: 16px;
23
- }
24
-
25
- .theme-toggler-container.checkbox label:after {
26
- left: 2px;
27
- width: 10px;
28
- height: 10px;
29
- }
30
-
31
- .theme-toggler-container.checkbox input:checked + label:after {
32
- left: calc(100% - 2px - 10px);
33
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/agentverse/environments/simulation_env/rules/visibility/pokemon.py DELETED
@@ -1,25 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import TYPE_CHECKING, Any
4
-
5
- from . import visibility_registry as VisibilityRegistry
6
- from .base import BaseVisibility
7
-
8
- if TYPE_CHECKING:
9
- from agentverse.environments import PokemonEnvironment
10
-
11
-
12
- @VisibilityRegistry.register("pokemon")
13
- class PokemonVisibility(BaseVisibility):
14
- """Visibility module for Pokemon environment"""
15
-
16
- def update_visible_agents(self, environment: PokemonEnvironment):
17
- for agent in environment.agents:
18
- agent_to_location = environment.get_agent_to_location()
19
- try:
20
- location = agent_to_location[agent.name]
21
- except KeyError:
22
- # Agent is on the way to a location
23
- continue
24
- agents_in_same_loc = environment.locations_to_agents[location]
25
- agent.set_receiver(agents_in_same_loc)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/bracketparser2-plugin.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import BracketParser from './bracketparser2';
2
-
3
- export default class BracketParserPlugin extends Phaser.Plugins.BasePlugin {
4
- add(
5
- config?: BracketParser.IConfig
6
- ): BracketParser;
7
-
8
- }
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/GetSizerConfig.js DELETED
@@ -1,8 +0,0 @@
1
- import GetSizerConfig from '../utils/GetSizerConfig.js';
2
-
3
- export default function (gameObject) {
4
- if (gameObject === undefined) {
5
- gameObject = this;
6
- }
7
- return GetSizerConfig(gameObject);
8
- }
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/flip/Flip.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import Flip from '../../../plugins/flip';
2
- export default Flip;
 
 
 
spaces/Al-Chan/Vits_League_of_Legends_Yuumi_TTS/denoise_audio.py DELETED
@@ -1,18 +0,0 @@
1
- import os
2
- import torchaudio
3
- raw_audio_dir = "./raw_audio/"
4
- denoise_audio_dir = "./denoised_audio/"
5
- filelist = list(os.walk(raw_audio_dir))[0][2]
6
-
7
- for file in filelist:
8
- if file.endswith(".wav"):
9
- os.system(f"demucs --two-stems=vocals {raw_audio_dir}{file}")
10
- for file in filelist:
11
- file = file.replace(".wav", "")
12
- wav, sr = torchaudio.load(f"./separated/htdemucs/{file}/vocals.wav", frame_offset=0, num_frames=-1, normalize=True,
13
- channels_first=True)
14
- # merge two channels into one
15
- wav = wav.mean(dim=0).unsqueeze(0)
16
- if sr != 22050:
17
- wav = torchaudio.transforms.Resample(orig_freq=sr, new_freq=22050)(wav)
18
- torchaudio.save(denoise_audio_dir + file + ".wav", wav, 22050, channels_first=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AlexWelcing/MusicLM/ setup.py DELETED
@@ -1,37 +0,0 @@
1
- from setuptools import setup, find_packages
2
-
3
- setup(
4
- name = 'musiclm-pytorch',
5
- packages = find_packages(exclude=[]),
6
- version = '0.0.3',
7
- license='MIT',
8
- description = 'MusicLM - AudioLM + Audio CLIP to text to music synthesis',
9
- author = 'Phil Wang',
10
- author_email = '[email protected]',
11
- long_description_content_type = 'text/markdown',
12
- url = 'https://github.com/lucidrains/musiclm-pytorch',
13
- keywords = [
14
- 'artificial intelligence',
15
- 'deep learning',
16
- 'transformers',
17
- 'attention mechanism',
18
- 'text to music',
19
- 'contrastive learning'
20
- ],
21
- install_requires=[
22
- 'audiolm-pytorch',
23
- 'beartype',
24
- 'einops>=0.4',
25
- 'vector-quantize-pytorch>=1.0.0',
26
- 'x-clip',
27
- 'torch>=1.6',
28
- 'torchaudio'
29
- ],
30
- classifiers=[
31
- 'Development Status :: 4 - Beta',
32
- 'Intended Audience :: Developers',
33
- 'Topic :: Scientific/Engineering :: Artificial Intelligence',
34
- 'License :: OSI Approved :: MIT License',
35
- 'Programming Language :: Python :: 3.6',
36
- ],
37
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alican/pixera/options/train_options.py DELETED
@@ -1,40 +0,0 @@
1
- from .base_options import BaseOptions
2
-
3
-
4
- class TrainOptions(BaseOptions):
5
- """This class includes training options.
6
-
7
- It also includes shared options defined in BaseOptions.
8
- """
9
-
10
- def initialize(self, parser):
11
- parser = BaseOptions.initialize(self, parser)
12
- # visdom and HTML visualization parameters
13
- parser.add_argument('--display_freq', type=int, default=400, help='frequency of showing training results on screen')
14
- parser.add_argument('--display_ncols', type=int, default=4, help='if positive, display all images in a single visdom web panel with certain number of images per row.')
15
- parser.add_argument('--display_id', type=int, default=1, help='window id of the web display')
16
- parser.add_argument('--display_server', type=str, default="http://localhost", help='visdom server of the web display')
17
- parser.add_argument('--display_env', type=str, default='main', help='visdom display environment name (default is "main")')
18
- parser.add_argument('--display_port', type=int, default=8097, help='visdom port of the web display')
19
- parser.add_argument('--update_html_freq', type=int, default=1000, help='frequency of saving training results to html')
20
- parser.add_argument('--print_freq', type=int, default=100, help='frequency of showing training results on console')
21
- parser.add_argument('--no_html', action='store_true', help='do not save intermediate training results to [opt.checkpoints_dir]/[opt.name]/web/')
22
- # network saving and loading parameters
23
- parser.add_argument('--save_latest_freq', type=int, default=5000, help='frequency of saving the latest results')
24
- parser.add_argument('--save_epoch_freq', type=int, default=5, help='frequency of saving checkpoints at the end of epochs')
25
- parser.add_argument('--save_by_iter', action='store_true', help='whether saves model by iteration')
26
- parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model')
27
- parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')
28
- parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc')
29
- # training parameters
30
- parser.add_argument('--n_epochs', type=int, default=100, help='number of epochs with the initial learning rate')
31
- parser.add_argument('--n_epochs_decay', type=int, default=100, help='number of epochs to linearly decay learning rate to zero')
32
- parser.add_argument('--beta1', type=float, default=0.5, help='momentum term of adam')
33
- parser.add_argument('--lr', type=float, default=0.0002, help='initial learning rate for adam')
34
- parser.add_argument('--gan_mode', type=str, default='lsgan', help='the type of GAN objective. [vanilla| lsgan | wgangp]. vanilla GAN loss is the cross-entropy objective used in the original GAN paper.')
35
- parser.add_argument('--pool_size', type=int, default=50, help='the size of image buffer that stores previously generated images')
36
- parser.add_argument('--lr_policy', type=str, default='linear', help='learning rate policy. [linear | step | plateau | cosine]')
37
- parser.add_argument('--lr_decay_iters', type=int, default=50, help='multiply by a gamma every lr_decay_iters iterations')
38
-
39
- self.isTrain = True
40
- return parser
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Amrrs/DragGan-Inversion/PTI/models/StyleCLIP/mapper/training/ranger.py DELETED
@@ -1,164 +0,0 @@
1
- # Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer.
2
-
3
- # https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer
4
- # and/or
5
- # https://github.com/lessw2020/Best-Deep-Learning-Optimizers
6
-
7
- # Ranger has now been used to capture 12 records on the FastAI leaderboard.
8
-
9
- # This version = 20.4.11
10
-
11
- # Credits:
12
- # Gradient Centralization --> https://arxiv.org/abs/2004.01461v2 (a new optimization technique for DNNs), github: https://github.com/Yonghongwei/Gradient-Centralization
13
- # RAdam --> https://github.com/LiyuanLucasLiu/RAdam
14
- # Lookahead --> rewritten by lessw2020, but big thanks to Github @LonePatient and @RWightman for ideas from their code.
15
- # Lookahead paper --> MZhang,G Hinton https://arxiv.org/abs/1907.08610
16
-
17
- # summary of changes:
18
- # 4/11/20 - add gradient centralization option. Set new testing benchmark for accuracy with it, toggle with use_gc flag at init.
19
- # full code integration with all updates at param level instead of group, moves slow weights into state dict (from generic weights),
20
- # supports group learning rates (thanks @SHolderbach), fixes sporadic load from saved model issues.
21
- # changes 8/31/19 - fix references to *self*.N_sma_threshold;
22
- # changed eps to 1e-5 as better default than 1e-8.
23
-
24
- import math
25
- import torch
26
- from torch.optim.optimizer import Optimizer
27
-
28
-
29
- class Ranger(Optimizer):
30
-
31
- def __init__(self, params, lr=1e-3, # lr
32
- alpha=0.5, k=6, N_sma_threshhold=5, # Ranger configs
33
- betas=(.95, 0.999), eps=1e-5, weight_decay=0, # Adam configs
34
- use_gc=True, gc_conv_only=False
35
- # Gradient centralization on or off, applied to conv layers only or conv + fc layers
36
- ):
37
-
38
- # parameter checks
39
- if not 0.0 <= alpha <= 1.0:
40
- raise ValueError(f'Invalid slow update rate: {alpha}')
41
- if not 1 <= k:
42
- raise ValueError(f'Invalid lookahead steps: {k}')
43
- if not lr > 0:
44
- raise ValueError(f'Invalid Learning Rate: {lr}')
45
- if not eps > 0:
46
- raise ValueError(f'Invalid eps: {eps}')
47
-
48
- # parameter comments:
49
- # beta1 (momentum) of .95 seems to work better than .90...
50
- # N_sma_threshold of 5 seems better in testing than 4.
51
- # In both cases, worth testing on your dataset (.90 vs .95, 4 vs 5) to make sure which works best for you.
52
-
53
- # prep defaults and init torch.optim base
54
- defaults = dict(lr=lr, alpha=alpha, k=k, step_counter=0, betas=betas, N_sma_threshhold=N_sma_threshhold,
55
- eps=eps, weight_decay=weight_decay)
56
- super().__init__(params, defaults)
57
-
58
- # adjustable threshold
59
- self.N_sma_threshhold = N_sma_threshhold
60
-
61
- # look ahead params
62
-
63
- self.alpha = alpha
64
- self.k = k
65
-
66
- # radam buffer for state
67
- self.radam_buffer = [[None, None, None] for ind in range(10)]
68
-
69
- # gc on or off
70
- self.use_gc = use_gc
71
-
72
- # level of gradient centralization
73
- self.gc_gradient_threshold = 3 if gc_conv_only else 1
74
-
75
- def __setstate__(self, state):
76
- super(Ranger, self).__setstate__(state)
77
-
78
- def step(self, closure=None):
79
- loss = None
80
-
81
- # Evaluate averages and grad, update param tensors
82
- for group in self.param_groups:
83
-
84
- for p in group['params']:
85
- if p.grad is None:
86
- continue
87
- grad = p.grad.data.float()
88
-
89
- if grad.is_sparse:
90
- raise RuntimeError('Ranger optimizer does not support sparse gradients')
91
-
92
- p_data_fp32 = p.data.float()
93
-
94
- state = self.state[p] # get state dict for this param
95
-
96
- if len(state) == 0: # if first time to run...init dictionary with our desired entries
97
- # if self.first_run_check==0:
98
- # self.first_run_check=1
99
- # print("Initializing slow buffer...should not see this at load from saved model!")
100
- state['step'] = 0
101
- state['exp_avg'] = torch.zeros_like(p_data_fp32)
102
- state['exp_avg_sq'] = torch.zeros_like(p_data_fp32)
103
-
104
- # look ahead weight storage now in state dict
105
- state['slow_buffer'] = torch.empty_like(p.data)
106
- state['slow_buffer'].copy_(p.data)
107
-
108
- else:
109
- state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)
110
- state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)
111
-
112
- # begin computations
113
- exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
114
- beta1, beta2 = group['betas']
115
-
116
- # GC operation for Conv layers and FC layers
117
- if grad.dim() > self.gc_gradient_threshold:
118
- grad.add_(-grad.mean(dim=tuple(range(1, grad.dim())), keepdim=True))
119
-
120
- state['step'] += 1
121
-
122
- # compute variance mov avg
123
- exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
124
- # compute mean moving avg
125
- exp_avg.mul_(beta1).add_(1 - beta1, grad)
126
-
127
- buffered = self.radam_buffer[int(state['step'] % 10)]
128
-
129
- if state['step'] == buffered[0]:
130
- N_sma, step_size = buffered[1], buffered[2]
131
- else:
132
- buffered[0] = state['step']
133
- beta2_t = beta2 ** state['step']
134
- N_sma_max = 2 / (1 - beta2) - 1
135
- N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)
136
- buffered[1] = N_sma
137
- if N_sma > self.N_sma_threshhold:
138
- step_size = math.sqrt(
139
- (1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / (
140
- N_sma_max - 2)) / (1 - beta1 ** state['step'])
141
- else:
142
- step_size = 1.0 / (1 - beta1 ** state['step'])
143
- buffered[2] = step_size
144
-
145
- if group['weight_decay'] != 0:
146
- p_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)
147
-
148
- # apply lr
149
- if N_sma > self.N_sma_threshhold:
150
- denom = exp_avg_sq.sqrt().add_(group['eps'])
151
- p_data_fp32.addcdiv_(-step_size * group['lr'], exp_avg, denom)
152
- else:
153
- p_data_fp32.add_(-step_size * group['lr'], exp_avg)
154
-
155
- p.data.copy_(p_data_fp32)
156
-
157
- # integrated look ahead...
158
- # we do it at the param level instead of group level
159
- if state['step'] % group['k'] == 0:
160
- slow_p = state['slow_buffer'] # get access to slow param tensor
161
- slow_p.add_(self.alpha, p.data - slow_p) # (fast weights - slow weights) * alpha
162
- p.data.copy_(slow_p) # copy interpolated weights to RAdam param tensor
163
-
164
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/examples/controlnet/train_controlnet_sdxl.py DELETED
@@ -1,1251 +0,0 @@
1
- #!/usr/bin/env python
2
- # coding=utf-8
3
- # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
-
16
- import argparse
17
- import functools
18
- import gc
19
- import logging
20
- import math
21
- import os
22
- import random
23
- import shutil
24
- from pathlib import Path
25
-
26
- import accelerate
27
- import numpy as np
28
- import torch
29
- import torch.nn.functional as F
30
- import torch.utils.checkpoint
31
- import transformers
32
- from accelerate import Accelerator
33
- from accelerate.logging import get_logger
34
- from accelerate.utils import ProjectConfiguration, set_seed
35
- from datasets import load_dataset
36
- from huggingface_hub import create_repo, upload_folder
37
- from packaging import version
38
- from PIL import Image
39
- from torchvision import transforms
40
- from tqdm.auto import tqdm
41
- from transformers import AutoTokenizer, PretrainedConfig
42
-
43
- import diffusers
44
- from diffusers import (
45
- AutoencoderKL,
46
- ControlNetModel,
47
- DDPMScheduler,
48
- StableDiffusionXLControlNetPipeline,
49
- UNet2DConditionModel,
50
- UniPCMultistepScheduler,
51
- )
52
- from diffusers.optimization import get_scheduler
53
- from diffusers.utils import check_min_version, is_wandb_available
54
- from diffusers.utils.import_utils import is_xformers_available
55
-
56
-
57
- if is_wandb_available():
58
- import wandb
59
-
60
- # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
61
- check_min_version("0.19.0")
62
-
63
- logger = get_logger(__name__)
64
-
65
-
66
- def image_grid(imgs, rows, cols):
67
- assert len(imgs) == rows * cols
68
-
69
- w, h = imgs[0].size
70
- grid = Image.new("RGB", size=(cols * w, rows * h))
71
-
72
- for i, img in enumerate(imgs):
73
- grid.paste(img, box=(i % cols * w, i // cols * h))
74
- return grid
75
-
76
-
77
- def log_validation(vae, unet, controlnet, args, accelerator, weight_dtype, step):
78
- logger.info("Running validation... ")
79
-
80
- controlnet = accelerator.unwrap_model(controlnet)
81
-
82
- pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(
83
- args.pretrained_model_name_or_path,
84
- vae=vae,
85
- unet=unet,
86
- controlnet=controlnet,
87
- revision=args.revision,
88
- torch_dtype=weight_dtype,
89
- )
90
- pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config)
91
- pipeline = pipeline.to(accelerator.device)
92
- pipeline.set_progress_bar_config(disable=True)
93
-
94
- if args.enable_xformers_memory_efficient_attention:
95
- pipeline.enable_xformers_memory_efficient_attention()
96
-
97
- if args.seed is None:
98
- generator = None
99
- else:
100
- generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
101
-
102
- if len(args.validation_image) == len(args.validation_prompt):
103
- validation_images = args.validation_image
104
- validation_prompts = args.validation_prompt
105
- elif len(args.validation_image) == 1:
106
- validation_images = args.validation_image * len(args.validation_prompt)
107
- validation_prompts = args.validation_prompt
108
- elif len(args.validation_prompt) == 1:
109
- validation_images = args.validation_image
110
- validation_prompts = args.validation_prompt * len(args.validation_image)
111
- else:
112
- raise ValueError(
113
- "number of `args.validation_image` and `args.validation_prompt` should be checked in `parse_args`"
114
- )
115
-
116
- image_logs = []
117
-
118
- for validation_prompt, validation_image in zip(validation_prompts, validation_images):
119
- validation_image = Image.open(validation_image).convert("RGB")
120
- validation_image = validation_image.resize((args.resolution, args.resolution))
121
-
122
- images = []
123
-
124
- for _ in range(args.num_validation_images):
125
- with torch.autocast("cuda"):
126
- image = pipeline(
127
- prompt=validation_prompt, image=validation_image, num_inference_steps=20, generator=generator
128
- ).images[0]
129
- images.append(image)
130
-
131
- image_logs.append(
132
- {"validation_image": validation_image, "images": images, "validation_prompt": validation_prompt}
133
- )
134
-
135
- for tracker in accelerator.trackers:
136
- if tracker.name == "tensorboard":
137
- for log in image_logs:
138
- images = log["images"]
139
- validation_prompt = log["validation_prompt"]
140
- validation_image = log["validation_image"]
141
-
142
- formatted_images = []
143
-
144
- formatted_images.append(np.asarray(validation_image))
145
-
146
- for image in images:
147
- formatted_images.append(np.asarray(image))
148
-
149
- formatted_images = np.stack(formatted_images)
150
-
151
- tracker.writer.add_images(validation_prompt, formatted_images, step, dataformats="NHWC")
152
- elif tracker.name == "wandb":
153
- formatted_images = []
154
-
155
- for log in image_logs:
156
- images = log["images"]
157
- validation_prompt = log["validation_prompt"]
158
- validation_image = log["validation_image"]
159
-
160
- formatted_images.append(wandb.Image(validation_image, caption="Controlnet conditioning"))
161
-
162
- for image in images:
163
- image = wandb.Image(image, caption=validation_prompt)
164
- formatted_images.append(image)
165
-
166
- tracker.log({"validation": formatted_images})
167
- else:
168
- logger.warn(f"image logging not implemented for {tracker.name}")
169
-
170
- del pipeline
171
- gc.collect()
172
- torch.cuda.empty_cache()
173
-
174
- return image_logs
175
-
176
-
177
- def import_model_class_from_model_name_or_path(
178
- pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
179
- ):
180
- text_encoder_config = PretrainedConfig.from_pretrained(
181
- pretrained_model_name_or_path, subfolder=subfolder, revision=revision
182
- )
183
- model_class = text_encoder_config.architectures[0]
184
-
185
- if model_class == "CLIPTextModel":
186
- from transformers import CLIPTextModel
187
-
188
- return CLIPTextModel
189
- elif model_class == "CLIPTextModelWithProjection":
190
- from transformers import CLIPTextModelWithProjection
191
-
192
- return CLIPTextModelWithProjection
193
- else:
194
- raise ValueError(f"{model_class} is not supported.")
195
-
196
-
197
- def save_model_card(repo_id: str, image_logs=None, base_model=str, repo_folder=None):
198
- img_str = ""
199
- if image_logs is not None:
200
- img_str = "You can find some example images below.\n"
201
- for i, log in enumerate(image_logs):
202
- images = log["images"]
203
- validation_prompt = log["validation_prompt"]
204
- validation_image = log["validation_image"]
205
- validation_image.save(os.path.join(repo_folder, "image_control.png"))
206
- img_str += f"prompt: {validation_prompt}\n"
207
- images = [validation_image] + images
208
- image_grid(images, 1, len(images)).save(os.path.join(repo_folder, f"images_{i}.png"))
209
- img_str += f"![images_{i})](./images_{i}.png)\n"
210
-
211
- yaml = f"""
212
- ---
213
- license: creativeml-openrail-m
214
- base_model: {base_model}
215
- tags:
216
- - stable-diffusion-xl
217
- - stable-diffusion-xl-diffusers
218
- - text-to-image
219
- - diffusers
220
- - controlnet
221
- inference: true
222
- ---
223
- """
224
- model_card = f"""
225
- # controlnet-{repo_id}
226
-
227
- These are controlnet weights trained on {base_model} with new type of conditioning.
228
- {img_str}
229
- """
230
- model_card += """
231
-
232
- ## License
233
-
234
- [SDXL 1.0 License](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/LICENSE.md)
235
- """
236
- with open(os.path.join(repo_folder, "README.md"), "w") as f:
237
- f.write(yaml + model_card)
238
-
239
-
240
- def parse_args(input_args=None):
241
- parser = argparse.ArgumentParser(description="Simple example of a ControlNet training script.")
242
- parser.add_argument(
243
- "--pretrained_model_name_or_path",
244
- type=str,
245
- default=None,
246
- required=True,
247
- help="Path to pretrained model or model identifier from huggingface.co/models.",
248
- )
249
- parser.add_argument(
250
- "--pretrained_vae_model_name_or_path",
251
- type=str,
252
- default=None,
253
- help="Path to an improved VAE to stabilize training. For more details check out: https://github.com/huggingface/diffusers/pull/4038.",
254
- )
255
- parser.add_argument(
256
- "--controlnet_model_name_or_path",
257
- type=str,
258
- default=None,
259
- help="Path to pretrained controlnet model or model identifier from huggingface.co/models."
260
- " If not specified controlnet weights are initialized from unet.",
261
- )
262
- parser.add_argument(
263
- "--revision",
264
- type=str,
265
- default=None,
266
- required=False,
267
- help=(
268
- "Revision of pretrained model identifier from huggingface.co/models. Trainable model components should be"
269
- " float32 precision."
270
- ),
271
- )
272
- parser.add_argument(
273
- "--tokenizer_name",
274
- type=str,
275
- default=None,
276
- help="Pretrained tokenizer name or path if not the same as model_name",
277
- )
278
- parser.add_argument(
279
- "--output_dir",
280
- type=str,
281
- default="controlnet-model",
282
- help="The output directory where the model predictions and checkpoints will be written.",
283
- )
284
- parser.add_argument(
285
- "--cache_dir",
286
- type=str,
287
- default=None,
288
- help="The directory where the downloaded models and datasets will be stored.",
289
- )
290
- parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
291
- parser.add_argument(
292
- "--resolution",
293
- type=int,
294
- default=512,
295
- help=(
296
- "The resolution for input images, all the images in the train/validation dataset will be resized to this"
297
- " resolution"
298
- ),
299
- )
300
- parser.add_argument(
301
- "--crops_coords_top_left_h",
302
- type=int,
303
- default=0,
304
- help=("Coordinate for (the height) to be included in the crop coordinate embeddings needed by SDXL UNet."),
305
- )
306
- parser.add_argument(
307
- "--crops_coords_top_left_w",
308
- type=int,
309
- default=0,
310
- help=("Coordinate for (the height) to be included in the crop coordinate embeddings needed by SDXL UNet."),
311
- )
312
- parser.add_argument(
313
- "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
314
- )
315
- parser.add_argument("--num_train_epochs", type=int, default=1)
316
- parser.add_argument(
317
- "--max_train_steps",
318
- type=int,
319
- default=None,
320
- help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
321
- )
322
- parser.add_argument(
323
- "--checkpointing_steps",
324
- type=int,
325
- default=500,
326
- help=(
327
- "Save a checkpoint of the training state every X updates. Checkpoints can be used for resuming training via `--resume_from_checkpoint`. "
328
- "In the case that the checkpoint is better than the final trained model, the checkpoint can also be used for inference."
329
- "Using a checkpoint for inference requires separate loading of the original pipeline and the individual checkpointed model components."
330
- "See https://huggingface.co/docs/diffusers/main/en/training/dreambooth#performing-inference-using-a-saved-checkpoint for step by step"
331
- "instructions."
332
- ),
333
- )
334
- parser.add_argument(
335
- "--checkpoints_total_limit",
336
- type=int,
337
- default=None,
338
- help=("Max number of checkpoints to store."),
339
- )
340
- parser.add_argument(
341
- "--resume_from_checkpoint",
342
- type=str,
343
- default=None,
344
- help=(
345
- "Whether training should be resumed from a previous checkpoint. Use a path saved by"
346
- ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
347
- ),
348
- )
349
- parser.add_argument(
350
- "--gradient_accumulation_steps",
351
- type=int,
352
- default=1,
353
- help="Number of updates steps to accumulate before performing a backward/update pass.",
354
- )
355
- parser.add_argument(
356
- "--gradient_checkpointing",
357
- action="store_true",
358
- help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
359
- )
360
- parser.add_argument(
361
- "--learning_rate",
362
- type=float,
363
- default=5e-6,
364
- help="Initial learning rate (after the potential warmup period) to use.",
365
- )
366
- parser.add_argument(
367
- "--scale_lr",
368
- action="store_true",
369
- default=False,
370
- help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
371
- )
372
- parser.add_argument(
373
- "--lr_scheduler",
374
- type=str,
375
- default="constant",
376
- help=(
377
- 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
378
- ' "constant", "constant_with_warmup"]'
379
- ),
380
- )
381
- parser.add_argument(
382
- "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
383
- )
384
- parser.add_argument(
385
- "--lr_num_cycles",
386
- type=int,
387
- default=1,
388
- help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
389
- )
390
- parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
391
- parser.add_argument(
392
- "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
393
- )
394
- parser.add_argument(
395
- "--dataloader_num_workers",
396
- type=int,
397
- default=0,
398
- help=(
399
- "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
400
- ),
401
- )
402
- parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
403
- parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
404
- parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
405
- parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
406
- parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
407
- parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
408
- parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
409
- parser.add_argument(
410
- "--hub_model_id",
411
- type=str,
412
- default=None,
413
- help="The name of the repository to keep in sync with the local `output_dir`.",
414
- )
415
- parser.add_argument(
416
- "--logging_dir",
417
- type=str,
418
- default="logs",
419
- help=(
420
- "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
421
- " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
422
- ),
423
- )
424
- parser.add_argument(
425
- "--allow_tf32",
426
- action="store_true",
427
- help=(
428
- "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
429
- " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
430
- ),
431
- )
432
- parser.add_argument(
433
- "--report_to",
434
- type=str,
435
- default="tensorboard",
436
- help=(
437
- 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
438
- ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
439
- ),
440
- )
441
- parser.add_argument(
442
- "--mixed_precision",
443
- type=str,
444
- default=None,
445
- choices=["no", "fp16", "bf16"],
446
- help=(
447
- "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
448
- " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
449
- " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
450
- ),
451
- )
452
- parser.add_argument(
453
- "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
454
- )
455
- parser.add_argument(
456
- "--set_grads_to_none",
457
- action="store_true",
458
- help=(
459
- "Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain"
460
- " behaviors, so disable this argument if it causes any problems. More info:"
461
- " https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html"
462
- ),
463
- )
464
- parser.add_argument(
465
- "--dataset_name",
466
- type=str,
467
- default=None,
468
- help=(
469
- "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
470
- " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
471
- " or to a folder containing files that 🤗 Datasets can understand."
472
- ),
473
- )
474
- parser.add_argument(
475
- "--dataset_config_name",
476
- type=str,
477
- default=None,
478
- help="The config of the Dataset, leave as None if there's only one config.",
479
- )
480
- parser.add_argument(
481
- "--train_data_dir",
482
- type=str,
483
- default=None,
484
- help=(
485
- "A folder containing the training data. Folder contents must follow the structure described in"
486
- " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
487
- " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
488
- ),
489
- )
490
- parser.add_argument(
491
- "--image_column", type=str, default="image", help="The column of the dataset containing the target image."
492
- )
493
- parser.add_argument(
494
- "--conditioning_image_column",
495
- type=str,
496
- default="conditioning_image",
497
- help="The column of the dataset containing the controlnet conditioning image.",
498
- )
499
- parser.add_argument(
500
- "--caption_column",
501
- type=str,
502
- default="text",
503
- help="The column of the dataset containing a caption or a list of captions.",
504
- )
505
- parser.add_argument(
506
- "--max_train_samples",
507
- type=int,
508
- default=None,
509
- help=(
510
- "For debugging purposes or quicker training, truncate the number of training examples to this "
511
- "value if set."
512
- ),
513
- )
514
- parser.add_argument(
515
- "--proportion_empty_prompts",
516
- type=float,
517
- default=0,
518
- help="Proportion of image prompts to be replaced with empty strings. Defaults to 0 (no prompt replacement).",
519
- )
520
- parser.add_argument(
521
- "--validation_prompt",
522
- type=str,
523
- default=None,
524
- nargs="+",
525
- help=(
526
- "A set of prompts evaluated every `--validation_steps` and logged to `--report_to`."
527
- " Provide either a matching number of `--validation_image`s, a single `--validation_image`"
528
- " to be used with all prompts, or a single prompt that will be used with all `--validation_image`s."
529
- ),
530
- )
531
- parser.add_argument(
532
- "--validation_image",
533
- type=str,
534
- default=None,
535
- nargs="+",
536
- help=(
537
- "A set of paths to the controlnet conditioning image be evaluated every `--validation_steps`"
538
- " and logged to `--report_to`. Provide either a matching number of `--validation_prompt`s, a"
539
- " a single `--validation_prompt` to be used with all `--validation_image`s, or a single"
540
- " `--validation_image` that will be used with all `--validation_prompt`s."
541
- ),
542
- )
543
- parser.add_argument(
544
- "--num_validation_images",
545
- type=int,
546
- default=4,
547
- help="Number of images to be generated for each `--validation_image`, `--validation_prompt` pair",
548
- )
549
- parser.add_argument(
550
- "--validation_steps",
551
- type=int,
552
- default=100,
553
- help=(
554
- "Run validation every X steps. Validation consists of running the prompt"
555
- " `args.validation_prompt` multiple times: `args.num_validation_images`"
556
- " and logging the images."
557
- ),
558
- )
559
- parser.add_argument(
560
- "--tracker_project_name",
561
- type=str,
562
- default="sd_xl_train_controlnet",
563
- help=(
564
- "The `project_name` argument passed to Accelerator.init_trackers for"
565
- " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
566
- ),
567
- )
568
-
569
- if input_args is not None:
570
- args = parser.parse_args(input_args)
571
- else:
572
- args = parser.parse_args()
573
-
574
- if args.dataset_name is None and args.train_data_dir is None:
575
- raise ValueError("Specify either `--dataset_name` or `--train_data_dir`")
576
-
577
- if args.dataset_name is not None and args.train_data_dir is not None:
578
- raise ValueError("Specify only one of `--dataset_name` or `--train_data_dir`")
579
-
580
- if args.proportion_empty_prompts < 0 or args.proportion_empty_prompts > 1:
581
- raise ValueError("`--proportion_empty_prompts` must be in the range [0, 1].")
582
-
583
- if args.validation_prompt is not None and args.validation_image is None:
584
- raise ValueError("`--validation_image` must be set if `--validation_prompt` is set")
585
-
586
- if args.validation_prompt is None and args.validation_image is not None:
587
- raise ValueError("`--validation_prompt` must be set if `--validation_image` is set")
588
-
589
- if (
590
- args.validation_image is not None
591
- and args.validation_prompt is not None
592
- and len(args.validation_image) != 1
593
- and len(args.validation_prompt) != 1
594
- and len(args.validation_image) != len(args.validation_prompt)
595
- ):
596
- raise ValueError(
597
- "Must provide either 1 `--validation_image`, 1 `--validation_prompt`,"
598
- " or the same number of `--validation_prompt`s and `--validation_image`s"
599
- )
600
-
601
- if args.resolution % 8 != 0:
602
- raise ValueError(
603
- "`--resolution` must be divisible by 8 for consistently sized encoded images between the VAE and the controlnet encoder."
604
- )
605
-
606
- return args
607
-
608
-
609
- def get_train_dataset(args, accelerator):
610
- # Get the datasets: you can either provide your own training and evaluation files (see below)
611
- # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
612
-
613
- # In distributed training, the load_dataset function guarantees that only one local process can concurrently
614
- # download the dataset.
615
- if args.dataset_name is not None:
616
- # Downloading and loading a dataset from the hub.
617
- dataset = load_dataset(
618
- args.dataset_name,
619
- args.dataset_config_name,
620
- cache_dir=args.cache_dir,
621
- )
622
- else:
623
- if args.train_data_dir is not None:
624
- dataset = load_dataset(
625
- args.train_data_dir,
626
- cache_dir=args.cache_dir,
627
- )
628
- # See more about loading custom images at
629
- # https://huggingface.co/docs/datasets/v2.0.0/en/dataset_script
630
-
631
- # Preprocessing the datasets.
632
- # We need to tokenize inputs and targets.
633
- column_names = dataset["train"].column_names
634
-
635
- # 6. Get the column names for input/target.
636
- if args.image_column is None:
637
- image_column = column_names[0]
638
- logger.info(f"image column defaulting to {image_column}")
639
- else:
640
- image_column = args.image_column
641
- if image_column not in column_names:
642
- raise ValueError(
643
- f"`--image_column` value '{args.image_column}' not found in dataset columns. Dataset columns are: {', '.join(column_names)}"
644
- )
645
-
646
- if args.caption_column is None:
647
- caption_column = column_names[1]
648
- logger.info(f"caption column defaulting to {caption_column}")
649
- else:
650
- caption_column = args.caption_column
651
- if caption_column not in column_names:
652
- raise ValueError(
653
- f"`--caption_column` value '{args.caption_column}' not found in dataset columns. Dataset columns are: {', '.join(column_names)}"
654
- )
655
-
656
- if args.conditioning_image_column is None:
657
- conditioning_image_column = column_names[2]
658
- logger.info(f"conditioning image column defaulting to {conditioning_image_column}")
659
- else:
660
- conditioning_image_column = args.conditioning_image_column
661
- if conditioning_image_column not in column_names:
662
- raise ValueError(
663
- f"`--conditioning_image_column` value '{args.conditioning_image_column}' not found in dataset columns. Dataset columns are: {', '.join(column_names)}"
664
- )
665
-
666
- with accelerator.main_process_first():
667
- train_dataset = dataset["train"].shuffle(seed=args.seed)
668
- if args.max_train_samples is not None:
669
- train_dataset = train_dataset.select(range(args.max_train_samples))
670
- return train_dataset
671
-
672
-
673
- # Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
674
- def encode_prompt(prompt_batch, text_encoders, tokenizers, proportion_empty_prompts, is_train=True):
675
- prompt_embeds_list = []
676
-
677
- captions = []
678
- for caption in prompt_batch:
679
- if random.random() < proportion_empty_prompts:
680
- captions.append("")
681
- elif isinstance(caption, str):
682
- captions.append(caption)
683
- elif isinstance(caption, (list, np.ndarray)):
684
- # take a random caption if there are multiple
685
- captions.append(random.choice(caption) if is_train else caption[0])
686
-
687
- with torch.no_grad():
688
- for tokenizer, text_encoder in zip(tokenizers, text_encoders):
689
- text_inputs = tokenizer(
690
- captions,
691
- padding="max_length",
692
- max_length=tokenizer.model_max_length,
693
- truncation=True,
694
- return_tensors="pt",
695
- )
696
- text_input_ids = text_inputs.input_ids
697
- prompt_embeds = text_encoder(
698
- text_input_ids.to(text_encoder.device),
699
- output_hidden_states=True,
700
- )
701
-
702
- # We are only ALWAYS interested in the pooled output of the final text encoder
703
- pooled_prompt_embeds = prompt_embeds[0]
704
- prompt_embeds = prompt_embeds.hidden_states[-2]
705
- bs_embed, seq_len, _ = prompt_embeds.shape
706
- prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
707
- prompt_embeds_list.append(prompt_embeds)
708
-
709
- prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
710
- pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
711
- return prompt_embeds, pooled_prompt_embeds
712
-
713
-
714
- def prepare_train_dataset(dataset, accelerator):
715
- image_transforms = transforms.Compose(
716
- [
717
- transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
718
- transforms.CenterCrop(args.resolution),
719
- transforms.ToTensor(),
720
- transforms.Normalize([0.5], [0.5]),
721
- ]
722
- )
723
-
724
- conditioning_image_transforms = transforms.Compose(
725
- [
726
- transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
727
- transforms.CenterCrop(args.resolution),
728
- transforms.ToTensor(),
729
- ]
730
- )
731
-
732
- def preprocess_train(examples):
733
- images = [image.convert("RGB") for image in examples[args.image_column]]
734
- images = [image_transforms(image) for image in images]
735
-
736
- conditioning_images = [image.convert("RGB") for image in examples[args.conditioning_image_column]]
737
- conditioning_images = [conditioning_image_transforms(image) for image in conditioning_images]
738
-
739
- examples["pixel_values"] = images
740
- examples["conditioning_pixel_values"] = conditioning_images
741
-
742
- return examples
743
-
744
- with accelerator.main_process_first():
745
- dataset = dataset.with_transform(preprocess_train)
746
-
747
- return dataset
748
-
749
-
750
- def collate_fn(examples):
751
- pixel_values = torch.stack([example["pixel_values"] for example in examples])
752
- pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
753
-
754
- conditioning_pixel_values = torch.stack([example["conditioning_pixel_values"] for example in examples])
755
- conditioning_pixel_values = conditioning_pixel_values.to(memory_format=torch.contiguous_format).float()
756
-
757
- prompt_ids = torch.stack([torch.tensor(example["prompt_embeds"]) for example in examples])
758
-
759
- add_text_embeds = torch.stack([torch.tensor(example["text_embeds"]) for example in examples])
760
- add_time_ids = torch.stack([torch.tensor(example["time_ids"]) for example in examples])
761
-
762
- return {
763
- "pixel_values": pixel_values,
764
- "conditioning_pixel_values": conditioning_pixel_values,
765
- "prompt_ids": prompt_ids,
766
- "unet_added_conditions": {"text_embeds": add_text_embeds, "time_ids": add_time_ids},
767
- }
768
-
769
-
770
- def main(args):
771
- logging_dir = Path(args.output_dir, args.logging_dir)
772
-
773
- accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
774
-
775
- accelerator = Accelerator(
776
- gradient_accumulation_steps=args.gradient_accumulation_steps,
777
- mixed_precision=args.mixed_precision,
778
- log_with=args.report_to,
779
- project_config=accelerator_project_config,
780
- )
781
-
782
- # Make one log on every process with the configuration for debugging.
783
- logging.basicConfig(
784
- format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
785
- datefmt="%m/%d/%Y %H:%M:%S",
786
- level=logging.INFO,
787
- )
788
- logger.info(accelerator.state, main_process_only=False)
789
- if accelerator.is_local_main_process:
790
- transformers.utils.logging.set_verbosity_warning()
791
- diffusers.utils.logging.set_verbosity_info()
792
- else:
793
- transformers.utils.logging.set_verbosity_error()
794
- diffusers.utils.logging.set_verbosity_error()
795
-
796
- # If passed along, set the training seed now.
797
- if args.seed is not None:
798
- set_seed(args.seed)
799
-
800
- # Handle the repository creation
801
- if accelerator.is_main_process:
802
- if args.output_dir is not None:
803
- os.makedirs(args.output_dir, exist_ok=True)
804
-
805
- if args.push_to_hub:
806
- repo_id = create_repo(
807
- repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
808
- ).repo_id
809
-
810
- # Load the tokenizers
811
- tokenizer_one = AutoTokenizer.from_pretrained(
812
- args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision, use_fast=False
813
- )
814
- tokenizer_two = AutoTokenizer.from_pretrained(
815
- args.pretrained_model_name_or_path, subfolder="tokenizer_2", revision=args.revision, use_fast=False
816
- )
817
-
818
- # import correct text encoder classes
819
- text_encoder_cls_one = import_model_class_from_model_name_or_path(
820
- args.pretrained_model_name_or_path, args.revision
821
- )
822
- text_encoder_cls_two = import_model_class_from_model_name_or_path(
823
- args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
824
- )
825
-
826
- # Load scheduler and models
827
- noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
828
- text_encoder_one = text_encoder_cls_one.from_pretrained(
829
- args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
830
- )
831
- text_encoder_two = text_encoder_cls_two.from_pretrained(
832
- args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision
833
- )
834
- vae_path = (
835
- args.pretrained_model_name_or_path
836
- if args.pretrained_vae_model_name_or_path is None
837
- else args.pretrained_vae_model_name_or_path
838
- )
839
- vae = AutoencoderKL.from_pretrained(
840
- vae_path,
841
- subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
842
- revision=args.revision,
843
- )
844
- unet = UNet2DConditionModel.from_pretrained(
845
- args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
846
- )
847
-
848
- if args.controlnet_model_name_or_path:
849
- logger.info("Loading existing controlnet weights")
850
- controlnet = ControlNetModel.from_pretrained(args.controlnet_model_name_or_path)
851
- else:
852
- logger.info("Initializing controlnet weights from unet")
853
- controlnet = ControlNetModel.from_unet(unet)
854
-
855
- # `accelerate` 0.16.0 will have better support for customized saving
856
- if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
857
- # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
858
- def save_model_hook(models, weights, output_dir):
859
- i = len(weights) - 1
860
-
861
- while len(weights) > 0:
862
- weights.pop()
863
- model = models[i]
864
-
865
- sub_dir = "controlnet"
866
- model.save_pretrained(os.path.join(output_dir, sub_dir))
867
-
868
- i -= 1
869
-
870
- def load_model_hook(models, input_dir):
871
- while len(models) > 0:
872
- # pop models so that they are not loaded again
873
- model = models.pop()
874
-
875
- # load diffusers style into model
876
- load_model = ControlNetModel.from_pretrained(input_dir, subfolder="controlnet")
877
- model.register_to_config(**load_model.config)
878
-
879
- model.load_state_dict(load_model.state_dict())
880
- del load_model
881
-
882
- accelerator.register_save_state_pre_hook(save_model_hook)
883
- accelerator.register_load_state_pre_hook(load_model_hook)
884
-
885
- vae.requires_grad_(False)
886
- unet.requires_grad_(False)
887
- text_encoder_one.requires_grad_(False)
888
- text_encoder_two.requires_grad_(False)
889
- controlnet.train()
890
-
891
- if args.enable_xformers_memory_efficient_attention:
892
- if is_xformers_available():
893
- import xformers
894
-
895
- xformers_version = version.parse(xformers.__version__)
896
- if xformers_version == version.parse("0.0.16"):
897
- logger.warn(
898
- "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
899
- )
900
- unet.enable_xformers_memory_efficient_attention()
901
- controlnet.enable_xformers_memory_efficient_attention()
902
- else:
903
- raise ValueError("xformers is not available. Make sure it is installed correctly")
904
-
905
- if args.gradient_checkpointing:
906
- controlnet.enable_gradient_checkpointing()
907
-
908
- # Check that all trainable models are in full precision
909
- low_precision_error_string = (
910
- " Please make sure to always have all model weights in full float32 precision when starting training - even if"
911
- " doing mixed precision training, copy of the weights should still be float32."
912
- )
913
-
914
- if accelerator.unwrap_model(controlnet).dtype != torch.float32:
915
- raise ValueError(
916
- f"Controlnet loaded as datatype {accelerator.unwrap_model(controlnet).dtype}. {low_precision_error_string}"
917
- )
918
-
919
- # Enable TF32 for faster training on Ampere GPUs,
920
- # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
921
- if args.allow_tf32:
922
- torch.backends.cuda.matmul.allow_tf32 = True
923
-
924
- if args.scale_lr:
925
- args.learning_rate = (
926
- args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
927
- )
928
-
929
- # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
930
- if args.use_8bit_adam:
931
- try:
932
- import bitsandbytes as bnb
933
- except ImportError:
934
- raise ImportError(
935
- "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
936
- )
937
-
938
- optimizer_class = bnb.optim.AdamW8bit
939
- else:
940
- optimizer_class = torch.optim.AdamW
941
-
942
- # Optimizer creation
943
- params_to_optimize = controlnet.parameters()
944
- optimizer = optimizer_class(
945
- params_to_optimize,
946
- lr=args.learning_rate,
947
- betas=(args.adam_beta1, args.adam_beta2),
948
- weight_decay=args.adam_weight_decay,
949
- eps=args.adam_epsilon,
950
- )
951
-
952
- # For mixed precision training we cast the text_encoder and vae weights to half-precision
953
- # as these models are only used for inference, keeping weights in full precision is not required.
954
- weight_dtype = torch.float32
955
- if accelerator.mixed_precision == "fp16":
956
- weight_dtype = torch.float16
957
- elif accelerator.mixed_precision == "bf16":
958
- weight_dtype = torch.bfloat16
959
-
960
- # Move vae, unet and text_encoder to device and cast to weight_dtype
961
- # The VAE is in float32 to avoid NaN losses.
962
- if args.pretrained_vae_model_name_or_path is not None:
963
- vae.to(accelerator.device, dtype=weight_dtype)
964
- else:
965
- vae.to(accelerator.device, dtype=torch.float32)
966
- unet.to(accelerator.device, dtype=weight_dtype)
967
- text_encoder_one.to(accelerator.device, dtype=weight_dtype)
968
- text_encoder_two.to(accelerator.device, dtype=weight_dtype)
969
-
970
- # Here, we compute not just the text embeddings but also the additional embeddings
971
- # needed for the SD XL UNet to operate.
972
- def compute_embeddings(batch, proportion_empty_prompts, text_encoders, tokenizers, is_train=True):
973
- original_size = (args.resolution, args.resolution)
974
- target_size = (args.resolution, args.resolution)
975
- crops_coords_top_left = (args.crops_coords_top_left_h, args.crops_coords_top_left_w)
976
- prompt_batch = batch[args.caption_column]
977
-
978
- prompt_embeds, pooled_prompt_embeds = encode_prompt(
979
- prompt_batch, text_encoders, tokenizers, proportion_empty_prompts, is_train
980
- )
981
- add_text_embeds = pooled_prompt_embeds
982
-
983
- # Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
984
- add_time_ids = list(original_size + crops_coords_top_left + target_size)
985
- add_time_ids = torch.tensor([add_time_ids])
986
-
987
- prompt_embeds = prompt_embeds.to(accelerator.device)
988
- add_text_embeds = add_text_embeds.to(accelerator.device)
989
- add_time_ids = add_time_ids.repeat(len(prompt_batch), 1)
990
- add_time_ids = add_time_ids.to(accelerator.device, dtype=prompt_embeds.dtype)
991
- unet_added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
992
-
993
- return {"prompt_embeds": prompt_embeds, **unet_added_cond_kwargs}
994
-
995
- # Let's first compute all the embeddings so that we can free up the text encoders
996
- # from memory.
997
- text_encoders = [text_encoder_one, text_encoder_two]
998
- tokenizers = [tokenizer_one, tokenizer_two]
999
- train_dataset = get_train_dataset(args, accelerator)
1000
- compute_embeddings_fn = functools.partial(
1001
- compute_embeddings,
1002
- text_encoders=text_encoders,
1003
- tokenizers=tokenizers,
1004
- proportion_empty_prompts=args.proportion_empty_prompts,
1005
- )
1006
- with accelerator.main_process_first():
1007
- from datasets.fingerprint import Hasher
1008
-
1009
- # fingerprint used by the cache for the other processes to load the result
1010
- # details: https://github.com/huggingface/diffusers/pull/4038#discussion_r1266078401
1011
- new_fingerprint = Hasher.hash(args)
1012
- train_dataset = train_dataset.map(compute_embeddings_fn, batched=True, new_fingerprint=new_fingerprint)
1013
-
1014
- del text_encoders, tokenizers
1015
- gc.collect()
1016
- torch.cuda.empty_cache()
1017
-
1018
- # Then get the training dataset ready to be passed to the dataloader.
1019
- train_dataset = prepare_train_dataset(train_dataset, accelerator)
1020
-
1021
- train_dataloader = torch.utils.data.DataLoader(
1022
- train_dataset,
1023
- shuffle=True,
1024
- collate_fn=collate_fn,
1025
- batch_size=args.train_batch_size,
1026
- num_workers=args.dataloader_num_workers,
1027
- )
1028
-
1029
- # Scheduler and math around the number of training steps.
1030
- overrode_max_train_steps = False
1031
- num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1032
- if args.max_train_steps is None:
1033
- args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1034
- overrode_max_train_steps = True
1035
-
1036
- lr_scheduler = get_scheduler(
1037
- args.lr_scheduler,
1038
- optimizer=optimizer,
1039
- num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
1040
- num_training_steps=args.max_train_steps * accelerator.num_processes,
1041
- num_cycles=args.lr_num_cycles,
1042
- power=args.lr_power,
1043
- )
1044
-
1045
- # Prepare everything with our `accelerator`.
1046
- controlnet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
1047
- controlnet, optimizer, train_dataloader, lr_scheduler
1048
- )
1049
-
1050
- # We need to recalculate our total training steps as the size of the training dataloader may have changed.
1051
- num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1052
- if overrode_max_train_steps:
1053
- args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1054
- # Afterwards we recalculate our number of training epochs
1055
- args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
1056
-
1057
- # We need to initialize the trackers we use, and also store our configuration.
1058
- # The trackers initializes automatically on the main process.
1059
- if accelerator.is_main_process:
1060
- tracker_config = dict(vars(args))
1061
-
1062
- # tensorboard cannot handle list types for config
1063
- tracker_config.pop("validation_prompt")
1064
- tracker_config.pop("validation_image")
1065
-
1066
- accelerator.init_trackers(args.tracker_project_name, config=tracker_config)
1067
-
1068
- # Train!
1069
- total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
1070
-
1071
- logger.info("***** Running training *****")
1072
- logger.info(f" Num examples = {len(train_dataset)}")
1073
- logger.info(f" Num batches each epoch = {len(train_dataloader)}")
1074
- logger.info(f" Num Epochs = {args.num_train_epochs}")
1075
- logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
1076
- logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
1077
- logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
1078
- logger.info(f" Total optimization steps = {args.max_train_steps}")
1079
- global_step = 0
1080
- first_epoch = 0
1081
-
1082
- # Potentially load in the weights and states from a previous save
1083
- if args.resume_from_checkpoint:
1084
- if args.resume_from_checkpoint != "latest":
1085
- path = os.path.basename(args.resume_from_checkpoint)
1086
- else:
1087
- # Get the most recent checkpoint
1088
- dirs = os.listdir(args.output_dir)
1089
- dirs = [d for d in dirs if d.startswith("checkpoint")]
1090
- dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
1091
- path = dirs[-1] if len(dirs) > 0 else None
1092
-
1093
- if path is None:
1094
- accelerator.print(
1095
- f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
1096
- )
1097
- args.resume_from_checkpoint = None
1098
- initial_global_step = 0
1099
- else:
1100
- accelerator.print(f"Resuming from checkpoint {path}")
1101
- accelerator.load_state(os.path.join(args.output_dir, path))
1102
- global_step = int(path.split("-")[1])
1103
-
1104
- initial_global_step = global_step
1105
- first_epoch = global_step // num_update_steps_per_epoch
1106
- else:
1107
- initial_global_step = 0
1108
-
1109
- progress_bar = tqdm(
1110
- range(0, args.max_train_steps),
1111
- initial=initial_global_step,
1112
- desc="Steps",
1113
- # Only show the progress bar once on each machine.
1114
- disable=not accelerator.is_local_main_process,
1115
- )
1116
-
1117
- image_logs = None
1118
- for epoch in range(first_epoch, args.num_train_epochs):
1119
- for step, batch in enumerate(train_dataloader):
1120
- with accelerator.accumulate(controlnet):
1121
- # Convert images to latent space
1122
- if args.pretrained_vae_model_name_or_path is not None:
1123
- pixel_values = batch["pixel_values"].to(dtype=weight_dtype)
1124
- else:
1125
- pixel_values = batch["pixel_values"]
1126
- latents = vae.encode(pixel_values).latent_dist.sample()
1127
- latents = latents * vae.config.scaling_factor
1128
- if args.pretrained_vae_model_name_or_path is None:
1129
- latents = latents.to(weight_dtype)
1130
-
1131
- # Sample noise that we'll add to the latents
1132
- noise = torch.randn_like(latents)
1133
- bsz = latents.shape[0]
1134
-
1135
- # Sample a random timestep for each image
1136
- timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
1137
- timesteps = timesteps.long()
1138
-
1139
- # Add noise to the latents according to the noise magnitude at each timestep
1140
- # (this is the forward diffusion process)
1141
- noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
1142
-
1143
- # ControlNet conditioning.
1144
- controlnet_image = batch["conditioning_pixel_values"].to(dtype=weight_dtype)
1145
- down_block_res_samples, mid_block_res_sample = controlnet(
1146
- noisy_latents,
1147
- timesteps,
1148
- encoder_hidden_states=batch["prompt_ids"],
1149
- added_cond_kwargs=batch["unet_added_conditions"],
1150
- controlnet_cond=controlnet_image,
1151
- return_dict=False,
1152
- )
1153
-
1154
- # Predict the noise residual
1155
- model_pred = unet(
1156
- noisy_latents,
1157
- timesteps,
1158
- encoder_hidden_states=batch["prompt_ids"],
1159
- added_cond_kwargs=batch["unet_added_conditions"],
1160
- down_block_additional_residuals=[
1161
- sample.to(dtype=weight_dtype) for sample in down_block_res_samples
1162
- ],
1163
- mid_block_additional_residual=mid_block_res_sample.to(dtype=weight_dtype),
1164
- ).sample
1165
-
1166
- # Get the target for loss depending on the prediction type
1167
- if noise_scheduler.config.prediction_type == "epsilon":
1168
- target = noise
1169
- elif noise_scheduler.config.prediction_type == "v_prediction":
1170
- target = noise_scheduler.get_velocity(latents, noise, timesteps)
1171
- else:
1172
- raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1173
- loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1174
-
1175
- accelerator.backward(loss)
1176
- if accelerator.sync_gradients:
1177
- params_to_clip = controlnet.parameters()
1178
- accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
1179
- optimizer.step()
1180
- lr_scheduler.step()
1181
- optimizer.zero_grad(set_to_none=args.set_grads_to_none)
1182
-
1183
- # Checks if the accelerator has performed an optimization step behind the scenes
1184
- if accelerator.sync_gradients:
1185
- progress_bar.update(1)
1186
- global_step += 1
1187
-
1188
- if accelerator.is_main_process:
1189
- if global_step % args.checkpointing_steps == 0:
1190
- # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1191
- if args.checkpoints_total_limit is not None:
1192
- checkpoints = os.listdir(args.output_dir)
1193
- checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1194
- checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1195
-
1196
- # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1197
- if len(checkpoints) >= args.checkpoints_total_limit:
1198
- num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1199
- removing_checkpoints = checkpoints[0:num_to_remove]
1200
-
1201
- logger.info(
1202
- f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1203
- )
1204
- logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1205
-
1206
- for removing_checkpoint in removing_checkpoints:
1207
- removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1208
- shutil.rmtree(removing_checkpoint)
1209
-
1210
- save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1211
- accelerator.save_state(save_path)
1212
- logger.info(f"Saved state to {save_path}")
1213
-
1214
- if args.validation_prompt is not None and global_step % args.validation_steps == 0:
1215
- image_logs = log_validation(
1216
- vae, unet, controlnet, args, accelerator, weight_dtype, global_step
1217
- )
1218
-
1219
- logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1220
- progress_bar.set_postfix(**logs)
1221
- accelerator.log(logs, step=global_step)
1222
-
1223
- if global_step >= args.max_train_steps:
1224
- break
1225
-
1226
- # Create the pipeline using using the trained modules and save it.
1227
- accelerator.wait_for_everyone()
1228
- if accelerator.is_main_process:
1229
- controlnet = accelerator.unwrap_model(controlnet)
1230
- controlnet.save_pretrained(args.output_dir)
1231
-
1232
- if args.push_to_hub:
1233
- save_model_card(
1234
- repo_id,
1235
- image_logs=image_logs,
1236
- base_model=args.pretrained_model_name_or_path,
1237
- repo_folder=args.output_dir,
1238
- )
1239
- upload_folder(
1240
- repo_id=repo_id,
1241
- folder_path=args.output_dir,
1242
- commit_message="End of training",
1243
- ignore_patterns=["step_*", "epoch_*"],
1244
- )
1245
-
1246
- accelerator.end_training()
1247
-
1248
-
1249
- if __name__ == "__main__":
1250
- args = parse_args()
1251
- main(args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AnishKumbhar/ChatBot/text-generation-webui-main/update_wsl.bat DELETED
@@ -1,11 +0,0 @@
1
- @echo off
2
-
3
- cd /D "%~dp0"
4
-
5
- set PATH=%PATH%;%SystemRoot%\system32
6
-
7
- @rem sed -i 's/\x0D$//' ./wsl.sh converts newlines to unix format in the wsl script calling wsl.sh with 'update' will run updater
8
- call wsl -e bash -lic "sed -i 's/\x0D$//' ./wsl.sh; source ./wsl.sh update"
9
-
10
- :end
11
- pause
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/utils/path.py DELETED
@@ -1,101 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
- import os
3
- import os.path as osp
4
- from pathlib import Path
5
-
6
- from .misc import is_str
7
-
8
-
9
- def is_filepath(x):
10
- return is_str(x) or isinstance(x, Path)
11
-
12
-
13
- def fopen(filepath, *args, **kwargs):
14
- if is_str(filepath):
15
- return open(filepath, *args, **kwargs)
16
- elif isinstance(filepath, Path):
17
- return filepath.open(*args, **kwargs)
18
- raise ValueError('`filepath` should be a string or a Path')
19
-
20
-
21
- def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
22
- if not osp.isfile(filename):
23
- raise FileNotFoundError(msg_tmpl.format(filename))
24
-
25
-
26
- def mkdir_or_exist(dir_name, mode=0o777):
27
- if dir_name == '':
28
- return
29
- dir_name = osp.expanduser(dir_name)
30
- os.makedirs(dir_name, mode=mode, exist_ok=True)
31
-
32
-
33
- def symlink(src, dst, overwrite=True, **kwargs):
34
- if os.path.lexists(dst) and overwrite:
35
- os.remove(dst)
36
- os.symlink(src, dst, **kwargs)
37
-
38
-
39
- def scandir(dir_path, suffix=None, recursive=False, case_sensitive=True):
40
- """Scan a directory to find the interested files.
41
-
42
- Args:
43
- dir_path (str | obj:`Path`): Path of the directory.
44
- suffix (str | tuple(str), optional): File suffix that we are
45
- interested in. Default: None.
46
- recursive (bool, optional): If set to True, recursively scan the
47
- directory. Default: False.
48
- case_sensitive (bool, optional) : If set to False, ignore the case of
49
- suffix. Default: True.
50
-
51
- Returns:
52
- A generator for all the interested files with relative paths.
53
- """
54
- if isinstance(dir_path, (str, Path)):
55
- dir_path = str(dir_path)
56
- else:
57
- raise TypeError('"dir_path" must be a string or Path object')
58
-
59
- if (suffix is not None) and not isinstance(suffix, (str, tuple)):
60
- raise TypeError('"suffix" must be a string or tuple of strings')
61
-
62
- if suffix is not None and not case_sensitive:
63
- suffix = suffix.lower() if isinstance(suffix, str) else tuple(
64
- item.lower() for item in suffix)
65
-
66
- root = dir_path
67
-
68
- def _scandir(dir_path, suffix, recursive, case_sensitive):
69
- for entry in os.scandir(dir_path):
70
- if not entry.name.startswith('.') and entry.is_file():
71
- rel_path = osp.relpath(entry.path, root)
72
- _rel_path = rel_path if case_sensitive else rel_path.lower()
73
- if suffix is None or _rel_path.endswith(suffix):
74
- yield rel_path
75
- elif recursive and os.path.isdir(entry.path):
76
- # scan recursively if entry.path is a directory
77
- yield from _scandir(entry.path, suffix, recursive,
78
- case_sensitive)
79
-
80
- return _scandir(dir_path, suffix, recursive, case_sensitive)
81
-
82
-
83
- def find_vcs_root(path, markers=('.git', )):
84
- """Finds the root directory (including itself) of specified markers.
85
-
86
- Args:
87
- path (str): Path of directory or file.
88
- markers (list[str], optional): List of file or directory names.
89
-
90
- Returns:
91
- The directory contained one of the markers or None if not found.
92
- """
93
- if osp.isfile(path):
94
- path = osp.dirname(path)
95
-
96
- prev, cur = None, osp.abspath(osp.expanduser(path))
97
- while cur != prev:
98
- if any(osp.exists(osp.join(cur, marker)) for marker in markers):
99
- return cur
100
- prev, cur = cur, osp.split(cur)[0]
101
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/.github/pull_request_template.md DELETED
@@ -1,10 +0,0 @@
1
- Thanks for your contribution!
2
-
3
- If you're sending a large PR (e.g., >100 lines),
4
- please open an issue first about the feature / bug, and indicate how you want to contribute.
5
-
6
- We do not always accept features.
7
- See https://detectron2.readthedocs.io/notes/contributing.html#pull-requests about how we handle PRs.
8
-
9
- Before submitting a PR, please run `dev/linter.sh` to lint the code.
10
-
 
 
 
 
 
 
 
 
 
 
 
spaces/BAAI/AltDiffusion/css_and_js.py DELETED
@@ -1,92 +0,0 @@
1
- from os import path
2
- import json
3
-
4
-
5
- def readTextFile(*args):
6
- dir = path.dirname(__file__)
7
- entry = path.join(dir, *args)
8
- with open(entry, "r", encoding="utf8") as f:
9
- data = f.read()
10
- return data
11
-
12
-
13
- def css(opt):
14
- styling = readTextFile("css", "styles.css")
15
- # TODO: @altryne restore this before merge
16
- if not opt.no_progressbar_hiding:
17
- styling += readTextFile("css", "no_progress_bar.css")
18
- return styling
19
-
20
-
21
- def js(opt):
22
- data = readTextFile("js", "index.js")
23
- data = "(z) => {" + data + "; return z ?? [] }"
24
- return data
25
-
26
-
27
- # TODO : @altryne fix this to the new JS format
28
- js_copy_txt2img_output = "(x) => {navigator.clipboard.writeText(document.querySelector('gradio-app').shadowRoot.querySelector('#highlight .textfield').textContent.replace(/\s+/g,' ').replace(/: /g,':'))}"
29
-
30
-
31
-
32
- js_parse_prompt ="""
33
- (txt2img_prompt, txt2img_width, txt2img_height, txt2img_steps, txt2img_seed, txt2img_batch_count, txt2img_cfg) => {
34
-
35
- const prompt_input = document.querySelector('gradio-app').shadowRoot.querySelector('#prompt_input [data-testid="textbox"]');
36
- const multiline = document.querySelector('gradio-app').shadowRoot.querySelector('#submit_on_enter label:nth-child(2)')
37
- if (prompt_input.scrollWidth > prompt_input.clientWidth + 10 ) {
38
- multiline.click();
39
- }
40
-
41
-
42
- let height_match = /(?:-h|-H|--height|height)[ :]?(?<height>\d+) /.exec(txt2img_prompt);
43
- if (height_match) {
44
- txt2img_height = Math.round(height_match.groups.height / 64) * 64;
45
- txt2img_prompt = txt2img_prompt.replace(height_match[0], '');
46
- }
47
- let width_match = /(?:-w|-W|--width|width)[ :]?(?<width>\d+) /.exec(txt2img_prompt);
48
- if (width_match) {
49
- txt2img_width = Math.round(width_match.groups.width / 64) * 64;
50
- txt2img_prompt = txt2img_prompt.replace(width_match[0], '');
51
- }
52
- let steps_match = /(?:-s|--steps|steps)[ :]?(?<steps>\d+) /.exec(txt2img_prompt);
53
- if (steps_match) {
54
- txt2img_steps = steps_match.groups.steps.trim();
55
- txt2img_prompt = txt2img_prompt.replace(steps_match[0], '');
56
- }
57
- let seed_match = /(?:-S|--seed|seed)[ :]?(?<seed>\d+) /.exec(txt2img_prompt);
58
- if (seed_match) {
59
- txt2img_seed = seed_match.groups.seed;
60
- txt2img_prompt = txt2img_prompt.replace(seed_match[0], '');
61
- }
62
- let batch_count_match = /(?:-n|-N|--number|number)[ :]?(?<batch_count>\d+) /.exec(txt2img_prompt);
63
- if (batch_count_match) {
64
- txt2img_batch_count = batch_count_match.groups.batch_count;
65
- txt2img_prompt = txt2img_prompt.replace(batch_count_match[0], '');
66
- }
67
- let cfg_scale_match = /(?:-c|-C|--cfg-scale|cfg_scale|cfg)[ :]?(?<cfgscale>\d\.?\d+?) /.exec(txt2img_prompt);
68
- if (cfg_scale_match) {
69
- txt2img_cfg = parseFloat(cfg_scale_match.groups.cfgscale).toFixed(1);
70
- txt2img_prompt = txt2img_prompt.replace(cfg_scale_match[0], '');
71
- }
72
- let sampler_match = /(?:-A|--sampler|sampler)[ :]?(?<sampler>\w+) /.exec(txt2img_prompt);
73
- if (sampler_match) {
74
-
75
- txt2img_prompt = txt2img_prompt.replace(sampler_match[0], '');
76
- }
77
-
78
- return [txt2img_prompt, parseInt(txt2img_width), parseInt(txt2img_height), parseInt(txt2img_steps), txt2img_seed, parseInt(txt2img_batch_count), parseFloat(txt2img_cfg)];
79
- }
80
- """
81
-
82
-
83
- # Wrap the typical SD method call into async closure for ease of use
84
- # Supplies the js function with a params object
85
- # That includes all the passed arguments and input from Gradio: x
86
- # ATTENTION: x is an array of values of all components passed to your
87
- # python event handler
88
- # Example call in Gradio component's event handler (pass the result to _js arg):
89
- # _js=call_JS("myJsMethod", arg1="string", arg2=100, arg3=[])
90
- def call_JS(sd_method, **kwargs):
91
- param_str = json.dumps(kwargs)
92
- return f"async (...x) => {{ return await SD.{sd_method}({{ x, ...{param_str} }}) ?? []; }}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Banbri/zcvzcv/src/components/ui/toaster.tsx DELETED
@@ -1,35 +0,0 @@
1
- "use client"
2
-
3
- import {
4
- Toast,
5
- ToastClose,
6
- ToastDescription,
7
- ToastProvider,
8
- ToastTitle,
9
- ToastViewport,
10
- } from "@/components/ui/toast"
11
- import { useToast } from "@/components/ui/use-toast"
12
-
13
- export function Toaster() {
14
- const { toasts } = useToast()
15
-
16
- return (
17
- <ToastProvider>
18
- {toasts.map(function ({ id, title, description, action, ...props }) {
19
- return (
20
- <Toast key={id} {...props}>
21
- <div className="grid gap-1">
22
- {title && <ToastTitle>{title}</ToastTitle>}
23
- {description && (
24
- <ToastDescription>{description}</ToastDescription>
25
- )}
26
- </div>
27
- {action}
28
- <ToastClose />
29
- </Toast>
30
- )
31
- })}
32
- <ToastViewport />
33
- </ToastProvider>
34
- )
35
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BernardoOlisan/vqganclip/taming-transformers/main.py DELETED
@@ -1,582 +0,0 @@
1
- import argparse, os, sys, datetime, glob, importlib
2
- from omegaconf import OmegaConf
3
- import numpy as np
4
- from PIL import Image
5
- import torch
6
- import torchvision
7
- from torch.utils.data import random_split, DataLoader, Dataset
8
- import pytorch_lightning as pl
9
- from pytorch_lightning import seed_everything
10
- from pytorch_lightning.trainer import Trainer
11
- from pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor
12
- from pytorch_lightning.utilities.distributed import rank_zero_only
13
-
14
- def get_obj_from_str(string, reload=False):
15
- module, cls = string.rsplit(".", 1)
16
- if reload:
17
- module_imp = importlib.import_module(module)
18
- importlib.reload(module_imp)
19
- return getattr(importlib.import_module(module, package=None), cls)
20
-
21
-
22
- def get_parser(**parser_kwargs):
23
- def str2bool(v):
24
- if isinstance(v, bool):
25
- return v
26
- if v.lower() in ("yes", "true", "t", "y", "1"):
27
- return True
28
- elif v.lower() in ("no", "false", "f", "n", "0"):
29
- return False
30
- else:
31
- raise argparse.ArgumentTypeError("Boolean value expected.")
32
-
33
- parser = argparse.ArgumentParser(**parser_kwargs)
34
- parser.add_argument(
35
- "-n",
36
- "--name",
37
- type=str,
38
- const=True,
39
- default="",
40
- nargs="?",
41
- help="postfix for logdir",
42
- )
43
- parser.add_argument(
44
- "-r",
45
- "--resume",
46
- type=str,
47
- const=True,
48
- default="",
49
- nargs="?",
50
- help="resume from logdir or checkpoint in logdir",
51
- )
52
- parser.add_argument(
53
- "-b",
54
- "--base",
55
- nargs="*",
56
- metavar="base_config.yaml",
57
- help="paths to base configs. Loaded from left-to-right. "
58
- "Parameters can be overwritten or added with command-line options of the form `--key value`.",
59
- default=list(),
60
- )
61
- parser.add_argument(
62
- "-t",
63
- "--train",
64
- type=str2bool,
65
- const=True,
66
- default=False,
67
- nargs="?",
68
- help="train",
69
- )
70
- parser.add_argument(
71
- "--no-test",
72
- type=str2bool,
73
- const=True,
74
- default=False,
75
- nargs="?",
76
- help="disable test",
77
- )
78
- parser.add_argument("-p", "--project", help="name of new or path to existing project")
79
- parser.add_argument(
80
- "-d",
81
- "--debug",
82
- type=str2bool,
83
- nargs="?",
84
- const=True,
85
- default=False,
86
- help="enable post-mortem debugging",
87
- )
88
- parser.add_argument(
89
- "-s",
90
- "--seed",
91
- type=int,
92
- default=23,
93
- help="seed for seed_everything",
94
- )
95
- parser.add_argument(
96
- "-f",
97
- "--postfix",
98
- type=str,
99
- default="",
100
- help="post-postfix for default name",
101
- )
102
-
103
- return parser
104
-
105
-
106
- def nondefault_trainer_args(opt):
107
- parser = argparse.ArgumentParser()
108
- parser = Trainer.add_argparse_args(parser)
109
- args = parser.parse_args([])
110
- return sorted(k for k in vars(args) if getattr(opt, k) != getattr(args, k))
111
-
112
-
113
- def instantiate_from_config(config):
114
- if not "target" in config:
115
- raise KeyError("Expected key `target` to instantiate.")
116
- return get_obj_from_str(config["target"])(**config.get("params", dict()))
117
-
118
-
119
- class WrappedDataset(Dataset):
120
- """Wraps an arbitrary object with __len__ and __getitem__ into a pytorch dataset"""
121
- def __init__(self, dataset):
122
- self.data = dataset
123
-
124
- def __len__(self):
125
- return len(self.data)
126
-
127
- def __getitem__(self, idx):
128
- return self.data[idx]
129
-
130
-
131
- class DataModuleFromConfig(pl.LightningDataModule):
132
- def __init__(self, batch_size, train=None, validation=None, test=None,
133
- wrap=False, num_workers=None):
134
- super().__init__()
135
- self.batch_size = batch_size
136
- self.dataset_configs = dict()
137
- self.num_workers = num_workers if num_workers is not None else batch_size*2
138
- if train is not None:
139
- self.dataset_configs["train"] = train
140
- self.train_dataloader = self._train_dataloader
141
- if validation is not None:
142
- self.dataset_configs["validation"] = validation
143
- self.val_dataloader = self._val_dataloader
144
- if test is not None:
145
- self.dataset_configs["test"] = test
146
- self.test_dataloader = self._test_dataloader
147
- self.wrap = wrap
148
-
149
- def prepare_data(self):
150
- for data_cfg in self.dataset_configs.values():
151
- instantiate_from_config(data_cfg)
152
-
153
- def setup(self, stage=None):
154
- self.datasets = dict(
155
- (k, instantiate_from_config(self.dataset_configs[k]))
156
- for k in self.dataset_configs)
157
- if self.wrap:
158
- for k in self.datasets:
159
- self.datasets[k] = WrappedDataset(self.datasets[k])
160
-
161
- def _train_dataloader(self):
162
- return DataLoader(self.datasets["train"], batch_size=self.batch_size,
163
- num_workers=self.num_workers, shuffle=True)
164
-
165
- def _val_dataloader(self):
166
- return DataLoader(self.datasets["validation"],
167
- batch_size=self.batch_size,
168
- num_workers=self.num_workers)
169
-
170
- def _test_dataloader(self):
171
- return DataLoader(self.datasets["test"], batch_size=self.batch_size,
172
- num_workers=self.num_workers)
173
-
174
-
175
- class SetupCallback(Callback):
176
- def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config):
177
- super().__init__()
178
- self.resume = resume
179
- self.now = now
180
- self.logdir = logdir
181
- self.ckptdir = ckptdir
182
- self.cfgdir = cfgdir
183
- self.config = config
184
- self.lightning_config = lightning_config
185
-
186
- def on_pretrain_routine_start(self, trainer, pl_module):
187
- if trainer.global_rank == 0:
188
- # Create logdirs and save configs
189
- os.makedirs(self.logdir, exist_ok=True)
190
- os.makedirs(self.ckptdir, exist_ok=True)
191
- os.makedirs(self.cfgdir, exist_ok=True)
192
-
193
- print("Project config")
194
- print(self.config.pretty())
195
- OmegaConf.save(self.config,
196
- os.path.join(self.cfgdir, "{}-project.yaml".format(self.now)))
197
-
198
- print("Lightning config")
199
- print(self.lightning_config.pretty())
200
- OmegaConf.save(OmegaConf.create({"lightning": self.lightning_config}),
201
- os.path.join(self.cfgdir, "{}-lightning.yaml".format(self.now)))
202
-
203
- else:
204
- # ModelCheckpoint callback created log directory --- remove it
205
- if not self.resume and os.path.exists(self.logdir):
206
- dst, name = os.path.split(self.logdir)
207
- dst = os.path.join(dst, "child_runs", name)
208
- os.makedirs(os.path.split(dst)[0], exist_ok=True)
209
- try:
210
- os.rename(self.logdir, dst)
211
- except FileNotFoundError:
212
- pass
213
-
214
-
215
- class ImageLogger(Callback):
216
- def __init__(self, batch_frequency, max_images, clamp=True, increase_log_steps=True):
217
- super().__init__()
218
- self.batch_freq = batch_frequency
219
- self.max_images = max_images
220
- self.logger_log_images = {
221
- pl.loggers.WandbLogger: self._wandb,
222
- pl.loggers.TestTubeLogger: self._testtube,
223
- }
224
- self.log_steps = [2 ** n for n in range(int(np.log2(self.batch_freq)) + 1)]
225
- if not increase_log_steps:
226
- self.log_steps = [self.batch_freq]
227
- self.clamp = clamp
228
-
229
- @rank_zero_only
230
- def _wandb(self, pl_module, images, batch_idx, split):
231
- raise ValueError("No way wandb")
232
- grids = dict()
233
- for k in images:
234
- grid = torchvision.utils.make_grid(images[k])
235
- grids[f"{split}/{k}"] = wandb.Image(grid)
236
- pl_module.logger.experiment.log(grids)
237
-
238
- @rank_zero_only
239
- def _testtube(self, pl_module, images, batch_idx, split):
240
- for k in images:
241
- grid = torchvision.utils.make_grid(images[k])
242
- grid = (grid+1.0)/2.0 # -1,1 -> 0,1; c,h,w
243
-
244
- tag = f"{split}/{k}"
245
- pl_module.logger.experiment.add_image(
246
- tag, grid,
247
- global_step=pl_module.global_step)
248
-
249
- @rank_zero_only
250
- def log_local(self, save_dir, split, images,
251
- global_step, current_epoch, batch_idx):
252
- root = os.path.join(save_dir, "images", split)
253
- for k in images:
254
- grid = torchvision.utils.make_grid(images[k], nrow=4)
255
-
256
- grid = (grid+1.0)/2.0 # -1,1 -> 0,1; c,h,w
257
- grid = grid.transpose(0,1).transpose(1,2).squeeze(-1)
258
- grid = grid.numpy()
259
- grid = (grid*255).astype(np.uint8)
260
- filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(
261
- k,
262
- global_step,
263
- current_epoch,
264
- batch_idx)
265
- path = os.path.join(root, filename)
266
- os.makedirs(os.path.split(path)[0], exist_ok=True)
267
- Image.fromarray(grid).save(path)
268
-
269
- def log_img(self, pl_module, batch, batch_idx, split="train"):
270
- if (self.check_frequency(batch_idx) and # batch_idx % self.batch_freq == 0
271
- hasattr(pl_module, "log_images") and
272
- callable(pl_module.log_images) and
273
- self.max_images > 0):
274
- logger = type(pl_module.logger)
275
-
276
- is_train = pl_module.training
277
- if is_train:
278
- pl_module.eval()
279
-
280
- with torch.no_grad():
281
- images = pl_module.log_images(batch, split=split)
282
-
283
- for k in images:
284
- N = min(images[k].shape[0], self.max_images)
285
- images[k] = images[k][:N]
286
- if isinstance(images[k], torch.Tensor):
287
- images[k] = images[k].detach().cpu()
288
- if self.clamp:
289
- images[k] = torch.clamp(images[k], -1., 1.)
290
-
291
- self.log_local(pl_module.logger.save_dir, split, images,
292
- pl_module.global_step, pl_module.current_epoch, batch_idx)
293
-
294
- logger_log_images = self.logger_log_images.get(logger, lambda *args, **kwargs: None)
295
- logger_log_images(pl_module, images, pl_module.global_step, split)
296
-
297
- if is_train:
298
- pl_module.train()
299
-
300
- def check_frequency(self, batch_idx):
301
- if (batch_idx % self.batch_freq) == 0 or (batch_idx in self.log_steps):
302
- try:
303
- self.log_steps.pop(0)
304
- except IndexError:
305
- pass
306
- return True
307
- return False
308
-
309
- def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
310
- self.log_img(pl_module, batch, batch_idx, split="train")
311
-
312
- def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
313
- self.log_img(pl_module, batch, batch_idx, split="val")
314
-
315
-
316
-
317
- if __name__ == "__main__":
318
- # custom parser to specify config files, train, test and debug mode,
319
- # postfix, resume.
320
- # `--key value` arguments are interpreted as arguments to the trainer.
321
- # `nested.key=value` arguments are interpreted as config parameters.
322
- # configs are merged from left-to-right followed by command line parameters.
323
-
324
- # model:
325
- # base_learning_rate: float
326
- # target: path to lightning module
327
- # params:
328
- # key: value
329
- # data:
330
- # target: main.DataModuleFromConfig
331
- # params:
332
- # batch_size: int
333
- # wrap: bool
334
- # train:
335
- # target: path to train dataset
336
- # params:
337
- # key: value
338
- # validation:
339
- # target: path to validation dataset
340
- # params:
341
- # key: value
342
- # test:
343
- # target: path to test dataset
344
- # params:
345
- # key: value
346
- # lightning: (optional, has sane defaults and can be specified on cmdline)
347
- # trainer:
348
- # additional arguments to trainer
349
- # logger:
350
- # logger to instantiate
351
- # modelcheckpoint:
352
- # modelcheckpoint to instantiate
353
- # callbacks:
354
- # callback1:
355
- # target: importpath
356
- # params:
357
- # key: value
358
-
359
- now = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
360
-
361
- # add cwd for convenience and to make classes in this file available when
362
- # running as `python main.py`
363
- # (in particular `main.DataModuleFromConfig`)
364
- sys.path.append(os.getcwd())
365
-
366
- parser = get_parser()
367
- parser = Trainer.add_argparse_args(parser)
368
-
369
- opt, unknown = parser.parse_known_args()
370
- if opt.name and opt.resume:
371
- raise ValueError(
372
- "-n/--name and -r/--resume cannot be specified both."
373
- "If you want to resume training in a new log folder, "
374
- "use -n/--name in combination with --resume_from_checkpoint"
375
- )
376
- if opt.resume:
377
- if not os.path.exists(opt.resume):
378
- raise ValueError("Cannot find {}".format(opt.resume))
379
- if os.path.isfile(opt.resume):
380
- paths = opt.resume.split("/")
381
- idx = len(paths)-paths[::-1].index("logs")+1
382
- logdir = "/".join(paths[:idx])
383
- ckpt = opt.resume
384
- else:
385
- assert os.path.isdir(opt.resume), opt.resume
386
- logdir = opt.resume.rstrip("/")
387
- ckpt = os.path.join(logdir, "checkpoints", "last.ckpt")
388
-
389
- opt.resume_from_checkpoint = ckpt
390
- base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*.yaml")))
391
- opt.base = base_configs+opt.base
392
- _tmp = logdir.split("/")
393
- nowname = _tmp[_tmp.index("logs")+1]
394
- else:
395
- if opt.name:
396
- name = "_"+opt.name
397
- elif opt.base:
398
- cfg_fname = os.path.split(opt.base[0])[-1]
399
- cfg_name = os.path.splitext(cfg_fname)[0]
400
- name = "_"+cfg_name
401
- else:
402
- name = ""
403
- nowname = now+name+opt.postfix
404
- logdir = os.path.join("logs", nowname)
405
-
406
- ckptdir = os.path.join(logdir, "checkpoints")
407
- cfgdir = os.path.join(logdir, "configs")
408
- seed_everything(opt.seed)
409
-
410
- try:
411
- # init and save configs
412
- configs = [OmegaConf.load(cfg) for cfg in opt.base]
413
- cli = OmegaConf.from_dotlist(unknown)
414
- config = OmegaConf.merge(*configs, cli)
415
- lightning_config = config.pop("lightning", OmegaConf.create())
416
- # merge trainer cli with config
417
- trainer_config = lightning_config.get("trainer", OmegaConf.create())
418
- # default to ddp
419
- trainer_config["distributed_backend"] = "ddp"
420
- for k in nondefault_trainer_args(opt):
421
- trainer_config[k] = getattr(opt, k)
422
- if not "gpus" in trainer_config:
423
- del trainer_config["distributed_backend"]
424
- cpu = True
425
- else:
426
- gpuinfo = trainer_config["gpus"]
427
- print(f"Running on GPUs {gpuinfo}")
428
- cpu = False
429
- trainer_opt = argparse.Namespace(**trainer_config)
430
- lightning_config.trainer = trainer_config
431
-
432
- # model
433
- model = instantiate_from_config(config.model)
434
-
435
- # trainer and callbacks
436
- trainer_kwargs = dict()
437
-
438
- # default logger configs
439
- # NOTE wandb < 0.10.0 interferes with shutdown
440
- # wandb >= 0.10.0 seems to fix it but still interferes with pudb
441
- # debugging (wrongly sized pudb ui)
442
- # thus prefer testtube for now
443
- default_logger_cfgs = {
444
- "wandb": {
445
- "target": "pytorch_lightning.loggers.WandbLogger",
446
- "params": {
447
- "name": nowname,
448
- "save_dir": logdir,
449
- "offline": opt.debug,
450
- "id": nowname,
451
- }
452
- },
453
- "testtube": {
454
- "target": "pytorch_lightning.loggers.TestTubeLogger",
455
- "params": {
456
- "name": "testtube",
457
- "save_dir": logdir,
458
- }
459
- },
460
- }
461
- default_logger_cfg = default_logger_cfgs["testtube"]
462
- logger_cfg = lightning_config.logger or OmegaConf.create()
463
- logger_cfg = OmegaConf.merge(default_logger_cfg, logger_cfg)
464
- trainer_kwargs["logger"] = instantiate_from_config(logger_cfg)
465
-
466
- # modelcheckpoint - use TrainResult/EvalResult(checkpoint_on=metric) to
467
- # specify which metric is used to determine best models
468
- default_modelckpt_cfg = {
469
- "target": "pytorch_lightning.callbacks.ModelCheckpoint",
470
- "params": {
471
- "dirpath": ckptdir,
472
- "filename": "{epoch:06}",
473
- "verbose": True,
474
- "save_last": True,
475
- }
476
- }
477
- if hasattr(model, "monitor"):
478
- print(f"Monitoring {model.monitor} as checkpoint metric.")
479
- default_modelckpt_cfg["params"]["monitor"] = model.monitor
480
- default_modelckpt_cfg["params"]["save_top_k"] = 3
481
-
482
- modelckpt_cfg = lightning_config.modelcheckpoint or OmegaConf.create()
483
- modelckpt_cfg = OmegaConf.merge(default_modelckpt_cfg, modelckpt_cfg)
484
- trainer_kwargs["checkpoint_callback"] = instantiate_from_config(modelckpt_cfg)
485
-
486
- # add callback which sets up log directory
487
- default_callbacks_cfg = {
488
- "setup_callback": {
489
- "target": "main.SetupCallback",
490
- "params": {
491
- "resume": opt.resume,
492
- "now": now,
493
- "logdir": logdir,
494
- "ckptdir": ckptdir,
495
- "cfgdir": cfgdir,
496
- "config": config,
497
- "lightning_config": lightning_config,
498
- }
499
- },
500
- "image_logger": {
501
- "target": "main.ImageLogger",
502
- "params": {
503
- "batch_frequency": 750,
504
- "max_images": 4,
505
- "clamp": True
506
- }
507
- },
508
- "learning_rate_logger": {
509
- "target": "main.LearningRateMonitor",
510
- "params": {
511
- "logging_interval": "step",
512
- #"log_momentum": True
513
- }
514
- },
515
- }
516
- callbacks_cfg = lightning_config.callbacks or OmegaConf.create()
517
- callbacks_cfg = OmegaConf.merge(default_callbacks_cfg, callbacks_cfg)
518
- trainer_kwargs["callbacks"] = [instantiate_from_config(callbacks_cfg[k]) for k in callbacks_cfg]
519
-
520
- trainer = Trainer.from_argparse_args(trainer_opt, **trainer_kwargs)
521
-
522
- # data
523
- data = instantiate_from_config(config.data)
524
- # NOTE according to https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
525
- # calling these ourselves should not be necessary but it is.
526
- # lightning still takes care of proper multiprocessing though
527
- data.prepare_data()
528
- data.setup()
529
-
530
- # configure learning rate
531
- bs, base_lr = config.data.params.batch_size, config.model.base_learning_rate
532
- if not cpu:
533
- ngpu = len(lightning_config.trainer.gpus.strip(",").split(','))
534
- else:
535
- ngpu = 1
536
- accumulate_grad_batches = lightning_config.trainer.accumulate_grad_batches or 1
537
- print(f"accumulate_grad_batches = {accumulate_grad_batches}")
538
- lightning_config.trainer.accumulate_grad_batches = accumulate_grad_batches
539
- model.learning_rate = accumulate_grad_batches * ngpu * bs * base_lr
540
- print("Setting learning rate to {:.2e} = {} (accumulate_grad_batches) * {} (num_gpus) * {} (batchsize) * {:.2e} (base_lr)".format(
541
- model.learning_rate, accumulate_grad_batches, ngpu, bs, base_lr))
542
-
543
- # allow checkpointing via USR1
544
- def melk(*args, **kwargs):
545
- # run all checkpoint hooks
546
- if trainer.global_rank == 0:
547
- print("Summoning checkpoint.")
548
- ckpt_path = os.path.join(ckptdir, "last.ckpt")
549
- trainer.save_checkpoint(ckpt_path)
550
-
551
- def divein(*args, **kwargs):
552
- if trainer.global_rank == 0:
553
- import pudb; pudb.set_trace()
554
-
555
- import signal
556
- signal.signal(signal.SIGUSR1, melk)
557
- signal.signal(signal.SIGUSR2, divein)
558
-
559
- # run
560
- if opt.train:
561
- try:
562
- trainer.fit(model, data)
563
- except Exception:
564
- melk()
565
- raise
566
- if not opt.no_test and not trainer.interrupted:
567
- trainer.test(model, data)
568
- except Exception:
569
- if opt.debug and trainer.global_rank==0:
570
- try:
571
- import pudb as debugger
572
- except ImportError:
573
- import pdb as debugger
574
- debugger.post_mortem()
575
- raise
576
- finally:
577
- # move newly created debug project to debug_runs
578
- if opt.debug and not opt.resume and trainer.global_rank==0:
579
- dst, name = os.path.split(logdir)
580
- dst = os.path.join(dst, "debug_runs", name)
581
- os.makedirs(os.path.split(dst)[0], exist_ok=True)
582
- os.rename(logdir, dst)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BetterAPI/BetterChat/src/lib/stores/pendingMessageIdToRetry.ts DELETED
@@ -1,4 +0,0 @@
1
- import type { Message } from "$lib/types/Message";
2
- import { writable } from "svelte/store";
3
-
4
- export const pendingMessageIdToRetry = writable<Message["id"] | null>(null);
 
 
 
 
 
spaces/BiTransSciencia/www/index.css DELETED
@@ -1,167 +0,0 @@
1
- ::-webkit-scrollbar {
2
- display: none;
3
- }
4
-
5
- * {
6
- cursor: url(datum/ico18__081.png), auto;
7
- overscroll-behavior: none;
8
- -webkit-user-select: none;/* Safari */
9
- -ms-user-select: none;/* IE 10+ */
10
- user-select: none;
11
- word-break: break-all;
12
- }
13
-
14
- pre {
15
- white-space: pre-wrap !important;
16
- word-wrap: break-word !important;
17
- word-break: break-all !important;
18
- }
19
-
20
- img:focus {
21
- pointer-events: none;
22
- }
23
-
24
- body {
25
- background-color: black;
26
- color: white;
27
- display: grid;
28
- text-align: justify;
29
- font-family: monospace !important;
30
- margin: auto auto;
31
- }
32
-
33
- fieldset {
34
- padding: 20px;
35
- }
36
-
37
- fieldset:hover{
38
- box-shadow: 0 0 8px white;
39
- }
40
-
41
- legend {
42
- border: 2px solid white;
43
- border-radius: 8px;
44
- padding: 6px;
45
- color: black;
46
- background-color: white;
47
- }
48
-
49
- hr {
50
- width: 100%;
51
- }
52
-
53
- /* .hr100 {
54
- width: 0%;
55
- border: 2px solid white;
56
- } */
57
-
58
- #logo__081 {
59
- width: 360px;
60
- height: 180px;
61
- margin: 0 auto;
62
- }
63
-
64
- #structure__081 {
65
- width: 600px;
66
- }
67
-
68
-
69
- #div__ack {
70
- text-align: center;
71
- }
72
-
73
- #div__ack a {
74
- color: white;
75
- text-decoration: none;
76
- border: 2px dotted white;
77
- padding: 6px;
78
- display: inline-block;
79
- margin-top: 6px;
80
- margin-bottom: 6px;
81
- }
82
-
83
- #div__ack>a:hover {
84
- color: black;
85
- background-color: white;
86
- font-weight: bold;
87
- }
88
-
89
- #p__ack_logo {
90
- font-size: 8px;
91
- text-align: center;
92
- }
93
-
94
- .p__license,
95
- .p__cc {
96
- text-align: center;
97
- font-size: 14px;
98
- }
99
-
100
- .p__cc * {
101
- text-decoration: none;
102
- color: white;
103
- }
104
-
105
- .div__dl {
106
- text-align: center;
107
- }
108
-
109
- #fs__download a {
110
- color: white;
111
- text-decoration: none;
112
- border: 2px dashed white;
113
- padding: 6px;
114
- }
115
-
116
- #fs__download a:hover {
117
- color: black;
118
- background-color: white;
119
- font-weight: bold;
120
- }
121
-
122
- .p__cc a:hover {
123
- text-decoration: underline;
124
- }
125
-
126
- .p__bts_license_usage {
127
- text-align: center;
128
- font-size: 8px;
129
- }
130
-
131
- .d3__KVNAditya {
132
- text-align: center;
133
-
134
- }
135
-
136
- .d3__KVNAditya * {
137
- display: inline-block;
138
- color: white;
139
- text-decoration: none;
140
- }
141
-
142
- .d3__KVNAditya a:hover {
143
- text-decoration: underline;
144
- font-weight: bold;
145
- }
146
-
147
- svg {
148
- background-color: black;
149
- }
150
-
151
- /* --- */
152
- .popup {
153
- position: fixed;
154
- top: 0;
155
- left: 0;
156
- width: 100%;
157
- height: 100%;
158
- background-color: rgba(0, 0, 0, 0.8);
159
- display: flex;
160
- justify-content: center;
161
- align-items: center;
162
- }
163
-
164
- .popup img {
165
- max-width: 90%;
166
- max-height: 90%;
167
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/botocore/vendored/requests/packages/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- from __future__ import absolute_import
2
-
3
- from . import urllib3
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/config/_validate_pyproject/__init__.py DELETED
@@ -1,34 +0,0 @@
1
- from functools import reduce
2
- from typing import Any, Callable, Dict
3
-
4
- from . import formats
5
- from .error_reporting import detailed_errors, ValidationError
6
- from .extra_validations import EXTRA_VALIDATIONS
7
- from .fastjsonschema_exceptions import JsonSchemaException, JsonSchemaValueException
8
- from .fastjsonschema_validations import validate as _validate
9
-
10
- __all__ = [
11
- "validate",
12
- "FORMAT_FUNCTIONS",
13
- "EXTRA_VALIDATIONS",
14
- "ValidationError",
15
- "JsonSchemaException",
16
- "JsonSchemaValueException",
17
- ]
18
-
19
-
20
- FORMAT_FUNCTIONS: Dict[str, Callable[[str], bool]] = {
21
- fn.__name__.replace("_", "-"): fn
22
- for fn in formats.__dict__.values()
23
- if callable(fn) and not fn.__name__.startswith("_")
24
- }
25
-
26
-
27
- def validate(data: Any) -> bool:
28
- """Validate the given ``data`` object using JSON Schema
29
- This function raises ``ValidationError`` if ``data`` is invalid.
30
- """
31
- with detailed_errors():
32
- _validate(data, custom_formats=FORMAT_FUNCTIONS)
33
- reduce(lambda acc, fn: fn(acc), EXTRA_VALIDATIONS, data)
34
- return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/package_index.py DELETED
@@ -1,1126 +0,0 @@
1
- """PyPI and direct package downloading"""
2
- import sys
3
- import os
4
- import re
5
- import io
6
- import shutil
7
- import socket
8
- import base64
9
- import hashlib
10
- import itertools
11
- import warnings
12
- import configparser
13
- import html
14
- import http.client
15
- import urllib.parse
16
- import urllib.request
17
- import urllib.error
18
- from functools import wraps
19
-
20
- import setuptools
21
- from pkg_resources import (
22
- CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST,
23
- Environment, find_distributions, safe_name, safe_version,
24
- to_filename, Requirement, DEVELOP_DIST, EGG_DIST, parse_version,
25
- )
26
- from distutils import log
27
- from distutils.errors import DistutilsError
28
- from fnmatch import translate
29
- from setuptools.wheel import Wheel
30
- from setuptools.extern.more_itertools import unique_everseen
31
-
32
-
33
- EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')
34
- HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I)
35
- PYPI_MD5 = re.compile(
36
- r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)'
37
- r'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\)'
38
- )
39
- URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match
40
- EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split()
41
-
42
- __all__ = [
43
- 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst',
44
- 'interpret_distro_name',
45
- ]
46
-
47
- _SOCKET_TIMEOUT = 15
48
-
49
- _tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}"
50
- user_agent = _tmpl.format(
51
- py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools)
52
-
53
-
54
- def parse_requirement_arg(spec):
55
- try:
56
- return Requirement.parse(spec)
57
- except ValueError as e:
58
- raise DistutilsError(
59
- "Not a URL, existing file, or requirement spec: %r" % (spec,)
60
- ) from e
61
-
62
-
63
- def parse_bdist_wininst(name):
64
- """Return (base,pyversion) or (None,None) for possible .exe name"""
65
-
66
- lower = name.lower()
67
- base, py_ver, plat = None, None, None
68
-
69
- if lower.endswith('.exe'):
70
- if lower.endswith('.win32.exe'):
71
- base = name[:-10]
72
- plat = 'win32'
73
- elif lower.startswith('.win32-py', -16):
74
- py_ver = name[-7:-4]
75
- base = name[:-16]
76
- plat = 'win32'
77
- elif lower.endswith('.win-amd64.exe'):
78
- base = name[:-14]
79
- plat = 'win-amd64'
80
- elif lower.startswith('.win-amd64-py', -20):
81
- py_ver = name[-7:-4]
82
- base = name[:-20]
83
- plat = 'win-amd64'
84
- return base, py_ver, plat
85
-
86
-
87
- def egg_info_for_url(url):
88
- parts = urllib.parse.urlparse(url)
89
- scheme, server, path, parameters, query, fragment = parts
90
- base = urllib.parse.unquote(path.split('/')[-1])
91
- if server == 'sourceforge.net' and base == 'download': # XXX Yuck
92
- base = urllib.parse.unquote(path.split('/')[-2])
93
- if '#' in base:
94
- base, fragment = base.split('#', 1)
95
- return base, fragment
96
-
97
-
98
- def distros_for_url(url, metadata=None):
99
- """Yield egg or source distribution objects that might be found at a URL"""
100
- base, fragment = egg_info_for_url(url)
101
- for dist in distros_for_location(url, base, metadata):
102
- yield dist
103
- if fragment:
104
- match = EGG_FRAGMENT.match(fragment)
105
- if match:
106
- for dist in interpret_distro_name(
107
- url, match.group(1), metadata, precedence=CHECKOUT_DIST
108
- ):
109
- yield dist
110
-
111
-
112
- def distros_for_location(location, basename, metadata=None):
113
- """Yield egg or source distribution objects based on basename"""
114
- if basename.endswith('.egg.zip'):
115
- basename = basename[:-4] # strip the .zip
116
- if basename.endswith('.egg') and '-' in basename:
117
- # only one, unambiguous interpretation
118
- return [Distribution.from_location(location, basename, metadata)]
119
- if basename.endswith('.whl') and '-' in basename:
120
- wheel = Wheel(basename)
121
- if not wheel.is_compatible():
122
- return []
123
- return [Distribution(
124
- location=location,
125
- project_name=wheel.project_name,
126
- version=wheel.version,
127
- # Increase priority over eggs.
128
- precedence=EGG_DIST + 1,
129
- )]
130
- if basename.endswith('.exe'):
131
- win_base, py_ver, platform = parse_bdist_wininst(basename)
132
- if win_base is not None:
133
- return interpret_distro_name(
134
- location, win_base, metadata, py_ver, BINARY_DIST, platform
135
- )
136
- # Try source distro extensions (.zip, .tgz, etc.)
137
- #
138
- for ext in EXTENSIONS:
139
- if basename.endswith(ext):
140
- basename = basename[:-len(ext)]
141
- return interpret_distro_name(location, basename, metadata)
142
- return [] # no extension matched
143
-
144
-
145
- def distros_for_filename(filename, metadata=None):
146
- """Yield possible egg or source distribution objects based on a filename"""
147
- return distros_for_location(
148
- normalize_path(filename), os.path.basename(filename), metadata
149
- )
150
-
151
-
152
- def interpret_distro_name(
153
- location, basename, metadata, py_version=None, precedence=SOURCE_DIST,
154
- platform=None
155
- ):
156
- """Generate alternative interpretations of a source distro name
157
-
158
- Note: if `location` is a filesystem filename, you should call
159
- ``pkg_resources.normalize_path()`` on it before passing it to this
160
- routine!
161
- """
162
- # Generate alternative interpretations of a source distro name
163
- # Because some packages are ambiguous as to name/versions split
164
- # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
165
- # So, we generate each possible interpretation (e.g. "adns, python-1.1.0"
166
- # "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
167
- # the spurious interpretations should be ignored, because in the event
168
- # there's also an "adns" package, the spurious "python-1.1.0" version will
169
- # compare lower than any numeric version number, and is therefore unlikely
170
- # to match a request for it. It's still a potential problem, though, and
171
- # in the long run PyPI and the distutils should go for "safe" names and
172
- # versions in distribution archive names (sdist and bdist).
173
-
174
- parts = basename.split('-')
175
- if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]):
176
- # it is a bdist_dumb, not an sdist -- bail out
177
- return
178
-
179
- for p in range(1, len(parts) + 1):
180
- yield Distribution(
181
- location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]),
182
- py_version=py_version, precedence=precedence,
183
- platform=platform
184
- )
185
-
186
-
187
- def unique_values(func):
188
- """
189
- Wrap a function returning an iterable such that the resulting iterable
190
- only ever yields unique items.
191
- """
192
-
193
- @wraps(func)
194
- def wrapper(*args, **kwargs):
195
- return unique_everseen(func(*args, **kwargs))
196
-
197
- return wrapper
198
-
199
-
200
- REL = re.compile(r"""<([^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*)>""", re.I)
201
- # this line is here to fix emacs' cruddy broken syntax highlighting
202
-
203
-
204
- @unique_values
205
- def find_external_links(url, page):
206
- """Find rel="homepage" and rel="download" links in `page`, yielding URLs"""
207
-
208
- for match in REL.finditer(page):
209
- tag, rel = match.groups()
210
- rels = set(map(str.strip, rel.lower().split(',')))
211
- if 'homepage' in rels or 'download' in rels:
212
- for match in HREF.finditer(tag):
213
- yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
214
-
215
- for tag in ("<th>Home Page", "<th>Download URL"):
216
- pos = page.find(tag)
217
- if pos != -1:
218
- match = HREF.search(page, pos)
219
- if match:
220
- yield urllib.parse.urljoin(url, htmldecode(match.group(1)))
221
-
222
-
223
- class ContentChecker:
224
- """
225
- A null content checker that defines the interface for checking content
226
- """
227
-
228
- def feed(self, block):
229
- """
230
- Feed a block of data to the hash.
231
- """
232
- return
233
-
234
- def is_valid(self):
235
- """
236
- Check the hash. Return False if validation fails.
237
- """
238
- return True
239
-
240
- def report(self, reporter, template):
241
- """
242
- Call reporter with information about the checker (hash name)
243
- substituted into the template.
244
- """
245
- return
246
-
247
-
248
- class HashChecker(ContentChecker):
249
- pattern = re.compile(
250
- r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='
251
- r'(?P<expected>[a-f0-9]+)'
252
- )
253
-
254
- def __init__(self, hash_name, expected):
255
- self.hash_name = hash_name
256
- self.hash = hashlib.new(hash_name)
257
- self.expected = expected
258
-
259
- @classmethod
260
- def from_url(cls, url):
261
- "Construct a (possibly null) ContentChecker from a URL"
262
- fragment = urllib.parse.urlparse(url)[-1]
263
- if not fragment:
264
- return ContentChecker()
265
- match = cls.pattern.search(fragment)
266
- if not match:
267
- return ContentChecker()
268
- return cls(**match.groupdict())
269
-
270
- def feed(self, block):
271
- self.hash.update(block)
272
-
273
- def is_valid(self):
274
- return self.hash.hexdigest() == self.expected
275
-
276
- def report(self, reporter, template):
277
- msg = template % self.hash_name
278
- return reporter(msg)
279
-
280
-
281
- class PackageIndex(Environment):
282
- """A distribution index that scans web pages for download URLs"""
283
-
284
- def __init__(
285
- self, index_url="https://pypi.org/simple/", hosts=('*',),
286
- ca_bundle=None, verify_ssl=True, *args, **kw
287
- ):
288
- super().__init__(*args, **kw)
289
- self.index_url = index_url + "/" [:not index_url.endswith('/')]
290
- self.scanned_urls = {}
291
- self.fetched_urls = {}
292
- self.package_pages = {}
293
- self.allows = re.compile('|'.join(map(translate, hosts))).match
294
- self.to_scan = []
295
- self.opener = urllib.request.urlopen
296
-
297
- def add(self, dist):
298
- # ignore invalid versions
299
- try:
300
- parse_version(dist.version)
301
- except Exception:
302
- return
303
- return super().add(dist)
304
-
305
- # FIXME: 'PackageIndex.process_url' is too complex (14)
306
- def process_url(self, url, retrieve=False): # noqa: C901
307
- """Evaluate a URL as a possible download, and maybe retrieve it"""
308
- if url in self.scanned_urls and not retrieve:
309
- return
310
- self.scanned_urls[url] = True
311
- if not URL_SCHEME(url):
312
- self.process_filename(url)
313
- return
314
- else:
315
- dists = list(distros_for_url(url))
316
- if dists:
317
- if not self.url_ok(url):
318
- return
319
- self.debug("Found link: %s", url)
320
-
321
- if dists or not retrieve or url in self.fetched_urls:
322
- list(map(self.add, dists))
323
- return # don't need the actual page
324
-
325
- if not self.url_ok(url):
326
- self.fetched_urls[url] = True
327
- return
328
-
329
- self.info("Reading %s", url)
330
- self.fetched_urls[url] = True # prevent multiple fetch attempts
331
- tmpl = "Download error on %s: %%s -- Some packages may not be found!"
332
- f = self.open_url(url, tmpl % url)
333
- if f is None:
334
- return
335
- if isinstance(f, urllib.error.HTTPError) and f.code == 401:
336
- self.info("Authentication error: %s" % f.msg)
337
- self.fetched_urls[f.url] = True
338
- if 'html' not in f.headers.get('content-type', '').lower():
339
- f.close() # not html, we can't process it
340
- return
341
-
342
- base = f.url # handle redirects
343
- page = f.read()
344
- if not isinstance(page, str):
345
- # In Python 3 and got bytes but want str.
346
- if isinstance(f, urllib.error.HTTPError):
347
- # Errors have no charset, assume latin1:
348
- charset = 'latin-1'
349
- else:
350
- charset = f.headers.get_param('charset') or 'latin-1'
351
- page = page.decode(charset, "ignore")
352
- f.close()
353
- for match in HREF.finditer(page):
354
- link = urllib.parse.urljoin(base, htmldecode(match.group(1)))
355
- self.process_url(link)
356
- if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:
357
- page = self.process_index(url, page)
358
-
359
- def process_filename(self, fn, nested=False):
360
- # process filenames or directories
361
- if not os.path.exists(fn):
362
- self.warn("Not found: %s", fn)
363
- return
364
-
365
- if os.path.isdir(fn) and not nested:
366
- path = os.path.realpath(fn)
367
- for item in os.listdir(path):
368
- self.process_filename(os.path.join(path, item), True)
369
-
370
- dists = distros_for_filename(fn)
371
- if dists:
372
- self.debug("Found: %s", fn)
373
- list(map(self.add, dists))
374
-
375
- def url_ok(self, url, fatal=False):
376
- s = URL_SCHEME(url)
377
- is_file = s and s.group(1).lower() == 'file'
378
- if is_file or self.allows(urllib.parse.urlparse(url)[1]):
379
- return True
380
- msg = (
381
- "\nNote: Bypassing %s (disallowed host; see "
382
- "http://bit.ly/2hrImnY for details).\n")
383
- if fatal:
384
- raise DistutilsError(msg % url)
385
- else:
386
- self.warn(msg, url)
387
-
388
- def scan_egg_links(self, search_path):
389
- dirs = filter(os.path.isdir, search_path)
390
- egg_links = (
391
- (path, entry)
392
- for path in dirs
393
- for entry in os.listdir(path)
394
- if entry.endswith('.egg-link')
395
- )
396
- list(itertools.starmap(self.scan_egg_link, egg_links))
397
-
398
- def scan_egg_link(self, path, entry):
399
- with open(os.path.join(path, entry)) as raw_lines:
400
- # filter non-empty lines
401
- lines = list(filter(None, map(str.strip, raw_lines)))
402
-
403
- if len(lines) != 2:
404
- # format is not recognized; punt
405
- return
406
-
407
- egg_path, setup_path = lines
408
-
409
- for dist in find_distributions(os.path.join(path, egg_path)):
410
- dist.location = os.path.join(path, *lines)
411
- dist.precedence = SOURCE_DIST
412
- self.add(dist)
413
-
414
- def _scan(self, link):
415
- # Process a URL to see if it's for a package page
416
- NO_MATCH_SENTINEL = None, None
417
- if not link.startswith(self.index_url):
418
- return NO_MATCH_SENTINEL
419
-
420
- parts = list(map(
421
- urllib.parse.unquote, link[len(self.index_url):].split('/')
422
- ))
423
- if len(parts) != 2 or '#' in parts[1]:
424
- return NO_MATCH_SENTINEL
425
-
426
- # it's a package page, sanitize and index it
427
- pkg = safe_name(parts[0])
428
- ver = safe_version(parts[1])
429
- self.package_pages.setdefault(pkg.lower(), {})[link] = True
430
- return to_filename(pkg), to_filename(ver)
431
-
432
- def process_index(self, url, page):
433
- """Process the contents of a PyPI page"""
434
-
435
- # process an index page into the package-page index
436
- for match in HREF.finditer(page):
437
- try:
438
- self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
439
- except ValueError:
440
- pass
441
-
442
- pkg, ver = self._scan(url) # ensure this page is in the page index
443
- if not pkg:
444
- return "" # no sense double-scanning non-package pages
445
-
446
- # process individual package page
447
- for new_url in find_external_links(url, page):
448
- # Process the found URL
449
- base, frag = egg_info_for_url(new_url)
450
- if base.endswith('.py') and not frag:
451
- if ver:
452
- new_url += '#egg=%s-%s' % (pkg, ver)
453
- else:
454
- self.need_version_info(url)
455
- self.scan_url(new_url)
456
-
457
- return PYPI_MD5.sub(
458
- lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page
459
- )
460
-
461
- def need_version_info(self, url):
462
- self.scan_all(
463
- "Page at %s links to .py file(s) without version info; an index "
464
- "scan is required.", url
465
- )
466
-
467
- def scan_all(self, msg=None, *args):
468
- if self.index_url not in self.fetched_urls:
469
- if msg:
470
- self.warn(msg, *args)
471
- self.info(
472
- "Scanning index of all packages (this may take a while)"
473
- )
474
- self.scan_url(self.index_url)
475
-
476
- def find_packages(self, requirement):
477
- self.scan_url(self.index_url + requirement.unsafe_name + '/')
478
-
479
- if not self.package_pages.get(requirement.key):
480
- # Fall back to safe version of the name
481
- self.scan_url(self.index_url + requirement.project_name + '/')
482
-
483
- if not self.package_pages.get(requirement.key):
484
- # We couldn't find the target package, so search the index page too
485
- self.not_found_in_index(requirement)
486
-
487
- for url in list(self.package_pages.get(requirement.key, ())):
488
- # scan each page that might be related to the desired package
489
- self.scan_url(url)
490
-
491
- def obtain(self, requirement, installer=None):
492
- self.prescan()
493
- self.find_packages(requirement)
494
- for dist in self[requirement.key]:
495
- if dist in requirement:
496
- return dist
497
- self.debug("%s does not match %s", requirement, dist)
498
- return super(PackageIndex, self).obtain(requirement, installer)
499
-
500
- def check_hash(self, checker, filename, tfp):
501
- """
502
- checker is a ContentChecker
503
- """
504
- checker.report(
505
- self.debug,
506
- "Validating %%s checksum for %s" % filename)
507
- if not checker.is_valid():
508
- tfp.close()
509
- os.unlink(filename)
510
- raise DistutilsError(
511
- "%s validation failed for %s; "
512
- "possible download problem?"
513
- % (checker.hash.name, os.path.basename(filename))
514
- )
515
-
516
- def add_find_links(self, urls):
517
- """Add `urls` to the list that will be prescanned for searches"""
518
- for url in urls:
519
- if (
520
- self.to_scan is None # if we have already "gone online"
521
- or not URL_SCHEME(url) # or it's a local file/directory
522
- or url.startswith('file:')
523
- or list(distros_for_url(url)) # or a direct package link
524
- ):
525
- # then go ahead and process it now
526
- self.scan_url(url)
527
- else:
528
- # otherwise, defer retrieval till later
529
- self.to_scan.append(url)
530
-
531
- def prescan(self):
532
- """Scan urls scheduled for prescanning (e.g. --find-links)"""
533
- if self.to_scan:
534
- list(map(self.scan_url, self.to_scan))
535
- self.to_scan = None # from now on, go ahead and process immediately
536
-
537
- def not_found_in_index(self, requirement):
538
- if self[requirement.key]: # we've seen at least one distro
539
- meth, msg = self.info, "Couldn't retrieve index page for %r"
540
- else: # no distros seen for this name, might be misspelled
541
- meth, msg = (
542
- self.warn,
543
- "Couldn't find index page for %r (maybe misspelled?)")
544
- meth(msg, requirement.unsafe_name)
545
- self.scan_all()
546
-
547
- def download(self, spec, tmpdir):
548
- """Locate and/or download `spec` to `tmpdir`, returning a local path
549
-
550
- `spec` may be a ``Requirement`` object, or a string containing a URL,
551
- an existing local filename, or a project/version requirement spec
552
- (i.e. the string form of a ``Requirement`` object). If it is the URL
553
- of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one
554
- that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is
555
- automatically created alongside the downloaded file.
556
-
557
- If `spec` is a ``Requirement`` object or a string containing a
558
- project/version requirement spec, this method returns the location of
559
- a matching distribution (possibly after downloading it to `tmpdir`).
560
- If `spec` is a locally existing file or directory name, it is simply
561
- returned unchanged. If `spec` is a URL, it is downloaded to a subpath
562
- of `tmpdir`, and the local filename is returned. Various errors may be
563
- raised if a problem occurs during downloading.
564
- """
565
- if not isinstance(spec, Requirement):
566
- scheme = URL_SCHEME(spec)
567
- if scheme:
568
- # It's a url, download it to tmpdir
569
- found = self._download_url(scheme.group(1), spec, tmpdir)
570
- base, fragment = egg_info_for_url(spec)
571
- if base.endswith('.py'):
572
- found = self.gen_setup(found, fragment, tmpdir)
573
- return found
574
- elif os.path.exists(spec):
575
- # Existing file or directory, just return it
576
- return spec
577
- else:
578
- spec = parse_requirement_arg(spec)
579
- return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)
580
-
581
- def fetch_distribution( # noqa: C901 # is too complex (14) # FIXME
582
- self, requirement, tmpdir, force_scan=False, source=False,
583
- develop_ok=False, local_index=None):
584
- """Obtain a distribution suitable for fulfilling `requirement`
585
-
586
- `requirement` must be a ``pkg_resources.Requirement`` instance.
587
- If necessary, or if the `force_scan` flag is set, the requirement is
588
- searched for in the (online) package index as well as the locally
589
- installed packages. If a distribution matching `requirement` is found,
590
- the returned distribution's ``location`` is the value you would have
591
- gotten from calling the ``download()`` method with the matching
592
- distribution's URL or filename. If no matching distribution is found,
593
- ``None`` is returned.
594
-
595
- If the `source` flag is set, only source distributions and source
596
- checkout links will be considered. Unless the `develop_ok` flag is
597
- set, development and system eggs (i.e., those using the ``.egg-info``
598
- format) will be ignored.
599
- """
600
- # process a Requirement
601
- self.info("Searching for %s", requirement)
602
- skipped = {}
603
- dist = None
604
-
605
- def find(req, env=None):
606
- if env is None:
607
- env = self
608
- # Find a matching distribution; may be called more than once
609
-
610
- for dist in env[req.key]:
611
-
612
- if dist.precedence == DEVELOP_DIST and not develop_ok:
613
- if dist not in skipped:
614
- self.warn(
615
- "Skipping development or system egg: %s", dist,
616
- )
617
- skipped[dist] = 1
618
- continue
619
-
620
- test = (
621
- dist in req
622
- and (dist.precedence <= SOURCE_DIST or not source)
623
- )
624
- if test:
625
- loc = self.download(dist.location, tmpdir)
626
- dist.download_location = loc
627
- if os.path.exists(dist.download_location):
628
- return dist
629
-
630
- if force_scan:
631
- self.prescan()
632
- self.find_packages(requirement)
633
- dist = find(requirement)
634
-
635
- if not dist and local_index is not None:
636
- dist = find(requirement, local_index)
637
-
638
- if dist is None:
639
- if self.to_scan is not None:
640
- self.prescan()
641
- dist = find(requirement)
642
-
643
- if dist is None and not force_scan:
644
- self.find_packages(requirement)
645
- dist = find(requirement)
646
-
647
- if dist is None:
648
- self.warn(
649
- "No local packages or working download links found for %s%s",
650
- (source and "a source distribution of " or ""),
651
- requirement,
652
- )
653
- else:
654
- self.info("Best match: %s", dist)
655
- return dist.clone(location=dist.download_location)
656
-
657
- def fetch(self, requirement, tmpdir, force_scan=False, source=False):
658
- """Obtain a file suitable for fulfilling `requirement`
659
-
660
- DEPRECATED; use the ``fetch_distribution()`` method now instead. For
661
- backward compatibility, this routine is identical but returns the
662
- ``location`` of the downloaded distribution instead of a distribution
663
- object.
664
- """
665
- dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)
666
- if dist is not None:
667
- return dist.location
668
- return None
669
-
670
- def gen_setup(self, filename, fragment, tmpdir):
671
- match = EGG_FRAGMENT.match(fragment)
672
- dists = match and [
673
- d for d in
674
- interpret_distro_name(filename, match.group(1), None) if d.version
675
- ] or []
676
-
677
- if len(dists) == 1: # unambiguous ``#egg`` fragment
678
- basename = os.path.basename(filename)
679
-
680
- # Make sure the file has been downloaded to the temp dir.
681
- if os.path.dirname(filename) != tmpdir:
682
- dst = os.path.join(tmpdir, basename)
683
- if not (os.path.exists(dst) and os.path.samefile(filename, dst)):
684
- shutil.copy2(filename, dst)
685
- filename = dst
686
-
687
- with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:
688
- file.write(
689
- "from setuptools import setup\n"
690
- "setup(name=%r, version=%r, py_modules=[%r])\n"
691
- % (
692
- dists[0].project_name, dists[0].version,
693
- os.path.splitext(basename)[0]
694
- )
695
- )
696
- return filename
697
-
698
- elif match:
699
- raise DistutilsError(
700
- "Can't unambiguously interpret project/version identifier %r; "
701
- "any dashes in the name or version should be escaped using "
702
- "underscores. %r" % (fragment, dists)
703
- )
704
- else:
705
- raise DistutilsError(
706
- "Can't process plain .py files without an '#egg=name-version'"
707
- " suffix to enable automatic setup script generation."
708
- )
709
-
710
- dl_blocksize = 8192
711
-
712
- def _download_to(self, url, filename):
713
- self.info("Downloading %s", url)
714
- # Download the file
715
- fp = None
716
- try:
717
- checker = HashChecker.from_url(url)
718
- fp = self.open_url(url)
719
- if isinstance(fp, urllib.error.HTTPError):
720
- raise DistutilsError(
721
- "Can't download %s: %s %s" % (url, fp.code, fp.msg)
722
- )
723
- headers = fp.info()
724
- blocknum = 0
725
- bs = self.dl_blocksize
726
- size = -1
727
- if "content-length" in headers:
728
- # Some servers return multiple Content-Length headers :(
729
- sizes = headers.get_all('Content-Length')
730
- size = max(map(int, sizes))
731
- self.reporthook(url, filename, blocknum, bs, size)
732
- with open(filename, 'wb') as tfp:
733
- while True:
734
- block = fp.read(bs)
735
- if block:
736
- checker.feed(block)
737
- tfp.write(block)
738
- blocknum += 1
739
- self.reporthook(url, filename, blocknum, bs, size)
740
- else:
741
- break
742
- self.check_hash(checker, filename, tfp)
743
- return headers
744
- finally:
745
- if fp:
746
- fp.close()
747
-
748
- def reporthook(self, url, filename, blocknum, blksize, size):
749
- pass # no-op
750
-
751
- # FIXME:
752
- def open_url(self, url, warning=None): # noqa: C901 # is too complex (12)
753
- if url.startswith('file:'):
754
- return local_open(url)
755
- try:
756
- return open_with_auth(url, self.opener)
757
- except (ValueError, http.client.InvalidURL) as v:
758
- msg = ' '.join([str(arg) for arg in v.args])
759
- if warning:
760
- self.warn(warning, msg)
761
- else:
762
- raise DistutilsError('%s %s' % (url, msg)) from v
763
- except urllib.error.HTTPError as v:
764
- return v
765
- except urllib.error.URLError as v:
766
- if warning:
767
- self.warn(warning, v.reason)
768
- else:
769
- raise DistutilsError("Download error for %s: %s"
770
- % (url, v.reason)) from v
771
- except http.client.BadStatusLine as v:
772
- if warning:
773
- self.warn(warning, v.line)
774
- else:
775
- raise DistutilsError(
776
- '%s returned a bad status line. The server might be '
777
- 'down, %s' %
778
- (url, v.line)
779
- ) from v
780
- except (http.client.HTTPException, socket.error) as v:
781
- if warning:
782
- self.warn(warning, v)
783
- else:
784
- raise DistutilsError("Download error for %s: %s"
785
- % (url, v)) from v
786
-
787
- def _download_url(self, scheme, url, tmpdir):
788
- # Determine download filename
789
- #
790
- name, fragment = egg_info_for_url(url)
791
- if name:
792
- while '..' in name:
793
- name = name.replace('..', '.').replace('\\', '_')
794
- else:
795
- name = "__downloaded__" # default if URL has no path contents
796
-
797
- if name.endswith('.egg.zip'):
798
- name = name[:-4] # strip the extra .zip before download
799
-
800
- filename = os.path.join(tmpdir, name)
801
-
802
- # Download the file
803
- #
804
- if scheme == 'svn' or scheme.startswith('svn+'):
805
- return self._download_svn(url, filename)
806
- elif scheme == 'git' or scheme.startswith('git+'):
807
- return self._download_git(url, filename)
808
- elif scheme.startswith('hg+'):
809
- return self._download_hg(url, filename)
810
- elif scheme == 'file':
811
- return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])
812
- else:
813
- self.url_ok(url, True) # raises error if not allowed
814
- return self._attempt_download(url, filename)
815
-
816
- def scan_url(self, url):
817
- self.process_url(url, True)
818
-
819
- def _attempt_download(self, url, filename):
820
- headers = self._download_to(url, filename)
821
- if 'html' in headers.get('content-type', '').lower():
822
- return self._download_html(url, headers, filename)
823
- else:
824
- return filename
825
-
826
- def _download_html(self, url, headers, filename):
827
- file = open(filename)
828
- for line in file:
829
- if line.strip():
830
- # Check for a subversion index page
831
- if re.search(r'<title>([^- ]+ - )?Revision \d+:', line):
832
- # it's a subversion index page:
833
- file.close()
834
- os.unlink(filename)
835
- return self._download_svn(url, filename)
836
- break # not an index page
837
- file.close()
838
- os.unlink(filename)
839
- raise DistutilsError("Unexpected HTML page found at " + url)
840
-
841
- def _download_svn(self, url, filename):
842
- warnings.warn("SVN download support is deprecated", UserWarning)
843
- url = url.split('#', 1)[0] # remove any fragment for svn's sake
844
- creds = ''
845
- if url.lower().startswith('svn:') and '@' in url:
846
- scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)
847
- if not netloc and path.startswith('//') and '/' in path[2:]:
848
- netloc, path = path[2:].split('/', 1)
849
- auth, host = _splituser(netloc)
850
- if auth:
851
- if ':' in auth:
852
- user, pw = auth.split(':', 1)
853
- creds = " --username=%s --password=%s" % (user, pw)
854
- else:
855
- creds = " --username=" + auth
856
- netloc = host
857
- parts = scheme, netloc, url, p, q, f
858
- url = urllib.parse.urlunparse(parts)
859
- self.info("Doing subversion checkout from %s to %s", url, filename)
860
- os.system("svn checkout%s -q %s %s" % (creds, url, filename))
861
- return filename
862
-
863
- @staticmethod
864
- def _vcs_split_rev_from_url(url, pop_prefix=False):
865
- scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)
866
-
867
- scheme = scheme.split('+', 1)[-1]
868
-
869
- # Some fragment identification fails
870
- path = path.split('#', 1)[0]
871
-
872
- rev = None
873
- if '@' in path:
874
- path, rev = path.rsplit('@', 1)
875
-
876
- # Also, discard fragment
877
- url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))
878
-
879
- return url, rev
880
-
881
- def _download_git(self, url, filename):
882
- filename = filename.split('#', 1)[0]
883
- url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
884
-
885
- self.info("Doing git clone from %s to %s", url, filename)
886
- os.system("git clone --quiet %s %s" % (url, filename))
887
-
888
- if rev is not None:
889
- self.info("Checking out %s", rev)
890
- os.system("git -C %s checkout --quiet %s" % (
891
- filename,
892
- rev,
893
- ))
894
-
895
- return filename
896
-
897
- def _download_hg(self, url, filename):
898
- filename = filename.split('#', 1)[0]
899
- url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)
900
-
901
- self.info("Doing hg clone from %s to %s", url, filename)
902
- os.system("hg clone --quiet %s %s" % (url, filename))
903
-
904
- if rev is not None:
905
- self.info("Updating to %s", rev)
906
- os.system("hg --cwd %s up -C -r %s -q" % (
907
- filename,
908
- rev,
909
- ))
910
-
911
- return filename
912
-
913
- def debug(self, msg, *args):
914
- log.debug(msg, *args)
915
-
916
- def info(self, msg, *args):
917
- log.info(msg, *args)
918
-
919
- def warn(self, msg, *args):
920
- log.warn(msg, *args)
921
-
922
-
923
- # This pattern matches a character entity reference (a decimal numeric
924
- # references, a hexadecimal numeric reference, or a named reference).
925
- entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub
926
-
927
-
928
- def decode_entity(match):
929
- what = match.group(0)
930
- return html.unescape(what)
931
-
932
-
933
- def htmldecode(text):
934
- """
935
- Decode HTML entities in the given text.
936
-
937
- >>> htmldecode(
938
- ... 'https://../package_name-0.1.2.tar.gz'
939
- ... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz')
940
- 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz'
941
- """
942
- return entity_sub(decode_entity, text)
943
-
944
-
945
- def socket_timeout(timeout=15):
946
- def _socket_timeout(func):
947
- def _socket_timeout(*args, **kwargs):
948
- old_timeout = socket.getdefaulttimeout()
949
- socket.setdefaulttimeout(timeout)
950
- try:
951
- return func(*args, **kwargs)
952
- finally:
953
- socket.setdefaulttimeout(old_timeout)
954
-
955
- return _socket_timeout
956
-
957
- return _socket_timeout
958
-
959
-
960
- def _encode_auth(auth):
961
- """
962
- Encode auth from a URL suitable for an HTTP header.
963
- >>> str(_encode_auth('username%3Apassword'))
964
- 'dXNlcm5hbWU6cGFzc3dvcmQ='
965
-
966
- Long auth strings should not cause a newline to be inserted.
967
- >>> long_auth = 'username:' + 'password'*10
968
- >>> chr(10) in str(_encode_auth(long_auth))
969
- False
970
- """
971
- auth_s = urllib.parse.unquote(auth)
972
- # convert to bytes
973
- auth_bytes = auth_s.encode()
974
- encoded_bytes = base64.b64encode(auth_bytes)
975
- # convert back to a string
976
- encoded = encoded_bytes.decode()
977
- # strip the trailing carriage return
978
- return encoded.replace('\n', '')
979
-
980
-
981
- class Credential:
982
- """
983
- A username/password pair. Use like a namedtuple.
984
- """
985
-
986
- def __init__(self, username, password):
987
- self.username = username
988
- self.password = password
989
-
990
- def __iter__(self):
991
- yield self.username
992
- yield self.password
993
-
994
- def __str__(self):
995
- return '%(username)s:%(password)s' % vars(self)
996
-
997
-
998
- class PyPIConfig(configparser.RawConfigParser):
999
- def __init__(self):
1000
- """
1001
- Load from ~/.pypirc
1002
- """
1003
- defaults = dict.fromkeys(['username', 'password', 'repository'], '')
1004
- super().__init__(defaults)
1005
-
1006
- rc = os.path.join(os.path.expanduser('~'), '.pypirc')
1007
- if os.path.exists(rc):
1008
- self.read(rc)
1009
-
1010
- @property
1011
- def creds_by_repository(self):
1012
- sections_with_repositories = [
1013
- section for section in self.sections()
1014
- if self.get(section, 'repository').strip()
1015
- ]
1016
-
1017
- return dict(map(self._get_repo_cred, sections_with_repositories))
1018
-
1019
- def _get_repo_cred(self, section):
1020
- repo = self.get(section, 'repository').strip()
1021
- return repo, Credential(
1022
- self.get(section, 'username').strip(),
1023
- self.get(section, 'password').strip(),
1024
- )
1025
-
1026
- def find_credential(self, url):
1027
- """
1028
- If the URL indicated appears to be a repository defined in this
1029
- config, return the credential for that repository.
1030
- """
1031
- for repository, cred in self.creds_by_repository.items():
1032
- if url.startswith(repository):
1033
- return cred
1034
-
1035
-
1036
- def open_with_auth(url, opener=urllib.request.urlopen):
1037
- """Open a urllib2 request, handling HTTP authentication"""
1038
-
1039
- parsed = urllib.parse.urlparse(url)
1040
- scheme, netloc, path, params, query, frag = parsed
1041
-
1042
- # Double scheme does not raise on macOS as revealed by a
1043
- # failing test. We would expect "nonnumeric port". Refs #20.
1044
- if netloc.endswith(':'):
1045
- raise http.client.InvalidURL("nonnumeric port: ''")
1046
-
1047
- if scheme in ('http', 'https'):
1048
- auth, address = _splituser(netloc)
1049
- else:
1050
- auth = None
1051
-
1052
- if not auth:
1053
- cred = PyPIConfig().find_credential(url)
1054
- if cred:
1055
- auth = str(cred)
1056
- info = cred.username, url
1057
- log.info('Authenticating as %s for %s (from .pypirc)', *info)
1058
-
1059
- if auth:
1060
- auth = "Basic " + _encode_auth(auth)
1061
- parts = scheme, address, path, params, query, frag
1062
- new_url = urllib.parse.urlunparse(parts)
1063
- request = urllib.request.Request(new_url)
1064
- request.add_header("Authorization", auth)
1065
- else:
1066
- request = urllib.request.Request(url)
1067
-
1068
- request.add_header('User-Agent', user_agent)
1069
- fp = opener(request)
1070
-
1071
- if auth:
1072
- # Put authentication info back into request URL if same host,
1073
- # so that links found on the page will work
1074
- s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)
1075
- if s2 == scheme and h2 == address:
1076
- parts = s2, netloc, path2, param2, query2, frag2
1077
- fp.url = urllib.parse.urlunparse(parts)
1078
-
1079
- return fp
1080
-
1081
-
1082
- # copy of urllib.parse._splituser from Python 3.8
1083
- def _splituser(host):
1084
- """splituser('user[:passwd]@host[:port]')
1085
- --> 'user[:passwd]', 'host[:port]'."""
1086
- user, delim, host = host.rpartition('@')
1087
- return (user if delim else None), host
1088
-
1089
-
1090
- # adding a timeout to avoid freezing package_index
1091
- open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)
1092
-
1093
-
1094
- def fix_sf_url(url):
1095
- return url # backward compatibility
1096
-
1097
-
1098
- def local_open(url):
1099
- """Read a local path, with special support for directories"""
1100
- scheme, server, path, param, query, frag = urllib.parse.urlparse(url)
1101
- filename = urllib.request.url2pathname(path)
1102
- if os.path.isfile(filename):
1103
- return urllib.request.urlopen(url)
1104
- elif path.endswith('/') and os.path.isdir(filename):
1105
- files = []
1106
- for f in os.listdir(filename):
1107
- filepath = os.path.join(filename, f)
1108
- if f == 'index.html':
1109
- with open(filepath, 'r') as fp:
1110
- body = fp.read()
1111
- break
1112
- elif os.path.isdir(filepath):
1113
- f += '/'
1114
- files.append('<a href="{name}">{name}</a>'.format(name=f))
1115
- else:
1116
- tmpl = (
1117
- "<html><head><title>{url}</title>"
1118
- "</head><body>{files}</body></html>")
1119
- body = tmpl.format(url=url, files='\n'.join(files))
1120
- status, message = 200, "OK"
1121
- else:
1122
- status, message, body = 404, "Path not found", "Not found"
1123
-
1124
- headers = {'content-type': 'text/html'}
1125
- body_stream = io.StringIO(body)
1126
- return urllib.error.HTTPError(url, status, message, headers, body_stream)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/system/detail/sequential/per_device_resource.h DELETED
@@ -1,22 +0,0 @@
1
- /*
2
- * Copyright 2018 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 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
-
17
- #pragma once
18
-
19
- #include <thrust/detail/config.h>
20
-
21
- // this system has no special per device resource functions
22
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CikeyQI/meme-api/meme_generator/download.py DELETED
@@ -1,117 +0,0 @@
1
- import asyncio
2
- import hashlib
3
- import json
4
- import time
5
- from pathlib import Path
6
- from typing import List, Tuple
7
-
8
- import httpx
9
- from rich.progress import Progress
10
-
11
- from .config import meme_config
12
- from .log import logger
13
- from .version import __version__
14
-
15
-
16
- def _resource_url(base_url: str, name: str) -> str:
17
- return f"{base_url}v{__version__}/{name}"
18
-
19
-
20
- # https://github.com/mnixry/nonebot-plugin-gocqhttp/blob/main/nonebot_plugin_gocqhttp/process/download.py
21
- async def get_fastest_mirror() -> List[str]:
22
- assert meme_config.resource.resource_urls, "No resource url specified."
23
-
24
- async def head_mirror(client: httpx.AsyncClient, base_url: str):
25
- begin_time = time.time()
26
- response = await client.head(
27
- _resource_url(base_url, "resources/fonts/NotoSansSC-Regular.otf"), timeout=5
28
- )
29
- response.raise_for_status()
30
- elapsed_time = (time.time() - begin_time) * 1000
31
- return {"base_url": base_url, "elapsed_time": elapsed_time}
32
-
33
- async with httpx.AsyncClient() as client:
34
- results = await asyncio.gather(
35
- *(
36
- head_mirror(client, domain)
37
- for domain in meme_config.resource.resource_urls
38
- ),
39
- return_exceptions=True,
40
- )
41
- results = sorted(
42
- (result for result in results if not isinstance(result, Exception)),
43
- key=lambda r: r["elapsed_time"],
44
- )
45
- return [result["base_url"] for result in results]
46
-
47
-
48
- async def check_resources():
49
- semaphore = asyncio.Semaphore(10)
50
-
51
- available_urls = (
52
- [meme_config.resource.resource_url]
53
- if meme_config.resource.resource_url
54
- else (await get_fastest_mirror())
55
- )
56
- logger.debug(f"Available resource urls: {available_urls}")
57
- if not available_urls:
58
- logger.warning("No resource url available.")
59
- return
60
-
61
- async def _download(client: httpx.AsyncClient, name: str):
62
- async with semaphore:
63
- for base_url in available_urls:
64
- url = _resource_url(base_url, name)
65
- try:
66
- resp = await client.get(url, timeout=20, follow_redirects=True)
67
- resp.raise_for_status()
68
- return resp.content
69
- except httpx.HTTPError:
70
- pass
71
- logger.warning(f"{name} download failed!")
72
-
73
- async with httpx.AsyncClient() as client:
74
- if content := await _download(client, "resources/resource_list.json"):
75
- resource_list = json.loads(content.decode("utf-8"))
76
- else:
77
- return
78
-
79
- download_list: List[Tuple[Path, str]] = []
80
- for resource in resource_list:
81
- file_name = str(resource["path"])
82
- file_hash = str(resource["hash"])
83
- file_path = Path(__file__).parent / "memes" / file_name
84
- if (
85
- file_path.exists()
86
- and hashlib.md5(file_path.read_bytes()).hexdigest() == file_hash
87
- ):
88
- continue
89
- else:
90
- download_list.append((file_path, f"meme_generator/memes/{file_name}"))
91
-
92
- if len(download_list):
93
- logger.info("Downloading images ...")
94
- else:
95
- return
96
-
97
- async with httpx.AsyncClient() as client:
98
-
99
- async def download_image(file_path: Path, file_name: str):
100
- if content := await _download(client, file_name):
101
- file_path.parent.mkdir(parents=True, exist_ok=True)
102
- with file_path.open("wb") as f:
103
- f.write(content)
104
-
105
- with Progress(
106
- *Progress.get_default_columns(), "[yellow]{task.completed}/{task.total}"
107
- ) as progress:
108
- progress_task = progress.add_task(
109
- "[green]Downloading...", total=len(download_list)
110
- )
111
- tasks = [
112
- download_image(file_path, file_name)
113
- for file_path, file_name in download_list
114
- ]
115
- for task in asyncio.as_completed(tasks):
116
- await task
117
- progress.update(progress_task, advance=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CikeyQI/meme-api/meme_generator/memes/alike/__init__.py DELETED
@@ -1,24 +0,0 @@
1
- from typing import List
2
-
3
- from pil_utils import BuildImage
4
-
5
- from meme_generator import add_meme
6
- from meme_generator.utils import make_jpg_or_gif
7
-
8
-
9
- def alike(images: List[BuildImage], texts, args):
10
- frame = BuildImage.new("RGBA", (470, 180), "white")
11
- frame.draw_text(
12
- (10, 10, 185, 140), "你怎么跟", max_fontsize=40, min_fontsize=30, halign="right"
13
- ).draw_text(
14
- (365, 10, 460, 140), "一样", max_fontsize=40, min_fontsize=30, halign="left"
15
- )
16
-
17
- def make(img: BuildImage) -> BuildImage:
18
- img = img.convert("RGBA").resize((150, 150), keep_ratio=True)
19
- return frame.copy().paste(img, (200, 15), alpha=True)
20
-
21
- return make_jpg_or_gif(images[0], make)
22
-
23
-
24
- add_meme("alike", alike, min_images=1, max_images=1, keywords=["一样"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cpp4App/Cpp4App/CDM/detect_merge/Element.py DELETED
@@ -1,113 +0,0 @@
1
- import numpy as np
2
- import cv2
3
-
4
-
5
- class Element:
6
- def __init__(self, id, corner, category, text_content=None):
7
- self.id = id
8
- self.category = category
9
- self.col_min, self.row_min, self.col_max, self.row_max = corner
10
- self.width = self.col_max - self.col_min
11
- self.height = self.row_max - self.row_min
12
- self.area = self.width * self.height
13
-
14
- self.text_content = text_content
15
- self.parent_id = None
16
- self.children = [] # list of elements
17
- self.label = None
18
-
19
- def init_bound(self):
20
- self.width = self.col_max - self.col_min
21
- self.height = self.row_max - self.row_min
22
- self.area = self.width * self.height
23
-
24
- def put_bbox(self):
25
- return self.col_min, self.row_min, self.col_max, self.row_max
26
-
27
- def wrap_info(self):
28
- info = {'id':self.id, 'class': self.category, 'height': self.height, 'width': self.width,
29
- 'position': {'column_min': self.col_min, 'row_min': self.row_min, 'column_max': self.col_max,
30
- 'row_max': self.row_max}, 'label': self.label}
31
- if self.text_content is not None:
32
- info['text_content'] = self.text_content
33
- if len(self.children) > 0:
34
- info['children'] = []
35
- for child in self.children:
36
- info['children'].append(child.id)
37
- if self.parent_id is not None:
38
- info['parent'] = self.parent_id
39
- return info
40
-
41
- def resize(self, resize_ratio):
42
- self.col_min = int(self.col_min * resize_ratio)
43
- self.row_min = int(self.row_min * resize_ratio)
44
- self.col_max = int(self.col_max * resize_ratio)
45
- self.row_max = int(self.row_max * resize_ratio)
46
- self.init_bound()
47
-
48
- def element_merge(self, element_b, new_element=False, new_category=None, new_id=None):
49
- col_min_a, row_min_a, col_max_a, row_max_a = self.put_bbox()
50
- col_min_b, row_min_b, col_max_b, row_max_b = element_b.put_bbox()
51
- new_corner = (min(col_min_a, col_min_b), min(row_min_a, row_min_b), max(col_max_a, col_max_b), max(row_max_a, row_max_b))
52
- if element_b.text_content is not None:
53
- self.text_content = element_b.text_content if self.text_content is None else self.text_content + '\n' + element_b.text_content
54
- if new_element:
55
- return Element(new_id, new_corner, new_category)
56
- else:
57
- self.col_min, self.row_min, self.col_max, self.row_max = new_corner
58
- self.init_bound()
59
-
60
- def calc_intersection_area(self, element_b, bias=(0, 0)):
61
- a = self.put_bbox()
62
- b = element_b.put_bbox()
63
- col_min_s = max(a[0], b[0]) - bias[0]
64
- row_min_s = max(a[1], b[1]) - bias[1]
65
- col_max_s = min(a[2], b[2])
66
- row_max_s = min(a[3], b[3])
67
- w = np.maximum(0, col_max_s - col_min_s)
68
- h = np.maximum(0, row_max_s - row_min_s)
69
- inter = w * h
70
-
71
- iou = inter / (self.area + element_b.area - inter)
72
- ioa = inter / self.area
73
- iob = inter / element_b.area
74
-
75
- return inter, iou, ioa, iob
76
-
77
- def element_relation(self, element_b, bias=(0, 0)):
78
- """
79
- @bias: (horizontal bias, vertical bias)
80
- :return: -1 : a in b
81
- 0 : a, b are not intersected
82
- 1 : b in a
83
- 2 : a, b are identical or intersected
84
- """
85
- inter, iou, ioa, iob = self.calc_intersection_area(element_b, bias)
86
-
87
- # area of intersection is 0
88
- if ioa == 0:
89
- return 0
90
- # a in b
91
- if ioa >= 1:
92
- return -1
93
- # b in a
94
- if iob >= 1:
95
- return 1
96
- return 2
97
-
98
- def visualize_element(self, img, color=(0, 255, 0), line=1, show=False, ratio=1):
99
- loc = self.put_bbox()
100
-
101
- if ratio != 1:
102
- loc = [int(x * ratio) for x in loc]
103
-
104
- # cv2.rectangle(img, loc[:2], loc[2:], color, line)
105
- cv2.rectangle(img, (loc[0], loc[1]), (loc[2], loc[3]), color, line)
106
- cv2.putText(img, str(int(self.id) + 1), (int(ratio*(self.col_min - 10)), int(ratio*(self.row_max + 10))), cv2.FONT_HERSHEY_SIMPLEX, 1,
107
- color, line)
108
- # for child in self.children:
109
- # child.visualize_element(img, color=(255, 0, 255), line=line)
110
- if show:
111
- cv2.imshow('element', img)
112
- cv2.waitKey(0)
113
- cv2.destroyWindow('element')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/varLib/cff.py DELETED
@@ -1,696 +0,0 @@
1
- from collections import namedtuple
2
- from fontTools.cffLib import (
3
- maxStackLimit,
4
- TopDictIndex,
5
- buildOrder,
6
- topDictOperators,
7
- topDictOperators2,
8
- privateDictOperators,
9
- privateDictOperators2,
10
- FDArrayIndex,
11
- FontDict,
12
- VarStoreData,
13
- )
14
- from io import BytesIO
15
- from fontTools.cffLib.specializer import specializeCommands, commandsToProgram
16
- from fontTools.ttLib import newTable
17
- from fontTools import varLib
18
- from fontTools.varLib.models import allEqual
19
- from fontTools.misc.roundTools import roundFunc
20
- from fontTools.misc.psCharStrings import T2CharString, T2OutlineExtractor
21
- from fontTools.pens.t2CharStringPen import T2CharStringPen
22
- from functools import partial
23
-
24
- from .errors import (
25
- VarLibCFFDictMergeError,
26
- VarLibCFFPointTypeMergeError,
27
- VarLibCFFHintTypeMergeError,
28
- VarLibMergeError,
29
- )
30
-
31
-
32
- # Backwards compatibility
33
- MergeDictError = VarLibCFFDictMergeError
34
- MergeTypeError = VarLibCFFPointTypeMergeError
35
-
36
-
37
- def addCFFVarStore(varFont, varModel, varDataList, masterSupports):
38
- fvarTable = varFont["fvar"]
39
- axisKeys = [axis.axisTag for axis in fvarTable.axes]
40
- varTupleList = varLib.builder.buildVarRegionList(masterSupports, axisKeys)
41
- varStoreCFFV = varLib.builder.buildVarStore(varTupleList, varDataList)
42
-
43
- topDict = varFont["CFF2"].cff.topDictIndex[0]
44
- topDict.VarStore = VarStoreData(otVarStore=varStoreCFFV)
45
- if topDict.FDArray[0].vstore is None:
46
- fdArray = topDict.FDArray
47
- for fontDict in fdArray:
48
- if hasattr(fontDict, "Private"):
49
- fontDict.Private.vstore = topDict.VarStore
50
-
51
-
52
- def lib_convertCFFToCFF2(cff, otFont):
53
- # This assumes a decompiled CFF table.
54
- cff2GetGlyphOrder = cff.otFont.getGlyphOrder
55
- topDictData = TopDictIndex(None, cff2GetGlyphOrder, None)
56
- topDictData.items = cff.topDictIndex.items
57
- cff.topDictIndex = topDictData
58
- topDict = topDictData[0]
59
- if hasattr(topDict, "Private"):
60
- privateDict = topDict.Private
61
- else:
62
- privateDict = None
63
- opOrder = buildOrder(topDictOperators2)
64
- topDict.order = opOrder
65
- topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
66
- if not hasattr(topDict, "FDArray"):
67
- fdArray = topDict.FDArray = FDArrayIndex()
68
- fdArray.strings = None
69
- fdArray.GlobalSubrs = topDict.GlobalSubrs
70
- topDict.GlobalSubrs.fdArray = fdArray
71
- charStrings = topDict.CharStrings
72
- if charStrings.charStringsAreIndexed:
73
- charStrings.charStringsIndex.fdArray = fdArray
74
- else:
75
- charStrings.fdArray = fdArray
76
- fontDict = FontDict()
77
- fontDict.setCFF2(True)
78
- fdArray.append(fontDict)
79
- fontDict.Private = privateDict
80
- privateOpOrder = buildOrder(privateDictOperators2)
81
- if privateDict is not None:
82
- for entry in privateDictOperators:
83
- key = entry[1]
84
- if key not in privateOpOrder:
85
- if key in privateDict.rawDict:
86
- # print "Removing private dict", key
87
- del privateDict.rawDict[key]
88
- if hasattr(privateDict, key):
89
- delattr(privateDict, key)
90
- # print "Removing privateDict attr", key
91
- else:
92
- # clean up the PrivateDicts in the fdArray
93
- fdArray = topDict.FDArray
94
- privateOpOrder = buildOrder(privateDictOperators2)
95
- for fontDict in fdArray:
96
- fontDict.setCFF2(True)
97
- for key in list(fontDict.rawDict.keys()):
98
- if key not in fontDict.order:
99
- del fontDict.rawDict[key]
100
- if hasattr(fontDict, key):
101
- delattr(fontDict, key)
102
-
103
- privateDict = fontDict.Private
104
- for entry in privateDictOperators:
105
- key = entry[1]
106
- if key not in privateOpOrder:
107
- if key in privateDict.rawDict:
108
- # print "Removing private dict", key
109
- del privateDict.rawDict[key]
110
- if hasattr(privateDict, key):
111
- delattr(privateDict, key)
112
- # print "Removing privateDict attr", key
113
- # Now delete up the deprecated topDict operators from CFF 1.0
114
- for entry in topDictOperators:
115
- key = entry[1]
116
- if key not in opOrder:
117
- if key in topDict.rawDict:
118
- del topDict.rawDict[key]
119
- if hasattr(topDict, key):
120
- delattr(topDict, key)
121
-
122
- # At this point, the Subrs and Charstrings are all still T2Charstring class
123
- # easiest to fix this by compiling, then decompiling again
124
- cff.major = 2
125
- file = BytesIO()
126
- cff.compile(file, otFont, isCFF2=True)
127
- file.seek(0)
128
- cff.decompile(file, otFont, isCFF2=True)
129
-
130
-
131
- def convertCFFtoCFF2(varFont):
132
- # Convert base font to a single master CFF2 font.
133
- cffTable = varFont["CFF "]
134
- lib_convertCFFToCFF2(cffTable.cff, varFont)
135
- newCFF2 = newTable("CFF2")
136
- newCFF2.cff = cffTable.cff
137
- varFont["CFF2"] = newCFF2
138
- del varFont["CFF "]
139
-
140
-
141
- def conv_to_int(num):
142
- if isinstance(num, float) and num.is_integer():
143
- return int(num)
144
- return num
145
-
146
-
147
- pd_blend_fields = (
148
- "BlueValues",
149
- "OtherBlues",
150
- "FamilyBlues",
151
- "FamilyOtherBlues",
152
- "BlueScale",
153
- "BlueShift",
154
- "BlueFuzz",
155
- "StdHW",
156
- "StdVW",
157
- "StemSnapH",
158
- "StemSnapV",
159
- )
160
-
161
-
162
- def get_private(regionFDArrays, fd_index, ri, fd_map):
163
- region_fdArray = regionFDArrays[ri]
164
- region_fd_map = fd_map[fd_index]
165
- if ri in region_fd_map:
166
- region_fdIndex = region_fd_map[ri]
167
- private = region_fdArray[region_fdIndex].Private
168
- else:
169
- private = None
170
- return private
171
-
172
-
173
- def merge_PrivateDicts(top_dicts, vsindex_dict, var_model, fd_map):
174
- """
175
- I step through the FontDicts in the FDArray of the varfont TopDict.
176
- For each varfont FontDict:
177
-
178
- * step through each key in FontDict.Private.
179
- * For each key, step through each relevant source font Private dict, and
180
- build a list of values to blend.
181
-
182
- The 'relevant' source fonts are selected by first getting the right
183
- submodel using ``vsindex_dict[vsindex]``. The indices of the
184
- ``subModel.locations`` are mapped to source font list indices by
185
- assuming the latter order is the same as the order of the
186
- ``var_model.locations``. I can then get the index of each subModel
187
- location in the list of ``var_model.locations``.
188
- """
189
-
190
- topDict = top_dicts[0]
191
- region_top_dicts = top_dicts[1:]
192
- if hasattr(region_top_dicts[0], "FDArray"):
193
- regionFDArrays = [fdTopDict.FDArray for fdTopDict in region_top_dicts]
194
- else:
195
- regionFDArrays = [[fdTopDict] for fdTopDict in region_top_dicts]
196
- for fd_index, font_dict in enumerate(topDict.FDArray):
197
- private_dict = font_dict.Private
198
- vsindex = getattr(private_dict, "vsindex", 0)
199
- # At the moment, no PrivateDict has a vsindex key, but let's support
200
- # how it should work. See comment at end of
201
- # merge_charstrings() - still need to optimize use of vsindex.
202
- sub_model, _ = vsindex_dict[vsindex]
203
- master_indices = []
204
- for loc in sub_model.locations[1:]:
205
- i = var_model.locations.index(loc) - 1
206
- master_indices.append(i)
207
- pds = [private_dict]
208
- last_pd = private_dict
209
- for ri in master_indices:
210
- pd = get_private(regionFDArrays, fd_index, ri, fd_map)
211
- # If the region font doesn't have this FontDict, just reference
212
- # the last one used.
213
- if pd is None:
214
- pd = last_pd
215
- else:
216
- last_pd = pd
217
- pds.append(pd)
218
- num_masters = len(pds)
219
- for key, value in private_dict.rawDict.items():
220
- dataList = []
221
- if key not in pd_blend_fields:
222
- continue
223
- if isinstance(value, list):
224
- try:
225
- values = [pd.rawDict[key] for pd in pds]
226
- except KeyError:
227
- print(
228
- "Warning: {key} in default font Private dict is "
229
- "missing from another font, and was "
230
- "discarded.".format(key=key)
231
- )
232
- continue
233
- try:
234
- values = zip(*values)
235
- except IndexError:
236
- raise VarLibCFFDictMergeError(key, value, values)
237
- """
238
- Row 0 contains the first value from each master.
239
- Convert each row from absolute values to relative
240
- values from the previous row.
241
- e.g for three masters, a list of values was:
242
- master 0 OtherBlues = [-217,-205]
243
- master 1 OtherBlues = [-234,-222]
244
- master 1 OtherBlues = [-188,-176]
245
- The call to zip() converts this to:
246
- [(-217, -234, -188), (-205, -222, -176)]
247
- and is converted finally to:
248
- OtherBlues = [[-217, 17.0, 46.0], [-205, 0.0, 0.0]]
249
- """
250
- prev_val_list = [0] * num_masters
251
- any_points_differ = False
252
- for val_list in values:
253
- rel_list = [
254
- (val - prev_val_list[i]) for (i, val) in enumerate(val_list)
255
- ]
256
- if (not any_points_differ) and not allEqual(rel_list):
257
- any_points_differ = True
258
- prev_val_list = val_list
259
- deltas = sub_model.getDeltas(rel_list)
260
- # For PrivateDict BlueValues, the default font
261
- # values are absolute, not relative to the prior value.
262
- deltas[0] = val_list[0]
263
- dataList.append(deltas)
264
- # If there are no blend values,then
265
- # we can collapse the blend lists.
266
- if not any_points_differ:
267
- dataList = [data[0] for data in dataList]
268
- else:
269
- values = [pd.rawDict[key] for pd in pds]
270
- if not allEqual(values):
271
- dataList = sub_model.getDeltas(values)
272
- else:
273
- dataList = values[0]
274
-
275
- # Convert numbers with no decimal part to an int
276
- if isinstance(dataList, list):
277
- for i, item in enumerate(dataList):
278
- if isinstance(item, list):
279
- for j, jtem in enumerate(item):
280
- dataList[i][j] = conv_to_int(jtem)
281
- else:
282
- dataList[i] = conv_to_int(item)
283
- else:
284
- dataList = conv_to_int(dataList)
285
-
286
- private_dict.rawDict[key] = dataList
287
-
288
-
289
- def _cff_or_cff2(font):
290
- if "CFF " in font:
291
- return font["CFF "]
292
- return font["CFF2"]
293
-
294
-
295
- def getfd_map(varFont, fonts_list):
296
- """Since a subset source font may have fewer FontDicts in their
297
- FDArray than the default font, we have to match up the FontDicts in
298
- the different fonts . We do this with the FDSelect array, and by
299
- assuming that the same glyph will reference matching FontDicts in
300
- each source font. We return a mapping from fdIndex in the default
301
- font to a dictionary which maps each master list index of each
302
- region font to the equivalent fdIndex in the region font."""
303
- fd_map = {}
304
- default_font = fonts_list[0]
305
- region_fonts = fonts_list[1:]
306
- num_regions = len(region_fonts)
307
- topDict = _cff_or_cff2(default_font).cff.topDictIndex[0]
308
- if not hasattr(topDict, "FDSelect"):
309
- # All glyphs reference only one FontDict.
310
- # Map the FD index for regions to index 0.
311
- fd_map[0] = {ri: 0 for ri in range(num_regions)}
312
- return fd_map
313
-
314
- gname_mapping = {}
315
- default_fdSelect = topDict.FDSelect
316
- glyphOrder = default_font.getGlyphOrder()
317
- for gid, fdIndex in enumerate(default_fdSelect):
318
- gname_mapping[glyphOrder[gid]] = fdIndex
319
- if fdIndex not in fd_map:
320
- fd_map[fdIndex] = {}
321
- for ri, region_font in enumerate(region_fonts):
322
- region_glyphOrder = region_font.getGlyphOrder()
323
- region_topDict = _cff_or_cff2(region_font).cff.topDictIndex[0]
324
- if not hasattr(region_topDict, "FDSelect"):
325
- # All the glyphs share the same FontDict. Pick any glyph.
326
- default_fdIndex = gname_mapping[region_glyphOrder[0]]
327
- fd_map[default_fdIndex][ri] = 0
328
- else:
329
- region_fdSelect = region_topDict.FDSelect
330
- for gid, fdIndex in enumerate(region_fdSelect):
331
- default_fdIndex = gname_mapping[region_glyphOrder[gid]]
332
- region_map = fd_map[default_fdIndex]
333
- if ri not in region_map:
334
- region_map[ri] = fdIndex
335
- return fd_map
336
-
337
-
338
- CVarData = namedtuple("CVarData", "varDataList masterSupports vsindex_dict")
339
-
340
-
341
- def merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder):
342
- topDict = varFont["CFF2"].cff.topDictIndex[0]
343
- top_dicts = [topDict] + [
344
- _cff_or_cff2(ttFont).cff.topDictIndex[0] for ttFont in ordered_fonts_list[1:]
345
- ]
346
- num_masters = len(model.mapping)
347
- cvData = merge_charstrings(glyphOrder, num_masters, top_dicts, model)
348
- fd_map = getfd_map(varFont, ordered_fonts_list)
349
- merge_PrivateDicts(top_dicts, cvData.vsindex_dict, model, fd_map)
350
- addCFFVarStore(varFont, model, cvData.varDataList, cvData.masterSupports)
351
-
352
-
353
- def _get_cs(charstrings, glyphName):
354
- if glyphName not in charstrings:
355
- return None
356
- return charstrings[glyphName]
357
-
358
-
359
- def _add_new_vsindex(
360
- model, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList
361
- ):
362
- varTupleIndexes = []
363
- for support in model.supports[1:]:
364
- if support not in masterSupports:
365
- masterSupports.append(support)
366
- varTupleIndexes.append(masterSupports.index(support))
367
- var_data = varLib.builder.buildVarData(varTupleIndexes, None, False)
368
- vsindex = len(vsindex_dict)
369
- vsindex_by_key[key] = vsindex
370
- vsindex_dict[vsindex] = (model, [key])
371
- varDataList.append(var_data)
372
- return vsindex
373
-
374
-
375
- def merge_charstrings(glyphOrder, num_masters, top_dicts, masterModel):
376
-
377
- vsindex_dict = {}
378
- vsindex_by_key = {}
379
- varDataList = []
380
- masterSupports = []
381
- default_charstrings = top_dicts[0].CharStrings
382
- for gid, gname in enumerate(glyphOrder):
383
- all_cs = [_get_cs(td.CharStrings, gname) for td in top_dicts]
384
- if len([gs for gs in all_cs if gs is not None]) == 1:
385
- continue
386
- model, model_cs = masterModel.getSubModel(all_cs)
387
- # create the first pass CFF2 charstring, from
388
- # the default charstring.
389
- default_charstring = model_cs[0]
390
- var_pen = CFF2CharStringMergePen([], gname, num_masters, 0)
391
- # We need to override outlineExtractor because these
392
- # charstrings do have widths in the 'program'; we need to drop these
393
- # values rather than post assertion error for them.
394
- default_charstring.outlineExtractor = MergeOutlineExtractor
395
- default_charstring.draw(var_pen)
396
-
397
- # Add the coordinates from all the other regions to the
398
- # blend lists in the CFF2 charstring.
399
- region_cs = model_cs[1:]
400
- for region_idx, region_charstring in enumerate(region_cs, start=1):
401
- var_pen.restart(region_idx)
402
- region_charstring.outlineExtractor = MergeOutlineExtractor
403
- region_charstring.draw(var_pen)
404
-
405
- # Collapse each coordinate list to a blend operator and its args.
406
- new_cs = var_pen.getCharString(
407
- private=default_charstring.private,
408
- globalSubrs=default_charstring.globalSubrs,
409
- var_model=model,
410
- optimize=True,
411
- )
412
- default_charstrings[gname] = new_cs
413
-
414
- if (not var_pen.seen_moveto) or ("blend" not in new_cs.program):
415
- # If this is not a marking glyph, or if there are no blend
416
- # arguments, then we can use vsindex 0. No need to
417
- # check if we need a new vsindex.
418
- continue
419
-
420
- # If the charstring required a new model, create
421
- # a VarData table to go with, and set vsindex.
422
- key = tuple(v is not None for v in all_cs)
423
- try:
424
- vsindex = vsindex_by_key[key]
425
- except KeyError:
426
- vsindex = _add_new_vsindex(
427
- model, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList
428
- )
429
- # We do not need to check for an existing new_cs.private.vsindex,
430
- # as we know it doesn't exist yet.
431
- if vsindex != 0:
432
- new_cs.program[:0] = [vsindex, "vsindex"]
433
-
434
- # If there is no variation in any of the charstrings, then vsindex_dict
435
- # never gets built. This could still be needed if there is variation
436
- # in the PrivatDict, so we will build the default data for vsindex = 0.
437
- if not vsindex_dict:
438
- key = (True,) * num_masters
439
- _add_new_vsindex(
440
- masterModel, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList
441
- )
442
- cvData = CVarData(
443
- varDataList=varDataList,
444
- masterSupports=masterSupports,
445
- vsindex_dict=vsindex_dict,
446
- )
447
- # XXX To do: optimize use of vsindex between the PrivateDicts and
448
- # charstrings
449
- return cvData
450
-
451
-
452
- class CFFToCFF2OutlineExtractor(T2OutlineExtractor):
453
- """This class is used to remove the initial width from the CFF
454
- charstring without trying to add the width to self.nominalWidthX,
455
- which is None."""
456
-
457
- def popallWidth(self, evenOdd=0):
458
- args = self.popall()
459
- if not self.gotWidth:
460
- if evenOdd ^ (len(args) % 2):
461
- args = args[1:]
462
- self.width = self.defaultWidthX
463
- self.gotWidth = 1
464
- return args
465
-
466
-
467
- class MergeOutlineExtractor(CFFToCFF2OutlineExtractor):
468
- """Used to extract the charstring commands - including hints - from a
469
- CFF charstring in order to merge it as another set of region data
470
- into a CFF2 variable font charstring."""
471
-
472
- def __init__(
473
- self,
474
- pen,
475
- localSubrs,
476
- globalSubrs,
477
- nominalWidthX,
478
- defaultWidthX,
479
- private=None,
480
- blender=None,
481
- ):
482
- super().__init__(
483
- pen, localSubrs, globalSubrs, nominalWidthX, defaultWidthX, private, blender
484
- )
485
-
486
- def countHints(self):
487
- args = self.popallWidth()
488
- self.hintCount = self.hintCount + len(args) // 2
489
- return args
490
-
491
- def _hint_op(self, type, args):
492
- self.pen.add_hint(type, args)
493
-
494
- def op_hstem(self, index):
495
- args = self.countHints()
496
- self._hint_op("hstem", args)
497
-
498
- def op_vstem(self, index):
499
- args = self.countHints()
500
- self._hint_op("vstem", args)
501
-
502
- def op_hstemhm(self, index):
503
- args = self.countHints()
504
- self._hint_op("hstemhm", args)
505
-
506
- def op_vstemhm(self, index):
507
- args = self.countHints()
508
- self._hint_op("vstemhm", args)
509
-
510
- def _get_hintmask(self, index):
511
- if not self.hintMaskBytes:
512
- args = self.countHints()
513
- if args:
514
- self._hint_op("vstemhm", args)
515
- self.hintMaskBytes = (self.hintCount + 7) // 8
516
- hintMaskBytes, index = self.callingStack[-1].getBytes(index, self.hintMaskBytes)
517
- return index, hintMaskBytes
518
-
519
- def op_hintmask(self, index):
520
- index, hintMaskBytes = self._get_hintmask(index)
521
- self.pen.add_hintmask("hintmask", [hintMaskBytes])
522
- return hintMaskBytes, index
523
-
524
- def op_cntrmask(self, index):
525
- index, hintMaskBytes = self._get_hintmask(index)
526
- self.pen.add_hintmask("cntrmask", [hintMaskBytes])
527
- return hintMaskBytes, index
528
-
529
-
530
- class CFF2CharStringMergePen(T2CharStringPen):
531
- """Pen to merge Type 2 CharStrings."""
532
-
533
- def __init__(
534
- self, default_commands, glyphName, num_masters, master_idx, roundTolerance=0.01
535
- ):
536
- # For roundTolerance see https://github.com/fonttools/fonttools/issues/2838
537
- super().__init__(
538
- width=None, glyphSet=None, CFF2=True, roundTolerance=roundTolerance
539
- )
540
- self.pt_index = 0
541
- self._commands = default_commands
542
- self.m_index = master_idx
543
- self.num_masters = num_masters
544
- self.prev_move_idx = 0
545
- self.seen_moveto = False
546
- self.glyphName = glyphName
547
- self.round = roundFunc(roundTolerance, round=round)
548
-
549
- def add_point(self, point_type, pt_coords):
550
- if self.m_index == 0:
551
- self._commands.append([point_type, [pt_coords]])
552
- else:
553
- cmd = self._commands[self.pt_index]
554
- if cmd[0] != point_type:
555
- raise VarLibCFFPointTypeMergeError(
556
- point_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName
557
- )
558
- cmd[1].append(pt_coords)
559
- self.pt_index += 1
560
-
561
- def add_hint(self, hint_type, args):
562
- if self.m_index == 0:
563
- self._commands.append([hint_type, [args]])
564
- else:
565
- cmd = self._commands[self.pt_index]
566
- if cmd[0] != hint_type:
567
- raise VarLibCFFHintTypeMergeError(
568
- hint_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName
569
- )
570
- cmd[1].append(args)
571
- self.pt_index += 1
572
-
573
- def add_hintmask(self, hint_type, abs_args):
574
- # For hintmask, fonttools.cffLib.specializer.py expects
575
- # each of these to be represented by two sequential commands:
576
- # first holding only the operator name, with an empty arg list,
577
- # second with an empty string as the op name, and the mask arg list.
578
- if self.m_index == 0:
579
- self._commands.append([hint_type, []])
580
- self._commands.append(["", [abs_args]])
581
- else:
582
- cmd = self._commands[self.pt_index]
583
- if cmd[0] != hint_type:
584
- raise VarLibCFFHintTypeMergeError(
585
- hint_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName
586
- )
587
- self.pt_index += 1
588
- cmd = self._commands[self.pt_index]
589
- cmd[1].append(abs_args)
590
- self.pt_index += 1
591
-
592
- def _moveTo(self, pt):
593
- if not self.seen_moveto:
594
- self.seen_moveto = True
595
- pt_coords = self._p(pt)
596
- self.add_point("rmoveto", pt_coords)
597
- # I set prev_move_idx here because add_point()
598
- # can change self.pt_index.
599
- self.prev_move_idx = self.pt_index - 1
600
-
601
- def _lineTo(self, pt):
602
- pt_coords = self._p(pt)
603
- self.add_point("rlineto", pt_coords)
604
-
605
- def _curveToOne(self, pt1, pt2, pt3):
606
- _p = self._p
607
- pt_coords = _p(pt1) + _p(pt2) + _p(pt3)
608
- self.add_point("rrcurveto", pt_coords)
609
-
610
- def _closePath(self):
611
- pass
612
-
613
- def _endPath(self):
614
- pass
615
-
616
- def restart(self, region_idx):
617
- self.pt_index = 0
618
- self.m_index = region_idx
619
- self._p0 = (0, 0)
620
-
621
- def getCommands(self):
622
- return self._commands
623
-
624
- def reorder_blend_args(self, commands, get_delta_func):
625
- """
626
- We first re-order the master coordinate values.
627
- For a moveto to lineto, the args are now arranged as::
628
-
629
- [ [master_0 x,y], [master_1 x,y], [master_2 x,y] ]
630
-
631
- We re-arrange this to::
632
-
633
- [ [master_0 x, master_1 x, master_2 x],
634
- [master_0 y, master_1 y, master_2 y]
635
- ]
636
-
637
- If the master values are all the same, we collapse the list to
638
- as single value instead of a list.
639
-
640
- We then convert this to::
641
-
642
- [ [master_0 x] + [x delta tuple] + [numBlends=1]
643
- [master_0 y] + [y delta tuple] + [numBlends=1]
644
- ]
645
- """
646
- for cmd in commands:
647
- # arg[i] is the set of arguments for this operator from master i.
648
- args = cmd[1]
649
- m_args = zip(*args)
650
- # m_args[n] is now all num_master args for the i'th argument
651
- # for this operation.
652
- cmd[1] = list(m_args)
653
- lastOp = None
654
- for cmd in commands:
655
- op = cmd[0]
656
- # masks are represented by two cmd's: first has only op names,
657
- # second has only args.
658
- if lastOp in ["hintmask", "cntrmask"]:
659
- coord = list(cmd[1])
660
- if not allEqual(coord):
661
- raise VarLibMergeError(
662
- "Hintmask values cannot differ between source fonts."
663
- )
664
- cmd[1] = [coord[0][0]]
665
- else:
666
- coords = cmd[1]
667
- new_coords = []
668
- for coord in coords:
669
- if allEqual(coord):
670
- new_coords.append(coord[0])
671
- else:
672
- # convert to deltas
673
- deltas = get_delta_func(coord)[1:]
674
- coord = [coord[0]] + deltas
675
- coord.append(1)
676
- new_coords.append(coord)
677
- cmd[1] = new_coords
678
- lastOp = op
679
- return commands
680
-
681
- def getCharString(
682
- self, private=None, globalSubrs=None, var_model=None, optimize=True
683
- ):
684
- commands = self._commands
685
- commands = self.reorder_blend_args(
686
- commands, partial(var_model.getDeltas, round=self.round)
687
- )
688
- if optimize:
689
- commands = specializeCommands(
690
- commands, generalizeFirst=False, maxstack=maxStackLimit
691
- )
692
- program = commandsToProgram(commands)
693
- charString = T2CharString(
694
- program=program, private=private, globalSubrs=globalSubrs
695
- )
696
- return charString
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/httpcore/_utils.py DELETED
@@ -1,36 +0,0 @@
1
- import select
2
- import socket
3
- import sys
4
- import typing
5
-
6
-
7
- def is_socket_readable(sock: typing.Optional[socket.socket]) -> bool:
8
- """
9
- Return whether a socket, as identifed by its file descriptor, is readable.
10
- "A socket is readable" means that the read buffer isn't empty, i.e. that calling
11
- .recv() on it would immediately return some data.
12
- """
13
- # NOTE: we want check for readability without actually attempting to read, because
14
- # we don't want to block forever if it's not readable.
15
-
16
- # In the case that the socket no longer exists, or cannot return a file
17
- # descriptor, we treat it as being readable, as if it the next read operation
18
- # on it is ready to return the terminating `b""`.
19
- sock_fd = None if sock is None else sock.fileno()
20
- if sock_fd is None or sock_fd < 0: # pragma: nocover
21
- return True
22
-
23
- # The implementation below was stolen from:
24
- # https://github.com/python-trio/trio/blob/20ee2b1b7376db637435d80e266212a35837ddcc/trio/_socket.py#L471-L478
25
- # See also: https://github.com/encode/httpcore/pull/193#issuecomment-703129316
26
-
27
- # Use select.select on Windows, and when poll is unavailable and select.poll
28
- # everywhere else. (E.g. When eventlet is in use. See #327)
29
- if (
30
- sys.platform == "win32" or getattr(select, "poll", None) is None
31
- ): # pragma: nocover
32
- rready, _, _ = select.select([sock_fd], [], [], 0)
33
- return bool(rready)
34
- p = select.poll()
35
- p.register(sock_fd, select.POLLIN)
36
- return bool(p.poll(0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Dao3/DaJuZi_OrangeCatTheGreat/style.css DELETED
@@ -1,84 +0,0 @@
1
- #col-container {
2
- max-width: 800px;
3
- margin-left: auto;
4
- margin-right: auto;
5
- }
6
- a {
7
- color: inherit;
8
- text-decoration: underline;
9
- }
10
- .gradio-container {
11
- font-family: 'IBM Plex Sans', sans-serif;
12
- }
13
- .gr-button {
14
- color: white;
15
- border-color: #9d66e5;
16
- background: #9d66e5;
17
- }
18
- input[type='range'] {
19
- accent-color: #9d66e5;
20
- }
21
- .dark input[type='range'] {
22
- accent-color: #dfdfdf;
23
- }
24
- .container {
25
- max-width: 800px;
26
- margin: auto;
27
- padding-top: 1.5rem;
28
- }
29
- #gallery {
30
- min-height: 22rem;
31
- margin-bottom: 15px;
32
- margin-left: auto;
33
- margin-right: auto;
34
- border-bottom-right-radius: .5rem !important;
35
- border-bottom-left-radius: .5rem !important;
36
- }
37
- #gallery>div>.h-full {
38
- min-height: 20rem;
39
- }
40
- .details:hover {
41
- text-decoration: underline;
42
- }
43
- .gr-button {
44
- white-space: nowrap;
45
- }
46
- .gr-button:focus {
47
- border-color: rgb(147 197 253 / var(--tw-border-opacity));
48
- outline: none;
49
- box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
50
- --tw-border-opacity: 1;
51
- --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
52
- --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
53
- --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
54
- --tw-ring-opacity: .5;
55
- }
56
- #advanced-options {
57
- margin-bottom: 20px;
58
- }
59
- .footer {
60
- margin-bottom: 45px;
61
- margin-top: 35px;
62
- text-align: center;
63
- border-bottom: 1px solid #e5e5e5;
64
- }
65
- .footer>p {
66
- font-size: .8rem;
67
- display: inline-block;
68
- padding: 0 10px;
69
- transform: translateY(10px);
70
- background: white;
71
- }
72
- .dark .logo{ filter: invert(1); }
73
- .dark .footer {
74
- border-color: #303030;
75
- }
76
- .dark .footer>p {
77
- background: #0b0f19;
78
- }
79
- .acknowledgments h4{
80
- margin: 1.25em 0 .25em 0;
81
- font-weight: bold;
82
- font-size: 115%;
83
- }
84
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Datasculptor/DescriptionGPT/tools/get_cc_tags.py DELETED
@@ -1,194 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates.
2
- import argparse
3
- import json
4
- from collections import defaultdict
5
-
6
- # This mapping is extracted from the official LVIS mapping:
7
- # https://github.com/lvis-dataset/lvis-api/blob/master/data/coco_to_synset.json
8
- COCO_SYNSET_CATEGORIES = [
9
- {"synset": "person.n.01", "coco_cat_id": 1},
10
- {"synset": "bicycle.n.01", "coco_cat_id": 2},
11
- {"synset": "car.n.01", "coco_cat_id": 3},
12
- {"synset": "motorcycle.n.01", "coco_cat_id": 4},
13
- {"synset": "airplane.n.01", "coco_cat_id": 5},
14
- {"synset": "bus.n.01", "coco_cat_id": 6},
15
- {"synset": "train.n.01", "coco_cat_id": 7},
16
- {"synset": "truck.n.01", "coco_cat_id": 8},
17
- {"synset": "boat.n.01", "coco_cat_id": 9},
18
- {"synset": "traffic_light.n.01", "coco_cat_id": 10},
19
- {"synset": "fireplug.n.01", "coco_cat_id": 11},
20
- {"synset": "stop_sign.n.01", "coco_cat_id": 13},
21
- {"synset": "parking_meter.n.01", "coco_cat_id": 14},
22
- {"synset": "bench.n.01", "coco_cat_id": 15},
23
- {"synset": "bird.n.01", "coco_cat_id": 16},
24
- {"synset": "cat.n.01", "coco_cat_id": 17},
25
- {"synset": "dog.n.01", "coco_cat_id": 18},
26
- {"synset": "horse.n.01", "coco_cat_id": 19},
27
- {"synset": "sheep.n.01", "coco_cat_id": 20},
28
- {"synset": "beef.n.01", "coco_cat_id": 21},
29
- {"synset": "elephant.n.01", "coco_cat_id": 22},
30
- {"synset": "bear.n.01", "coco_cat_id": 23},
31
- {"synset": "zebra.n.01", "coco_cat_id": 24},
32
- {"synset": "giraffe.n.01", "coco_cat_id": 25},
33
- {"synset": "backpack.n.01", "coco_cat_id": 27},
34
- {"synset": "umbrella.n.01", "coco_cat_id": 28},
35
- {"synset": "bag.n.04", "coco_cat_id": 31},
36
- {"synset": "necktie.n.01", "coco_cat_id": 32},
37
- {"synset": "bag.n.06", "coco_cat_id": 33},
38
- {"synset": "frisbee.n.01", "coco_cat_id": 34},
39
- {"synset": "ski.n.01", "coco_cat_id": 35},
40
- {"synset": "snowboard.n.01", "coco_cat_id": 36},
41
- {"synset": "ball.n.06", "coco_cat_id": 37},
42
- {"synset": "kite.n.03", "coco_cat_id": 38},
43
- {"synset": "baseball_bat.n.01", "coco_cat_id": 39},
44
- {"synset": "baseball_glove.n.01", "coco_cat_id": 40},
45
- {"synset": "skateboard.n.01", "coco_cat_id": 41},
46
- {"synset": "surfboard.n.01", "coco_cat_id": 42},
47
- {"synset": "tennis_racket.n.01", "coco_cat_id": 43},
48
- {"synset": "bottle.n.01", "coco_cat_id": 44},
49
- {"synset": "wineglass.n.01", "coco_cat_id": 46},
50
- {"synset": "cup.n.01", "coco_cat_id": 47},
51
- {"synset": "fork.n.01", "coco_cat_id": 48},
52
- {"synset": "knife.n.01", "coco_cat_id": 49},
53
- {"synset": "spoon.n.01", "coco_cat_id": 50},
54
- {"synset": "bowl.n.03", "coco_cat_id": 51},
55
- {"synset": "banana.n.02", "coco_cat_id": 52},
56
- {"synset": "apple.n.01", "coco_cat_id": 53},
57
- {"synset": "sandwich.n.01", "coco_cat_id": 54},
58
- {"synset": "orange.n.01", "coco_cat_id": 55},
59
- {"synset": "broccoli.n.01", "coco_cat_id": 56},
60
- {"synset": "carrot.n.01", "coco_cat_id": 57},
61
- # {"synset": "frank.n.02", "coco_cat_id": 58},
62
- {"synset": "sausage.n.01", "coco_cat_id": 58},
63
- {"synset": "pizza.n.01", "coco_cat_id": 59},
64
- {"synset": "doughnut.n.02", "coco_cat_id": 60},
65
- {"synset": "cake.n.03", "coco_cat_id": 61},
66
- {"synset": "chair.n.01", "coco_cat_id": 62},
67
- {"synset": "sofa.n.01", "coco_cat_id": 63},
68
- {"synset": "pot.n.04", "coco_cat_id": 64},
69
- {"synset": "bed.n.01", "coco_cat_id": 65},
70
- {"synset": "dining_table.n.01", "coco_cat_id": 67},
71
- {"synset": "toilet.n.02", "coco_cat_id": 70},
72
- {"synset": "television_receiver.n.01", "coco_cat_id": 72},
73
- {"synset": "laptop.n.01", "coco_cat_id": 73},
74
- {"synset": "mouse.n.04", "coco_cat_id": 74},
75
- {"synset": "remote_control.n.01", "coco_cat_id": 75},
76
- {"synset": "computer_keyboard.n.01", "coco_cat_id": 76},
77
- {"synset": "cellular_telephone.n.01", "coco_cat_id": 77},
78
- {"synset": "microwave.n.02", "coco_cat_id": 78},
79
- {"synset": "oven.n.01", "coco_cat_id": 79},
80
- {"synset": "toaster.n.02", "coco_cat_id": 80},
81
- {"synset": "sink.n.01", "coco_cat_id": 81},
82
- {"synset": "electric_refrigerator.n.01", "coco_cat_id": 82},
83
- {"synset": "book.n.01", "coco_cat_id": 84},
84
- {"synset": "clock.n.01", "coco_cat_id": 85},
85
- {"synset": "vase.n.01", "coco_cat_id": 86},
86
- {"synset": "scissors.n.01", "coco_cat_id": 87},
87
- {"synset": "teddy.n.01", "coco_cat_id": 88},
88
- {"synset": "hand_blower.n.01", "coco_cat_id": 89},
89
- {"synset": "toothbrush.n.01", "coco_cat_id": 90},
90
- ]
91
-
92
- def map_name(x):
93
- x = x.replace('_', ' ')
94
- if '(' in x:
95
- x = x[:x.find('(')]
96
- return x.lower().strip()
97
-
98
- if __name__ == '__main__':
99
- parser = argparse.ArgumentParser()
100
- parser.add_argument('--cc_ann', default='datasets/cc3m/train_image_info.json')
101
- parser.add_argument('--out_path', default='datasets/cc3m/train_image_info_tags.json')
102
- parser.add_argument('--keep_images', action='store_true')
103
- parser.add_argument('--allcaps', action='store_true')
104
- parser.add_argument('--cat_path', default='')
105
- parser.add_argument('--convert_caption', action='store_true')
106
- # parser.add_argument('--lvis_ann', default='datasets/lvis/lvis_v1_val.json')
107
- args = parser.parse_args()
108
-
109
- # lvis_data = json.load(open(args.lvis_ann, 'r'))
110
- cc_data = json.load(open(args.cc_ann, 'r'))
111
- if args.convert_caption:
112
- num_caps = 0
113
- caps = defaultdict(list)
114
- for x in cc_data['annotations']:
115
- caps[x['image_id']].append(x['caption'])
116
- for x in cc_data['images']:
117
- x['captions'] = caps[x['id']]
118
- num_caps += len(x['captions'])
119
- print('# captions', num_caps)
120
-
121
- if args.cat_path != '':
122
- print('Loading', args.cat_path)
123
- cats = json.load(open(args.cat_path))['categories']
124
- if 'synonyms' not in cats[0]:
125
- cocoid2synset = {x['coco_cat_id']: x['synset'] \
126
- for x in COCO_SYNSET_CATEGORIES}
127
- synset2synonyms = {x['synset']: x['synonyms'] \
128
- for x in cc_data['categories']}
129
- for x in cats:
130
- synonyms = synset2synonyms[cocoid2synset[x['id']]]
131
- x['synonyms'] = synonyms
132
- x['frequency'] = 'f'
133
- cc_data['categories'] = cats
134
-
135
- id2cat = {x['id']: x for x in cc_data['categories']}
136
- class_count = {x['id']: 0 for x in cc_data['categories']}
137
- class_data = {x['id']: [' ' + map_name(xx) + ' ' for xx in x['synonyms']] \
138
- for x in cc_data['categories']}
139
- num_examples = 5
140
- examples = {x['id']: [] for x in cc_data['categories']}
141
-
142
- print('class_data', class_data)
143
-
144
- images = []
145
- for i, x in enumerate(cc_data['images']):
146
- if i % 10000 == 0:
147
- print(i, len(cc_data['images']))
148
- if args.allcaps:
149
- caption = (' '.join(x['captions'])).lower()
150
- else:
151
- caption = x['captions'][0].lower()
152
- x['pos_category_ids'] = []
153
- for cat_id, cat_names in class_data.items():
154
- find = False
155
- for c in cat_names:
156
- if c in caption or caption.startswith(c[1:]) \
157
- or caption.endswith(c[:-1]):
158
- find = True
159
- break
160
- if find:
161
- x['pos_category_ids'].append(cat_id)
162
- class_count[cat_id] += 1
163
- if len(examples[cat_id]) < num_examples:
164
- examples[cat_id].append(caption)
165
- if len(x['pos_category_ids']) > 0 or args.keep_images:
166
- images.append(x)
167
-
168
- zero_class = []
169
- for cat_id, count in class_count.items():
170
- print(id2cat[cat_id]['name'], count, end=', ')
171
- if count == 0:
172
- zero_class.append(id2cat[cat_id])
173
- print('==')
174
- print('zero class', zero_class)
175
-
176
- # for freq in ['r', 'c', 'f']:
177
- # print('#cats', freq, len([x for x in cc_data['categories'] \
178
- # if x['frequency'] == freq] and class_count[x['id']] > 0))
179
-
180
- for freq in ['r', 'c', 'f']:
181
- print('#Images', freq, sum([v for k, v in class_count.items() \
182
- if id2cat[k]['frequency'] == freq]))
183
-
184
- try:
185
- out_data = {'images': images, 'categories': cc_data['categories'], \
186
- 'annotations': []}
187
- for k, v in out_data.items():
188
- print(k, len(v))
189
- if args.keep_images and not args.out_path.endswith('_full.json'):
190
- args.out_path = args.out_path[:-5] + '_full.json'
191
- print('Writing to', args.out_path)
192
- json.dump(out_data, open(args.out_path, 'w'))
193
- except:
194
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Dinoking/Guccio-AI-Designer/netdissect/upsegmodel/resnext.py DELETED
@@ -1,183 +0,0 @@
1
- import os
2
- import sys
3
- import torch
4
- import torch.nn as nn
5
- import math
6
- try:
7
- from lib.nn import SynchronizedBatchNorm2d
8
- except ImportError:
9
- from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d
10
-
11
- try:
12
- from urllib import urlretrieve
13
- except ImportError:
14
- from urllib.request import urlretrieve
15
-
16
-
17
- __all__ = ['ResNeXt', 'resnext101'] # support resnext 101
18
-
19
-
20
- model_urls = {
21
- #'resnext50': 'http://sceneparsing.csail.mit.edu/model/pretrained_resnet/resnext50-imagenet.pth',
22
- 'resnext101': 'http://sceneparsing.csail.mit.edu/model/pretrained_resnet/resnext101-imagenet.pth'
23
- }
24
-
25
-
26
- def conv3x3(in_planes, out_planes, stride=1):
27
- "3x3 convolution with padding"
28
- return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
29
- padding=1, bias=False)
30
-
31
-
32
- class GroupBottleneck(nn.Module):
33
- expansion = 2
34
-
35
- def __init__(self, inplanes, planes, stride=1, groups=1, downsample=None):
36
- super(GroupBottleneck, self).__init__()
37
- self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
38
- self.bn1 = SynchronizedBatchNorm2d(planes)
39
- self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
40
- padding=1, groups=groups, bias=False)
41
- self.bn2 = SynchronizedBatchNorm2d(planes)
42
- self.conv3 = nn.Conv2d(planes, planes * 2, kernel_size=1, bias=False)
43
- self.bn3 = SynchronizedBatchNorm2d(planes * 2)
44
- self.relu = nn.ReLU(inplace=True)
45
- self.downsample = downsample
46
- self.stride = stride
47
-
48
- def forward(self, x):
49
- residual = x
50
-
51
- out = self.conv1(x)
52
- out = self.bn1(out)
53
- out = self.relu(out)
54
-
55
- out = self.conv2(out)
56
- out = self.bn2(out)
57
- out = self.relu(out)
58
-
59
- out = self.conv3(out)
60
- out = self.bn3(out)
61
-
62
- if self.downsample is not None:
63
- residual = self.downsample(x)
64
-
65
- out += residual
66
- out = self.relu(out)
67
-
68
- return out
69
-
70
-
71
- class ResNeXt(nn.Module):
72
-
73
- def __init__(self, block, layers, groups=32, num_classes=1000):
74
- self.inplanes = 128
75
- super(ResNeXt, self).__init__()
76
- self.conv1 = conv3x3(3, 64, stride=2)
77
- self.bn1 = SynchronizedBatchNorm2d(64)
78
- self.relu1 = nn.ReLU(inplace=True)
79
- self.conv2 = conv3x3(64, 64)
80
- self.bn2 = SynchronizedBatchNorm2d(64)
81
- self.relu2 = nn.ReLU(inplace=True)
82
- self.conv3 = conv3x3(64, 128)
83
- self.bn3 = SynchronizedBatchNorm2d(128)
84
- self.relu3 = nn.ReLU(inplace=True)
85
- self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
86
-
87
- self.layer1 = self._make_layer(block, 128, layers[0], groups=groups)
88
- self.layer2 = self._make_layer(block, 256, layers[1], stride=2, groups=groups)
89
- self.layer3 = self._make_layer(block, 512, layers[2], stride=2, groups=groups)
90
- self.layer4 = self._make_layer(block, 1024, layers[3], stride=2, groups=groups)
91
- self.avgpool = nn.AvgPool2d(7, stride=1)
92
- self.fc = nn.Linear(1024 * block.expansion, num_classes)
93
-
94
- for m in self.modules():
95
- if isinstance(m, nn.Conv2d):
96
- n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels // m.groups
97
- m.weight.data.normal_(0, math.sqrt(2. / n))
98
- elif isinstance(m, SynchronizedBatchNorm2d):
99
- m.weight.data.fill_(1)
100
- m.bias.data.zero_()
101
-
102
- def _make_layer(self, block, planes, blocks, stride=1, groups=1):
103
- downsample = None
104
- if stride != 1 or self.inplanes != planes * block.expansion:
105
- downsample = nn.Sequential(
106
- nn.Conv2d(self.inplanes, planes * block.expansion,
107
- kernel_size=1, stride=stride, bias=False),
108
- SynchronizedBatchNorm2d(planes * block.expansion),
109
- )
110
-
111
- layers = []
112
- layers.append(block(self.inplanes, planes, stride, groups, downsample))
113
- self.inplanes = planes * block.expansion
114
- for i in range(1, blocks):
115
- layers.append(block(self.inplanes, planes, groups=groups))
116
-
117
- return nn.Sequential(*layers)
118
-
119
- def forward(self, x):
120
- x = self.relu1(self.bn1(self.conv1(x)))
121
- x = self.relu2(self.bn2(self.conv2(x)))
122
- x = self.relu3(self.bn3(self.conv3(x)))
123
- x = self.maxpool(x)
124
-
125
- x = self.layer1(x)
126
- x = self.layer2(x)
127
- x = self.layer3(x)
128
- x = self.layer4(x)
129
-
130
- x = self.avgpool(x)
131
- x = x.view(x.size(0), -1)
132
- x = self.fc(x)
133
-
134
- return x
135
-
136
-
137
- '''
138
- def resnext50(pretrained=False, **kwargs):
139
- """Constructs a ResNet-50 model.
140
-
141
- Args:
142
- pretrained (bool): If True, returns a model pre-trained on Places
143
- """
144
- model = ResNeXt(GroupBottleneck, [3, 4, 6, 3], **kwargs)
145
- if pretrained:
146
- model.load_state_dict(load_url(model_urls['resnext50']), strict=False)
147
- return model
148
- '''
149
-
150
-
151
- def resnext101(pretrained=False, **kwargs):
152
- """Constructs a ResNet-101 model.
153
-
154
- Args:
155
- pretrained (bool): If True, returns a model pre-trained on Places
156
- """
157
- model = ResNeXt(GroupBottleneck, [3, 4, 23, 3], **kwargs)
158
- if pretrained:
159
- model.load_state_dict(load_url(model_urls['resnext101']), strict=False)
160
- return model
161
-
162
-
163
- # def resnext152(pretrained=False, **kwargs):
164
- # """Constructs a ResNeXt-152 model.
165
- #
166
- # Args:
167
- # pretrained (bool): If True, returns a model pre-trained on Places
168
- # """
169
- # model = ResNeXt(GroupBottleneck, [3, 8, 36, 3], **kwargs)
170
- # if pretrained:
171
- # model.load_state_dict(load_url(model_urls['resnext152']))
172
- # return model
173
-
174
-
175
- def load_url(url, model_dir='./pretrained', map_location=None):
176
- if not os.path.exists(model_dir):
177
- os.makedirs(model_dir)
178
- filename = url.split('/')[-1]
179
- cached_file = os.path.join(model_dir, filename)
180
- if not os.path.exists(cached_file):
181
- sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
182
- urlretrieve(url, cached_file)
183
- return torch.load(cached_file, map_location=map_location)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DragGan/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/utils/__init__.py DELETED
File without changes
spaces/Eddycrack864/Applio-Inference/lib/uvr5_pack/lib_v5/nets_123821KB.py DELETED
@@ -1,122 +0,0 @@
1
- import torch
2
- from torch import nn
3
- import torch.nn.functional as F
4
-
5
- from . import layers_123821KB as layers
6
-
7
-
8
- class BaseASPPNet(nn.Module):
9
- def __init__(self, nin, ch, dilations=(4, 8, 16)):
10
- super(BaseASPPNet, self).__init__()
11
- self.enc1 = layers.Encoder(nin, ch, 3, 2, 1)
12
- self.enc2 = layers.Encoder(ch, ch * 2, 3, 2, 1)
13
- self.enc3 = layers.Encoder(ch * 2, ch * 4, 3, 2, 1)
14
- self.enc4 = layers.Encoder(ch * 4, ch * 8, 3, 2, 1)
15
-
16
- self.aspp = layers.ASPPModule(ch * 8, ch * 16, dilations)
17
-
18
- self.dec4 = layers.Decoder(ch * (8 + 16), ch * 8, 3, 1, 1)
19
- self.dec3 = layers.Decoder(ch * (4 + 8), ch * 4, 3, 1, 1)
20
- self.dec2 = layers.Decoder(ch * (2 + 4), ch * 2, 3, 1, 1)
21
- self.dec1 = layers.Decoder(ch * (1 + 2), ch, 3, 1, 1)
22
-
23
- def __call__(self, x):
24
- h, e1 = self.enc1(x)
25
- h, e2 = self.enc2(h)
26
- h, e3 = self.enc3(h)
27
- h, e4 = self.enc4(h)
28
-
29
- h = self.aspp(h)
30
-
31
- h = self.dec4(h, e4)
32
- h = self.dec3(h, e3)
33
- h = self.dec2(h, e2)
34
- h = self.dec1(h, e1)
35
-
36
- return h
37
-
38
-
39
- class CascadedASPPNet(nn.Module):
40
- def __init__(self, n_fft):
41
- super(CascadedASPPNet, self).__init__()
42
- self.stg1_low_band_net = BaseASPPNet(2, 32)
43
- self.stg1_high_band_net = BaseASPPNet(2, 32)
44
-
45
- self.stg2_bridge = layers.Conv2DBNActiv(34, 16, 1, 1, 0)
46
- self.stg2_full_band_net = BaseASPPNet(16, 32)
47
-
48
- self.stg3_bridge = layers.Conv2DBNActiv(66, 32, 1, 1, 0)
49
- self.stg3_full_band_net = BaseASPPNet(32, 64)
50
-
51
- self.out = nn.Conv2d(64, 2, 1, bias=False)
52
- self.aux1_out = nn.Conv2d(32, 2, 1, bias=False)
53
- self.aux2_out = nn.Conv2d(32, 2, 1, bias=False)
54
-
55
- self.max_bin = n_fft // 2
56
- self.output_bin = n_fft // 2 + 1
57
-
58
- self.offset = 128
59
-
60
- def forward(self, x, aggressiveness=None):
61
- mix = x.detach()
62
- x = x.clone()
63
-
64
- x = x[:, :, : self.max_bin]
65
-
66
- bandw = x.size()[2] // 2
67
- aux1 = torch.cat(
68
- [
69
- self.stg1_low_band_net(x[:, :, :bandw]),
70
- self.stg1_high_band_net(x[:, :, bandw:]),
71
- ],
72
- dim=2,
73
- )
74
-
75
- h = torch.cat([x, aux1], dim=1)
76
- aux2 = self.stg2_full_band_net(self.stg2_bridge(h))
77
-
78
- h = torch.cat([x, aux1, aux2], dim=1)
79
- h = self.stg3_full_band_net(self.stg3_bridge(h))
80
-
81
- mask = torch.sigmoid(self.out(h))
82
- mask = F.pad(
83
- input=mask,
84
- pad=(0, 0, 0, self.output_bin - mask.size()[2]),
85
- mode="replicate",
86
- )
87
-
88
- if self.training:
89
- aux1 = torch.sigmoid(self.aux1_out(aux1))
90
- aux1 = F.pad(
91
- input=aux1,
92
- pad=(0, 0, 0, self.output_bin - aux1.size()[2]),
93
- mode="replicate",
94
- )
95
- aux2 = torch.sigmoid(self.aux2_out(aux2))
96
- aux2 = F.pad(
97
- input=aux2,
98
- pad=(0, 0, 0, self.output_bin - aux2.size()[2]),
99
- mode="replicate",
100
- )
101
- return mask * mix, aux1 * mix, aux2 * mix
102
- else:
103
- if aggressiveness:
104
- mask[:, :, : aggressiveness["split_bin"]] = torch.pow(
105
- mask[:, :, : aggressiveness["split_bin"]],
106
- 1 + aggressiveness["value"] / 3,
107
- )
108
- mask[:, :, aggressiveness["split_bin"] :] = torch.pow(
109
- mask[:, :, aggressiveness["split_bin"] :],
110
- 1 + aggressiveness["value"],
111
- )
112
-
113
- return mask * mix
114
-
115
- def predict(self, x_mag, aggressiveness=None):
116
- h = self.forward(x_mag, aggressiveness)
117
-
118
- if self.offset > 0:
119
- h = h[:, :, :, self.offset : -self.offset]
120
- assert h.size()[3] > 0
121
-
122
- return h
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Felix123456/bingo/src/components/learn-more.tsx DELETED
@@ -1,39 +0,0 @@
1
- import React from 'react'
2
- import { SourceAttribution } from '@/lib/bots/bing/types'
3
-
4
- export interface LearnMoreProps {
5
- sourceAttributions?: SourceAttribution[]
6
- }
7
-
8
- export function LearnMore({ sourceAttributions }: LearnMoreProps) {
9
- if (!sourceAttributions?.length) {
10
- return null
11
- }
12
-
13
- return (
14
- <div className="learn-more-root" role="list" aria-label="了解详细信息:">
15
- <div className="learn-more">了解详细信息:</div>
16
- <div className="attribution-container">
17
- <div className="attribution-items">
18
- {sourceAttributions.map((attribution, index) => {
19
- const { providerDisplayName, seeMoreUrl } = attribution
20
- const { host } = new URL(seeMoreUrl)
21
- return (
22
- <a
23
- key={index}
24
- className="attribution-item"
25
- target="_blank"
26
- role="listitem"
27
- href={seeMoreUrl}
28
- title={providerDisplayName}
29
- tabIndex={index}
30
- >
31
- {index + 1}. {host}
32
- </a>
33
- )
34
- })}
35
- </div>
36
- </div>
37
- </div>
38
- )
39
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Fengbinbin/gpt-academic/crazy_functions/test_project/cpp/cppipc/queue.h DELETED
@@ -1,216 +0,0 @@
1
- #pragma once
2
-
3
- #include <type_traits>
4
- #include <new>
5
- #include <utility> // [[since C++14]]: std::exchange
6
- #include <algorithm>
7
- #include <atomic>
8
- #include <tuple>
9
- #include <thread>
10
- #include <chrono>
11
- #include <string>
12
- #include <cassert> // assert
13
-
14
- #include "libipc/def.h"
15
- #include "libipc/shm.h"
16
- #include "libipc/rw_lock.h"
17
-
18
- #include "libipc/utility/log.h"
19
- #include "libipc/platform/detail.h"
20
- #include "libipc/circ/elem_def.h"
21
-
22
- namespace ipc {
23
- namespace detail {
24
-
25
- class queue_conn {
26
- protected:
27
- circ::cc_t connected_ = 0;
28
- shm::handle elems_h_;
29
-
30
- template <typename Elems>
31
- Elems* open(char const * name) {
32
- if (name == nullptr || name[0] == '\0') {
33
- ipc::error("fail open waiter: name is empty!\n");
34
- return nullptr;
35
- }
36
- if (!elems_h_.acquire(name, sizeof(Elems))) {
37
- return nullptr;
38
- }
39
- auto elems = static_cast<Elems*>(elems_h_.get());
40
- if (elems == nullptr) {
41
- ipc::error("fail acquire elems: %s\n", name);
42
- return nullptr;
43
- }
44
- elems->init();
45
- return elems;
46
- }
47
-
48
- void close() {
49
- elems_h_.release();
50
- }
51
-
52
- public:
53
- queue_conn() = default;
54
- queue_conn(const queue_conn&) = delete;
55
- queue_conn& operator=(const queue_conn&) = delete;
56
-
57
- bool connected() const noexcept {
58
- return connected_ != 0;
59
- }
60
-
61
- circ::cc_t connected_id() const noexcept {
62
- return connected_;
63
- }
64
-
65
- template <typename Elems>
66
- auto connect(Elems* elems) noexcept
67
- /*needs 'optional' here*/
68
- -> std::tuple<bool, bool, decltype(std::declval<Elems>().cursor())> {
69
- if (elems == nullptr) return {};
70
- // if it's already connected, just return
71
- if (connected()) return {connected(), false, 0};
72
- connected_ = elems->connect_receiver();
73
- return {connected(), true, elems->cursor()};
74
- }
75
-
76
- template <typename Elems>
77
- bool disconnect(Elems* elems) noexcept {
78
- if (elems == nullptr) return false;
79
- // if it's already disconnected, just return false
80
- if (!connected()) return false;
81
- elems->disconnect_receiver(std::exchange(connected_, 0));
82
- return true;
83
- }
84
- };
85
-
86
- template <typename Elems>
87
- class queue_base : public queue_conn {
88
- using base_t = queue_conn;
89
-
90
- public:
91
- using elems_t = Elems;
92
- using policy_t = typename elems_t::policy_t;
93
-
94
- protected:
95
- elems_t * elems_ = nullptr;
96
- decltype(std::declval<elems_t>().cursor()) cursor_ = 0;
97
- bool sender_flag_ = false;
98
-
99
- public:
100
- using base_t::base_t;
101
-
102
- queue_base() = default;
103
-
104
- explicit queue_base(char const * name)
105
- : queue_base{} {
106
- elems_ = open<elems_t>(name);
107
- }
108
-
109
- explicit queue_base(elems_t * elems) noexcept
110
- : queue_base{} {
111
- assert(elems != nullptr);
112
- elems_ = elems;
113
- }
114
-
115
- /* not virtual */ ~queue_base() {
116
- base_t::close();
117
- }
118
-
119
- elems_t * elems() noexcept { return elems_; }
120
- elems_t const * elems() const noexcept { return elems_; }
121
-
122
- bool ready_sending() noexcept {
123
- if (elems_ == nullptr) return false;
124
- return sender_flag_ || (sender_flag_ = elems_->connect_sender());
125
- }
126
-
127
- void shut_sending() noexcept {
128
- if (elems_ == nullptr) return;
129
- if (!sender_flag_) return;
130
- elems_->disconnect_sender();
131
- }
132
-
133
- bool connect() noexcept {
134
- auto tp = base_t::connect(elems_);
135
- if (std::get<0>(tp) && std::get<1>(tp)) {
136
- cursor_ = std::get<2>(tp);
137
- return true;
138
- }
139
- return std::get<0>(tp);
140
- }
141
-
142
- bool disconnect() noexcept {
143
- return base_t::disconnect(elems_);
144
- }
145
-
146
- std::size_t conn_count() const noexcept {
147
- return (elems_ == nullptr) ? static_cast<std::size_t>(invalid_value) : elems_->conn_count();
148
- }
149
-
150
- bool valid() const noexcept {
151
- return elems_ != nullptr;
152
- }
153
-
154
- bool empty() const noexcept {
155
- return !valid() || (cursor_ == elems_->cursor());
156
- }
157
-
158
- template <typename T, typename F, typename... P>
159
- bool push(F&& prep, P&&... params) {
160
- if (elems_ == nullptr) return false;
161
- return elems_->push(this, [&](void* p) {
162
- if (prep(p)) ::new (p) T(std::forward<P>(params)...);
163
- });
164
- }
165
-
166
- template <typename T, typename F, typename... P>
167
- bool force_push(F&& prep, P&&... params) {
168
- if (elems_ == nullptr) return false;
169
- return elems_->force_push(this, [&](void* p) {
170
- if (prep(p)) ::new (p) T(std::forward<P>(params)...);
171
- });
172
- }
173
-
174
- template <typename T, typename F>
175
- bool pop(T& item, F&& out) {
176
- if (elems_ == nullptr) {
177
- return false;
178
- }
179
- return elems_->pop(this, &(this->cursor_), [&item](void* p) {
180
- ::new (&item) T(std::move(*static_cast<T*>(p)));
181
- }, std::forward<F>(out));
182
- }
183
- };
184
-
185
- } // namespace detail
186
-
187
- template <typename T, typename Policy>
188
- class queue final : public detail::queue_base<typename Policy::template elems_t<sizeof(T), alignof(T)>> {
189
- using base_t = detail::queue_base<typename Policy::template elems_t<sizeof(T), alignof(T)>>;
190
-
191
- public:
192
- using value_t = T;
193
-
194
- using base_t::base_t;
195
-
196
- template <typename... P>
197
- bool push(P&&... params) {
198
- return base_t::template push<T>(std::forward<P>(params)...);
199
- }
200
-
201
- template <typename... P>
202
- bool force_push(P&&... params) {
203
- return base_t::template force_push<T>(std::forward<P>(params)...);
204
- }
205
-
206
- bool pop(T& item) {
207
- return base_t::pop(item, [](bool) {});
208
- }
209
-
210
- template <typename F>
211
- bool pop(T& item, F&& out) {
212
- return base_t::pop(item, std::forward<F>(out));
213
- }
214
- };
215
-
216
- } // namespace ipc