parquet-converter commited on
Commit
4230bd7
·
1 Parent(s): 12c1a30

Update parquet files (step 24 of 121)

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/1gistliPinn/ChatGPT4/Examples/Aurora 3D Presentation 20.01.30 Crack [Full Review] [2021].md +0 -6
  2. spaces/1gistliPinn/ChatGPT4/Examples/Elysium 720p In Dual Audio Hindi [REPACK].md +0 -11
  3. spaces/1gistliPinn/ChatGPT4/Examples/Frontdesigner 3 0 Full !EXCLUSIVE! Version Download.rar.md +0 -9
  4. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Android Gameplay How to Sync Your Progress and Earn Rewards Across Devices.md +0 -162
  5. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Bloons TD 6 APK How to Install and Play the Latest Version of the Epic Monkey Game.md +0 -162
  6. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Boss Domino APK A Local Indonesian Game with Various Slots.md +0 -132
  7. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Car Parking Multiplayer APK A Free Game with Realistic Cars and Maps.md +0 -66
  8. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/College Romance Season 1 A Hilarious Story of Three BFFs and Their Love Lives.md +0 -111
  9. spaces/1phancelerku/anime-remove-background/ARK Survival Evolved - Primal Fear Mod A Guide to the Best Dinos and Items.md +0 -125
  10. spaces/1phancelerku/anime-remove-background/Download Business WhatsApp Sender 7.0.1.1 for Free and Boost Your Business.md +0 -124
  11. spaces/1phancelerku/anime-remove-background/Experience the Epic Battle of Godzilla and Kong in PUBG Mobile 1.4 (APK).md +0 -103
  12. spaces/AIConsultant/MusicGen/audiocraft/optim/linear_warmup_lr_scheduler.py +0 -35
  13. spaces/AIGC-Audio/AudioGPT/NeuralSeq/data_gen/tts/wav_processors/base_processor.py +0 -25
  14. spaces/AIGC-Audio/Make_An_Audio_inpaint/vocoder/bigvgan/alias_free_torch/resample.py +0 -49
  15. spaces/AILab-CVC/EvalCrafter/app.py +0 -121
  16. spaces/ALSv/FSW/roop/processors/frame/core.py +0 -91
  17. spaces/AONYLMR/White-box-Cartoonization/wbc/guided_filter.py +0 -87
  18. spaces/AchyuthGamer/OpenGPT/g4f/Provider/Acytoo.py +0 -51
  19. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/gridtable/input/PointerUpDownCell.js +0 -13
  20. spaces/Alpaca233/SadTalker/src/audio2pose_models/res_unet.py +0 -65
  21. spaces/Alycer/VITS-Umamusume-voice-synthesizer/hubert_model.py +0 -221
  22. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/singlestep_dpm_solver.md +0 -20
  23. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +0 -494
  24. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_flax.py +0 -99
  25. spaces/Andy1621/uniformer_image_detection/configs/res2net/mask_rcnn_r2_101_fpn_2x_coco.py +0 -4
  26. spaces/Andy1621/uniformer_image_detection/mmdet/models/roi_heads/double_roi_head.py +0 -33
  27. spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/AutoGPTQ_loader.py +0 -72
  28. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/fileio/parse.py +0 -97
  29. spaces/Anustup/NS_AI_LABS/src/vad.py +0 -477
  30. spaces/Ariharasudhan/YoloV5/utils/loss.py +0 -234
  31. spaces/Arnx/MusicGenXvAKN/audiocraft/modules/conv.py +0 -245
  32. spaces/Ash123/stable-diffusion-nano/share_btn.py +0 -60
  33. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/utils/appdirs.py +0 -52
  34. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/tomli/__init__.py +0 -11
  35. spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_400ep_LSJ.py +0 -14
  36. spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/modeling/test_backbone.py +0 -34
  37. spaces/Bart92/RVC_HF/demucs/__main__.py +0 -317
  38. spaces/Benson/text-generation/Examples/Blockman Go Skyblock Hack Apk.md +0 -86
  39. spaces/Benson/text-generation/Examples/Conseguir Sobre l Descarga Gratuita 2023 Apk.md +0 -65
  40. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/distlib/resources.py +0 -358
  41. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/segment.py +0 -739
  42. spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/text_file.py +0 -287
  43. spaces/BrianL/CoE197-Fil-DialectTranslator/README.md +0 -13
  44. spaces/CForGETaass/vits-uma-genshin-honkai/modules.py +0 -388
  45. spaces/ChandraMohanNayal/AutoGPT/autogpt/commands/web_playwright.py +0 -80
  46. spaces/Codecooker/rvcapi/src/infer_pack/modules.py +0 -522
  47. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/ImageMorph.py +0 -254
  48. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fastapi/_compat.py +0 -616
  49. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/colorLib/builder.py +0 -659
  50. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/h11/_writers.py +0 -145
spaces/1gistliPinn/ChatGPT4/Examples/Aurora 3D Presentation 20.01.30 Crack [Full Review] [2021].md DELETED
@@ -1,6 +0,0 @@
1
- <h2>Aurora 3D Presentation 20.01.30 Crack [Full review]</h2><br /><p><b><b>Download</b> &#10042; <a href="https://imgfil.com/2uxY7o">https://imgfil.com/2uxY7o</a></b></p><br /><br />
2
-
3
- This page is about Aurora 3D Templates,contains Aurora Printable Disney ... 3D Presentation 16.01.07 Multilingual Full Keygen,Aurora 3D Text & Logo Maker and more... ... Aurora 3D Text & Logo Maker 20.01.30 + Crack. Aurora 3D Templates Aurora 3D Text & Logo Maker - Free download and software reviews - CNET ... 1fdad05405<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Elysium 720p In Dual Audio Hindi [REPACK].md DELETED
@@ -1,11 +0,0 @@
1
- <br />
2
- <h1>Elysium: A Dystopian Sci-Fi Thriller in Hindi</h1>
3
- <p>Elysium is a 2013 American dystopian science fiction action film written, produced, and directed by Neill Blomkamp. It was Blomkamp's second directorial effort. The film stars Matt Damon and Jodie Foster alongside Sharlto Copley, Alice Braga, Diego Luna, Wagner Moura, and William Fichtner. [^2^]</p>
4
- <p>The film takes place on both a ravaged Earth and a luxurious artificial world called Elysium. The planet’s citizens live in poverty while the rich and powerful live on Elysium, an orbiting space station just outside of Earth’s atmosphere. Spider, a hacker living on Earth in Los Angeles, runs three space shuttle flights to Elysium to smuggle people in to use their Med-Bays, devices that can heal any disease or condition. Elysium Defense Secretary Delacourt shoots down two of the spacecraft in space, killing everyone on board, and has everyone on the shuttle that does reach Elysium arrested and deported. Elysium President Patel reprimands Delacourt for her actions, threatening discharge for any more actions of a similar manner. In retaliation, she offers Armadyne Corp CEO John Carlyle defense contracts for life in exchange for a program that will allow Delacourt to conduct a coup and install herself as president. Carlyle writes the program and stores it inside his brain. [^2^]</p>
5
- <h2>Elysium 720p In Dual Audio Hindi</h2><br /><p><b><b>Download</b> &#8250;&#8250;&#8250; <a href="https://imgfil.com/2uxWWg">https://imgfil.com/2uxWWg</a></b></p><br /><br />
6
- <p>On Earth, parolee Max Da Costa is working for Armadyne Corp as a laborer when he is accidentally exposed to a lethal dose of radiation. He is given medication and told he has five days to live after being dismissed by Carlyle from Armadyne. Max and his friend Julio approach Spider and make a deal: If Max can successfully steal information from a powerful Elysium citizen, in exchange Spider will give Max a shuttle ride to Elysium to use a Med-Bay to cure his condition. Max agrees to steal the information from Carlyle's brain, unaware that it contains the coup program. [^2^]</p>
7
- <p>When Delacourt learns that the information she needs to become president was stolen from Carlyle's brain, she sends the notorious agent Kruger to hunt down Max and recover the software at any cost. Max must fight for his life and his chance to reach Elysium before it's too late. [^2^]</p>
8
- <p>Elysium is a film that offers deliberate social commentary that explores political and sociological themes such as immigration, overpopulation, transhumanism, health care, worker exploitation, the justice system, technology, and social class issues. [^2^] It received positive reviews from critics but was considered disappointing after Blomkamp's first film District 9. [^2^] It grossed $286 million worldwide and was released on DVD and Blu-ray on December 17, 2013. [^2^]</p>
9
- <p>If you are looking for a thrilling and thought-provoking sci-fi film with amazing visuals and action scenes, you should watch Elysium in Hindi dubbed dual audio 720p quality. You can download it from <a href="https://mkvbollyhut.blogspot.com/2020/07/elysium-2013-bluray-hindi-dubbed-dual.html">this link</a> [^1^] or watch it online on various streaming platforms.</p> d5da3c52bf<br />
10
- <br />
11
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Frontdesigner 3 0 Full !EXCLUSIVE! Version Download.rar.md DELETED
@@ -1,9 +0,0 @@
1
- <h2>frontdesigner 3 0 FULL Version download.rar</h2><br /><p><b><b>Download Zip</b> &#10031; <a href="https://imgfil.com/2uy1kM">https://imgfil.com/2uy1kM</a></b></p><br /><br />
2
-
3
- August 14, 2020 - IBM Lotus Domino Server 8.5.3 64-bit. Note that Lotus Domino 8.5 was a 64-bit version of the application, and the internal data structures are . 1 byte.
4
- There are currently 64-bit versions available in the environment, so we cannot use 64-bit types and data structures, but we can use 32-bit types and data structures such as int32 which are .4 bytes in size.
5
- How can I tell which version is using 64-bit or 32-bit frameworks and use 64-bit versions to work with 64-bit applications, and also use 32-bit versions to work with 32-bit applications?
6
- Gratitude 8a78ff9644<br />
7
- <br />
8
- <br />
9
- <p></p>
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Android Gameplay How to Sync Your Progress and Earn Rewards Across Devices.md DELETED
@@ -1,162 +0,0 @@
1
- <br />
2
- <h1>Android Gameplay: A Guide for Gamers and Developers</h1>
3
- <p>Android gameplay is also popular because it offers a wide range of games in different genres, catering to different tastes and preferences. Whether you are looking for adventure, arcade, puzzle, racing, strategy, or any other type of game, you can find it on Android. Here are some of the best Android games in different genres that you can try out:</p>
4
- <h2>android gameplay</h2><br /><p><b><b>Download</b> &#127775; <a href="https://urlin.us/2uT1EM">https://urlin.us/2uT1EM</a></b></p><br /><br />
5
- <h2>The Best Android Games in Different Genres</h2>
6
- <h3>Adventure Games</h3>
7
- <p>Adventure games are games that involve exploration, story, puzzles, and interaction with characters and environments. Adventure games often have immersive graphics, sound effects, and voice acting that create a rich and engaging experience. Some of the best adventure games on Android are:</p>
8
- <ul>
9
- <li><strong>The Room series</strong>: The Room is a series of puzzle games that challenge you to solve mysterious and intricate contraptions in a dark and atmospheric setting. The games have stunning graphics, realistic physics, and captivating stories that will keep you hooked. The latest game in the series is The Room: Old Sins, which takes you to a haunted dollhouse where you must uncover the secrets of a missing engineer and his wife.</li>
10
- <li><strong>Lara Croft GO</strong>: Lara Croft GO is a turn-based puzzle game that follows the iconic heroine as she explores ancient ruins and faces deadly enemies. The game has beautiful visuals, clever puzzles, and a relaxing soundtrack that make it a perfect game for casual gamers. You can also unlock new outfits and collectibles as you progress through the game.</li>
11
- <li><strong>Life is Strange</strong>: Life is Strange is a choice-based adventure game that tells the story of Max Caulfield, a teenage girl who discovers that she can rewind time and change the course of events. The game has a compelling plot, realistic characters, and multiple endings that depend on your choices. You can also use your camera to take photos and collect memories along the way.</li>
12
- </ul>
13
- <h3>Arcade Games</h3>
14
- <p>Arcade games are games that are fast-paced, simple, and addictive. Arcade games usually have simple controls, high scores, and endless levels that test your reflexes and skills. Some of the best arcade games on Android are:</p>
15
- <ul>
16
- <li><strong>Subway Surfers</strong>: Subway Surfers is an endless runner game that has you running away from the police on a subway track. You can swipe left or right to dodge obstacles, jump or roll to avoid trains, and collect coins and power-ups to boost your score. You can also customize your character and unlock new hoverboards and jetpacks.</li>
17
- <li><strong>Fruit Ninja</strong>: Fruit Ninja is a classic arcade game that has you slicing fruits with your finger as they fly across the screen. You can play in different modes, such as Classic, Arcade, Zen, or Online Multiplayer, and use different blades and dojos to enhance your gameplay. You can also unlock achievements and compete with your friends on the leaderboards.</li>
18
- <li><strong>Angry Birds 2</strong>: Angry Birds 2 is the sequel to the popular arcade game that has you launching birds at pigs using a slingshot. The game has improved graphics, new levels, new birds, new powers, and new challenges that make it more fun and exciting than ever. You can also join clans and play with other players online.</li>
19
- <h3>Puzzle Games</h3>
20
- <p>Puzzle games are games that require logic, strategy, and problem-solving skills. Puzzle games often have relaxing graphics, sound effects, and music that create a soothing and satisfying experience. Some of the best puzzle games on Android are:</p>
21
- <ul>
22
- <li><strong>Monument Valley 2</strong>: Monument Valley 2 is a beautiful puzzle game that has you guiding a mother and her child through a world of impossible architecture and optical illusions. The game has stunning visuals, enchanting music, and clever puzzles that will challenge your perception and imagination.</li>
23
- <li><strong>Candy Crush Saga</strong>: Candy Crush Saga is a popular puzzle game that has you matching candies of the same color to clear them from the board. The game has hundreds of levels, each with different goals and obstacles. You can also use boosters and power-ups to help you along the way. You can also play with your friends and compete for the highest score.</li>
24
- <li><strong>2048</strong>: 2048 is a simple but addictive puzzle game that has you sliding tiles with numbers on them to combine them and create larger numbers. The game ends when you reach the 2048 tile or when there are no more moves left. You can also try different modes and variations of the game, such as 4x4, 5x5, 6x6, or Fibonacci.</li>
25
- </ul>
26
- <h3>Racing Games</h3>
27
- <p>Racing games are games that involve driving or riding vehicles at high speeds and competing with other racers or against the clock. Racing games often have realistic graphics, sound effects, and physics that create a thrilling and immersive experience. Some of the best racing games on Android are:</p>
28
- <ul>
29
- <li><strong>Asphalt 9: Legends</strong>: Asphalt 9: Legends is a stunning racing game that has you driving some of the most prestigious cars in the world on exotic locations. The game has amazing graphics, smooth controls, and a variety of modes and events. You can also customize your cars, join clubs, and play with other players online.</li>
30
- <li><strong>Mario Kart Tour</strong>: Mario Kart Tour is a fun racing game that features characters and tracks from the Mario franchise. The game has colorful graphics, catchy music, and easy controls. You can also use items and power-ups to boost your speed or hinder your opponents. You can also play with your friends and compete in rankings and tournaments.</li>
31
- <li><strong>Real Racing 3</strong>: Real Racing 3 is a realistic racing game that has you driving some of the most authentic cars on real tracks around the world. The game has impressive graphics, realistic physics, and a variety of modes and challenges. You can also upgrade your cars, join teams, and play with other players online.</li>
32
- <h3>Strategy Games</h3>
33
- <p>Strategy games are games that involve planning, decision-making, and resource management. Strategy games often have complex and challenging gameplay that require tactical thinking and long-term vision. Some of the best strategy games on Android are:</p>
34
- <ul>
35
- <li><strong>Clash of Clans</strong>: Clash of Clans is a popular strategy game that has you building and defending your own village from other players. You can also join clans, train troops, and attack other villages to loot resources and trophies. You can also participate in clan wars, events, and seasons to earn rewards and bonuses.</li>
36
- <li><strong>Plants vs. Zombies 2</strong>: Plants vs. Zombies 2 is a fun strategy game that has you planting and growing plants to fend off waves of zombies. The game has colorful graphics, humorous characters, and a variety of modes and levels. You can also collect and upgrade your plants, travel through time and space, and face boss battles.</li>
37
- <li><strong>Civilization VI</strong>: Civilization VI is a classic strategy game that has you leading a civilization from the ancient to the modern era. You can choose from different leaders, cultures, and policies to shape your civilization's history and destiny. You can also explore, expand, exploit, and exterminate other civilizations on a randomly generated map.</li>
38
- </ul>
39
- <h3>Other Genres</h3>
40
- <p>Of course, there are many other genres of games that you can enjoy on Android, such as role-playing, simulation, sports, trivia, word, and more. You can browse the Google Play Store to discover new and trending games in different categories. You can also check out some of the best Android games of 2023 according to TechRadar and PCMag.</p>
41
- <h2>The Best Android Gaming Tips and Tricks</h2>
42
- <p>Now that you have some ideas of what games to play on Android, you might want to know some tips and tricks to enhance your gaming experience. Here are some of the best Android gaming tips and tricks that you can use:</p>
43
- <p>android gameplay offline<br />
44
- android gameplay 2023<br />
45
- android gameplay channel<br />
46
- android gameplay horror<br />
47
- android gameplay rpg<br />
48
- android gameplay racing<br />
49
- android gameplay adventure<br />
50
- android gameplay action<br />
51
- android gameplay strategy<br />
52
- android gameplay simulation<br />
53
- android gameplay multiplayer<br />
54
- android gameplay shooter<br />
55
- android gameplay puzzle<br />
56
- android gameplay platformer<br />
57
- android gameplay arcade<br />
58
- android gameplay fps<br />
59
- android gameplay mmorpg<br />
60
- android gameplay survival<br />
61
- android gameplay zombie<br />
62
- android gameplay hack and slash<br />
63
- android gameplay roguelike<br />
64
- android gameplay tower defense<br />
65
- android gameplay moba<br />
66
- android gameplay card game<br />
67
- android gameplay battle royale<br />
68
- android gameplay open world<br />
69
- android gameplay sandbox<br />
70
- android gameplay stealth<br />
71
- android gameplay fighting<br />
72
- android gameplay sports<br />
73
- android gameplay vr<br />
74
- android gameplay idle<br />
75
- android gameplay clicker<br />
76
- android gameplay tycoon<br />
77
- android gameplay city builder<br />
78
- android gameplay match 3<br />
79
- android gameplay hidden object<br />
80
- android gameplay trivia<br />
81
- android gameplay word game<br />
82
- android gameplay educational<br />
83
- android gameplay casual<br />
84
- android gameplay runner<br />
85
- android gameplay music game<br />
86
- android gameplay rhythm game<br />
87
- android gameplay board game<br />
88
- android gameplay chess game</p>
89
- <h3>How to use digital wellbeing features</h3>
90
- <p>Android has some digital wellbeing features that can help you manage your screen time and avoid distractions while gaming. For example, you can use Focus mode to pause notifications from certain apps while you play. You can also use Bedtime mode to dim your screen and mute sounds at night. You can access these features from the Settings app or the Quick Settings panel.</p>
91
- <h3>How to use voice search and commands</h3>
92
- <p>Android has a built-in voice assistant called Google Assistant that can help you search for games, launch apps, control settings, and more with your voice. You can activate Google Assistant by saying "Hey Google" or by tapping the microphone icon on the search bar or the home screen. You can then ask Google Assistant questions or give commands related to gaming, such as "What are some good racing games?" or "Turn on Do Not Disturb mode".</p>
93
- <h3>How to uninstall unwanted apps</h3>
94
- <h3>How to sync your progress across devices</h3>
95
- <p>If you have more than one Android device, you might want to sync your game progress across them so that you can continue playing where you left off. You can do this by using Google Play Games, a service that lets you save your game data, achievements, and leaderboards online. You can sign in to Google Play Games with your Google account and enable cloud save for the games that support it. You can also use Google Play Games to play with other players online and discover new games.</p>
96
- <h3>How to earn rewards with Google Play Points</h3>
97
- <p>Google Play Points is a program that rewards you for using the Google Play Store. You can earn points by downloading and playing games, making in-app purchases, subscribing to services, and more. You can then redeem your points for rewards, such as discounts, coupons, free apps, and more. You can also use your points to support causes that you care about. You can join Google Play Points for free and start earning points today.</p>
98
- <h2>The Mobile Gaming Market Statistics and Trends</h2>
99
- <p>Android gameplay is not only fun and exciting, but also lucrative and influential. The mobile gaming market is one of the fastest-growing and most profitable segments of the gaming industry. Here are some of the mobile gaming market statistics and trends that you should know:</p>
100
- <h3>The global and U.S. revenue and user numbers</h3>
101
- <p>According to Statista, the global mobile gaming market generated $86.3 billion in revenue in 2020, accounting for 49% of the total gaming market. The number of mobile gamers worldwide reached 2.7 billion in 2020, representing 34% of the global population. The U.S. mobile gaming market generated $13.9 billion in revenue in 2020, ranking second after China. The number of mobile gamers in the U.S. reached 203 million in 2020, representing 61% of the U.S. population.</p>
102
- <h3>The most downloaded and highest-grossing apps</h3>
103
- <p>According to Statista, the most-downloaded Android gaming app worldwide in September 2022 was Garena Free Fire, with 63 million downloads. The second-most downloaded app was Subway Surfers, with 40 million downloads, followed by Among Us, with 38 million downloads. The highest-grossing Android gaming app worldwide in September 2022 was Honor of Kings, with $240 million in revenue. The second-highest grossing app was PUBG Mobile, with $198 million in revenue, followed by Genshin Impact, with $156 million in revenue.</p>
104
- <h3>The most popular genres and platforms</h3>
105
- <h3>The future projections and opportunities</h3>
106
- <p>According to Statista, the global mobile gaming market is expected to grow to $116.4 billion in revenue by 2024, with a compound annual growth rate of 7.7%. The number of mobile gamers worldwide is expected to reach 3.1 billion by 2024, with a compound annual growth rate of 3.6%. The U.S. mobile gaming market is expected to grow to $18.8 billion in revenue by 2024, with a compound annual growth rate of 7.8%. The number of mobile gamers in the U.S. is expected to reach 222 million by 2024, with a compound annual growth rate of 2.3%.</p>
107
- <p>The mobile gaming market offers many opportunities for both gamers and developers, as technology, innovation, and creativity continue to evolve and improve. Some of the trends and opportunities that are shaping the future of mobile gaming are:</p>
108
- <ul>
109
- <li><strong>Cloud gaming</strong>: Cloud gaming is a service that allows gamers to stream games from remote servers without downloading or installing them on their devices. Cloud gaming enables gamers to access high-quality games on any device, regardless of their hardware specifications or storage capacity. Cloud gaming also reduces the cost and complexity of game development and distribution for developers. Some of the cloud gaming services that are available or in development are Google Stadia, Microsoft xCloud, Amazon Luna, and Nvidia GeForce Now.</li>
110
- <li><strong>5G technology</strong>: 5G technology is the next generation of wireless communication that offers faster speed, lower latency, higher bandwidth, and more reliability than 4G technology. 5G technology enables gamers to enjoy smoother and more immersive gameplay, especially for online multiplayer and cloud gaming. 5G technology also allows developers to create more complex and realistic games that can leverage the full potential of mobile devices.</li>
111
- <li><strong>Augmented reality and virtual reality</strong>: Augmented reality (AR) and virtual reality (VR) are technologies that create interactive and immersive experiences by overlaying digital elements on the real world or creating a simulated environment. AR and VR enable gamers to experience games in a new and exciting way, as they can interact with their surroundings and feel more immersed in the game world. AR and VR also offer new possibilities for game design and storytelling for developers. Some of the AR and VR games that are available or in development are Pokemon Go, Harry Potter: Wizards Unite, Minecraft Earth, Beat Saber, Half-Life: Alyx, and The Walking Dead: Saints & Sinners.</li>
112
- </ul>
113
- <h2>Conclusion</h2>
114
- <p>Android gameplay is a fascinating and diverse topic that covers many aspects of gaming on Android devices. Android gameplay offers many benefits for both gamers and developers, such as entertainment, challenge, learning, creativity, market potential, platform flexibility, community support, and more. Android gameplay also offers a wide range of games in different genres, such as adventure, arcade, puzzle, racing, strategy, and more. Android gameplay also has some tips and tricks that can enhance your gaming experience, such as using digital wellbeing features, voice search and commands, uninstalling unwanted apps, syncing your progress across devices, and earning rewards with Google Play Points. Android gameplay also has some statistics and trends that show its growth and popularity in the global and U.S. markets, as well as its future projections and opportunities in terms of technology, innovation, and creativity.</p>
115
- <p>If you are interested in android gameplay, you can try out some of the games that we have recommended in this article or explore other games on the Google Play Store. You can also use Google Play Games to save your game data online, play with other players online, and discover new games. You can also use Google Assistant to search for games, launch apps, control settings, and more with your voice.</p>
116
- <p>If you are a developer or aspiring to be one, you can use Android Studio to create your own games for Android devices. You can also use Firebase to add features such as authentication, database, storage, analytics, and more to your games. You can also use Google Play Console to publish your games on the Google Play Store and reach millions of users worldwide.</p>
117
- <p>We hope that this article has given you some useful information and insights about android gameplay. We also hope that you have enjoyed reading it as much as we have enjoyed writing it. Thank you for your time and attention.</p>
118
- <h2>Frequently Asked Questions</h2>
119
- <p>Here are some frequently asked questions about android gameplay that you might find helpful:</p>
120
- <h3>What are some of the advantages of android gameplay over other platforms?</h3>
121
- <p>Some of the advantages of android gameplay over other platforms are:</p>
122
- <ul>
123
- <li>Android devices have a larger and more diverse user base than other devices</li>
124
- <li>Android devices have a more open and flexible platform than other devices</li>
125
- <li>Android devices have a more diverse and dynamic range of games than other devices</li>
126
- <li>Android devices have more features and functions that can enhance gaming than other devices</li>
127
- </ul>
128
- <h3>What are some of the challenges or drawbacks of android gameplay?</h3>
129
- <p>Some of the challenges or drawbacks of android gameplay are:</p>
130
- <ul>
131
- <li>Android devices have a lower performance and battery life than other devices</li>
132
- <li>Android devices have a higher risk of malware and security issues than other devices</li>
133
- <li>Android devices have a more fragmented and inconsistent platform than other devices</li>
134
- <li>Android devices have a more competitive and saturated market than other devices</li>
135
- </ul>
136
- <h3>How can I improve my android gameplay experience?</h3>
137
- <p>Some of the ways that you can improve your android gameplay experience are:</p>
138
- <ul>
139
- <li>Choose games that are compatible and optimized for your device model and specifications</li>
140
- <li>Update your device software and apps regularly to ensure smooth and secure performance</li>
141
- <li>Clear your device storage and cache frequently to free up space and speed up your device</li>
142
- <li>Adjust your device settings and preferences to suit your gaming needs and preferences</li>
143
- <li>Use accessories such as headphones, controllers, stands, chargers, and more to enhance your gaming comfort and convenience</li>
144
- </ul>
145
- <h3>How can I learn more about android gameplay?</h3>
146
- <p>Some of the ways that you can learn more about android gameplay are:</p>
147
- <ul>
148
- <li>Read blogs, magazines, reviews, guides, and news about android gameplay online or offline</li>
149
- <li>Watch videos, podcasts, streams, tutorials, and demos about android gameplay online or offline</li>
150
- <li>Join forums, communities, groups, and events about android gameplay online or offline</li>
151
- <li>Ask questions, share opinions, give feedback, and exchange tips about android gameplay online or offline</li>
152
- <li>Play games, experiment with features, explore genres, and discover new games on Android</li>
153
- </ul>
154
- <h3>What are some of the best resources for android gameplay?</h3>
155
- <p>Some of the best resources for android gameplay are:</p>
156
- <ul>
157
- <li><strong>The Google Play Store</strong>: The Google Play Store is the official app store for Android devices that offers millions of games in different categories. You can browse, download, update, rate, review, and share games on the Google Play Store. You can also access Google Play Games, Google Play Points, Google Play Pass, and Google Play Protect on the Google Play Store.</li>
158
- <li><strong>The Android Developers website</strong>: The Android Developers website is the official website for Android developers that offers tools, documentation, guides, tutorials, courses, and more for creating games for Android devices. You can access Android Studio, Firebase, Google Play Console, Google Play Services, and more on the Android Developers website.</li>
159
- <li><strong>The Android Authority website</strong>: The Android Authority website is one of the leading websites for Android news, reviews, tips, tricks, and more. You can find articles, videos, podcasts, newsletters, deals, and more about android gameplay on the Android Authority website.</li>
160
- </ul></p> 197e85843d<br />
161
- <br />
162
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Bloons TD 6 APK How to Install and Play the Latest Version of the Epic Monkey Game.md DELETED
@@ -1,162 +0,0 @@
1
-
2
- <h1>Bloons TD 6 APK: A Fun and Challenging Tower Defense Game</h1>
3
- <p>If you are a fan of tower defense games, you might have heard of Bloons TD 6, the latest installment in the popular Bloons TD series. But did you know that you can download and play Bloons TD 6 APK on your device for free? In this article, we will tell you everything you need to know about Bloons TD 6 APK, including what it is, how to download and install it, how to play and enjoy it, and more. Read on to find out more!</p>
4
- <h2>bloons td 6 apk.com</h2><br /><p><b><b>Download Zip</b> &#9733;&#9733;&#9733; <a href="https://urlin.us/2uSZL5">https://urlin.us/2uSZL5</a></b></p><br /><br />
5
- <h2>What is Bloons TD 6?</h2>
6
- <p>Bloons TD 6 is a 3D tower defense game developed and published by Ninja Kiwi, a New Zealand-based game studio. It was released in June 2018 for iOS, Android, Windows, and Mac platforms. It is the sixth main game in the Bloons TD series, which has been around since 2007.</p>
7
- <h3>The history and features of the Bloons TD series</h3>
8
- <p>The Bloons TD series is one of the most popular and successful tower defense franchises in the world. It has over a billion downloads across all platforms, and has received positive reviews from critics and players alike. The series is known for its colorful graphics, humorous animations, addictive gameplay, and diverse content.</p>
9
- <p>The premise of the series is simple: you have to stop the invading balloons (called bloons) from reaching the end of the path by placing various monkey towers along the way. Each monkey tower has its own unique abilities, upgrades, and activated powers that can help you pop the bloons. The bloons come in different types, colors, and sizes, each with their own characteristics and resistances. Some bloons can even contain other bloons inside them, making them harder to pop.</p>
10
- <p>The series has evolved over time, adding new features and improvements with each game. Some of the notable features include:</p>
11
- <p>bloons td 6 apk download free<br />
12
- bloons td 6 apk mod unlimited money<br />
13
- bloons td 6 apk latest version<br />
14
- bloons td 6 apk obb<br />
15
- bloons td 6 apk android<br />
16
- bloons td 6 apk ios<br />
17
- bloons td 6 apk reddit<br />
18
- bloons td 6 apk online<br />
19
- bloons td 6 apk no ads<br />
20
- bloons td 6 apk offline<br />
21
- bloons td 6 apk hack<br />
22
- bloons td 6 apk cracked<br />
23
- bloons td 6 apk full<br />
24
- bloons td 6 apk pc<br />
25
- bloons td 6 apk update<br />
26
- bloons td 6 apk revdl<br />
27
- bloons td 6 apk pure<br />
28
- bloons td 6 apk mirror<br />
29
- bloons td 6 apk data<br />
30
- bloons td 6 apk google play<br />
31
- bloons td 6 apk cheats<br />
32
- bloons td 6 apk unlocked<br />
33
- bloons td 6 apk original<br />
34
- bloons td 6 apk paid<br />
35
- bloons td 6 apk premium<br />
36
- bloons td 6 apk best towers<br />
37
- bloons td 6 apk tips and tricks<br />
38
- bloons td 6 apk guide<br />
39
- bloons td 6 apk review<br />
40
- bloons td 6 apk gameplay<br />
41
- bloons td 6 apk strategy<br />
42
- bloons td 6 apk co op<br />
43
- bloons td 6 apk sandbox mode<br />
44
- bloons td 6 apk challenges<br />
45
- bloons td 6 apk achievements<br />
46
- bloons td 6 apk maps<br />
47
- bloons td 6 apk heroes<br />
48
- bloons td 6 apk skins<br />
49
- bloons td 6 apk monkey knowledge<br />
50
- bloons td 6 apk insta monkeys<br />
51
- bloons td 6 apk powers<br />
52
- bloons td 6 apk races<br />
53
- bloons td 6 apk odyssey mode<br />
54
- bloons td 6 apk daily rewards<br />
55
- bloons td 6 apk trophies<br />
56
- bloons td 6 apk editor mode<br />
57
- bloons td 6 apk custom maps<br />
58
- bloons td 6 apk multiplayer mode</p>
59
- <ul>
60
- <li>Co-op mode: You can team up with up to three other players online or locally to play any map or mode together.</li>
61
- <li>Heroes: You can choose from a roster of 14 heroes, each with their own personality, voiceover, signature upgrades, and special abilities. Heroes level up automatically during the game, making them more powerful as you progress.</li>
62
- <li>Monkey Knowledge: You can unlock over 100 meta-upgrades that add passive bonuses to your monkey towers or gameplay mechanics.</li>
63
- <li>Trophy Store: You can earn trophies by completing various achievements or events, and use them to buy cosmetic items that customize your monkeys, bloons, animations, music, and more.</li>
64
- <li>Content Browser: You can create your own challenges and odysseys using various settings and modifiers, and share them with other players online. You can also browse and play the most liked and played community content.</li>
65
- </ul>
66
- <h3>The gameplay and content of Bloons TD 6</h3>
67
- <p>Bloons TD 6 offers a huge amount of gameplay and content for players of all skill levels and preferences. The game has over 60 handcrafted maps, each with their own theme, layout, difficulty, and special rules. The maps range from easy to expert, and some of them have alternate versions that change the bloon spawns or tower placements.</p <p>Continuing the article:</p>
68
- <h3>The advantages and disadvantages of downloading the APK version</h3>
69
- <p>Bloons TD 6 is a premium game that costs $6.99 on the official app stores. However, you can also download and play Bloons TD 6 APK for free from various third-party sources. APK stands for Android Package Kit, and it is the file format used by Android devices to install and distribute apps. By downloading Bloons TD 6 APK, you can enjoy the game without paying anything.</p>
70
- <p>However, there are also some drawbacks and risks of using Bloons TD 6 APK. Here are some of them:</p>
71
- <ul>
72
- <li>You may not get the latest updates and features of the game, as the APK version may not be updated as frequently as the official version.</li>
73
- <li>You may encounter compatibility issues or bugs that affect the performance or stability of the game.</li>
74
- <li>You may not be able to access some online features or modes of the game, such as co-op, boss events, odysseys, or content browser.</li>
75
- <li>You may violate the terms of service or privacy policy of Ninja Kiwi, and risk getting banned or suspended from the game.</li>
76
- <li>You may expose your device to malware or viruses that can harm your data or security.</li>
77
- </ul>
78
- <p>Therefore, you should weigh the pros and cons of downloading Bloons TD 6 APK before deciding to do so. You should also make sure that you download Bloons TD 6 APK from a reputable and trustworthy source, and scan it with an antivirus software before installing it.</p>
79
- <h2>How to download and install Bloons TD 6 APK on your device?</h2>
80
- <p>If you have decided to download and install Bloons TD 6 APK on your device, you will need to follow some steps to do so. The steps may vary depending on whether you are using an Android device or a PC. Here are the steps for both platforms:</p>
81
- <h3>The steps to download and install Bloons TD 6 APK on Android</h3>
82
- <ol>
83
- <li>Go to a reliable website that offers Bloons TD 6 APK, such as . Make sure that the website is safe and secure, and that the APK file is compatible with your device.</li>
84
- <li>Tap on the download button to start downloading Bloons TD 6 APK. You may need to allow downloads from unknown sources in your device settings.</li>
85
- <li>Once the download is complete, locate the APK file in your device storage and tap on it to start installing it. You may need to grant some permissions for the app to run properly.</li>
86
- <li>Wait for the installation to finish, and then launch Bloons TD 6 from your app drawer or home screen. Enjoy!</li>
87
- </ol>
88
- <h3>The steps to download and install Bloons TD 6 APK on PC</h3>
89
- <ol>
90
- <li>Go to a reliable website that offers Bloons TD 6 APK, such as . Make sure that the website is safe and secure, and that the APK file is compatible with your PC.</li>
91
- <li>Click on the download button to start downloading Bloons TD 6 APK. You may need to save it in a folder where you can easily find it later.</li>
92
- <li>Download and install an Android emulator on your PC, such as BlueStacks, NoxPlayer, or LDPlayer. An Android emulator is a software that allows you to run Android apps on your PC.</li>
93
- <li>Launch the Android emulator and sign in with your Google account. You may need to create one if you don't have one already.</li>
94
- <li>Drag and drop the Bloons TD 6 APK file into the emulator window, or use the built-in browser to locate and install it. You may need to allow installations from unknown sources in the emulator settings.</li>
95
- <li>Wait for the installation to finish, and then launch Bloons TD 6 from the emulator app drawer or home screen. Enjoy!</li>
96
- </ol>
97
- <h3>The precautions and risks of using Bloons TD 6 APK</h3>
98
- <p>As mentioned earlier, using Bloons TD 6 APK comes with some potential dangers and disadvantages. Therefore, you should take some precautions and be aware of the risks before playing Bloons TD 6 APK. Here are some tips to help you:</p>
99
- <ul>
100
- <li>Always backup your data before installing or updating Bloons TD 6 APK. You can use a cloud service or an external storage device to do so.</li>
101
- <li>Always scan Bloons TD 6 APK with an antivirus software before installing it. You can use a reputable antivirus app on your device or PC, such as Avast, McAfee, or Kaspersky.</li>
102
- <li>Always check the reviews and ratings of Bloons TD 6 APK on the website where you download <p>Continuing the article:</p>
103
- <li>Always check the reviews and ratings of Bloons TD 6 APK on the website where you download it. You can also read the comments and feedback from other users who have tried it. This can help you avoid fake or malicious APK files.</li>
104
- <li>Always update Bloons TD 6 APK whenever a new version is available. This can help you fix any bugs or glitches, and enjoy the latest features and content of the game.</li>
105
- <li>Always respect the rights and policies of Ninja Kiwi, the developer and publisher of Bloons TD 6. Do not use Bloons TD 6 APK to cheat, hack, or exploit the game. Do not distribute or share Bloons TD 6 APK without permission. Do not claim ownership or credit for Bloons TD 6 APK.</li>
106
- </ul>
107
- <p>By following these tips, you can reduce the risks and enhance the experience of playing Bloons TD 6 APK. However, you should still be careful and responsible when using Bloons TD 6 APK, as there is no guarantee that it will work perfectly or safely on your device or PC.</p>
108
- <h2>How to play and enjoy Bloons TD 6?</h2>
109
- <p>Bloons TD 6 is a fun and challenging tower defense game that can keep you entertained for hours. Whether you are a beginner or an expert, you can find something to suit your taste and skill level in Bloons TD 6. Here are some tips on how to play and enjoy Bloons TD 6:</p>
110
- <h3>The basic tips and tricks for beginners</h3>
111
- <p>If you are new to Bloons TD 6, you may want to start with the tutorial mode, which will teach you the basics of the game, such as how to place towers, upgrade them, use powers, and pop bloons. You can also play the easy maps and modes first, to get familiar with the game mechanics and strategies.</p>
112
- <p>Here are some basic tips and tricks for beginners:</p>
113
- <ul>
114
- <li>Try different combinations of monkey towers and heroes, and see what works best for you. Each tower and hero has its own strengths and weaknesses, and can synergize well with others.</li>
115
- <li>Upgrade your monkey towers wisely, and don't spend all your money on one tower. You can choose from three upgrade paths for each tower, each with five tiers of upgrades. The higher tiers are more expensive but more powerful.</li>
116
- <li>Use your activated powers and abilities sparingly, and save them for when you really need them. Activated powers are consumable items that can give you an edge in the game, such as extra lives, cash, or damage. Abilities are special skills that your towers or heroes can use once they reach a certain level.</li>
117
- <li>Pop as many bloons as possible, and don't let them escape. Each bloon that escapes will cost you one life (or more, depending on the bloon type). If you lose all your lives, you will lose the game.</li>
118
- <li>Have fun and experiment with different settings and modifiers. You can change the game speed, difficulty, mode, map, and more to suit your preference and challenge yourself.</li>
119
- </ul>
120
- <h3>The best strategies and builds for advanced players</h3>
121
- <p>If you are an experienced player of Bloons TD 6, you may want to try some of the harder maps and modes, such as impoppable, chimps, or expert. These modes will test your skills and knowledge of the game, and require you to use more advanced strategies and builds.</p>
122
- <p>Here are some of the best strategies and builds for advanced players:</p>
123
- <ul>
124
- <li>Use monkey knowledge points to unlock meta-upgrades that can boost your performance in the game. Monkey knowledge points are earned by leveling up in the game, and can be spent on various categories of upgrades, such as primary, military, magic, support, powers, heroes, or balance.</li>
125
- <li>Use monkey money to buy premium items that can enhance your gameplay experience. Monkey money is earned by completing maps or achievements in the game, and can be used to buy skins, insta-monkeys, powers, heroes, or knowledge respecs.</li>
126
- <li>Use trophies to buy cosmetic items that can customize your appearance in the game. Trophies are earned by completing events or challenges in the game, and can be used to buy decals, <p>Continuing the article:</p>
127
- <li>Use trophies to buy cosmetic items that can customize your appearance in the game. Trophies are earned by completing events or challenges in the game, and can be used to buy decals, portraits, music, sound effects, and more.</li>
128
- <li>Use the alchemist tower to buff your other towers with powerful potions. The alchemist tower can apply various effects to nearby towers, such as increased damage, range, pierce, attack speed, or cash per pop. The alchemist tower is especially effective with fast-firing or multi-shot towers, such as the ninja, dartling gunner, or super monkey.</li>
129
- <li>Use the perma-spike tower to create a reliable backup defense. The perma-spike tower can produce spikes that last until they are used up, and can deal massive damage to bloons. The perma-spike tower is especially useful for dealing with late-game bloons, such as DDTs, ZOMGs, or BADs.</li>
130
- <li>Use the sun avatar tower to unleash devastating beams of plasma. The sun avatar tower is one of the most powerful towers in the game, capable of popping almost any type of bloon with ease. The sun avatar tower can also be upgraded to the sun temple or the true sun god, which are even more powerful and can affect other towers in their range.</li>
131
- <li>Use the banana farm tower to generate extra income. The banana farm tower can produce bananas that can be collected for cash, or automatically deposited into your account. The banana farm tower can also be upgraded to increase its production rate, value, or efficiency.</li>
132
- </ul>
133
- <h3>The fun and creative modes and challenges for everyone</h3>
134
- <p>Bloons TD 6 is not only a challenging game, but also a fun and creative one. You can play various modes and challenges that can spice up your gameplay and test your skills in different ways. Here are some of the fun and creative modes and challenges for everyone:</p>
135
- <ul>
136
- <li>Sandbox mode: You can create your own scenarios and experiments using unlimited money, lives, towers, bloons, and powers. You can also modify the bloon properties, such as speed, health, immunity, or regrowth. Sandbox mode is a great way to test your strategies, learn new things, or just have fun.</li>
137
- <li>Races mode: You can compete with other players online to see who can complete a map or a challenge faster. You can also create your own races and share them with others. Races mode is a great way to challenge yourself, improve your skills, or show off your achievements.</li>
138
- <li>Daily challenges: You can play a new challenge every day that has different settings and modifiers. You can also vote for the next daily challenge from a list of options. Daily challenges are a great way to discover new possibilities, earn rewards, or join the community.</li>
139
- <li>Advanced challenges: You can play a special challenge every week that has more difficult settings and modifiers. You can also submit your own advanced challenges for others to play. Advanced challenges are a great way to push your limits, earn trophies, or showcase your creativity.</li>
140
- <li>Achievements: You can complete various achievements that have different objectives and criteria. You can also view your progress and statistics in the game. Achievements are a great way to track your goals, earn monkey money, or unlock new items.</li>
141
- </ul>
142
- <h2>Conclusion</h2>
143
- <p>Bloons TD 6 is a fun and challenging tower defense game that has something for everyone. Whether you want to pop some bloons, build some towers, or create some challenges, you can do it all in Bloons TD 6. You can also download and play Bloons TD 6 APK for free from various sources online.</p>
144
- <p>However, you should also be careful and responsible when using Bloons TD 6 APK, as there are some risks and drawbacks involved. You should always backup your data, scan your APK file, <p>Continuing the article:</p>
145
- <p>However, you should also be careful and responsible when using Bloons TD 6 APK, as there are some risks and drawbacks involved. You should always backup your data, scan your APK file, check the reviews and ratings, update your APK version, and respect the rights and policies of Ninja Kiwi. By doing so, you can reduce the dangers and enhance the enjoyment of playing Bloons TD 6 APK.</p>
146
- <p>Bloons TD 6 is a game that can provide you with hours of fun and challenge. Whether you play it on your device or PC, with the official version or the APK version, you can experience the thrill and excitement of popping bloons and building towers. So what are you waiting for? Download Bloons TD 6 APK today and join the monkey madness!</p>
147
- <h3>FAQs</h3>
148
- <p>Here are some of the frequently asked questions about Bloons TD 6 APK:</p>
149
- <ul>
150
- <li><b>Q: Is Bloons TD 6 APK safe to use?</b></li>
151
- <li>A: Bloons TD 6 APK is safe to use as long as you download it from a reputable and trustworthy source, and scan it with an antivirus software before installing it. However, there is no guarantee that Bloons TD 6 APK will work perfectly or safely on your device or PC, so use it at your own risk.</li>
152
- <li><b>Q: Is Bloons TD 6 APK legal to use?</b></li>
153
- <li>A: Bloons TD 6 APK is not legal to use, as it violates the terms of service and privacy policy of Ninja Kiwi, the developer and publisher of Bloons TD 6. By using Bloons TD 6 APK, you are infringing on the intellectual property rights of Ninja Kiwi, and risk getting banned or suspended from the game.</li>
154
- <li><b>Q: Is Bloons TD 6 APK free to use?</b></li>
155
- <li>A: Bloons TD 6 APK is free to use, as you do not have to pay anything to download or play it. However, you may not get the full features and content of the game, as the APK version may not be updated as frequently as the official version. You may also encounter compatibility issues or bugs that affect the performance or stability of the game.</li>
156
- <li><b>Q: How to update Bloons TD 6 APK?</b></li>
157
- <li>A: To update Bloons TD 6 APK, you will need to download and install the latest version of the APK file from a reliable website. You may need to uninstall the previous version of Bloons TD 6 APK before installing the new one. You may also need to backup your data before updating Bloons TD 6 APK, as you may lose your progress or settings.</li>
158
- <li><b>Q: How to uninstall Bloons TD 6 APK?</b></li>
159
- <li>A: To uninstall Bloons TD 6 APK, you will need to delete the APK file from your device or PC storage. You may also need to remove any residual files or folders related to Bloons TD 6 APK. You may also need to restore your device or PC settings to their original state.</li>
160
- </ul></p> 197e85843d<br />
161
- <br />
162
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Boss Domino APK A Local Indonesian Game with Various Slots.md DELETED
@@ -1,132 +0,0 @@
1
-
2
- <h1>Boss Domino APK: A Fun and Exciting Casino Game for Android</h1>
3
- <p>If you are looking for a casino game that offers a variety of local Indonesian games, such as Domino Gaple, Domino Qiu Qiu, and various slots, then you should try Boss Domino APK. Boss Domino APK is a free Android game that lets you play casino games online with your friends or other players. You can also win free coins, bonuses, jackpots, and prizes by playing Boss Domino APK. In this article, we will tell you everything you need to know about Boss Domino APK, including what it is, how to download and install it, how to play it, and why you should play it.</p>
4
- <h2>What is Boss Domino APK?</h2>
5
- <p>Boss Domino APK is an Android game that provides local Indonesian casino games, such as Domino Gaple , Domino Qiu Qiu, and various slots. Domino Gaple is a popular card game in Indonesia that is similar to poker, but uses domino tiles instead of cards. Domino Qiu Qiu is another domino game that is also known as 99 or Kiu Kiu, and involves forming the best combination of four tiles out of six tiles in your hand. Slots are games of chance that involve spinning reels and matching symbols to win prizes.</p>
6
- <h2>boss domino apk</h2><br /><p><b><b>DOWNLOAD</b> &#9989; <a href="https://urlin.us/2uT146">https://urlin.us/2uT146</a></b></p><br /><br />
7
- <p>Boss Domino APK is not only a game, but also a social platform where you can chat with other players, send emoticons, and make friends. You can also join clubs, participate in tournaments, and rank on the leaderboard. Boss Domino APK is designed with attractive graphics, sound effects, and animations that make the gameplay more enjoyable and realistic. You can also customize your avatar, profile, and game settings according to your preferences.</p>
8
- <h2>How to download and install Boss Domino APK?</h2>
9
- <p>Boss Domino APK is not available on the official Google Play Store, but you can still download and install it from other sources. There are two ways to download and install Boss Domino APK: from APKCombo or from Google Play Store using a VPN.</p>
10
- <h3>Steps to download Boss Domino APK from APKCombo</h3>
11
- <p>APKCombo is a website that provides APK and XAPK files for Android apps and games. You can download Boss Domino APK from APKCombo by following these steps:</p>
12
- <ol>
13
- <li>Visit the <a href="">APKCombo website</a> on your browser.</li>
14
- <li>Search for Boss Domino APK in the search bar.</li>
15
- <li>Choose the latest version of Boss Domino APK and download the XAPK file to your device.</li>
16
- <li>Install the XAPK file using <a href="">APKCombo Installer</a>, which is an app that can extract and install XAPK files.</li>
17
- <li>Open Boss Domino APK and enjoy playing.</li>
18
- </ol>
19
- <h3>Steps to download Boss Domino APK from Google Play Store</h3>
20
- <p>If you prefer to download Boss Domino APK from Google Play Store, you will need to use a VPN app that can change your location to Indonesia. This is because Boss Domino APK is only available in Indonesia on Google Play Store. You can download Boss Domino APK from Google Play Store using a VPN by following these steps:</p>
21
- <ol>
22
- <li>Open the VPN app on your Android device and connect to an Indonesian server.</li>
23
- <li>Open the Google Play Store app on your Android device and search for Boss Domino in the search bar.</li>
24
- <li>Tap on the Boss Domino icon and then tap on Install.</li>
25
- <li>Wait for the installation to complete and then open Boss Domino APK.</li>
26
- <li>Disconnect the VPN app and enjoy playing.</li>
27
- </ol>
28
- <h2>How to play Boss Domino APK?</h2>
29
- <p>Boss Domino APK offers three types of casino games: Domino Gaple, Domino Qiu Qiu, and slots. Each game has its own rules, tips, and features that you need to know before playing. Here are some basic guidelines for playing each game:</p>
30
- <h3>Rules and tips for playing Domino Gaple</h3>
31
- <p>Domino Gaple is a card game that uses domino tiles instead of cards. The objective of the game is to get rid of all your tiles before your opponents. Here are some rules and tips for playing Domino Gaple:</p>
32
- <ul>
33
- <li>Each player starts with seven tiles and one tile is placed on the table as the starter.</li>
34
- <li>On your turn, you can either place a tile that matches one of the ends of the chain on the table, or draw a tile from the stock if you have no matching tiles.</li>
35
- <li>The game ends when one player runs out of tiles or when the stock is empty and no one can make a move.</li>
36
- <li>The player with the lowest total value of tiles in their hand wins the game.</li>
37
- <li>You can use strategies such as blocking, bluffing, or counting tiles to gain an advantage over your opponents.</li>
38
- </ul>
39
- <h3>Rules and tips for playing Domino Qiu Qiu</h3>
40
- <p>Domino Qiu Qiu is another domino game that is also known as 99 or Kiu Kiu. The objective of the game is to form the best combination of four tiles out of six tiles in your hand. Here are some rules and tips for playing Domino Qiu Qiu:</p>
41
- <ul>
42
- <li>Each player starts with six tiles and four rounds of betting take place.</li>
43
- <li>On each round, you can either check, raise, call, fold, or all-in depending on your tiles and the bets of other players.</li>
44
- <li>The game ends when one player wins all the chips or when all players except one fold.</li>
45
- <li>The ranking of tile combinations is as follows: six gods > four balak > pure big > pure small > three doubles > two doubles > one double > high card.</li>
46
- <li>You can use strategies such as bluffing, folding, or all-in to influence the bets of other players.</li>
47
- </ul>
48
- <h3>Rules and tips for playing slot games</h3>
49
- <p>Slots are games of chance that involve spinning reels and matching symbols to win prizes. The objective of the game is to match symbols on the reels and win prizes. Here are some rules and tips for playing slot games:</p>
50
- <p>boss domino apk download<br />
51
- boss domino apk mod<br />
52
- boss domino apk latest version<br />
53
- boss domino apk free<br />
54
- boss domino apk android<br />
55
- boss domino apk offline<br />
56
- boss domino apk online<br />
57
- boss domino apk hack<br />
58
- boss domino apk update<br />
59
- boss domino apk 2023<br />
60
- boss domino game apk<br />
61
- boss domino gaple apk<br />
62
- boss domino qiu qiu apk<br />
63
- boss domino slot apk<br />
64
- boss domino casino apk<br />
65
- boss domino indonesia apk<br />
66
- boss domino higgs island apk<br />
67
- boss domino 99 apk<br />
68
- boss domino kiu kiu apk<br />
69
- boss domino qq apk<br />
70
- download boss domino apk gratis<br />
71
- download boss domino apk terbaru<br />
72
- download boss domino apk mod unlimited money<br />
73
- download boss domino apk for pc<br />
74
- download boss domino apk versi lama<br />
75
- cara download boss domino apk<br />
76
- link download boss domino apk<br />
77
- situs download boss domino apk<br />
78
- unduh boss domino apk<br />
79
- install boss domino apk<br />
80
- mainkan boss domino apk<br />
81
- daftar boss domino apk<br />
82
- login boss domino apk<br />
83
- cheat boss domino apk<br />
84
- tips boss domino apk<br />
85
- trik boss domino apk<br />
86
- strategi boss domino apk<br />
87
- panduan boss domino apk<br />
88
- tutorial boss domino apk<br />
89
- review boss domino apk<br />
90
- rating boss domino apk<br />
91
- komentar boss domino apk<br />
92
- testimoni boss domino apk<br />
93
- bonus boss domino apk<br />
94
- jackpot boss domino apk<br />
95
- hadiah boss domino apk<br />
96
- koin emas boss domino apk<br />
97
- emotikon interaktif boss domino apk <br />
98
- tampilan game menarik boss domino apk</p>
99
- <ul>
100
- <li>Each slot game has different themes, paylines, symbols, and features.</li>
101
- <li>You can adjust your bet size and number of paylines before spinning the reels.</li>
102
- <li>You can also use auto spin, turbo spin, or max bet options to speed up the gameplay.</li>
103
- <li>You can win free spins, bonus games, jackpots, or multipliers depending on the slot game.</li>
104
- <li>You can use strategies such as choosing the right slot game, managing your bankroll, or betting wisely to increase your chances of winning.</li>
105
- </ul>
106
- <h2>Why should you play Boss Domino APK?</h2>
107
- <p>Boss Domino APK is not just a game, but also a fun and exciting way to spend your time. There are many benefits of playing Boss Domino APK, such as:</p>
108
- <h3>Benefits of playing Boss Domino APK</h3>
109
- <ul>
110
- <li>You can enjoy various casino games in one app.</li>
111
- <li>You can play with your friends or other players online.</li>
112
- <li>You can improve your skills and strategies in domino games.</li>
113
- <li>You can have fun and relax with colorful graphics and sound effects.</li>
114
- <li>You can win real money or prizes by playing slot games.</li>
115
- </ul>
116
- <h2>Conclusion</h2>
117
- <p>Boss Domino APK is a free Android game that offers a variety of local Indonesian casino games, such as Domino Gaple, Domino Qiu Qiu, and various slots. You can download and install Boss Domino APK from APKCombo or Google Play Store using a VPN. You can also play Boss Domino APK online with your friends or other players. You can also win free coins, bonuses, jackpots, and prizes by playing Boss Domino APK. Boss Domino APK is a fun and exciting casino game that you should try if you love casino games.</p>
118
- <h2>FAQs</h2>
119
- <ol>
120
- <li>What is the difference between APK and XAPK files?</li>
121
- <p>APK files are Android application packages that contain the app code and resources. XAPK files are extended APK files that contain additional data such as OBB files or split APKs.</p>
122
- <li>How can I get more free coins and bonuses in Boss Domino APK?</li>
123
- <p>You can get more free coins and bonuses in Boss Domino APK by logging in daily, completing tasks, inviting friends, joining clubs, participating in tournaments, or watching ads.</p>
124
- <li>Is Boss Domino APK safe to download and play?</li>
125
- <p>Boss Domino APK is safe to download and play as long as you download it from a trusted source such as APKCombo or Google Play Store using a VPN. You should also avoid using any modded or hacked versions of Boss Domino APK as they may contain viruses or malware.</p>
126
- <li>Can I play Boss Domino APK offline?</li>
127
- <p>No, you cannot play Boss Domino APK offline as it requires an internet connection to access the online features and games. You can only play Boss Domino APK online with your friends or other players.</p>
128
- <li>Can I play Boss Domino APK on PC?</li>
129
- <p>Yes, you can play Boss Domino APK on PC by using an Android emulator such as BlueStacks or NoxPlayer. You can download and install the emulator on your PC and then download and install Boss Domino APK from the emulator's app store.</p>
130
- </ol></p> 197e85843d<br />
131
- <br />
132
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Car Parking Multiplayer APK A Free Game with Realistic Cars and Maps.md DELETED
@@ -1,66 +0,0 @@
1
- <br />
2
- <h1>Free Download Car Parking Multiplayer APK: A Realistic Driving Simulator for Android</h1>
3
- <p>Do you love driving and parking games? Do you want to experience a realistic simulation of driving various vehicles in a detailed city? Do you want to challenge yourself and other players in different parking scenarios? If you answered yes to any of these questions, then you should try Car Parking Multiplayer, a popular game for Android devices that lets you enjoy all these features and more. In this article, we will tell you what Car Parking Multiplayer is, how to download and install it on your device, and some tips and tricks for playing it.</p>
4
- <h2>free download car parking multiplayer apk</h2><br /><p><b><b>Download</b> === <a href="https://urlin.us/2uSVRU">https://urlin.us/2uSVRU</a></b></p><br /><br />
5
- <h2>What is Car Parking Multiplayer?</h2>
6
- <p>Car Parking Multiplayer is a 3D driving simulator game developed by olzhass, a studio that specializes in creating realistic car games. The game has over 100 million downloads on Google Play Store and has received positive reviews from players and critics alike. The game offers more than just parking, as you can also explore an open-world city with various locations, such as airports, gas stations, car washes, garages, and more. You can also customize your car with different paint colors, stickers, rims, spoilers, and other accessories. Moreover, you can play online with other players in multiplayer mode, where you can chat, race, trade cars, or even prank each other.</p>
7
- <h3>Features of Car Parking Multiplayer</h3>
8
- <h4>Realistic graphics and physics</h4>
9
- <p>One of the main attractions of Car Parking Multiplayer is its realistic graphics and physics. The game uses high-quality 3D models and textures to create a lifelike environment that you can explore. The game also simulates the physics of different vehicles, such as their weight, speed, acceleration, braking, steering, suspension, and damage. You can also experience different weather conditions, such as rain, snow, fog, or night time. The game also has realistic sound effects that match the engine sounds, horn sounds, tire sounds, and collision sounds of each vehicle.</p>
10
- <h4>Variety of vehicles and customization options</h4>
11
- <p>The game features over 100 vehicles that you can drive and park in various scenarios. You can choose from different categories of vehicles, such as cars, trucks, buses, motorcycles, or even helicopters. Each vehicle has its own characteristics and performance that affect how it handles on the road. You can also customize your vehicle with different options, such as paint color, stickers, rims, spoilers, neon lights, license plates, and more. You can also modify your vehicle's engine power, transmission type, brake force, steering sensitivity, and other settings.</p>
12
- <h4>Open-world exploration and multiplayer mode</h4>
13
- <p>The game allows you to explore an open-world city with various locations that you can visit. You can drive around freely or follow the GPS directions to find your destination. You can also interact with different objects in the city, such as traffic lights, gas stations, car washes, garages, or even animals. You can also play online with other players in multiplayer mode, where you can join different servers based on your region or language. You can chat with other players, race with them, trade cars with them, or even prank them by blocking their way or honking at them.</p>
14
- <h3>How to download and install Car Parking Multiplayer APK?</h3>
15
- <h4>Download from official sources</h4>
16
- <p>The easiest way to download Car Parking Multiplayer APK is to use the official sources, such as Google Play Store or Upt <h4>Enable unknown sources on your device</h4>
17
- <p>If you download Car Parking Multiplayer APK from a third-party source, such as Uptodown, you will need to enable unknown sources on your device. This is because Android devices normally block the installation of apps that are not from the official sources, such as Google Play Store. To enable unknown sources, you need to go to your device's settings, then security, then toggle on the option that says "allow installation of apps from unknown sources". This will allow you to install Car Parking Multiplayer APK on your device.</p>
18
- <p>How to install car parking multiplayer apk on Windows PC<br />
19
- Car parking multiplayer apk mod with unlimited money and all cars unlocked<br />
20
- Car parking multiplayer apk latest version 4.8.9.4.4 free download<br />
21
- Car parking multiplayer apk gameplay and features review<br />
22
- Car parking multiplayer apk hack tool for Android devices<br />
23
- Car parking multiplayer apk online mode with friends and voice chat<br />
24
- Car parking multiplayer apk offline mode with AI and custom maps<br />
25
- Car parking multiplayer apk best cars and tuning tips<br />
26
- Car parking multiplayer apk cheats and tricks for easy parking<br />
27
- Car parking multiplayer apk comparison with other parking games<br />
28
- Car parking multiplayer apk problems and solutions for common issues<br />
29
- Car parking multiplayer apk update and patch notes for 2023<br />
30
- Car parking multiplayer apk requirements and compatibility for different devices<br />
31
- Car parking multiplayer apk guide and walkthrough for beginners<br />
32
- Car parking multiplayer apk download link and installation instructions</p>
33
- <h4>Install the APK file and launch the game</h4>
34
- <p>Once you have downloaded Car Parking Multiplayer APK from your preferred source, you need to locate the file on your device's storage. You can use a file manager app to find the file, or you can check your download folder. Once you find the file, tap on it to start the installation process. Follow the instructions on the screen to complete the installation. After the installation is done, you can launch the game by tapping on its icon on your home screen or app drawer. Enjoy playing Car Parking Multiplayer on your Android device!</p>
35
- <h3>Tips and tricks for playing Car Parking Multiplayer</h3>
36
- <h4>Learn the basics of parking and driving</h4>
37
- <p>Before you start playing Car Parking Multiplayer, you should learn the basics of parking and driving in the game. The game has a tutorial mode that teaches you how to use the controls, such as the steering wheel, pedals, gearbox, handbrake, and camera. You should also practice parking in different situations, such as parallel parking, reverse parking, diagonal parking, and more. You can also adjust the difficulty level of the parking challenges, from easy to hard. The game also has a driving school mode that teaches you how to follow traffic rules, such as speed limits, stop signs, traffic lights, and more.</p>
38
- <h4>Use the map and GPS to find your destination</h4>
39
- <p>The game has a large open-world city that you can explore freely. However, if you want to find a specific location or complete a mission, you will need to use the map and GPS features. The map shows you the layout of the city and the locations of different places, such as gas stations, car washes, garages, airports, and more. You can also see your current position and direction on the map. The GPS feature helps you navigate to your destination by showing you the best route and giving you voice directions. You can also set waypoints on the map to mark places that you want to visit.</p>
40
- <h4>Earn money and upgrade your car</h4>
41
- <p>The game allows you to earn money by completing missions, parking challenges, races, or other activities. You can use the money to buy new cars or upgrade your existing ones. You can also sell your cars or trade them with other players online. You can upgrade your car's performance by modifying its engine power, transmission type, brake force, steering sensitivity, and other settings. You can also customize your car's appearance by changing its paint color, stickers, rims, spoilers, neon lights, license plates, and more.</p>
42
- <h4>Join online servers and interact with other players</h4>
43
- <p>The game has a multiplayer mode that lets you play online with other players from around the world. You can join different servers based on your region or language. You can chat with other players, race with them, trade cars with them, or even prank them by blocking their way or honking at them. You can also create your own server and invite your friends to join. You can also join clans or groups of players who share similar interests or goals in the game.</p>
44
- <h2>Conclusion</h2>
45
- <p>Car Parking Multiplayer is a realistic driving simulator game for Android devices that offers more than just parking. You can explore an open-world city with various locations, customize your car with different options, and play online with other players in multiplayer mode. The game has realistic graphics and physics, a variety of vehicles and customization options, and an easy-to-use interface. If you want to download Car Parking Multiplayer APK for free, you can use the official sources, such as Google Play Store or Uptodown, or any other trusted third-party source. However, you will need to enable unknown sources on your device before installing the APK file. You can also follow our tips and tricks for playing Car Parking Multiplayer to improve your skills and enjoy the game more.</p>
46
- <h3>FAQs</h3>
47
- <ul>
48
- <li><b>Q: Is Car Parking Multiplayer safe to download?</b></li>
49
- <li>A: Yes, Car Parking Multiplayer is safe to download if you use official sources, such as Google Play Store or Uptodown[^1^ or any other trusted third-party source. However, you should always scan the APK file for viruses or malware before installing it on your device.</li>
50
- <li><b>Q: How much storage space does Car Parking Multiplayer require?</b></li>
51
- <li>A: Car Parking Multiplayer requires about 500 MB of storage space on your device. However, this may vary depending on the updates and additional content that you download in the game.</li>
52
- <li><b>Q: Can I play Car Parking Multiplayer offline?</b></li>
53
- <li>A: Yes, you can play Car Parking Multiplayer offline in single-player mode. However, you will need an internet connection to play online in multiplayer mode or to access some features, such as the car market or the clan system.</li>
54
- <li><b>Q: What are the minimum requirements to play Car Parking Multiplayer on Android?</b></li>
55
- <li>A: The minimum requirements to play Car Parking Multiplayer on Android are as follows: <ul>
56
- <li>Android version: 4.4 or higher</li>
57
- <li>RAM: 1 GB or higher</li>
58
- <li>CPU: 1.5 GHz or higher</li>
59
- <li>GPU: Mali-400 MP or higher</li>
60
- </ul>
61
- </li>
62
- <li><b>Q: How can I contact the developers of Car Parking Multiplayer?</b></li>
63
- <li>A: You can contact the developers of Car Parking Multiplayer by sending them an email at [email protected] or by visiting their website at https://olzhass.com/. You can also follow them on Facebook, Instagram, YouTube, or Discord for the latest news and updates about the game.</li>
64
- </ul></p> 197e85843d<br />
65
- <br />
66
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/College Romance Season 1 A Hilarious Story of Three BFFs and Their Love Lives.md DELETED
@@ -1,111 +0,0 @@
1
- <br />
2
- <h1>College Romance Season 1 Download Filmyzilla: Is It Legal and Safe?</h1>
3
- <p>College Romance is a popular web series that depicts the lives and loves of three college friends. The first season of the show was released in 2018 and received rave reviews from the audience. The show is full of humor, drama, romance, and nostalgia. It is available to watch online on Sony Liv and TVF Play.</p>
4
- <h2>college romance season 1 download filmyzilla</h2><br /><p><b><b>Download Zip</b> &#187; <a href="https://urlin.us/2uSXrt">https://urlin.us/2uSXrt</a></b></p><br /><br />
5
- <p>Filmyzilla is a notorious website that leaks movies and shows online for free. The website has a huge collection of pirated content from various genres and languages. One can find the latest movies, Bollywood movies, dubbed movies, Telugu movies, Tamil movies, Hollywood movies, web series, and more on this website.</p>
6
- <p>But is it legal and safe to download College Romance season 1 from Filmyzilla? In this article, we will answer this question and provide you with some alternatives and solutions to watch College Romance season 1 online legally and safely.</p>
7
- <h2>College Romance Season 1: A Fun and Relatable Web Series</h2>
8
- <h3>The Plot and Characters of College Romance Season 1</h3>
9
- <p>College Romance season 1 follows the adventures of three best friends - Naira, Trippy, and Karan - who are looking for love, laughs, and some lifelong memories while attending college together. Naira is a smart and confident girl who helps her friends with their relationship problems. Trippy is a fun-loving guy who has a crush on a senior girl named Raveena. Karan is a confused guy who is dating a girl named Deepika but is not sure about his feelings for her.</p>
10
- <p>The show explores the various aspects of college life such as parties, exams, friendships, breakups, hookups, and more. The show also features some hilarious situations and dialogues that will make you laugh out loud. The show has a total of five episodes, each lasting for about 20 minutes.</p>
11
- <p>College Romance Season 1 free streaming online<br />
12
- How to watch College Romance Season 1 on Sony Liv<br />
13
- College Romance Season 1 full episodes HD quality<br />
14
- College Romance Season 1 cast and crew details<br />
15
- College Romance Season 1 review and ratings<br />
16
- College Romance Season 1 best scenes and moments<br />
17
- College Romance Season 1 download in Hindi<br />
18
- College Romance Season 1 subtitles download<br />
19
- College Romance Season 1 plot summary and spoilers<br />
20
- College Romance Season 1 memes and fan reactions<br />
21
- College Romance Season 1 behind the scenes and bloopers<br />
22
- College Romance Season 1 trivia and facts<br />
23
- College Romance Season 1 soundtrack and songs<br />
24
- College Romance Season 1 awards and nominations<br />
25
- College Romance Season 1 release date and time<br />
26
- College Romance Season 1 trailer and teaser<br />
27
- College Romance Season 1 comparison with other web series<br />
28
- College Romance Season 1 season 2 predictions and updates<br />
29
- College Romance Season 1 Filmyzilla alternatives and options<br />
30
- College Romance Season 1 torrent download links<br />
31
- College Romance Season 1 watch party ideas and tips<br />
32
- College Romance Season 1 merchandise and products<br />
33
- College Romance Season 1 fan art and creations<br />
34
- College Romance Season 1 quotes and dialogues<br />
35
- College Romance Season 1 characters and relationships<br />
36
- College Romance Season 1 genre and themes<br />
37
- College Romance Season 1 controversies and issues<br />
38
- College Romance Season 1 interviews and podcasts<br />
39
- College Romance Season 1 fan theories and speculations<br />
40
- College Romance Season 1 funniest episodes and jokes<br />
41
- College Romance Season 1 romantic episodes and scenes<br />
42
- College Romance Season 1 emotional episodes and scenes<br />
43
- College Romance Season 1 action-packed episodes and scenes<br />
44
- College Romance Season 1 twisty episodes and scenes<br />
45
- College Romance Season 1 most liked episodes and scenes<br />
46
- College Romance Season 1 most disliked episodes and scenes<br />
47
- College Romance Season 1 most surprising episodes and scenes<br />
48
- College Romance Season 1 most relatable episodes and scenes<br />
49
- College Romance Season 1 most memorable episodes and scenes<br />
50
- College Romance Season 1 binge-watch guide and tips<br />
51
- College Romance Season 1 rewatch value and ranking<br />
52
- College Romance Season 1 feedback and suggestions<br />
53
- College Romance Season 1 quiz and games<br />
54
- College Romance Season 1 coupons and discounts<br />
55
- College Romance Season 1 news and updates<br />
56
- College Romance Season 1 social media accounts and hashtags</p>
57
- <h3>The Popularity and Reception of College Romance Season 1</h3>
58
- <p>College Romance season 1 was a huge hit among the viewers, especially the youth. The show received positive feedback from the critics and the audience alike. The show was praised for its realistic portrayal of college life, its relatable characters, its witty humor, its catchy music, and its engaging storyline. The show also won several awards and nominations, such as the Indian Television Academy Awards, the Indian Web Series Awards, the Streamy Awards India, and more.</p>
59
- <p>The show has a rating of 8.7 out of 10 on IMDb and a rating of 4.5 out of 5 on JustWatch. The show has also garnered a huge fan following on social media platforms such as YouTube, Instagram, Facebook, Twitter, etc. The show has over 100 million views on YouTube and over one million followers on Instagram.</p>
60
- <h2>Filmyzilla: A Notorious Movie Piracy Website</h2>
61
- <h3>How Filmyzilla Leaks Movies and Shows Online</h3>
62
- <p>Filmyzilla is one of the many torrent websites that illegally provide leaked and pirated movies and shows for free. The website has a large library of movies and shows of different genres and categories. One can find the latest movies, Bollywood movies, dubbed movies, Telugu movies, Tamil movies, Hollywood movies, web series, and more on this website. The website also offers various formats and resolutions to choose from, such as 360p, 480p, 720p, 1080p, HD, etc.</p>
63
- <p>Filmyzilla leaks movies and shows online by uploading them on its servers or by providing links to other sources. The website often uploads the movies and shows before or soon after their official release. The website also changes its domain name frequently to avoid detection and legal action. Some of the domain names used by Filmyzilla are filmyzilla.com, filmyzilla.in, filmyzilla.net, filmyzilla.vip, filmyzilla.pro, filmyzilla.me, etc.</p>
64
- <h3>The Risks and Consequences of Using Filmyzilla</h3>
65
- <p>Using Filmyzilla or any other torrent website is not only illegal but also risky and harmful. Here are some of the risks and consequences of using Filmyzilla:</p>
66
- <ul>
67
- <li><b>Legal trouble:</b> Downloading or streaming movies and shows from Filmyzilla is a violation of the Indian Copyright Act of 1957 and the Information Technology Act of 2000. Anyone who is caught using Filmyzilla can face legal action such as fines, imprisonment, or both.</li>
68
- <li><b>Malware infection:</b> Filmyzilla or any other torrent website may contain viruses, malware, spyware, ransomware, or other malicious software that can infect your device and compromise your data and security. These malware can also damage your device or make it vulnerable to hackers.</li>
69
- <li><b>Poor quality:</b> Filmyzilla or any other torrent website may not provide you with the best quality of movies and shows. The movies and shows may be low in resolution, audio quality, subtitles, or synchronization. They may also have watermarks, advertisements, or other interruptions that can ruin your viewing experience.</li>
70
- <li><b>Unethical behavior:</b> Using Filmyzilla or any other torrent website is an unethical and immoral act that harms the film industry and the artists. By downloading or streaming movies and shows from Filmyzilla, you are depriving the filmmakers and actors of their rightful earnings and recognition. You are also supporting the illegal and criminal activities of the piracy websites.</li>
71
- </ul>
72
- <h2>College Romance Season 1 Download Filmyzilla: Why You Should Avoid It</h2>
73
- <h3>The Legal Issues of Downloading College Romance Season 1 from Filmyzilla</h3>
74
- <p>Downloading College Romance season 1 from Filmyzilla is a clear case of piracy and infringement of intellectual property rights. College Romance season 1 is the original work of The Viral Fever (TVF) and Sony Liv, who own the exclusive rights to distribute and exhibit the show online. By downloading College Romance season 1 from Filmyzilla, you are violating their rights and breaking the law.</p>
75
- <p>The makers of College Romance season 1 have taken several measures to prevent the piracy of their show. They have filed complaints against Filmyzilla and other piracy websites that have leaked their show online. They have also urged the viewers to watch their show only on the official platforms such as Sony Liv and TVF Play. They have also warned the viewers about the legal consequences of using piracy websites such as Filmyzilla.</p>
76
- <h3>The Quality and Security Issues of Downloading College Romance Season 1 from Filmyzilla</h3>
77
- <p>Downloading College Romance season 1 from Filmyzilla is not only illegal but also unsafe and unsatisfactory. As mentioned earlier, Filmyzilla may expose you to various malware threats that can harm your device and data. Moreover, Filmyzilla may not provide you with the best quality of College Romance season 1. The show may be low in resolution, audio quality, subtitles, or synchronization. It may also have watermarks, advertisements, or other interruptions that can spoil your enjoyment.</p>
78
- <p>Downloading College Romance season 1 from Filmyzilla is also a waste of time and resources. You may have to spend a lot of time searching for a working link or a suitable format on Filmyzilla. You may also have to deal with slow download speed, broken links, corrupted files, or incomplete downloads on Filmyzilla. You may also end up consuming a lot of data bandwidth or storage space on your device by downloading College Romance season 1 from Filmyzilla.</p>
79
- <h2>College Romance Season 1 Download Filmyzilla: Alternatives and Solutions</h2>
80
- <h3>The Legal and Safe Ways to Watch College Romance Season 1 Online</h3>
81
- <p>The best way to watch College Romance season 1 online is to use the legal and safe platforms that have the official rights to stream the show online. These platforms are Sony Liv and TVF Play. Sony Liv is a premium video-on-demand service that offers a variety of movies, shows, sports, and live TV channels. Sony Liv has the exclusive streaming rights for College Romance season 1 in India. You can watch College Romance season 1 on Sony Liv by subscribing to one of its plans. The plans start from Rs. 299 per month or Rs. 999 per year. You can also get a free trial for 7 days before subscribing to Sony Liv. You can access Sony Liv on your web browser, mobile app, smart TV, or gaming console.</p>
82
- TVF Play is a free online video platform that offers original and creative content from The Viral Fever (TVF). TVF Play has the co-production rights for College Romance season 1 along with Sony Liv. You can watch College Romance season 1 on TVF Play for free without any subscription or registration. You can access TVF Play on your web browser, mobile app, or YouTube channel.</p>
83
- <h3>The Benefits and Advantages of Watching College Romance Season 1 Online</h3>
84
- <p>Watching College Romance season 1 online on Sony Liv or TVF Play has many benefits and advantages over downloading it from Filmyzilla or any other piracy website. Here are some of them:</p>
85
- <ul>
86
- <li><b>Legal and ethical:</b> Watching College Romance season 1 online on Sony Liv or TVF Play is a legal and ethical way to enjoy the show. You are respecting the rights and efforts of the makers and actors of the show. You are also supporting the growth and development of the Indian web series industry.</li>
87
- <li><b>Safe and secure:</b> Watching College Romance season 1 online on Sony Liv or TVF Play is a safe and secure way to enjoy the show. You are not exposing yourself to any malware threats or legal troubles. You are also protecting your device and data from any damage or loss.</li>
88
- <li><b>High quality:</b> Watching College Romance season 1 online on Sony Liv or TVF Play is a high-quality way to enjoy the show. You are getting the best resolution, audio quality, subtitles, and synchronization of the show. You are also getting a smooth and uninterrupted streaming experience without any watermarks, advertisements, or other distractions.</li>
89
- <li><b>Convenient and flexible:</b> Watching College Romance season 1 online on Sony Liv or TVF Play is a convenient and flexible way to enjoy the show. You can watch the show anytime, anywhere, and on any device of your choice. You can also pause, resume, rewind, or fast-forward the show as per your preference. You can also watch the show offline by downloading it on your device.</li>
90
- </ul>
91
- <h2>Conclusion</h2>
92
- <p>College Romance season 1 is a fun and relatable web series that you should not miss. The show has a great plot, characters, humor, music, and message. The show is available to watch online on Sony Liv and TVF Play legally and safely.</p>
93
- <p>Downloading College Romance season 1 from Filmyzilla or any other piracy website is illegal, risky, harmful, and unethical. You should avoid using Filmyzilla or any other torrent website for downloading or streaming movies and shows online.</p>
94
- <p>Instead, you should use the legal and safe platforms such as Sony Liv and TVF Play to watch College Romance season 1 online. You will get many benefits and advantages by doing so.</p>
95
- <p>We hope this article has helped you understand why you should not download College Romance season 1 from Filmyzilla or any other piracy website. We also hope you have enjoyed reading this article as much as we have enjoyed writing it for you.</p>
96
- <h2>Frequently Asked Questions</h2>
97
- <p>Here are some of the frequently asked questions about College Romance season 1 download Filmyzilla:</p>
98
- <ol>
99
- <li><b>Is College Romance season 1 available on Netflix?</b></li>
100
- <p>No, College Romance season 1 is not available on Netflix. The show is only available on Sony Liv and TVF Play.</p>
101
- <li><b>Is College Romance season 1 based on a true story?</b></li>
102
- <p>No, College Romance season 1 is not based on a true story. The show is a fictional comedy-drama that depicts the lives and loves of three college friends.</p>
103
- <li><b>Is College Romance season 2 coming soon?</b></li>
104
- <p>Yes, College Romance season 2 is coming soon. The makers of the show have announced that they are working on the second season of the show and it will be released in 2023.</p>
105
- <li><b>Is Filmyzilla banned in India?</b></li>
106
- <p>Yes, Filmyzilla is banned in India by the government along with many other piracy websites. However, Filmyzilla keeps changing its domain name and proxy servers to evade the ban and continue to operate.</p>
107
- <li><b>Is there any penalty for using Filmyzilla?</b></li>
108
- <p>Yes, there is a penalty for using Filmyzilla or any other piracy website. According to the Indian law, anyone who is found using Filmyzilla or any other piracy website can face a fine of up to Rs. 3 lakhs or imprisonment of up to 3 years or both.</p>
109
- </ol></p> 197e85843d<br />
110
- <br />
111
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/ARK Survival Evolved - Primal Fear Mod A Guide to the Best Dinos and Items.md DELETED
@@ -1,125 +0,0 @@
1
-
2
- <h1>How to Download and Install Primal Fear Mod for Ark: Survival Evolved</h1>
3
- <p>If you are looking for a new and exciting way to play Ark: Survival Evolved, you might want to try out the Primal Fear mod. This mod adds over 200 different creatures, as well as new items, weapons, armor, and bosses. In this article, we will show you how to download and install Primal Fear mod for Ark, as well as some of its features and creatures.</p>
4
- <h2>What is Primal Fear Mod?</h2>
5
- <p>Primal Fear is a massive dino mod for Ark, developed by Steam user Pikkon38. The mod participated in the Ark Modding Contest of 2018 and placed in 4th. In June 2020, Primal Fear joined the Sponsored Mod program.</p>
6
- <h2>ark survival evolved primal fear mod download</h2><br /><p><b><b>Download File</b> &bull; <a href="https://jinyurl.com/2uNMSp">https://jinyurl.com/2uNMSp</a></b></p><br /><br />
7
- <h3>Features of Primal Fear Mod</h3>
8
- <p>Primal Fear mod adds many features to enhance your gameplay, such as:</p>
9
- <ul>
10
- <li>Tame, breed, and ride all new creatures to expand on your gameplay</li>
11
- <li>Adds new taming mechanics for custom creatures</li>
12
- <li>Custom tiered kibble system</li>
13
- <li>New and more powerful weapons and armor</li>
14
- <li>Adds crafting stations designated for the mod</li>
15
- <li>Expansions for Scorched Earth, Aberration, Extinction, and Genesis maps</li>
16
- </ul>
17
- <h3>Creatures of Primal Fear Mod</h3>
18
- <p>Primal Fear mod currently has over 200 different creatures in it, and more creatures are added in the development process. The creatures are divided into different tiers, such as:</p>
19
- <ul>
20
- <li>Toxic Creatures: The first tier of creatures that have a 7% chance of spawning. They drop Toxic Blood and Toxic Hide when harvested.</li>
21
- <li>Alpha Creatures: The second tier of creatures that have a 5% chance of spawning. They require Alpha Kibble to tame, which requires Toxic Egg and Toxic Blood. They drop Alpha Blood and Alpha Hide when harvested.</li>
22
- <li>Elemental Creatures: The third tier of creatures that have a 3% chance of spawning. They require Elemental Kibble to tame, which requires Apex Egg, Apex Blood, and various Feathers. They drop Elemental Hide and Feathers when harvested.</li>
23
- <li>Apex Creatures: The fourth tier of creatures that have a 3.5% chance of spawning. They require Apex Kibble to tame, which requires Alpha Blood and Elemental Egg. They drop Apex Blood and Apex Hide when harvested.</li>
24
- <li>Fabled Creatures: The fifth tier of creatures that have a 2.75% chance of spawning. They require Fabled Kibble to tame, which requires Apex Blood and Apex Egg. They drop Fabled Blood and Fabled Hide when harvested.</li>
25
- <li>Celestial Creatures: The sixth tier of creatures that have a 2.25% chance of spawning. They require Celestial Kibble to tame, which requires Fabled Blood and Fabled Egg. They drop Celestial Soul when killed.</li>
26
- <li>Demonic Creatures: The seventh tier of creatures that have a 2% chance of spawning. They require Demonic Kibble to tame, which requires Celestial Soul and Demonic Soul. They drop Demonic Soul when killed.</li>
27
- <li>Primal Creatures: The eighth tier of creatures that are bosses in Primal Fear. They have a full black body, a red outline, a thick red aura, old Dragon OST playing while near them, as well as being noticeably larger than their vanilla counterparts.</li>
28
- <li>And many more...</li>
29
- </ul>
30
- <h2>How to Find and Subscribe to Primal Fear Mod on Steam Workshop</h2>
31
- <p>To install mods on Ark, you need to subscribe to them from the Steam Workshop. Here are the steps to find and subscribe to Primal Fear mod on Steam Workshop:</p>
32
- <ol>
33
- <li>Open Steam and go to the Library tab.</li>
34
- <li>Right-click on Ark: Survival Evolved and select Properties.</li>
35
- <li>Go to the Local Files tab and click on Browse Local Files.</li>
36
- <li>Open the ShooterGame folder and then the Content folder.</li>
37
- <li>Copy the Mods folder and paste it somewhere safe as a backup.</li>
38
- <li>Go back to Steam and click on the Community tab.</li>
39
- <li>Click on Workshop and search for Ark: Survival Evolved.</li>
40
- <li>In the search bar, type Primal Fear and press Enter.</li>
41
- <li>You will see a list of mods related to Primal Fear. The main mod is called Primal Fear and has over 1.5 million subscribers. You can also subscribe to other mods that are compatible with Primal Fear, such as Primal Fear Boss Expansion, Primal Fear Aberration Expansion, Primal Fear Genesis Expansion, etc.</li>
42
- <li>To subscribe to a mod, click on it and then click on the green Subscribe button. The mod will start downloading automatically.</li>
43
- </ol>
44
- <h2>How to Install and Activate Primal Fear Mod on Ark</h2>
45
- <p>After subscribing to the mods, you need to install and activate them on Ark. Here are the steps to do that:</p>
46
- <p>How to install primal fear mod for ark survival evolved<br />
47
- Primal fear mod features and creatures for ark survival evolved<br />
48
- Best settings and maps for primal fear mod in ark survival evolved<br />
49
- Primal fear mod review and gameplay for ark survival evolved<br />
50
- Primal fear mod wiki and guides for ark survival evolved<br />
51
- How to tame and breed primal fear dinos in ark survival evolved<br />
52
- Primal fear mod expansions and updates for ark survival evolved<br />
53
- Primal fear mod boss battles and loot for ark survival evolved<br />
54
- How to join primal fear official server in ark survival evolved<br />
55
- Primal fear mod troubleshooting and compatibility for ark survival evolved<br />
56
- How to spawn primal fear dinos and items in ark survival evolved<br />
57
- Primal fear mod tips and tricks for beginners in ark survival evolved<br />
58
- Primal fear mod best armor and weapons for ark survival evolved<br />
59
- Primal fear mod custom kibble system for ark survival evolved<br />
60
- Primal fear mod tier list and rankings for ark survival evolved<br />
61
- How to uninstall primal fear mod from ark survival evolved<br />
62
- Primal fear mod challenges and achievements for ark survival evolved<br />
63
- Primal fear mod community and discord for ark survival evolved<br />
64
- Primal fear mod comparison and differences with other mods in ark survival evolved<br />
65
- Primal fear mod patch notes and changelog for ark survival evolved<br />
66
- How to backup and restore primal fear mod save files in ark survival evolved<br />
67
- Primal fear mod cheats and hacks for ark survival evolved<br />
68
- Primal fear mod best base locations and designs for ark survival evolved<br />
69
- Primal fear mod easter eggs and secrets for ark survival evolved<br />
70
- Primal fear mod fan art and videos for ark survival evolved<br />
71
- How to optimize primal fear mod performance and graphics in ark survival evolved<br />
72
- Primal fear mod lore and story for ark survival evolved<br />
73
- Primal fear mod FAQs and common issues for ark survival evolved<br />
74
- Primal fear mod feedback and suggestions for ark survival evolved<br />
75
- Primal fear mod donation and support options for ark survival evolved<br />
76
- How to create primal fear mod content and mods for ark survival evolved<br />
77
- Primal fear mod best dinos and mounts for ark survival evolved<br />
78
- Primal fear mod console commands and admin codes for ark survival evolved<br />
79
- Primal fear mod fun facts and trivia for ark survival evolved<br />
80
- Primal fear mod pros and cons for ark survival evolved<br />
81
- How to play primal fear mod solo or co-op in ark survival evolved<br />
82
- Primal fear mod best mods to use with it in ark survival evolved<br />
83
- Primal fear mod future plans and roadmap for ark survival evolved<br />
84
- Primal fear mod steam workshop page and ratings for ark survival evolved<br />
85
- Primal fear mod tutorials and walkthroughs for ark survival evolved</p>
86
- <h3>How to Copy and Extract the Mods</h3>
87
- <ol>
88
- <li>Go to the Mods folder that you copied earlier and open it.</li>
89
- <li>You will see a bunch of folders with numbers as their names. These are the mods that you subscribed to. Each folder has a .mod file inside it.</li>
90
- <li>Copy all the folders and paste them into the Mods folder inside the Content folder of Ark. This will overwrite the existing folders.</li>
91
- <li>Open each folder and extract the .mod file using a program like WinRAR or 7-Zip. You will get a folder with the same name as the .mod file.</li>
92
- <li>Delete the .mod file and keep the extracted folder.</li>
93
- </ol>
94
- <h3>How to Select and Load the Mods</h3>
95
- <ol>
96
- <li>Launch Ark: Survival Evolved from Steam.</li>
97
- <li>In the main menu, click on Host/Local.</li>
98
- <li>Click on Play Single Player or Host Non-Dedicated Session, depending on your preference.</li>
99
- <li>In the Game Settings tab, scroll down to Active Mods and click on Select Mod.</li>
100
- <li>You will see a list of mods that you installed. Select Primal Fear as the first mod, followed by any other mods that you want to use. You can also change the order of the mods by dragging them up or down.</li>
101
- <li>Click on Save Changes and then click on Play With Mods.</li>
102
- </ol>
103
- <h3>How to Update and Backup the Mods</h3>
104
- <p>To update the mods, you need to unsubscribe and resubscribe to them from Steam Workshop. This will download the latest version of the mods. You can also check for updates manually by going to Steam Workshop and clicking on Updates in the left sidebar. To backup the mods, you need to copy the Mods folder from Ark's Content folder and paste it somewhere safe. You can also use a program like Ark Server Manager to manage your mods more easily.</p>
105
- <h2>Conclusion</h2>
106
- <p>Primal Fear is a great mod for Ark: Survival Evolved that adds a lot of new content and challenges to the game. It is easy to download and install from Steam Workshop, and you can customize your gameplay with different expansions and settings. If you are looking for a fresh and fun way to play Ark, you should definitely give Primal Fear a try!</p>
107
- <h2>FAQs</h2>
108
- <ul>
109
- <li><b>Q: What are the system requirements for Primal Fear mod?</b></li>
110
- <li>A: Primal Fear mod is quite demanding on your system, especially if you use multiple expansions and high settings. You should have at least 8 GB of RAM, a quad-core processor, and a dedicated graphics card with 4 GB of VRAM or more.</li>
111
- <li><b>Q: How do I uninstall Primal Fear mod?</b></li>
112
- <li>A: To uninstall Primal Fear mod, you need to unsubscribe from it on Steam Workshop, delete its folders from Ark's Mods folder, and remove it from your Active Mods list in Ark's Game Settings.</li>
113
- <li><b>Q: How do I spawn Primal Fear creatures using commands?</b></li>
114
- <li>A: To spawn Primal Fear creatures using commands, you need to know their spawn codes. You can find them on Primal Fear's Wiki page. You can also use the Beacon app to generate spawn codes for Primal Fear creatures. To spawn a creature using commands, you need to open the console by pressing Tab, and then type cheat spawndino followed by the spawn code. For example, to spawn an Apex Reaper King, you can type: cheat spawndino "Blueprint'/Game/Mods/Primal_Fear/Dinos/Apex/Apex_Reaper/King/PFApexXenomorph_Character_BP_Male_Tamed_Child.PFApexXenomorph_Character_BP_Male_Tamed_Child'" 1 1 1 30 You can also change the numbers at the end to adjust the level, location, and quantity of the spawned creature.</li>
115
- <li><b>Q: How do I tame Primal Fear creatures?</b></li>
116
- <li>A: To tame Primal Fear creatures, you need to use different types of kibble depending on the tier of the creature. You can craft kibble using the Primal Smithy or the Primal Cooking Pot. You also need to use tranquilizers that are strong enough to knock out the creature. You can use the Primal Pike, the Primal Rifle, or the Primal Compound Bow with different types of arrows and darts. You can also use special items like Potent Narcotics, Tame Helpers, and Wake Up Stimulants to help with the taming process.</li>
117
- <li><b>Q: How do I fight Primal Fear bosses?</b></li>
118
- <li>A: To fight Primal Fear bosses, you need to summon them using special items called Summoners. You can craft Summoners using the Primal Smithy or the Primal Cooking Pot. You also need to have a strong team of creatures and weapons to face the bosses. Some bosses have special abilities and weaknesses that you need to be aware of. For example, Nova the Destroyer has three AOE attacks and is immune to fire damage, but is vulnerable to electric damage.</li>
119
- <li><b>Q: How do I get Primal Fear expansions?</b></li>
120
- <li>A: To get Primal Fear expansions, you need to subscribe to them on Steam Workshop, just like the main mod. You can find them by searching for Primal Fear on Workshop and looking for the ones that have Expansion in their name. You also need to install and activate them on Ark, just like the main mod. You can use them on any map that supports them.</li>
121
- <li><b>Q: How do I get support for Primal Fear mod?</b></li>
122
- <li>A: To get support for Primal Fear mod, you can join their Discord server, where you can ask questions, report bugs, give feedback, and chat with other players and developers. You can also check their Wiki page for more information and guides.</li>
123
- </ul></p> 197e85843d<br />
124
- <br />
125
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download Business WhatsApp Sender 7.0.1.1 for Free and Boost Your Business.md DELETED
@@ -1,124 +0,0 @@
1
-
2
- <h1>Business WhatsApp Sender 7.0.1.1 Free Download: A Powerful Tool for WhatsApp Marketing</h1>
3
- <p>WhatsApp is one of the most popular and widely used messaging apps in the world, with over 2 billion users as of 2020. It is not only a great tool for personal communication, but also a powerful platform for business marketing. With WhatsApp Business, you can create a professional profile for your business, communicate more efficiently with your customers, and grow your business.</p>
4
- <h2>business whatsapp sender 7.0.1.1 free download</h2><br /><p><b><b>Download</b> ---> <a href="https://jinyurl.com/2uNPGM">https://jinyurl.com/2uNPGM</a></b></p><br /><br />
5
- <p>However, if you want to take your WhatsApp marketing to the next level, you need a software that can help you send bulk messages, automate responses, filter contacts, and more. That's where Business WhatsApp Sender 7.0.1.1 comes in handy.</p>
6
- <h2>What is Business WhatsApp Sender 7.0.1.1?</h2>
7
- <p>Business WhatsApp Sender 7.0.1.1 is a software that allows you to send unlimited messages to your potential and existing customers using WhatsApp Business. It is a 100% safe and reliable tool that secures your account and reduces the chances of getting blocked.</p>
8
- <h3>Features of Business WhatsApp Sender 7.0.1.1</h3>
9
- <p>Business WhatsApp Sender 7.0.1.1 offers various features that make it a must-have tool for any WhatsApp marketer:</p>
10
- <ul>
11
- <li>You can send text, images, audio, document files, etc.</li>
12
- <li>You can import or extract contacts from various sources such as Google Maps, groups, files, etc.</li>
13
- <li>You can create and customize your messages with variables, emojis, links, etc.</li>
14
- <li>You can set up dynamic chatbots and auto-reply options for different scenarios.</li>
15
- <li>You can control the speed, delay, and sleep time of your campaigns.</li>
16
- <li>You can verify and filter mobile numbers before sending messages.</li>
17
- <li>You can support multi-language functionality.</li>
18
- <li>You can view reports and statistics of your campaigns.</li>
19
- </ul>
20
- <h3>Benefits of Business WhatsApp Sender 7.0.1.1</h3>
21
- <p>By using Business WhatsApp Sender 7.0.1.1, you can enjoy many benefits for your business such as:</p>
22
- <ul>
23
- <li>You can reach a large number of customers in a short time.</li>
24
- <li>You can increase your brand awareness and visibility.</li>
25
- <li>You can improve your customer engagement and loyalty.</li>
26
- <li>You can generate more leads and sales.</li>
27
- <li>You can save time and money on marketing.</li>
28
- </ul>
29
- <h2>How to Download and Activate Business WhatsApp Sender 7.0.1.1?</h2>
30
- <p>If you are interested in using Business WhatsApp Sender 7.0.1.1 for your business marketing, here are the steps you need to follow:</p>
31
- <p>How to download and install WhatsApp Business Sender 7.0.1.1<br />
32
- WhatsApp Business Sender 7.0.1.1 features and benefits<br />
33
- WhatsApp Business Sender 7.0.1.1 review and rating<br />
34
- WhatsApp Business Sender 7.0.1.1 activation and license key<br />
35
- WhatsApp Business Sender 7.0.1.1 tutorial and guide<br />
36
- WhatsApp Business Sender 7.0.1.1 support and customer service<br />
37
- WhatsApp Business Sender 7.0.1.1 alternative and comparison<br />
38
- WhatsApp Business Sender 7.0.1.1 update and upgrade<br />
39
- WhatsApp Business Sender 7.0.1.1 discount and coupon code<br />
40
- WhatsApp Business Sender 7.0.1.1 demo and trial version<br />
41
- WhatsApp Business Sender 7.0.1.1 for Android and iOS devices<br />
42
- WhatsApp Business Sender 7.0.1.1 for Windows and Mac computers<br />
43
- WhatsApp Business Sender 7.0.1.1 for small and medium businesses<br />
44
- WhatsApp Business Sender 7.0.1.1 for e-commerce and online stores<br />
45
- WhatsApp Business Sender 7.0.1.1 for marketing and sales campaigns<br />
46
- WhatsApp Business Sender 7.0.1.1 for lead generation and conversion<br />
47
- WhatsApp Business Sender 7.0.1.1 for customer engagement and retention<br />
48
- WhatsApp Business Sender 7.0.1.1 for communication and feedback<br />
49
- WhatsApp Business Sender 7.0.1.1 for automation and scheduling<br />
50
- WhatsApp Business Sender 7.0.1.1 for personalization and customization<br />
51
- WhatsApp Business Sender 7.0.1.1 with Google Map Extractor tool<br />
52
- WhatsApp Business Sender 7.0.1.1 with Dynamic Chatbots feature<br />
53
- WhatsApp Business Sender 7.0.1.1 with Auto Reply function<br />
54
- WhatsApp Business Sender 7.0.1.1 with Import/Export Contents option<br />
55
- WhatsApp Business Sender 7.0.1.1 with Sending Customized Messages capability<br />
56
- WhatsApp Business Sender 7.0.1.1 with Supports Multi-Language functionality<br />
57
- WhatsApp Business Sender 7.0 .11 with Bulk Whatsapp Marketing Software integration<br />
58
- WhatsApp Business Sender 7 .01 .11 with Catalogue Cloud Based Ecommerce System compatibility<br />
59
- WhatsApp Business Sender .01 .11 with Easy GST Billing Software for Inventory and Accounting connection<br />
60
- WhatsApp Business .01 .11 with A Complete Lead Management Software (CRM) association<br />
61
- Download WhatsApp Business from Meta for free on Google Play Store [^4^]<br />
62
- Communicate more efficiently with your customers using WhatsApp Business [^4^]<br />
63
- Grow your business with WhatsApp Business from Meta [^4^]<br />
64
- Create a profile for your business on WhatsApp Business [^4^]<br />
65
- Use business messaging tools on WhatsApp Business [^4^]<br />
66
- Use a landline or fixed number to register on WhatsApp Business [^4^]<br />
67
- Run both WhatsApp Messenger and WhatsApp Business on the same phone [^4^]<br />
68
- Use WhatsApp Web to respond to your customers from your computer [^4^]<br />
69
- Send multimedia, free calls, free international messaging, group chat, offline messages, and more on WhatsApp Business [^4^]<br />
70
- Contact [email protected] or follow @WhatsApp on Twitter for feedback, questions, or concerns about WhatsApp Business [^4^]</p>
71
- <h3>Step 1: Download the software from the official website</h3>
72
- <p>The first step is to download the software from the official website. You can choose between the trial version and the full version. The trial version allows you to send up to 10 messages per day for free, while the full version costs $49 and allows you to send unlimited messages.</p>
73
- <h3>Step 2: Install the software on your PC</h3>
74
- <p>The next step is to install the software on your PC. You need to have Windows 7 or higher, .NET Framework 4.5 or higher, and WhatsApp Business installed on your PC. You also need to have a valid WhatsApp Business number and a QR code scanner. To install the software, follow these steps:</p>
75
- <ol>
76
- <li>Run the setup file and follow the instructions.</li>
77
- <li>Accept the terms and conditions and click Next.</li>
78
- <li>Choose the destination folder and click Next.</li>
79
- <li>Wait for the installation to complete and click Finish.</li>
80
- </ol>
81
- <h3>Step 3: Generate an order number and send it to the developer</h3>
82
- <p>The third step is to generate an order number and send it to the developer. This is required to activate the full version of the software. To generate an order number, follow these steps:</p>
83
- <ol>
84
- <li>Open the software and click on Register.</li>
85
- <li>Enter your name, email, phone number, and country.</li>
86
- <li>Click on Generate Order Number and copy it.</li>
87
- <li>Send the order number to the developer via email or WhatsApp.</li>
88
- </ol>
89
- <h3>Step 4: Receive the activation code and enter it in the software</h3>
90
- <p>The final step is to receive the activation code and enter it in the software. This will unlock all the features of the software and allow you to use it without any limitations. To activate the software, follow these steps:</p>
91
- <ol>
92
- <li>Wait for the developer to send you the activation code via email or WhatsApp.</li>
93
- <li>Open the software and click on Register.</li>
94
- <li>Enter your name, email, phone number, country, and activation code.</li>
95
- <li>Click on Activate and enjoy the software.</li>
96
- </ol>
97
- <h2>How to Use Business WhatsApp Sender 7.0.1.1 for WhatsApp Marketing?</h2>
98
- <p>Now that you have downloaded and activated Business WhatsApp Sender 7.0.1.1, you are ready to use it for your WhatsApp marketing campaigns. Here are some tips on how to use it effectively:</p>
99
- <h3>Import or extract contacts from various sources</h3>
100
- <p>The first thing you need to do is to import or extract contacts from various sources such as Google Maps, groups, files, etc. You can do this by clicking on Contacts > Import Contacts or Contacts > Extract Contacts. You can also filter contacts by country code, gender, name, etc.</p>
101
- <h3>Create and customize your messages with text, images, audio, documents, etc.</h3>
102
- <p>The next thing you need to do is to create and customize your messages with text, images, audio, documents, etc. You can do this by clicking on Messages > Create Message or Messages > Edit Message. You can also use variables, emojis, links, etc. to make your messages more personalized and engaging.</p>
103
- <h3>Set up dynamic chatbots and auto-reply options</h3>
104
- <p>The third thing you need to do is to set up dynamic chatbots and auto-reply options for different scenarios. You can do this by clicking on Settings > Chatbot Settings or Settings > Auto Reply Settings. You can also use keywords, conditions, actions, etc. to make your chatbots and auto-replies more intelligent and responsive.</p>
105
- <h3>Control the speed, delay, and sleep time of your campaigns</h3>
106
- <p>The last thing you need to do is to control the speed, delay, and sleep time of your campaigns. You can do this by clicking on Settings > General Settings or Settings > Campaign Settings. You can also use timers, schedulers, etc. to make your campaigns more efficient and effective.</p>
107
- <h2>Conclusion</h2>
108
- <p>Business WhatsApp Sender 7.0.1.1 is a powerful tool for WhatsApp marketing that allows you to send unlimited messages to your potential and existing customers using WhatsApp Business. It offers various features and benefits that make it a must-have tool for any WhatsApp marketer. To download and activate Business WhatsApp Sender 7.0.1.1, you need to follow four simple steps: download the software from the official website, install it on your PC, generate an order number and send it to the developer, receive the activation code and enter it in the software. To use Business WhatsApp Sender 7.0.1.1 for WhatsApp marketing, you need to follow some tips on how to import or extract contacts from various sources, create and customize your messages with text, images, audio, documents, etc., set up dynamic chatbots and auto-reply options, and control the speed, delay, and sleep time of your campaigns. By following these tips, you can make the most out of Business WhatsApp Sender 7.0.1.1 and achieve your marketing goals.</p>
109
- <h2>FAQs</h2>
110
- <p>Here are some frequently asked questions about Business WhatsApp Sender 7.0.1.1:</p>
111
- <ol>
112
- <li>Is Business WhatsApp Sender 7.0.1.1 compatible with WhatsApp Web?</li>
113
- <p>No, Business WhatsApp Sender 7.0.1.1 is not compatible with WhatsApp Web. You need to have WhatsApp Business installed on your PC to use the software.</p>
114
- <li>How many messages can I send per day using Business WhatsApp Sender 7.0.1.1?</li>
115
- <p>There is no limit on how many messages you can send per day using Business WhatsApp Sender 7.0.1.1. However, you should avoid sending too many messages to avoid getting blocked by WhatsApp.</p>
116
- <li>Can I use Business WhatsApp Sender 7.0.1.1 on multiple PCs?</li>
117
- <p>No, you can only use Business WhatsApp Sender 7.0.1.1 on one PC per license. If you want to use it on multiple PCs, you need to buy multiple licenses.</p>
118
- <li>Does Business WhatsApp Sender 7.0.1.1 support multi-language functionality?</li>
119
- <p>Yes, Business WhatsApp Sender 7.0.1.1 supports multi-language functionality. You can send messages in any language you want.</p>
120
- <li>What is the refund policy of Business WhatsApp Sender 7.0.1.1?</li>
121
- <p>Business WhatsApp Sender 7.0.1.1 offers a 30-day money-back guarantee if you are not satisfied with the software.</p>
122
- </ol></p> 197e85843d<br />
123
- <br />
124
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Experience the Epic Battle of Godzilla and Kong in PUBG Mobile 1.4 (APK).md DELETED
@@ -1,103 +0,0 @@
1
-
2
- <h1>PUBG Mobile Godzilla Modu Indir APK: How to Download and Play the New Update</h1>
3
- <p>PUBG Mobile is one of the most popular and addictive battle royale games on mobile devices. It offers a thrilling and immersive gameplay experience with realistic graphics, diverse maps, and various modes. But what if you could spice up your game with some giant monsters from the Godzilla vs Kong movie? Well, that's exactly what the latest update of PUBG Mobile offers. In this article, we will tell you everything you need to know about the PUBG Mobile Godzilla Modu, how to download it, and what are the new features and changes that it brings.</p>
4
- <h2>pubg mobile godzilla modu indir apk</h2><br /><p><b><b>Download File</b> &#10038;&#10038;&#10038; <a href="https://jinyurl.com/2uNNdr">https://jinyurl.com/2uNNdr</a></b></p><br /><br />
5
- <h2>What is PUBG Mobile Godzilla Modu?</h2>
6
- <h3>A brief introduction to the new mode and its features</h3>
7
- <p>PUBG Mobile Godzilla Modu is a new mode that is part of the 1.4 update of the game. It is also known as Titan Strikes mode, as it features three titans from the Godzilla vs Kong movie: Godzilla, Kong, and Mechagodzilla. These titans will appear on different maps (Erangel, Sanhok, and Livik) and will roam around, causing havoc and destruction. Players will have to avoid or fight them, while also dealing with other enemies.</p>
8
- <h3>The collaboration between PUBG Mobile and Godzilla vs Kong movie</h3>
9
- <p>The PUBG Mobile Godzilla Modu is a result of a unique collaboration between Tencent, the developer of PUBG Mobile, and Legendary Pictures, the producer of the Godzilla vs Kong movie. The movie is an action-packed blockbuster that pits two iconic monsters against each other in an epic battle for supremacy. The collaboration aims to bring some of the excitement and spectacle of the movie to the game, as well as to celebrate the third anniversary of PUBG Mobile.</p>
10
- <h2>How to Download PUBG Mobile Godzilla Modu APK?</h2>
11
- <h3>The difference between regular and compact versions of the APK</h3>
12
- <p>To download and play the PUBG Mobile Godzilla Modu, you will need to update your game to the latest version (1.4). You can do this by using the Google Play Store or by downloading the APK file from the official website of PUBG Mobile. There are two variants of the APK file available: regular version and compact version. The regular version has a size of 990 MB and includes all the new content. The compact version has a size of 661 MB and requires additional resource packs to be downloaded in-game.</p>
13
- <h3>The step-by-step guide to download and install the APK file</h3>
14
- <p>Here are the steps that you need to follow to download and install the PUBG Mobile Godzilla Modu APK file:</p>
15
- <ol>
16
- <li>Click on one of these links to download either the regular version or the compact version of the APK file.</li>
17
- <li>Once the file is downloaded, locate it on your device and tap on it to install it. Make sure that you have enabled the "Install from Unknown Source" option in your settings.</li>
18
- <li>After the installation is complete, open PUBG Mobile on your device. If you have downloaded the compact version, you will have to download some resource packs in-game.</li>
19
- <li>Login to your account and enjoy playing PUBG Mobile Godzilla Modu.</li>
20
- </ol>
21
- <h3>The disclaimer for users from India and other banned countries</h3>
22
- <p>Disclaimer <p>Disclaimer: PUBG Mobile is banned in some countries, such as India, due to various reasons. Therefore, we do not recommend or endorse downloading or playing the game in those regions. Please follow the laws and regulations of your country and respect the rights of others.</p>
23
- <p>pubg mobile godzilla vs kong apk download<br />
24
- pubg mobile 1.4 update apk obb download<br />
25
- pubg mobile titan strikes mode apk indir<br />
26
- pubg mobile godzilla modu nasıl indirilir<br />
27
- pubg mobile 1.4 global version apk link<br />
28
- pubg mobile godzilla vs kong collaboration apk<br />
29
- pubg mobile 1.4 update features and download<br />
30
- pubg mobile godzilla modu kurulumu<br />
31
- pubg mobile 1.4 apk download for android<br />
32
- pubg mobile godzilla vs kong mode gameplay<br />
33
- pubg mobile 1.4 update release date and time<br />
34
- pubg mobile godzilla modu hileleri<br />
35
- pubg mobile 1.4 patch notes and changes<br />
36
- pubg mobile godzilla vs kong trailer and rewards<br />
37
- pubg mobile 1.4 update size and requirements<br />
38
- pubg mobile godzilla modu yükleme<br />
39
- pubg mobile 1.4 new vehicle and shooting mode<br />
40
- pubg mobile godzilla vs kong event and missions<br />
41
- pubg mobile 1.4 update problems and solutions<br />
42
- pubg mobile godzilla modu oynama<br />
43
- pubg mobile 1.4 update review and rating<br />
44
- pubg mobile godzilla vs kong tips and tricks<br />
45
- pubg mobile 1.4 update bugs and fixes<br />
46
- pubg mobile godzilla modu indirme linki<br />
47
- pubg mobile 1.4 update best settings and sensitivity<br />
48
- pubg mobile godzilla vs kong wallpapers and images<br />
49
- pubg mobile 1.4 update new maps and locations<br />
50
- pubg mobile godzilla modu nedir ve nasıl çalışır<br />
51
- pubg mobile 1.4 update new weapons and skins<br />
52
- pubg mobile godzilla vs kong live stream and videos<br />
53
- pubg mobile 1.4 update new emotes and outfits<br />
54
- pubg mobile godzilla modu güncellemesi ne zaman gelecek<br />
55
- pubg mobile 1.4 update new characters and voice packs<br />
56
- pubg mobile godzilla vs kong comparison and analysis<br />
57
- pubg mobile 1.4 update new achievements and titles<br />
58
- pubg mobile godzilla modu sistem gereksinimleri ve optimizasyonu<br />
59
- pubg mobile 1.4 update new crates and lucky draws<br />
60
- pubg mobile godzilla vs kong memes and jokes<br />
61
- pubg mobile 1.4 update new lobby and theme music<br />
62
- pubg mobile godzilla modu silinmesi ve geri yüklenmesi</p>
63
- <h2>What are the New Features and Changes in PUBG Mobile Godzilla Modu?</h2>
64
- <h3>The appearance of Titans (Godzilla, Kong, and Mechagodzilla) on the maps</h3>
65
- <p>One of the most exciting features of PUBG Mobile Godzilla Modu is the appearance of the three titans from the Godzilla vs Kong movie on different maps. Each titan has its own behavior, abilities, and impact on the environment. Here is a brief overview of each titan and its map:</p>
66
- <ul>
67
- <li>Godzilla: The king of the monsters will appear on Erangel, the classic map of PUBG Mobile. He will spawn randomly on the map and will move towards specific locations, such as Mylta Power, School, Military Base, and others. He will also roar occasionally, which will alert nearby players of his presence. Godzilla can attack players with his tail, claws, and atomic breath. He can also destroy buildings and vehicles with his sheer size and strength.</li>
68
- <li>Kong: The king of Skull Island will appear on Sanhok, the tropical map of PUBG Mobile. He will spawn at the ruins in the center of the map and will stay there for a while. He will then move to one of the four Apex Camps (more on that later) and will defend it from other players. Kong can attack players with his fists, feet, and roar. He can also throw rocks and trees at players and vehicles.</li>
69
- <li>Mechagodzilla: The mechanical titan will appear on Livik, the smallest map of PUBG Mobile. He will spawn at a random location on the map and will patrol around it. He will also shoot lasers and missiles at players and vehicles. Mechagodzilla can also create an electromagnetic pulse that will disable all electronic devices in a certain radius.</li>
70
- </ul>
71
- <h3>The new Titan Crystals that grant special abilities to players</h3>
72
- <p>Another new feature of PUBG Mobile Godzilla Modu is the Titan Crystals. These are special items that can be found on the maps where the titans appear. They are dropped by the titans or by special helicopters that fly over the maps. There are two types of Titan Crystals: Erangel Titan Crystal and Sanhok Titan Crystal.</p>
73
- <p>The Erangel Titan Crystal is a blue crystal that can be used to create a protective shield around the player for a short time. The shield can block bullets and other projectiles, but not melee attacks or explosions. The shield also has a cooldown time after each use.</p>
74
- <p>The Sanhok Titan Crystal is a yellow crystal that can be used to enhance the player's abilities for a short time. The player can jump higher, run faster, and deal more damage with melee attacks. The player can also see footprints of nearby enemies on the mini-map. The effect also has a cooldown time after each use.</p>
75
- <h3>The new Apex Camps that offer high-quality loot and supplies</h3>
76
- <p>The Apex Camps are new locations that can be found on Sanhok, where Kong appears. There are four Apex Camps on the map: Alpha, Beta, Gamma, and Delta. Each camp has a different theme and layout, such as a temple, a cave, a village, or a factory. Each camp also has high-quality loot and supplies, such as weapons, armor, ammo, health kits, and more.</p>
77
- <p>However, there is a catch: only one Apex Camp is active at a time, and it is guarded by Kong. Players will have to fight their way through Kong's attacks and other enemies to reach the camp and loot it. The active camp will change every few minutes, so players will have to keep an eye on the mini-map to know where to go next.</p>
78
- <h3>The new vehicle (Coupe RB) and the new shooting mode (OTS)</h3>
79
- <p>PUBG Mobile Godzilla Modu also introduces a new vehicle and a new shooting mode to the game. The new vehicle is called Coupe RB, and it is a sports car that can fit two players. It has a high speed and acceleration, but a low durability and stability. It can be found on Erangel, Miramar, Sanhok, and Livik.</p>
80
- <p>The new shooting mode is called OTS (Over The Shoulder), and it is an alternative to TPP (Third Person Perspective) and FPP (First Person Perspective). OTS mode allows players to aim more accurately over their shoulder without using the scope or iron sight. It also reduces the recoil of weapons, but increases the weapon sway. OTS mode can be toggled on or off by pressing a button on the screen. OTS mode can be used on all maps and modes, except for FPP-only modes.</p>
81
- <h2>Conclusion</h2>
82
- <p>PUBG Mobile Godzilla Modu is a new and exciting mode that brings the epic monsters from the Godzilla vs Kong movie to the game. It offers a unique and thrilling gameplay experience, as players have to survive and fight against the titans, while also competing with other players. The mode also introduces new features and changes, such as Titan Crystals, Apex Camps, Coupe RB, and OTS mode. If you are a fan of PUBG Mobile and Godzilla vs Kong, you should definitely try out this mode and enjoy the action-packed adventure.</p>
83
- <p>To download and play PUBG Mobile Godzilla Modu, you will need to update your game to the latest version (1.4) by using the Google Play Store or by downloading the APK file from the official website of PUBG Mobile. However, please note that PUBG Mobile is banned in some countries, such as India, and we do not recommend or endorse playing the game in those regions.</p>
84
- <p>We hope that this article has helped you to learn more about PUBG Mobile Godzilla Modu and how to download and play it. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading and happy gaming!</p>
85
- <h2>FAQs</h2>
86
- <h3>Q: How long will PUBG Mobile Godzilla Modu last?</h3>
87
- <p>A: According to the official announcement, PUBG Mobile Godzilla Modu will last until June 8, 2023. However, there might be extensions or changes depending on the feedback and popularity of the mode.</p>
88
- <h3>Q: Can I play PUBG Mobile Godzilla Modu with my friends?</h3>
89
- <p>A: Yes, you can play PUBG Mobile Godzilla Modu with your friends in squad mode or duo mode. You can also invite your friends to join your team or match with random players online.</p>
90
- <h3>Q: How can I get more Titan Crystals?</h3>
91
- <p>A: You can get more Titan Crystals by finding them on the maps where the titans appear. They are dropped by the titans or by special helicopters that fly over the maps. You can also get them by completing missions or events related to the mode.</p>
92
- <h3>Q: What are the benefits of playing PUBG Mobile Godzilla Modu?</h3>
93
- <p>A: Playing PUBG Mobile Godzilla Modu can give you several benefits, such as:</p>
94
- <ul>
95
- <li>Enjoying a new and fun gameplay experience with giant monsters and special abilities.</li>
96
- <li>Earning rewards and achievements related to the mode, such as skins, outfits, emotes, and more.</li>
97
- <li>Improving your skills and strategies by facing different challenges and scenarios.</li>
98
- <li>Supporting the collaboration between PUBG Mobile and Godzilla vs Kong movie.</li>
99
- </ul>
100
- <h3>Q: Is PUBG Mobile Godzilla Modu safe and legal to play?</h3>
101
- <p>A: PUBG Mobile Godzilla Modu is safe and legal to play in most countries where PUBG Mobile is available. However, there are some countries where PUBG Mobile is banned or restricted, such as India, Pakistan, China, and others. In those countries, playing PUBG Mobile Godzilla Modu might be risky or illegal, and we do not recommend or endorse doing so. Please follow the laws and regulations of your country and respect the rights of others.</p> 197e85843d<br />
102
- <br />
103
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIConsultant/MusicGen/audiocraft/optim/linear_warmup_lr_scheduler.py DELETED
@@ -1,35 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the license found in the
5
- # LICENSE file in the root directory of this source tree.
6
-
7
- import typing as tp
8
-
9
- from torch.optim import Optimizer
10
- from torch.optim.lr_scheduler import _LRScheduler
11
-
12
-
13
- class LinearWarmupLRScheduler(_LRScheduler):
14
- """Inverse square root LR scheduler.
15
-
16
- Args:
17
- optimizer (Optimizer): Torch optimizer.
18
- warmup_steps (int): Number of warmup steps.
19
- warmup_init_lr (tp.Optional[float]): Initial learning rate
20
- during warmup phase. When not set, use the provided learning rate.
21
- """
22
- def __init__(self, optimizer: Optimizer, warmup_steps: int, warmup_init_lr: tp.Optional[float] = 0):
23
- self.warmup_steps = warmup_steps
24
- self.warmup_init_lr = warmup_init_lr
25
- super().__init__(optimizer)
26
-
27
- def _get_sched_lr(self, lr: float, step: int):
28
- if step < self.warmup_steps:
29
- warmup_init_lr = self.warmup_init_lr or 0
30
- lr_step = (lr - warmup_init_lr) / self.warmup_steps
31
- lr = warmup_init_lr + step * lr_step
32
- return lr
33
-
34
- def get_lr(self):
35
- return [self._get_sched_lr(base_lr, self.last_epoch) for base_lr in self.base_lrs]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/NeuralSeq/data_gen/tts/wav_processors/base_processor.py DELETED
@@ -1,25 +0,0 @@
1
- REGISTERED_WAV_PROCESSORS = {}
2
-
3
-
4
- def register_wav_processors(name):
5
- def _f(cls):
6
- REGISTERED_WAV_PROCESSORS[name] = cls
7
- return cls
8
-
9
- return _f
10
-
11
-
12
- def get_wav_processor_cls(name):
13
- return REGISTERED_WAV_PROCESSORS.get(name, None)
14
-
15
-
16
- class BaseWavProcessor:
17
- @property
18
- def name(self):
19
- raise NotImplementedError
20
-
21
- def output_fn(self, input_fn):
22
- return f'{input_fn[:-4]}_{self.name}.wav'
23
-
24
- def process(self, input_fn, sr, tmp_dir, processed_dir, item_name, preprocess_args):
25
- raise NotImplementedError
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/Make_An_Audio_inpaint/vocoder/bigvgan/alias_free_torch/resample.py DELETED
@@ -1,49 +0,0 @@
1
- # Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
2
- # LICENSE is in incl_licenses directory.
3
-
4
- import torch.nn as nn
5
- from torch.nn import functional as F
6
- from .filter import LowPassFilter1d
7
- from .filter import kaiser_sinc_filter1d
8
-
9
-
10
- class UpSample1d(nn.Module):
11
- def __init__(self, ratio=2, kernel_size=None):
12
- super().__init__()
13
- self.ratio = ratio
14
- self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
15
- self.stride = ratio
16
- self.pad = self.kernel_size // ratio - 1
17
- self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2
18
- self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2
19
- filter = kaiser_sinc_filter1d(cutoff=0.5 / ratio,
20
- half_width=0.6 / ratio,
21
- kernel_size=self.kernel_size)
22
- self.register_buffer("filter", filter)
23
-
24
- # x: [B, C, T]
25
- def forward(self, x):
26
- _, C, _ = x.shape
27
-
28
- x = F.pad(x, (self.pad, self.pad), mode='replicate')
29
- x = self.ratio * F.conv_transpose1d(
30
- x, self.filter.expand(C, -1, -1), stride=self.stride, groups=C)
31
- x = x[..., self.pad_left:-self.pad_right]
32
-
33
- return x
34
-
35
-
36
- class DownSample1d(nn.Module):
37
- def __init__(self, ratio=2, kernel_size=None):
38
- super().__init__()
39
- self.ratio = ratio
40
- self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size
41
- self.lowpass = LowPassFilter1d(cutoff=0.5 / ratio,
42
- half_width=0.6 / ratio,
43
- stride=ratio,
44
- kernel_size=self.kernel_size)
45
-
46
- def forward(self, x):
47
- xx = self.lowpass(x)
48
-
49
- return xx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AILab-CVC/EvalCrafter/app.py DELETED
@@ -1,121 +0,0 @@
1
- """
2
- Adapted from the SEED-Bench Leaderboard by AILab-CVC
3
- Source: https://huggingface.co/spaces/AILab-CVC/SEED-Bench_Leaderboard
4
- """
5
-
6
- __all__ = ['block', 'make_clickable_model', 'make_clickable_user', 'get_submissions']
7
-
8
- import gradio as gr
9
- import pandas as pd
10
- import json
11
- import pdb
12
- import tempfile
13
-
14
- from constants import *
15
- from src.auto_leaderboard.model_metadata_type import ModelType
16
-
17
- global data_component, filter_component
18
-
19
-
20
- def upload_file(files):
21
- file_paths = [file.name for file in files]
22
- return file_paths
23
-
24
- def get_baseline_df():
25
- df = pd.read_csv(CSV_DIR)
26
- df = df.sort_values(by="Final Sum Score", ascending=False)
27
- present_columns = MODEL_INFO + checkbox_group.value
28
- df = df[present_columns]
29
- print(df)
30
- return df
31
-
32
- def get_all_df():
33
- df = pd.read_csv(CSV_DIR)
34
- df = df.sort_values(by="Final Sum Score", ascending=False)
35
- print(df)
36
- return df
37
-
38
- block = gr.Blocks()
39
-
40
-
41
- with block:
42
- gr.Markdown(
43
- LEADERBORAD_INTRODUCTION
44
- )
45
- with gr.Tabs(elem_classes="tab-buttons") as tabs:
46
- with gr.TabItem("🏅 EvalCrafter Benchmark", elem_id="evalcrafter-benchmark-tab-table", id=0):
47
-
48
- gr.Markdown(
49
- TABLE_INTRODUCTION
50
- )
51
-
52
- # selection for column part:
53
- checkbox_group = gr.CheckboxGroup(
54
- choices=TASK_INFO_v2,
55
- value=AVG_INFO,
56
- label="Select options",
57
- interactive=True,
58
- )
59
-
60
- # 创建数据帧组件
61
- # pdb.set_trace()
62
- data_component = gr.components.Dataframe(
63
- value=get_baseline_df,
64
- headers=COLUMN_NAMES,
65
- type="pandas",
66
- datatype=DATA_TITILE_TYPE,
67
- interactive=False,
68
- visible=True,
69
- )
70
-
71
- def on_checkbox_group_change(selected_columns):
72
- # pdb.set_trace()
73
- selected_columns = [item for item in TASK_INFO_v2 if item in selected_columns]
74
- present_columns = MODEL_INFO + selected_columns
75
- updated_data = get_all_df()[present_columns]
76
- updated_data = updated_data.sort_values(by=present_columns[3], ascending=False)
77
- updated_headers = present_columns
78
- update_datatype = [DATA_TITILE_TYPE[COLUMN_NAMES.index(x)] for x in updated_headers]
79
-
80
- # pdb.set_trace()
81
- filter_component = gr.components.Dataframe(
82
- value=updated_data,
83
- headers=updated_headers,
84
- type="pandas",
85
- datatype=update_datatype,
86
- interactive=False,
87
- visible=True,
88
- )
89
- # pdb.set_trace()
90
- return filter_component.value
91
-
92
- # 将复选框组关联到处理函数
93
- checkbox_group.change(fn=on_checkbox_group_change, inputs=checkbox_group, outputs=data_component)
94
-
95
-
96
- # table 2
97
- with gr.TabItem("📝 About", elem_id="evalcrafter-benchmark-tab-table", id=2):
98
- gr.Markdown(LEADERBORAD_INFO, elem_classes="markdown-text")
99
-
100
-
101
- with gr.Row():
102
- data_run = gr.Button("Refresh")
103
- data_run.click(
104
- get_baseline_df, outputs=data_component
105
- )
106
-
107
- gr.Markdown(r"""
108
- Please cite this paper if you find it useful ♥️:
109
-
110
- ```bibtex
111
- @inproceedings{Liu2023EvalCrafterBA,
112
- title={EvalCrafter: Benchmarking and Evaluating Large Video Generation Models},
113
- author={Yaofang Liu and Xiaodong Cun and Xuebo Liu and Xintao Wang and Yong Zhang and Haoxin Chen and Yang Liu and Tieyong Zeng and Raymond Chan and Ying Shan},
114
- year={2023},
115
- url={https://api.semanticscholar.org/CorpusID:264172222}
116
- }
117
- ```
118
- """)
119
- # block.load(get_baseline_df, outputs=data_title)
120
-
121
- block.launch(share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ALSv/FSW/roop/processors/frame/core.py DELETED
@@ -1,91 +0,0 @@
1
- import os
2
- import sys
3
- import importlib
4
- import psutil
5
- from concurrent.futures import ThreadPoolExecutor, as_completed
6
- from queue import Queue
7
- from types import ModuleType
8
- from typing import Any, List, Callable
9
- from tqdm import tqdm
10
-
11
- import roop
12
-
13
- FRAME_PROCESSORS_MODULES: List[ModuleType] = []
14
- FRAME_PROCESSORS_INTERFACE = [
15
- 'pre_check',
16
- 'pre_start',
17
- 'process_frame',
18
- 'process_frames',
19
- 'process_image',
20
- 'process_video',
21
- 'post_process'
22
- ]
23
-
24
-
25
- def load_frame_processor_module(frame_processor: str) -> Any:
26
- try:
27
- frame_processor_module = importlib.import_module(f'roop.processors.frame.{frame_processor}')
28
- for method_name in FRAME_PROCESSORS_INTERFACE:
29
- if not hasattr(frame_processor_module, method_name):
30
- raise NotImplementedError
31
- except ModuleNotFoundError:
32
- sys.exit(f'Frame processor {frame_processor} not found.')
33
- except NotImplementedError:
34
- sys.exit(f'Frame processor {frame_processor} not implemented correctly.')
35
- return frame_processor_module
36
-
37
-
38
- def get_frame_processors_modules(frame_processors: List[str]) -> List[ModuleType]:
39
- global FRAME_PROCESSORS_MODULES
40
-
41
- if not FRAME_PROCESSORS_MODULES:
42
- for frame_processor in frame_processors:
43
- frame_processor_module = load_frame_processor_module(frame_processor)
44
- FRAME_PROCESSORS_MODULES.append(frame_processor_module)
45
- return FRAME_PROCESSORS_MODULES
46
-
47
-
48
- def multi_process_frame(source_path: str, temp_frame_paths: List[str], process_frames: Callable[[str, List[str], Any], None], update: Callable[[], None]) -> None:
49
- with ThreadPoolExecutor(max_workers=roop.globals.execution_threads) as executor:
50
- futures = []
51
- queue = create_queue(temp_frame_paths)
52
- queue_per_future = max(len(temp_frame_paths) // roop.globals.execution_threads, 1)
53
- while not queue.empty():
54
- future = executor.submit(process_frames, source_path, pick_queue(queue, queue_per_future), update)
55
- futures.append(future)
56
- for future in as_completed(futures):
57
- future.result()
58
-
59
-
60
- def create_queue(temp_frame_paths: List[str]) -> Queue[str]:
61
- queue: Queue[str] = Queue()
62
- for frame_path in temp_frame_paths:
63
- queue.put(frame_path)
64
- return queue
65
-
66
-
67
- def pick_queue(queue: Queue[str], queue_per_future: int) -> List[str]:
68
- queues = []
69
- for _ in range(queue_per_future):
70
- if not queue.empty():
71
- queues.append(queue.get())
72
- return queues
73
-
74
-
75
- def process_video(source_path: str, frame_paths: list[str], process_frames: Callable[[str, List[str], Any], None]) -> None:
76
- progress_bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]'
77
- total = len(frame_paths)
78
- with tqdm(total=total, desc='Processing', unit='frame', dynamic_ncols=True, bar_format=progress_bar_format) as progress:
79
- multi_process_frame(source_path, frame_paths, process_frames, lambda: update_progress(progress))
80
-
81
-
82
- def update_progress(progress: Any = None) -> None:
83
- process = psutil.Process(os.getpid())
84
- memory_usage = process.memory_info().rss / 1024 / 1024 / 1024
85
- progress.set_postfix({
86
- 'memory_usage': '{:.2f}'.format(memory_usage).zfill(5) + 'GB',
87
- 'execution_providers': roop.globals.execution_providers,
88
- 'execution_threads': roop.globals.execution_threads
89
- })
90
- progress.refresh()
91
- progress.update(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AONYLMR/White-box-Cartoonization/wbc/guided_filter.py DELETED
@@ -1,87 +0,0 @@
1
- import tensorflow as tf
2
- import numpy as np
3
-
4
-
5
-
6
-
7
- def tf_box_filter(x, r):
8
- k_size = int(2*r+1)
9
- ch = x.get_shape().as_list()[-1]
10
- weight = 1/(k_size**2)
11
- box_kernel = weight*np.ones((k_size, k_size, ch, 1))
12
- box_kernel = np.array(box_kernel).astype(np.float32)
13
- output = tf.nn.depthwise_conv2d(x, box_kernel, [1, 1, 1, 1], 'SAME')
14
- return output
15
-
16
-
17
-
18
- def guided_filter(x, y, r, eps=1e-2):
19
-
20
- x_shape = tf.shape(x)
21
- #y_shape = tf.shape(y)
22
-
23
- N = tf_box_filter(tf.ones((1, x_shape[1], x_shape[2], 1), dtype=x.dtype), r)
24
-
25
- mean_x = tf_box_filter(x, r) / N
26
- mean_y = tf_box_filter(y, r) / N
27
- cov_xy = tf_box_filter(x * y, r) / N - mean_x * mean_y
28
- var_x = tf_box_filter(x * x, r) / N - mean_x * mean_x
29
-
30
- A = cov_xy / (var_x + eps)
31
- b = mean_y - A * mean_x
32
-
33
- mean_A = tf_box_filter(A, r) / N
34
- mean_b = tf_box_filter(b, r) / N
35
-
36
- output = mean_A * x + mean_b
37
-
38
- return output
39
-
40
-
41
-
42
- def fast_guided_filter(lr_x, lr_y, hr_x, r=1, eps=1e-8):
43
-
44
- #assert lr_x.shape.ndims == 4 and lr_y.shape.ndims == 4 and hr_x.shape.ndims == 4
45
-
46
- lr_x_shape = tf.shape(lr_x)
47
- #lr_y_shape = tf.shape(lr_y)
48
- hr_x_shape = tf.shape(hr_x)
49
-
50
- N = tf_box_filter(tf.ones((1, lr_x_shape[1], lr_x_shape[2], 1), dtype=lr_x.dtype), r)
51
-
52
- mean_x = tf_box_filter(lr_x, r) / N
53
- mean_y = tf_box_filter(lr_y, r) / N
54
- cov_xy = tf_box_filter(lr_x * lr_y, r) / N - mean_x * mean_y
55
- var_x = tf_box_filter(lr_x * lr_x, r) / N - mean_x * mean_x
56
-
57
- A = cov_xy / (var_x + eps)
58
- b = mean_y - A * mean_x
59
-
60
- mean_A = tf.image.resize_images(A, hr_x_shape[1: 3])
61
- mean_b = tf.image.resize_images(b, hr_x_shape[1: 3])
62
-
63
- output = mean_A * hr_x + mean_b
64
-
65
- return output
66
-
67
-
68
- if __name__ == '__main__':
69
- import cv2
70
- from tqdm import tqdm
71
-
72
- input_photo = tf.placeholder(tf.float32, [1, None, None, 3])
73
- #input_superpixel = tf.placeholder(tf.float32, [16, 256, 256, 3])
74
- output = guided_filter(input_photo, input_photo, 5, eps=1)
75
- image = cv2.imread('output_figure1/cartoon2.jpg')
76
- image = image/127.5 - 1
77
- image = np.expand_dims(image, axis=0)
78
-
79
- config = tf.ConfigProto()
80
- config.gpu_options.allow_growth = True
81
- sess = tf.Session(config=config)
82
- sess.run(tf.global_variables_initializer())
83
-
84
- out = sess.run(output, feed_dict={input_photo: image})
85
- out = (np.squeeze(out)+1)*127.5
86
- out = np.clip(out, 0, 255).astype(np.uint8)
87
- cv2.imwrite('output_figure1/cartoon2_filter.jpg', out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AchyuthGamer/OpenGPT/g4f/Provider/Acytoo.py DELETED
@@ -1,51 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from aiohttp import ClientSession
4
-
5
- from ..typing import AsyncGenerator
6
- from .base_provider import AsyncGeneratorProvider
7
-
8
-
9
- class Acytoo(AsyncGeneratorProvider):
10
- url = 'https://chat.acytoo.com'
11
- working = True
12
- supports_gpt_35_turbo = True
13
-
14
- @classmethod
15
- async def create_async_generator(
16
- cls,
17
- model: str,
18
- messages: list[dict[str, str]],
19
- proxy: str = None,
20
- **kwargs
21
- ) -> AsyncGenerator:
22
-
23
- async with ClientSession(
24
- headers=_create_header()
25
- ) as session:
26
- async with session.post(
27
- cls.url + '/api/completions',
28
- proxy=proxy,
29
- json=_create_payload(messages, **kwargs)
30
- ) as response:
31
- response.raise_for_status()
32
- async for stream in response.content.iter_any():
33
- if stream:
34
- yield stream.decode()
35
-
36
-
37
- def _create_header():
38
- return {
39
- 'accept': '*/*',
40
- 'content-type': 'application/json',
41
- }
42
-
43
-
44
- def _create_payload(messages: list[dict[str, str]], temperature: float = 0.5, **kwargs):
45
- return {
46
- 'key' : '',
47
- 'model' : 'gpt-3.5-turbo',
48
- 'messages' : messages,
49
- 'temperature' : temperature,
50
- 'password' : ''
51
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/gridtable/input/PointerUpDownCell.js DELETED
@@ -1,13 +0,0 @@
1
- import EmitCellEvent from './EmitCellEvent.js';
2
-
3
- var PointerUpDownCell = function (table, tableConfig) {
4
- table
5
- .on('pointerdown', function (pointer, localX, localY, event) {
6
- EmitCellEvent(this.eventEmitter, 'cell.down', table, pointer.worldX, pointer.worldY, pointer, event);
7
- }, this)
8
- .on('pointerup', function (pointer, localX, localY, event) {
9
- EmitCellEvent(this.eventEmitter, 'cell.up', table, pointer.worldX, pointer.worldY, pointer, event);
10
- }, this)
11
- }
12
-
13
- export default PointerUpDownCell;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alpaca233/SadTalker/src/audio2pose_models/res_unet.py DELETED
@@ -1,65 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- from src.audio2pose_models.networks import ResidualConv, Upsample
4
-
5
-
6
- class ResUnet(nn.Module):
7
- def __init__(self, channel=1, filters=[32, 64, 128, 256]):
8
- super(ResUnet, self).__init__()
9
-
10
- self.input_layer = nn.Sequential(
11
- nn.Conv2d(channel, filters[0], kernel_size=3, padding=1),
12
- nn.BatchNorm2d(filters[0]),
13
- nn.ReLU(),
14
- nn.Conv2d(filters[0], filters[0], kernel_size=3, padding=1),
15
- )
16
- self.input_skip = nn.Sequential(
17
- nn.Conv2d(channel, filters[0], kernel_size=3, padding=1)
18
- )
19
-
20
- self.residual_conv_1 = ResidualConv(filters[0], filters[1], stride=(2,1), padding=1)
21
- self.residual_conv_2 = ResidualConv(filters[1], filters[2], stride=(2,1), padding=1)
22
-
23
- self.bridge = ResidualConv(filters[2], filters[3], stride=(2,1), padding=1)
24
-
25
- self.upsample_1 = Upsample(filters[3], filters[3], kernel=(2,1), stride=(2,1))
26
- self.up_residual_conv1 = ResidualConv(filters[3] + filters[2], filters[2], stride=1, padding=1)
27
-
28
- self.upsample_2 = Upsample(filters[2], filters[2], kernel=(2,1), stride=(2,1))
29
- self.up_residual_conv2 = ResidualConv(filters[2] + filters[1], filters[1], stride=1, padding=1)
30
-
31
- self.upsample_3 = Upsample(filters[1], filters[1], kernel=(2,1), stride=(2,1))
32
- self.up_residual_conv3 = ResidualConv(filters[1] + filters[0], filters[0], stride=1, padding=1)
33
-
34
- self.output_layer = nn.Sequential(
35
- nn.Conv2d(filters[0], 1, 1, 1),
36
- nn.Sigmoid(),
37
- )
38
-
39
- def forward(self, x):
40
- # Encode
41
- x1 = self.input_layer(x) + self.input_skip(x)
42
- x2 = self.residual_conv_1(x1)
43
- x3 = self.residual_conv_2(x2)
44
- # Bridge
45
- x4 = self.bridge(x3)
46
-
47
- # Decode
48
- x4 = self.upsample_1(x4)
49
- x5 = torch.cat([x4, x3], dim=1)
50
-
51
- x6 = self.up_residual_conv1(x5)
52
-
53
- x6 = self.upsample_2(x6)
54
- x7 = torch.cat([x6, x2], dim=1)
55
-
56
- x8 = self.up_residual_conv2(x7)
57
-
58
- x8 = self.upsample_3(x8)
59
- x9 = torch.cat([x8, x1], dim=1)
60
-
61
- x10 = self.up_residual_conv3(x9)
62
-
63
- output = self.output_layer(x10)
64
-
65
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alycer/VITS-Umamusume-voice-synthesizer/hubert_model.py DELETED
@@ -1,221 +0,0 @@
1
- import copy
2
- from typing import Optional, Tuple
3
- import random
4
-
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
9
-
10
- class Hubert(nn.Module):
11
- def __init__(self, num_label_embeddings: int = 100, mask: bool = True):
12
- super().__init__()
13
- self._mask = mask
14
- self.feature_extractor = FeatureExtractor()
15
- self.feature_projection = FeatureProjection()
16
- self.positional_embedding = PositionalConvEmbedding()
17
- self.norm = nn.LayerNorm(768)
18
- self.dropout = nn.Dropout(0.1)
19
- self.encoder = TransformerEncoder(
20
- nn.TransformerEncoderLayer(
21
- 768, 12, 3072, activation="gelu", batch_first=True
22
- ),
23
- 12,
24
- )
25
- self.proj = nn.Linear(768, 256)
26
-
27
- self.masked_spec_embed = nn.Parameter(torch.FloatTensor(768).uniform_())
28
- self.label_embedding = nn.Embedding(num_label_embeddings, 256)
29
-
30
- def mask(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
31
- mask = None
32
- if self.training and self._mask:
33
- mask = _compute_mask((x.size(0), x.size(1)), 0.8, 10, x.device, 2)
34
- x[mask] = self.masked_spec_embed.to(x.dtype)
35
- return x, mask
36
-
37
- def encode(
38
- self, x: torch.Tensor, layer: Optional[int] = None
39
- ) -> Tuple[torch.Tensor, torch.Tensor]:
40
- x = self.feature_extractor(x)
41
- x = self.feature_projection(x.transpose(1, 2))
42
- x, mask = self.mask(x)
43
- x = x + self.positional_embedding(x)
44
- x = self.dropout(self.norm(x))
45
- x = self.encoder(x, output_layer=layer)
46
- return x, mask
47
-
48
- def logits(self, x: torch.Tensor) -> torch.Tensor:
49
- logits = torch.cosine_similarity(
50
- x.unsqueeze(2),
51
- self.label_embedding.weight.unsqueeze(0).unsqueeze(0),
52
- dim=-1,
53
- )
54
- return logits / 0.1
55
-
56
- def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
57
- x, mask = self.encode(x)
58
- x = self.proj(x)
59
- logits = self.logits(x)
60
- return logits, mask
61
-
62
-
63
- class HubertSoft(Hubert):
64
- def __init__(self):
65
- super().__init__()
66
-
67
- @torch.inference_mode()
68
- def units(self, wav: torch.Tensor) -> torch.Tensor:
69
- wav = F.pad(wav, ((400 - 320) // 2, (400 - 320) // 2))
70
- x, _ = self.encode(wav)
71
- return self.proj(x)
72
-
73
-
74
- class FeatureExtractor(nn.Module):
75
- def __init__(self):
76
- super().__init__()
77
- self.conv0 = nn.Conv1d(1, 512, 10, 5, bias=False)
78
- self.norm0 = nn.GroupNorm(512, 512)
79
- self.conv1 = nn.Conv1d(512, 512, 3, 2, bias=False)
80
- self.conv2 = nn.Conv1d(512, 512, 3, 2, bias=False)
81
- self.conv3 = nn.Conv1d(512, 512, 3, 2, bias=False)
82
- self.conv4 = nn.Conv1d(512, 512, 3, 2, bias=False)
83
- self.conv5 = nn.Conv1d(512, 512, 2, 2, bias=False)
84
- self.conv6 = nn.Conv1d(512, 512, 2, 2, bias=False)
85
-
86
- def forward(self, x: torch.Tensor) -> torch.Tensor:
87
- x = F.gelu(self.norm0(self.conv0(x)))
88
- x = F.gelu(self.conv1(x))
89
- x = F.gelu(self.conv2(x))
90
- x = F.gelu(self.conv3(x))
91
- x = F.gelu(self.conv4(x))
92
- x = F.gelu(self.conv5(x))
93
- x = F.gelu(self.conv6(x))
94
- return x
95
-
96
-
97
- class FeatureProjection(nn.Module):
98
- def __init__(self):
99
- super().__init__()
100
- self.norm = nn.LayerNorm(512)
101
- self.projection = nn.Linear(512, 768)
102
- self.dropout = nn.Dropout(0.1)
103
-
104
- def forward(self, x: torch.Tensor) -> torch.Tensor:
105
- x = self.norm(x)
106
- x = self.projection(x)
107
- x = self.dropout(x)
108
- return x
109
-
110
-
111
- class PositionalConvEmbedding(nn.Module):
112
- def __init__(self):
113
- super().__init__()
114
- self.conv = nn.Conv1d(
115
- 768,
116
- 768,
117
- kernel_size=128,
118
- padding=128 // 2,
119
- groups=16,
120
- )
121
- self.conv = nn.utils.weight_norm(self.conv, name="weight", dim=2)
122
-
123
- def forward(self, x: torch.Tensor) -> torch.Tensor:
124
- x = self.conv(x.transpose(1, 2))
125
- x = F.gelu(x[:, :, :-1])
126
- return x.transpose(1, 2)
127
-
128
-
129
- class TransformerEncoder(nn.Module):
130
- def __init__(
131
- self, encoder_layer: nn.TransformerEncoderLayer, num_layers: int
132
- ) -> None:
133
- super(TransformerEncoder, self).__init__()
134
- self.layers = nn.ModuleList(
135
- [copy.deepcopy(encoder_layer) for _ in range(num_layers)]
136
- )
137
- self.num_layers = num_layers
138
-
139
- def forward(
140
- self,
141
- src: torch.Tensor,
142
- mask: torch.Tensor = None,
143
- src_key_padding_mask: torch.Tensor = None,
144
- output_layer: Optional[int] = None,
145
- ) -> torch.Tensor:
146
- output = src
147
- for layer in self.layers[:output_layer]:
148
- output = layer(
149
- output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
150
- )
151
- return output
152
-
153
-
154
- def _compute_mask(
155
- shape: Tuple[int, int],
156
- mask_prob: float,
157
- mask_length: int,
158
- device: torch.device,
159
- min_masks: int = 0,
160
- ) -> torch.Tensor:
161
- batch_size, sequence_length = shape
162
-
163
- if mask_length < 1:
164
- raise ValueError("`mask_length` has to be bigger than 0.")
165
-
166
- if mask_length > sequence_length:
167
- raise ValueError(
168
- f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`"
169
- )
170
-
171
- # compute number of masked spans in batch
172
- num_masked_spans = int(mask_prob * sequence_length / mask_length + random.random())
173
- num_masked_spans = max(num_masked_spans, min_masks)
174
-
175
- # make sure num masked indices <= sequence_length
176
- if num_masked_spans * mask_length > sequence_length:
177
- num_masked_spans = sequence_length // mask_length
178
-
179
- # SpecAugment mask to fill
180
- mask = torch.zeros((batch_size, sequence_length), device=device, dtype=torch.bool)
181
-
182
- # uniform distribution to sample from, make sure that offset samples are < sequence_length
183
- uniform_dist = torch.ones(
184
- (batch_size, sequence_length - (mask_length - 1)), device=device
185
- )
186
-
187
- # get random indices to mask
188
- mask_indices = torch.multinomial(uniform_dist, num_masked_spans)
189
-
190
- # expand masked indices to masked spans
191
- mask_indices = (
192
- mask_indices.unsqueeze(dim=-1)
193
- .expand((batch_size, num_masked_spans, mask_length))
194
- .reshape(batch_size, num_masked_spans * mask_length)
195
- )
196
- offsets = (
197
- torch.arange(mask_length, device=device)[None, None, :]
198
- .expand((batch_size, num_masked_spans, mask_length))
199
- .reshape(batch_size, num_masked_spans * mask_length)
200
- )
201
- mask_idxs = mask_indices + offsets
202
-
203
- # scatter indices to mask
204
- mask = mask.scatter(1, mask_idxs, True)
205
-
206
- return mask
207
-
208
-
209
- def hubert_soft(
210
- path: str
211
- ) -> HubertSoft:
212
- r"""HuBERT-Soft from `"A Comparison of Discrete and Soft Speech Units for Improved Voice Conversion"`.
213
- Args:
214
- path (str): path of a pretrained model
215
- """
216
- hubert = HubertSoft()
217
- checkpoint = torch.load(path)
218
- consume_prefix_in_state_dict_if_present(checkpoint, "module.")
219
- hubert.load_state_dict(checkpoint)
220
- hubert.eval()
221
- return hubert
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/schedulers/singlestep_dpm_solver.md DELETED
@@ -1,20 +0,0 @@
1
- <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
-
3
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
- the License. You may obtain a copy of the License at
5
-
6
- http://www.apache.org/licenses/LICENSE-2.0
7
-
8
- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
- an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
- specific language governing permissions and limitations under the License.
11
- -->
12
-
13
- # Singlestep DPM-Solver
14
-
15
- ## Overview
16
-
17
- Original paper can be found [here](https://arxiv.org/abs/2206.00927) and the [improved version](https://arxiv.org/abs/2211.01095). The original implementation can be found [here](https://github.com/LuChengTHU/dpm-solver).
18
-
19
- ## DPMSolverSinglestepScheduler
20
- [[autodoc]] DPMSolverSinglestepScheduler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py DELETED
@@ -1,494 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import warnings
16
- from typing import Callable, List, Optional, Union
17
-
18
- import numpy as np
19
- import PIL
20
- import torch
21
- import torch.nn.functional as F
22
- from transformers import CLIPTextModel, CLIPTokenizer
23
-
24
- from ...image_processor import VaeImageProcessor
25
- from ...models import AutoencoderKL, UNet2DConditionModel
26
- from ...schedulers import EulerDiscreteScheduler
27
- from ...utils import logging, randn_tensor
28
- from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
29
-
30
-
31
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
32
-
33
-
34
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.preprocess
35
- def preprocess(image):
36
- warnings.warn(
37
- "The preprocess method is deprecated and will be removed in a future version. Please"
38
- " use VaeImageProcessor.preprocess instead",
39
- FutureWarning,
40
- )
41
- if isinstance(image, torch.Tensor):
42
- return image
43
- elif isinstance(image, PIL.Image.Image):
44
- image = [image]
45
-
46
- if isinstance(image[0], PIL.Image.Image):
47
- w, h = image[0].size
48
- w, h = (x - x % 64 for x in (w, h)) # resize to integer multiple of 64
49
-
50
- image = [np.array(i.resize((w, h)))[None, :] for i in image]
51
- image = np.concatenate(image, axis=0)
52
- image = np.array(image).astype(np.float32) / 255.0
53
- image = image.transpose(0, 3, 1, 2)
54
- image = 2.0 * image - 1.0
55
- image = torch.from_numpy(image)
56
- elif isinstance(image[0], torch.Tensor):
57
- image = torch.cat(image, dim=0)
58
- return image
59
-
60
-
61
- class StableDiffusionLatentUpscalePipeline(DiffusionPipeline):
62
- r"""
63
- Pipeline for upscaling Stable Diffusion output image resolution by a factor of 2.
64
-
65
- This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
66
- implemented for all pipelines (downloading, saving, running on a particular device, etc.).
67
-
68
- Args:
69
- vae ([`AutoencoderKL`]):
70
- Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
71
- text_encoder ([`~transformers.CLIPTextModel`]):
72
- Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
73
- tokenizer ([`~transformers.CLIPTokenizer`]):
74
- A `CLIPTokenizer` to tokenize text.
75
- unet ([`UNet2DConditionModel`]):
76
- A `UNet2DConditionModel` to denoise the encoded image latents.
77
- scheduler ([`SchedulerMixin`]):
78
- A [`EulerDiscreteScheduler`] to be used in combination with `unet` to denoise the encoded image latents.
79
- """
80
-
81
- def __init__(
82
- self,
83
- vae: AutoencoderKL,
84
- text_encoder: CLIPTextModel,
85
- tokenizer: CLIPTokenizer,
86
- unet: UNet2DConditionModel,
87
- scheduler: EulerDiscreteScheduler,
88
- ):
89
- super().__init__()
90
-
91
- self.register_modules(
92
- vae=vae,
93
- text_encoder=text_encoder,
94
- tokenizer=tokenizer,
95
- unet=unet,
96
- scheduler=scheduler,
97
- )
98
- self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
99
- self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, resample="bicubic")
100
-
101
- def _encode_prompt(self, prompt, device, do_classifier_free_guidance, negative_prompt):
102
- r"""
103
- Encodes the prompt into text encoder hidden states.
104
-
105
- Args:
106
- prompt (`str` or `list(int)`):
107
- prompt to be encoded
108
- device: (`torch.device`):
109
- torch device
110
- do_classifier_free_guidance (`bool`):
111
- whether to use classifier free guidance or not
112
- negative_prompt (`str` or `List[str]`):
113
- The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
114
- if `guidance_scale` is less than `1`).
115
- """
116
- batch_size = len(prompt) if isinstance(prompt, list) else 1
117
-
118
- text_inputs = self.tokenizer(
119
- prompt,
120
- padding="max_length",
121
- max_length=self.tokenizer.model_max_length,
122
- truncation=True,
123
- return_length=True,
124
- return_tensors="pt",
125
- )
126
- text_input_ids = text_inputs.input_ids
127
-
128
- untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
129
-
130
- if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
131
- removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
132
- logger.warning(
133
- "The following part of your input was truncated because CLIP can only handle sequences up to"
134
- f" {self.tokenizer.model_max_length} tokens: {removed_text}"
135
- )
136
-
137
- text_encoder_out = self.text_encoder(
138
- text_input_ids.to(device),
139
- output_hidden_states=True,
140
- )
141
- text_embeddings = text_encoder_out.hidden_states[-1]
142
- text_pooler_out = text_encoder_out.pooler_output
143
-
144
- # get unconditional embeddings for classifier free guidance
145
- if do_classifier_free_guidance:
146
- uncond_tokens: List[str]
147
- if negative_prompt is None:
148
- uncond_tokens = [""] * batch_size
149
- elif type(prompt) is not type(negative_prompt):
150
- raise TypeError(
151
- f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
152
- f" {type(prompt)}."
153
- )
154
- elif isinstance(negative_prompt, str):
155
- uncond_tokens = [negative_prompt]
156
- elif batch_size != len(negative_prompt):
157
- raise ValueError(
158
- f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
159
- f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
160
- " the batch size of `prompt`."
161
- )
162
- else:
163
- uncond_tokens = negative_prompt
164
-
165
- max_length = text_input_ids.shape[-1]
166
- uncond_input = self.tokenizer(
167
- uncond_tokens,
168
- padding="max_length",
169
- max_length=max_length,
170
- truncation=True,
171
- return_length=True,
172
- return_tensors="pt",
173
- )
174
-
175
- uncond_encoder_out = self.text_encoder(
176
- uncond_input.input_ids.to(device),
177
- output_hidden_states=True,
178
- )
179
-
180
- uncond_embeddings = uncond_encoder_out.hidden_states[-1]
181
- uncond_pooler_out = uncond_encoder_out.pooler_output
182
-
183
- # For classifier free guidance, we need to do two forward passes.
184
- # Here we concatenate the unconditional and text embeddings into a single batch
185
- # to avoid doing two forward passes
186
- text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
187
- text_pooler_out = torch.cat([uncond_pooler_out, text_pooler_out])
188
-
189
- return text_embeddings, text_pooler_out
190
-
191
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
192
- def decode_latents(self, latents):
193
- warnings.warn(
194
- "The decode_latents method is deprecated and will be removed in a future version. Please"
195
- " use VaeImageProcessor instead",
196
- FutureWarning,
197
- )
198
- latents = 1 / self.vae.config.scaling_factor * latents
199
- image = self.vae.decode(latents, return_dict=False)[0]
200
- image = (image / 2 + 0.5).clamp(0, 1)
201
- # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
202
- image = image.cpu().permute(0, 2, 3, 1).float().numpy()
203
- return image
204
-
205
- def check_inputs(self, prompt, image, callback_steps):
206
- if not isinstance(prompt, str) and not isinstance(prompt, list):
207
- raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
208
-
209
- if (
210
- not isinstance(image, torch.Tensor)
211
- and not isinstance(image, PIL.Image.Image)
212
- and not isinstance(image, list)
213
- ):
214
- raise ValueError(
215
- f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or `list` but is {type(image)}"
216
- )
217
-
218
- # verify batch size of prompt and image are same if image is a list or tensor
219
- if isinstance(image, list) or isinstance(image, torch.Tensor):
220
- if isinstance(prompt, str):
221
- batch_size = 1
222
- else:
223
- batch_size = len(prompt)
224
- if isinstance(image, list):
225
- image_batch_size = len(image)
226
- else:
227
- image_batch_size = image.shape[0] if image.ndim == 4 else 1
228
- if batch_size != image_batch_size:
229
- raise ValueError(
230
- f"`prompt` has batch size {batch_size} and `image` has batch size {image_batch_size}."
231
- " Please make sure that passed `prompt` matches the batch size of `image`."
232
- )
233
-
234
- if (callback_steps is None) or (
235
- callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
236
- ):
237
- raise ValueError(
238
- f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
239
- f" {type(callback_steps)}."
240
- )
241
-
242
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.prepare_latents
243
- def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
244
- shape = (batch_size, num_channels_latents, height, width)
245
- if latents is None:
246
- latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
247
- else:
248
- if latents.shape != shape:
249
- raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
250
- latents = latents.to(device)
251
-
252
- # scale the initial noise by the standard deviation required by the scheduler
253
- latents = latents * self.scheduler.init_noise_sigma
254
- return latents
255
-
256
- @torch.no_grad()
257
- def __call__(
258
- self,
259
- prompt: Union[str, List[str]],
260
- image: Union[
261
- torch.FloatTensor,
262
- PIL.Image.Image,
263
- np.ndarray,
264
- List[torch.FloatTensor],
265
- List[PIL.Image.Image],
266
- List[np.ndarray],
267
- ] = None,
268
- num_inference_steps: int = 75,
269
- guidance_scale: float = 9.0,
270
- negative_prompt: Optional[Union[str, List[str]]] = None,
271
- generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
272
- latents: Optional[torch.FloatTensor] = None,
273
- output_type: Optional[str] = "pil",
274
- return_dict: bool = True,
275
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
276
- callback_steps: int = 1,
277
- ):
278
- r"""
279
- The call function to the pipeline for generation.
280
-
281
- Args:
282
- prompt (`str` or `List[str]`):
283
- The prompt or prompts to guide image upscaling.
284
- image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
285
- `Image` or tensor representing an image batch to be upscaled. If it's a tensor, it can be either a
286
- latent output from a Stable Diffusion model or an image tensor in the range `[-1, 1]`. It is considered
287
- a `latent` if `image.shape[1]` is `4`; otherwise, it is considered to be an image representation and
288
- encoded using this pipeline's `vae` encoder.
289
- num_inference_steps (`int`, *optional*, defaults to 50):
290
- The number of denoising steps. More denoising steps usually lead to a higher quality image at the
291
- expense of slower inference.
292
- guidance_scale (`float`, *optional*, defaults to 7.5):
293
- A higher guidance scale value encourages the model to generate images closely linked to the text
294
- `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
295
- negative_prompt (`str` or `List[str]`, *optional*):
296
- The prompt or prompts to guide what to not include in image generation. If not defined, you need to
297
- pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
298
- eta (`float`, *optional*, defaults to 0.0):
299
- Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
300
- to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
301
- generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
302
- A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
303
- generation deterministic.
304
- latents (`torch.FloatTensor`, *optional*):
305
- Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
306
- generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
307
- tensor is generated by sampling using the supplied random `generator`.
308
- output_type (`str`, *optional*, defaults to `"pil"`):
309
- The output format of the generated image. Choose between `PIL.Image` or `np.array`.
310
- return_dict (`bool`, *optional*, defaults to `True`):
311
- Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
312
- plain tuple.
313
- callback (`Callable`, *optional*):
314
- A function that calls every `callback_steps` steps during inference. The function is called with the
315
- following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
316
- callback_steps (`int`, *optional*, defaults to 1):
317
- The frequency at which the `callback` function is called. If not specified, the callback is called at
318
- every step.
319
-
320
- Examples:
321
- ```py
322
- >>> from diffusers import StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline
323
- >>> import torch
324
-
325
-
326
- >>> pipeline = StableDiffusionPipeline.from_pretrained(
327
- ... "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
328
- ... )
329
- >>> pipeline.to("cuda")
330
-
331
- >>> model_id = "stabilityai/sd-x2-latent-upscaler"
332
- >>> upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
333
- >>> upscaler.to("cuda")
334
-
335
- >>> prompt = "a photo of an astronaut high resolution, unreal engine, ultra realistic"
336
- >>> generator = torch.manual_seed(33)
337
-
338
- >>> low_res_latents = pipeline(prompt, generator=generator, output_type="latent").images
339
-
340
- >>> with torch.no_grad():
341
- ... image = pipeline.decode_latents(low_res_latents)
342
- >>> image = pipeline.numpy_to_pil(image)[0]
343
-
344
- >>> image.save("../images/a1.png")
345
-
346
- >>> upscaled_image = upscaler(
347
- ... prompt=prompt,
348
- ... image=low_res_latents,
349
- ... num_inference_steps=20,
350
- ... guidance_scale=0,
351
- ... generator=generator,
352
- ... ).images[0]
353
-
354
- >>> upscaled_image.save("../images/a2.png")
355
- ```
356
-
357
- Returns:
358
- [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
359
- If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
360
- otherwise a `tuple` is returned where the first element is a list with the generated images.
361
- """
362
-
363
- # 1. Check inputs
364
- self.check_inputs(prompt, image, callback_steps)
365
-
366
- # 2. Define call parameters
367
- batch_size = 1 if isinstance(prompt, str) else len(prompt)
368
- device = self._execution_device
369
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
370
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
371
- # corresponds to doing no classifier free guidance.
372
- do_classifier_free_guidance = guidance_scale > 1.0
373
-
374
- if guidance_scale == 0:
375
- prompt = [""] * batch_size
376
-
377
- # 3. Encode input prompt
378
- text_embeddings, text_pooler_out = self._encode_prompt(
379
- prompt, device, do_classifier_free_guidance, negative_prompt
380
- )
381
-
382
- # 4. Preprocess image
383
- image = self.image_processor.preprocess(image)
384
- image = image.to(dtype=text_embeddings.dtype, device=device)
385
- if image.shape[1] == 3:
386
- # encode image if not in latent-space yet
387
- image = self.vae.encode(image).latent_dist.sample() * self.vae.config.scaling_factor
388
-
389
- # 5. set timesteps
390
- self.scheduler.set_timesteps(num_inference_steps, device=device)
391
- timesteps = self.scheduler.timesteps
392
-
393
- batch_multiplier = 2 if do_classifier_free_guidance else 1
394
- image = image[None, :] if image.ndim == 3 else image
395
- image = torch.cat([image] * batch_multiplier)
396
-
397
- # 5. Add noise to image (set to be 0):
398
- # (see below notes from the author):
399
- # "the This step theoretically can make the model work better on out-of-distribution inputs, but mostly just seems to make it match the input less, so it's turned off by default."
400
- noise_level = torch.tensor([0.0], dtype=torch.float32, device=device)
401
- noise_level = torch.cat([noise_level] * image.shape[0])
402
- inv_noise_level = (noise_level**2 + 1) ** (-0.5)
403
-
404
- image_cond = F.interpolate(image, scale_factor=2, mode="nearest") * inv_noise_level[:, None, None, None]
405
- image_cond = image_cond.to(text_embeddings.dtype)
406
-
407
- noise_level_embed = torch.cat(
408
- [
409
- torch.ones(text_pooler_out.shape[0], 64, dtype=text_pooler_out.dtype, device=device),
410
- torch.zeros(text_pooler_out.shape[0], 64, dtype=text_pooler_out.dtype, device=device),
411
- ],
412
- dim=1,
413
- )
414
-
415
- timestep_condition = torch.cat([noise_level_embed, text_pooler_out], dim=1)
416
-
417
- # 6. Prepare latent variables
418
- height, width = image.shape[2:]
419
- num_channels_latents = self.vae.config.latent_channels
420
- latents = self.prepare_latents(
421
- batch_size,
422
- num_channels_latents,
423
- height * 2, # 2x upscale
424
- width * 2,
425
- text_embeddings.dtype,
426
- device,
427
- generator,
428
- latents,
429
- )
430
-
431
- # 7. Check that sizes of image and latents match
432
- num_channels_image = image.shape[1]
433
- if num_channels_latents + num_channels_image != self.unet.config.in_channels:
434
- raise ValueError(
435
- f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
436
- f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
437
- f" `num_channels_image`: {num_channels_image} "
438
- f" = {num_channels_latents+num_channels_image}. Please verify the config of"
439
- " `pipeline.unet` or your `image` input."
440
- )
441
-
442
- # 9. Denoising loop
443
- num_warmup_steps = 0
444
-
445
- with self.progress_bar(total=num_inference_steps) as progress_bar:
446
- for i, t in enumerate(timesteps):
447
- sigma = self.scheduler.sigmas[i]
448
- # expand the latents if we are doing classifier free guidance
449
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
450
- scaled_model_input = self.scheduler.scale_model_input(latent_model_input, t)
451
-
452
- scaled_model_input = torch.cat([scaled_model_input, image_cond], dim=1)
453
- # preconditioning parameter based on Karras et al. (2022) (table 1)
454
- timestep = torch.log(sigma) * 0.25
455
-
456
- noise_pred = self.unet(
457
- scaled_model_input,
458
- timestep,
459
- encoder_hidden_states=text_embeddings,
460
- timestep_cond=timestep_condition,
461
- ).sample
462
-
463
- # in original repo, the output contains a variance channel that's not used
464
- noise_pred = noise_pred[:, :-1]
465
-
466
- # apply preconditioning, based on table 1 in Karras et al. (2022)
467
- inv_sigma = 1 / (sigma**2 + 1)
468
- noise_pred = inv_sigma * latent_model_input + self.scheduler.scale_model_input(sigma, t) * noise_pred
469
-
470
- # perform guidance
471
- if do_classifier_free_guidance:
472
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
473
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
474
-
475
- # compute the previous noisy sample x_t -> x_t-1
476
- latents = self.scheduler.step(noise_pred, t, latents).prev_sample
477
-
478
- # call the callback, if provided
479
- if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
480
- progress_bar.update()
481
- if callback is not None and i % callback_steps == 0:
482
- callback(i, t, latents)
483
-
484
- if not output_type == "latent":
485
- image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
486
- else:
487
- image = latents
488
-
489
- image = self.image_processor.postprocess(image, output_type=output_type)
490
-
491
- if not return_dict:
492
- return (image,)
493
-
494
- return ImagePipelineOutput(images=image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_flax.py DELETED
@@ -1,99 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2023 HuggingFace Inc.
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
- import gc
17
- import unittest
18
-
19
- from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
20
- from diffusers.utils import is_flax_available, slow
21
- from diffusers.utils.testing_utils import require_flax
22
-
23
-
24
- if is_flax_available():
25
- import jax
26
- import jax.numpy as jnp
27
- from flax.jax_utils import replicate
28
- from flax.training.common_utils import shard
29
-
30
-
31
- @slow
32
- @require_flax
33
- class FlaxStableDiffusion2PipelineIntegrationTests(unittest.TestCase):
34
- def tearDown(self):
35
- # clean up the VRAM after each test
36
- super().tearDown()
37
- gc.collect()
38
-
39
- def test_stable_diffusion_flax(self):
40
- sd_pipe, params = FlaxStableDiffusionPipeline.from_pretrained(
41
- "stabilityai/stable-diffusion-2",
42
- revision="bf16",
43
- dtype=jnp.bfloat16,
44
- )
45
-
46
- prompt = "A painting of a squirrel eating a burger"
47
- num_samples = jax.device_count()
48
- prompt = num_samples * [prompt]
49
- prompt_ids = sd_pipe.prepare_inputs(prompt)
50
-
51
- params = replicate(params)
52
- prompt_ids = shard(prompt_ids)
53
-
54
- prng_seed = jax.random.PRNGKey(0)
55
- prng_seed = jax.random.split(prng_seed, jax.device_count())
56
-
57
- images = sd_pipe(prompt_ids, params, prng_seed, num_inference_steps=25, jit=True)[0]
58
- assert images.shape == (jax.device_count(), 1, 768, 768, 3)
59
-
60
- images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
61
- image_slice = images[0, 253:256, 253:256, -1]
62
-
63
- output_slice = jnp.asarray(jax.device_get(image_slice.flatten()))
64
- expected_slice = jnp.array([0.4238, 0.4414, 0.4395, 0.4453, 0.4629, 0.4590, 0.4531, 0.45508, 0.4512])
65
- print(f"output_slice: {output_slice}")
66
- assert jnp.abs(output_slice - expected_slice).max() < 1e-2
67
-
68
- def test_stable_diffusion_dpm_flax(self):
69
- model_id = "stabilityai/stable-diffusion-2"
70
- scheduler, scheduler_params = FlaxDPMSolverMultistepScheduler.from_pretrained(model_id, subfolder="scheduler")
71
- sd_pipe, params = FlaxStableDiffusionPipeline.from_pretrained(
72
- model_id,
73
- scheduler=scheduler,
74
- revision="bf16",
75
- dtype=jnp.bfloat16,
76
- )
77
- params["scheduler"] = scheduler_params
78
-
79
- prompt = "A painting of a squirrel eating a burger"
80
- num_samples = jax.device_count()
81
- prompt = num_samples * [prompt]
82
- prompt_ids = sd_pipe.prepare_inputs(prompt)
83
-
84
- params = replicate(params)
85
- prompt_ids = shard(prompt_ids)
86
-
87
- prng_seed = jax.random.PRNGKey(0)
88
- prng_seed = jax.random.split(prng_seed, jax.device_count())
89
-
90
- images = sd_pipe(prompt_ids, params, prng_seed, num_inference_steps=25, jit=True)[0]
91
- assert images.shape == (jax.device_count(), 1, 768, 768, 3)
92
-
93
- images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
94
- image_slice = images[0, 253:256, 253:256, -1]
95
-
96
- output_slice = jnp.asarray(jax.device_get(image_slice.flatten()))
97
- expected_slice = jnp.array([0.4336, 0.42969, 0.4453, 0.4199, 0.4297, 0.4531, 0.4434, 0.4434, 0.4297])
98
- print(f"output_slice: {output_slice}")
99
- assert jnp.abs(output_slice - expected_slice).max() < 1e-2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_detection/configs/res2net/mask_rcnn_r2_101_fpn_2x_coco.py DELETED
@@ -1,4 +0,0 @@
1
- _base_ = '../mask_rcnn/mask_rcnn_r50_fpn_2x_coco.py'
2
- model = dict(
3
- pretrained='open-mmlab://res2net101_v1d_26w_4s',
4
- backbone=dict(type='Res2Net', depth=101, scales=4, base_width=26))
 
 
 
 
 
spaces/Andy1621/uniformer_image_detection/mmdet/models/roi_heads/double_roi_head.py DELETED
@@ -1,33 +0,0 @@
1
- from ..builder import HEADS
2
- from .standard_roi_head import StandardRoIHead
3
-
4
-
5
- @HEADS.register_module()
6
- class DoubleHeadRoIHead(StandardRoIHead):
7
- """RoI head for Double Head RCNN.
8
-
9
- https://arxiv.org/abs/1904.06493
10
- """
11
-
12
- def __init__(self, reg_roi_scale_factor, **kwargs):
13
- super(DoubleHeadRoIHead, self).__init__(**kwargs)
14
- self.reg_roi_scale_factor = reg_roi_scale_factor
15
-
16
- def _bbox_forward(self, x, rois):
17
- """Box head forward function used in both training and testing time."""
18
- bbox_cls_feats = self.bbox_roi_extractor(
19
- x[:self.bbox_roi_extractor.num_inputs], rois)
20
- bbox_reg_feats = self.bbox_roi_extractor(
21
- x[:self.bbox_roi_extractor.num_inputs],
22
- rois,
23
- roi_scale_factor=self.reg_roi_scale_factor)
24
- if self.with_shared_head:
25
- bbox_cls_feats = self.shared_head(bbox_cls_feats)
26
- bbox_reg_feats = self.shared_head(bbox_reg_feats)
27
- cls_score, bbox_pred = self.bbox_head(bbox_cls_feats, bbox_reg_feats)
28
-
29
- bbox_results = dict(
30
- cls_score=cls_score,
31
- bbox_pred=bbox_pred,
32
- bbox_feats=bbox_cls_feats)
33
- return bbox_results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/AutoGPTQ_loader.py DELETED
@@ -1,72 +0,0 @@
1
- from pathlib import Path
2
-
3
- from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
4
-
5
- import modules.shared as shared
6
- from modules.logging_colors import logger
7
- from modules.models import get_max_memory_dict
8
-
9
-
10
- def load_quantized(model_name):
11
- path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
12
- pt_path = None
13
-
14
- # Find the model checkpoint
15
- if shared.args.checkpoint:
16
- pt_path = Path(shared.args.checkpoint)
17
- else:
18
- for ext in ['.safetensors', '.pt', '.bin']:
19
- found = list(path_to_model.glob(f"*{ext}"))
20
- if len(found) > 0:
21
- if len(found) > 1:
22
- logger.warning(f'More than one {ext} model has been found. The last one will be selected. It could be wrong.')
23
-
24
- pt_path = found[-1]
25
- break
26
-
27
- if pt_path is None:
28
- logger.error("The model could not be loaded because its checkpoint file in .bin/.pt/.safetensors format could not be located.")
29
- return
30
-
31
- use_safetensors = pt_path.suffix == '.safetensors'
32
- if not (path_to_model / "quantize_config.json").exists():
33
- quantize_config = BaseQuantizeConfig(
34
- bits=bits if (bits := shared.args.wbits) > 0 else 4,
35
- group_size=gs if (gs := shared.args.groupsize) > 0 else -1,
36
- desc_act=shared.args.desc_act
37
- )
38
- else:
39
- quantize_config = None
40
-
41
- # Define the params for AutoGPTQForCausalLM.from_quantized
42
- params = {
43
- 'model_basename': pt_path.stem,
44
- 'device': "cuda:0" if not shared.args.cpu else "cpu",
45
- 'use_triton': shared.args.triton,
46
- 'inject_fused_attention': not shared.args.no_inject_fused_attention,
47
- 'inject_fused_mlp': not shared.args.no_inject_fused_mlp,
48
- 'use_safetensors': use_safetensors,
49
- 'trust_remote_code': shared.args.trust_remote_code,
50
- 'max_memory': get_max_memory_dict(),
51
- 'quantize_config': quantize_config,
52
- 'use_cuda_fp16': not shared.args.no_use_cuda_fp16,
53
- 'disable_exllama': shared.args.disable_exllama,
54
- }
55
-
56
- logger.info(f"The AutoGPTQ params are: {params}")
57
- model = AutoGPTQForCausalLM.from_quantized(path_to_model, **params)
58
-
59
- # These lines fix the multimodal extension when used with AutoGPTQ
60
- if hasattr(model, 'model'):
61
- if not hasattr(model, 'dtype'):
62
- if hasattr(model.model, 'dtype'):
63
- model.dtype = model.model.dtype
64
-
65
- if hasattr(model.model, 'model') and hasattr(model.model.model, 'embed_tokens'):
66
- if not hasattr(model, 'embed_tokens'):
67
- model.embed_tokens = model.model.model.embed_tokens
68
-
69
- if not hasattr(model.model, 'embed_tokens'):
70
- model.model.embed_tokens = model.model.model.embed_tokens
71
-
72
- return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/fileio/parse.py DELETED
@@ -1,97 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
-
3
- from io import StringIO
4
-
5
- from .file_client import FileClient
6
-
7
-
8
- def list_from_file(filename,
9
- prefix='',
10
- offset=0,
11
- max_num=0,
12
- encoding='utf-8',
13
- file_client_args=None):
14
- """Load a text file and parse the content as a list of strings.
15
-
16
- Note:
17
- In v1.3.16 and later, ``list_from_file`` supports loading a text file
18
- which can be storaged in different backends and parsing the content as
19
- a list for strings.
20
-
21
- Args:
22
- filename (str): Filename.
23
- prefix (str): The prefix to be inserted to the beginning of each item.
24
- offset (int): The offset of lines.
25
- max_num (int): The maximum number of lines to be read,
26
- zeros and negatives mean no limitation.
27
- encoding (str): Encoding used to open the file. Default utf-8.
28
- file_client_args (dict, optional): Arguments to instantiate a
29
- FileClient. See :class:`mmcv.fileio.FileClient` for details.
30
- Default: None.
31
-
32
- Examples:
33
- >>> list_from_file('/path/of/your/file') # disk
34
- ['hello', 'world']
35
- >>> list_from_file('s3://path/of/your/file') # ceph or petrel
36
- ['hello', 'world']
37
-
38
- Returns:
39
- list[str]: A list of strings.
40
- """
41
- cnt = 0
42
- item_list = []
43
- file_client = FileClient.infer_client(file_client_args, filename)
44
- with StringIO(file_client.get_text(filename, encoding)) as f:
45
- for _ in range(offset):
46
- f.readline()
47
- for line in f:
48
- if 0 < max_num <= cnt:
49
- break
50
- item_list.append(prefix + line.rstrip('\n\r'))
51
- cnt += 1
52
- return item_list
53
-
54
-
55
- def dict_from_file(filename,
56
- key_type=str,
57
- encoding='utf-8',
58
- file_client_args=None):
59
- """Load a text file and parse the content as a dict.
60
-
61
- Each line of the text file will be two or more columns split by
62
- whitespaces or tabs. The first column will be parsed as dict keys, and
63
- the following columns will be parsed as dict values.
64
-
65
- Note:
66
- In v1.3.16 and later, ``dict_from_file`` supports loading a text file
67
- which can be storaged in different backends and parsing the content as
68
- a dict.
69
-
70
- Args:
71
- filename(str): Filename.
72
- key_type(type): Type of the dict keys. str is user by default and
73
- type conversion will be performed if specified.
74
- encoding (str): Encoding used to open the file. Default utf-8.
75
- file_client_args (dict, optional): Arguments to instantiate a
76
- FileClient. See :class:`mmcv.fileio.FileClient` for details.
77
- Default: None.
78
-
79
- Examples:
80
- >>> dict_from_file('/path/of/your/file') # disk
81
- {'key1': 'value1', 'key2': 'value2'}
82
- >>> dict_from_file('s3://path/of/your/file') # ceph or petrel
83
- {'key1': 'value1', 'key2': 'value2'}
84
-
85
- Returns:
86
- dict: The parsed contents.
87
- """
88
- mapping = {}
89
- file_client = FileClient.infer_client(file_client_args, filename)
90
- with StringIO(file_client.get_text(filename, encoding)) as f:
91
- for line in f:
92
- items = line.rstrip('\n').split()
93
- assert len(items) >= 2
94
- key = key_type(items[0])
95
- val = items[1:] if len(items) > 2 else items[1]
96
- mapping[key] = val
97
- return mapping
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anustup/NS_AI_LABS/src/vad.py DELETED
@@ -1,477 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- from collections import Counter, deque
3
-
4
- from typing import Any, Deque, Iterator, List, Dict
5
-
6
- from pprint import pprint
7
-
8
- from src.segments import merge_timestamps
9
-
10
- # Workaround for https://github.com/tensorflow/tensorflow/issues/48797
11
- try:
12
- import tensorflow as tf
13
- except ModuleNotFoundError:
14
- # Error handling
15
- pass
16
-
17
- import torch
18
-
19
- import ffmpeg
20
- import numpy as np
21
-
22
- from src.utils import format_timestamp
23
- from enum import Enum
24
-
25
- class NonSpeechStrategy(Enum):
26
- """
27
- Ignore non-speech frames segments.
28
- """
29
- SKIP = 1
30
- """
31
- Just treat non-speech segments as speech.
32
- """
33
- CREATE_SEGMENT = 2
34
- """
35
- Expand speech segments into subsequent non-speech segments.
36
- """
37
- EXPAND_SEGMENT = 3
38
-
39
- # Defaults for Silero
40
- SPEECH_TRESHOLD = 0.3
41
-
42
- # Minimum size of segments to process
43
- MIN_SEGMENT_DURATION = 1
44
-
45
- # The maximum time for texts from old segments to be used in the next segment
46
- MAX_PROMPT_WINDOW = 0 # seconds (0 = disabled)
47
- PROMPT_NO_SPEECH_PROB = 0.1 # Do not pass the text from segments with a no speech probability higher than this
48
-
49
- VAD_MAX_PROCESSING_CHUNK = 60 * 60 # 60 minutes of audio
50
-
51
- class TranscriptionConfig(ABC):
52
- def __init__(self, non_speech_strategy: NonSpeechStrategy = NonSpeechStrategy.SKIP,
53
- segment_padding_left: float = None, segment_padding_right = None, max_silent_period: float = None,
54
- max_merge_size: float = None, max_prompt_window: float = None):
55
- self.non_speech_strategy = non_speech_strategy
56
- self.segment_padding_left = segment_padding_left
57
- self.segment_padding_right = segment_padding_right
58
- self.max_silent_period = max_silent_period
59
- self.max_merge_size = max_merge_size
60
- self.max_prompt_window = max_prompt_window
61
-
62
- class PeriodicTranscriptionConfig(TranscriptionConfig):
63
- def __init__(self, periodic_duration: float, non_speech_strategy: NonSpeechStrategy = NonSpeechStrategy.SKIP,
64
- segment_padding_left: float = None, segment_padding_right = None, max_silent_period: float = None,
65
- max_merge_size: float = None, max_prompt_window: float = None):
66
- super().__init__(non_speech_strategy, segment_padding_left, segment_padding_right, max_silent_period, max_merge_size, max_prompt_window)
67
- self.periodic_duration = periodic_duration
68
-
69
- class AbstractTranscription(ABC):
70
- def __init__(self, sampling_rate: int = 16000):
71
- self.sampling_rate = sampling_rate
72
-
73
- def get_audio_segment(self, str, start_time: str = None, duration: str = None):
74
- return load_audio(str, self.sampling_rate, start_time, duration)
75
-
76
- @abstractmethod
77
- def get_transcribe_timestamps(self, audio: str, config: TranscriptionConfig):
78
- """
79
- Get the start and end timestamps of the sections that should be transcribed by this VAD method.
80
-
81
- Parameters
82
- ----------
83
- audio: str
84
- The audio file.
85
- config: TranscriptionConfig
86
- The transcription configuration.
87
-
88
- Returns
89
- -------
90
- A list of start and end timestamps, in fractional seconds.
91
- """
92
- return
93
-
94
- def transcribe(self, audio: str, whisperCallable, config: TranscriptionConfig):
95
- """
96
- Transcribe the given audo file.
97
-
98
- Parameters
99
- ----------
100
- audio: str
101
- The audio file.
102
-
103
- whisperCallable: Callable[[Union[str, np.ndarray, torch.Tensor], int, str, str], dict[str, Union[dict, Any]]]
104
- The callback that is used to invoke Whisper on an audio file/buffer. The first parameter is the audio file/buffer,
105
- the second parameter is an optional text prompt, and the last is the current detected language. The return value is the result of the Whisper call.
106
-
107
- Returns
108
- -------
109
- A list of start and end timestamps, in fractional seconds.
110
- """
111
-
112
- # get speech timestamps from full audio file
113
- seconds_timestamps = self.get_transcribe_timestamps(audio, config)
114
-
115
- #for seconds_timestamp in seconds_timestamps:
116
- # print("VAD timestamp ", format_timestamp(seconds_timestamp['start']), " to ", format_timestamp(seconds_timestamp['end']))
117
-
118
- merged = merge_timestamps(seconds_timestamps, config.max_silent_period, config.max_merge_size, config.segment_padding_left, config.segment_padding_right)
119
-
120
- # A deque of transcribed segments that is passed to the next segment as a prompt
121
- prompt_window = deque()
122
-
123
- print("Timestamps:")
124
- pprint(merged)
125
-
126
- if config.non_speech_strategy != NonSpeechStrategy.SKIP:
127
- max_audio_duration = get_audio_duration(audio)
128
-
129
- # Expand segments to include the gaps between them
130
- if (config.non_speech_strategy == NonSpeechStrategy.CREATE_SEGMENT):
131
- # When we have a prompt window, we create speech segments betwen each segment if we exceed the merge size
132
- merged = self.fill_gaps(merged, total_duration=max_audio_duration, max_expand_size=config.max_merge_size)
133
- elif config.non_speech_strategy == NonSpeechStrategy.EXPAND_SEGMENT:
134
- # With no prompt window, it is better to just expand the segments (this effectively passes the prompt to the next segment)
135
- merged = self.expand_gaps(merged, total_duration=max_audio_duration)
136
- else:
137
- raise Exception("Unknown non-speech strategy: " + str(config.non_speech_strategy))
138
-
139
- print("Transcribing non-speech:")
140
- pprint(merged)
141
-
142
- result = {
143
- 'text': "",
144
- 'segments': [],
145
- 'language': ""
146
- }
147
- languageCounter = Counter()
148
- detected_language = None
149
-
150
- segment_index = -1
151
-
152
- # For each time segment, run whisper
153
- for segment in merged:
154
- segment_index += 1
155
- segment_start = segment['start']
156
- segment_end = segment['end']
157
- segment_expand_amount = segment.get('expand_amount', 0)
158
- segment_gap = segment.get('gap', False)
159
-
160
- segment_duration = segment_end - segment_start
161
-
162
- if segment_duration < MIN_SEGMENT_DURATION:
163
- continue;
164
-
165
- # Audio to run on Whisper
166
- segment_audio = self.get_audio_segment(audio, start_time = str(segment_start), duration = str(segment_duration))
167
- # Previous segments to use as a prompt
168
- segment_prompt = ' '.join([segment['text'] for segment in prompt_window]) if len(prompt_window) > 0 else None
169
-
170
- # Detected language
171
- detected_language = languageCounter.most_common(1)[0][0] if len(languageCounter) > 0 else None
172
-
173
- print("Running whisper from ", format_timestamp(segment_start), " to ", format_timestamp(segment_end), ", duration: ",
174
- segment_duration, "expanded: ", segment_expand_amount, "prompt: ", segment_prompt, "language: ", detected_language)
175
- segment_result = whisperCallable(segment_audio, segment_index, segment_prompt, detected_language)
176
-
177
- adjusted_segments = self.adjust_timestamp(segment_result["segments"], adjust_seconds=segment_start, max_source_time=segment_duration)
178
-
179
- # Propagate expand amount to the segments
180
- if (segment_expand_amount > 0):
181
- segment_without_expansion = segment_duration - segment_expand_amount
182
-
183
- for adjusted_segment in adjusted_segments:
184
- adjusted_segment_end = adjusted_segment['end']
185
-
186
- # Add expand amount if the segment got expanded
187
- if (adjusted_segment_end > segment_without_expansion):
188
- adjusted_segment["expand_amount"] = adjusted_segment_end - segment_without_expansion
189
-
190
- # Append to output
191
- result['text'] += segment_result['text']
192
- result['segments'].extend(adjusted_segments)
193
-
194
- # Increment detected language
195
- if not segment_gap:
196
- languageCounter[segment_result['language']] += 1
197
-
198
- # Update prompt window
199
- self.__update_prompt_window(prompt_window, adjusted_segments, segment_end, segment_gap, config)
200
-
201
- if detected_language is not None:
202
- result['language'] = detected_language
203
-
204
- return result
205
-
206
- def __update_prompt_window(self, prompt_window: Deque, adjusted_segments: List, segment_end: float, segment_gap: bool, config: TranscriptionConfig):
207
- if (config.max_prompt_window is not None and config.max_prompt_window > 0):
208
- # Add segments to the current prompt window (unless it is a speech gap)
209
- if not segment_gap:
210
- for segment in adjusted_segments:
211
- if segment.get('no_speech_prob', 0) <= PROMPT_NO_SPEECH_PROB:
212
- prompt_window.append(segment)
213
-
214
- while (len(prompt_window) > 0):
215
- first_end_time = prompt_window[0].get('end', 0)
216
- # Time expanded in the segments should be discounted from the prompt window
217
- first_expand_time = prompt_window[0].get('expand_amount', 0)
218
-
219
- if (first_end_time - first_expand_time < segment_end - config.max_prompt_window):
220
- prompt_window.popleft()
221
- else:
222
- break
223
-
224
- def include_gaps(self, segments: Iterator[dict], min_gap_length: float, total_duration: float):
225
- result = []
226
- last_end_time = 0
227
-
228
- for segment in segments:
229
- segment_start = float(segment['start'])
230
- segment_end = float(segment['end'])
231
-
232
- if (last_end_time != segment_start):
233
- delta = segment_start - last_end_time
234
-
235
- if (min_gap_length is None or delta >= min_gap_length):
236
- result.append( { 'start': last_end_time, 'end': segment_start, 'gap': True } )
237
-
238
- last_end_time = segment_end
239
- result.append(segment)
240
-
241
- # Also include total duration if specified
242
- if (total_duration is not None and last_end_time < total_duration):
243
- delta = total_duration - segment_start
244
-
245
- if (min_gap_length is None or delta >= min_gap_length):
246
- result.append( { 'start': last_end_time, 'end': total_duration, 'gap': True } )
247
-
248
- return result
249
-
250
- # Expand the end time of each segment to the start of the next segment
251
- def expand_gaps(self, segments: List[Dict[str, Any]], total_duration: float):
252
- result = []
253
-
254
- if len(segments) == 0:
255
- return result
256
-
257
- # Add gap at the beginning if needed
258
- if (segments[0]['start'] > 0):
259
- result.append({ 'start': 0, 'end': segments[0]['start'], 'gap': True } )
260
-
261
- for i in range(len(segments) - 1):
262
- current_segment = segments[i]
263
- next_segment = segments[i + 1]
264
-
265
- delta = next_segment['start'] - current_segment['end']
266
-
267
- # Expand if the gap actually exists
268
- if (delta >= 0):
269
- current_segment = current_segment.copy()
270
- current_segment['expand_amount'] = delta
271
- current_segment['end'] = next_segment['start']
272
-
273
- result.append(current_segment)
274
-
275
- # Add last segment
276
- last_segment = segments[-1]
277
- result.append(last_segment)
278
-
279
- # Also include total duration if specified
280
- if (total_duration is not None):
281
- last_segment = result[-1]
282
-
283
- if (last_segment['end'] < total_duration):
284
- last_segment = last_segment.copy()
285
- last_segment['end'] = total_duration
286
- result[-1] = last_segment
287
-
288
- return result
289
-
290
- def fill_gaps(self, segments: List[Dict[str, Any]], total_duration: float, max_expand_size: float = None):
291
- result = []
292
-
293
- if len(segments) == 0:
294
- return result
295
-
296
- # Add gap at the beginning if needed
297
- if (segments[0]['start'] > 0):
298
- result.append({ 'start': 0, 'end': segments[0]['start'], 'gap': True } )
299
-
300
- for i in range(len(segments) - 1):
301
- expanded = False
302
- current_segment = segments[i]
303
- next_segment = segments[i + 1]
304
-
305
- delta = next_segment['start'] - current_segment['end']
306
-
307
- if (max_expand_size is not None and delta <= max_expand_size):
308
- # Just expand the current segment
309
- current_segment = current_segment.copy()
310
- current_segment['expand_amount'] = delta
311
- current_segment['end'] = next_segment['start']
312
- expanded = True
313
-
314
- result.append(current_segment)
315
-
316
- # Add a gap to the next segment if needed
317
- if (delta >= 0 and not expanded):
318
- result.append({ 'start': current_segment['end'], 'end': next_segment['start'], 'gap': True } )
319
-
320
- # Add last segment
321
- last_segment = segments[-1]
322
- result.append(last_segment)
323
-
324
- # Also include total duration if specified
325
- if (total_duration is not None):
326
- last_segment = result[-1]
327
-
328
- delta = total_duration - last_segment['end']
329
-
330
- if (delta > 0):
331
- if (max_expand_size is not None and delta <= max_expand_size):
332
- # Expand the last segment
333
- last_segment = last_segment.copy()
334
- last_segment['expand_amount'] = delta
335
- last_segment['end'] = total_duration
336
- result[-1] = last_segment
337
- else:
338
- result.append({ 'start': last_segment['end'], 'end': total_duration, 'gap': True } )
339
-
340
- return result
341
-
342
- def adjust_timestamp(self, segments: Iterator[dict], adjust_seconds: float, max_source_time: float = None):
343
- result = []
344
-
345
- for segment in segments:
346
- segment_start = float(segment['start'])
347
- segment_end = float(segment['end'])
348
-
349
- # Filter segments?
350
- if (max_source_time is not None):
351
- if (segment_start > max_source_time):
352
- continue
353
- segment_end = min(max_source_time, segment_end)
354
-
355
- new_segment = segment.copy()
356
-
357
- # Add to start and end
358
- new_segment['start'] = segment_start + adjust_seconds
359
- new_segment['end'] = segment_end + adjust_seconds
360
- result.append(new_segment)
361
- return result
362
-
363
- def multiply_timestamps(self, timestamps: List[Dict[str, Any]], factor: float):
364
- result = []
365
-
366
- for entry in timestamps:
367
- start = entry['start']
368
- end = entry['end']
369
-
370
- result.append({
371
- 'start': start * factor,
372
- 'end': end * factor
373
- })
374
- return result
375
-
376
- class VadSileroTranscription(AbstractTranscription):
377
- def __init__(self, sampling_rate: int = 16000):
378
- super().__init__(sampling_rate=sampling_rate)
379
-
380
- self.model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad')
381
- (self.get_speech_timestamps, _, _, _, _) = utils
382
-
383
-
384
- def get_transcribe_timestamps(self, audio: str, config: TranscriptionConfig):
385
- audio_duration = get_audio_duration(audio)
386
- result = []
387
-
388
- # Divide procesisng of audio into chunks
389
- chunk_start = 0.0
390
-
391
- while (chunk_start < audio_duration):
392
- chunk_duration = min(audio_duration - chunk_start, VAD_MAX_PROCESSING_CHUNK)
393
-
394
- print("Processing VAD in chunk from {} to {}".format(format_timestamp(chunk_start), format_timestamp(chunk_start + chunk_duration)))
395
- wav = self.get_audio_segment(audio, str(chunk_start), str(chunk_duration))
396
-
397
- sample_timestamps = self.get_speech_timestamps(wav, self.model, sampling_rate=self.sampling_rate, threshold=SPEECH_TRESHOLD)
398
- seconds_timestamps = self.multiply_timestamps(sample_timestamps, factor=1 / self.sampling_rate)
399
- adjusted = self.adjust_timestamp(seconds_timestamps, adjust_seconds=chunk_start, max_source_time=chunk_start + chunk_duration)
400
-
401
- #pprint(adjusted)
402
-
403
- result.extend(adjusted)
404
- chunk_start += chunk_duration
405
-
406
- return result
407
-
408
- # A very simple VAD that just marks every N seconds as speech
409
- class VadPeriodicTranscription(AbstractTranscription):
410
- def __init__(self, sampling_rate: int = 16000):
411
- super().__init__(sampling_rate=sampling_rate)
412
-
413
- def get_transcribe_timestamps(self, audio: str, config: PeriodicTranscriptionConfig):
414
- # Get duration in seconds
415
- audio_duration = get_audio_duration(audio)
416
- result = []
417
-
418
- # Generate a timestamp every N seconds
419
- start_timestamp = 0
420
-
421
- while (start_timestamp < audio_duration):
422
- end_timestamp = min(start_timestamp + config.periodic_duration, audio_duration)
423
- segment_duration = end_timestamp - start_timestamp
424
-
425
- # Minimum duration is 1 second
426
- if (segment_duration >= 1):
427
- result.append( { 'start': start_timestamp, 'end': end_timestamp } )
428
-
429
- start_timestamp = end_timestamp
430
-
431
- return result
432
-
433
- def get_audio_duration(file: str):
434
- return float(ffmpeg.probe(file)["format"]["duration"])
435
-
436
- def load_audio(file: str, sample_rate: int = 16000,
437
- start_time: str = None, duration: str = None):
438
- """
439
- Open an audio file and read as mono waveform, resampling as necessary
440
-
441
- Parameters
442
- ----------
443
- file: str
444
- The audio file to open
445
-
446
- sr: int
447
- The sample rate to resample the audio if necessary
448
-
449
- start_time: str
450
- The start time, using the standard FFMPEG time duration syntax, or None to disable.
451
-
452
- duration: str
453
- The duration, using the standard FFMPEG time duration syntax, or None to disable.
454
-
455
- Returns
456
- -------
457
- A NumPy array containing the audio waveform, in float32 dtype.
458
- """
459
- try:
460
- inputArgs = {'threads': 0}
461
-
462
- if (start_time is not None):
463
- inputArgs['ss'] = start_time
464
- if (duration is not None):
465
- inputArgs['t'] = duration
466
-
467
- # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
468
- # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
469
- out, _ = (
470
- ffmpeg.input(file, **inputArgs)
471
- .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sample_rate)
472
- .run(cmd="ffmpeg", capture_stdout=True, capture_stderr=True)
473
- )
474
- except ffmpeg.Error as e:
475
- raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}")
476
-
477
- return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ariharasudhan/YoloV5/utils/loss.py DELETED
@@ -1,234 +0,0 @@
1
- # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
- """
3
- Loss functions
4
- """
5
-
6
- import torch
7
- import torch.nn as nn
8
-
9
- from utils.metrics import bbox_iou
10
- from utils.torch_utils import de_parallel
11
-
12
-
13
- def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
14
- # return positive, negative label smoothing BCE targets
15
- return 1.0 - 0.5 * eps, 0.5 * eps
16
-
17
-
18
- class BCEBlurWithLogitsLoss(nn.Module):
19
- # BCEwithLogitLoss() with reduced missing label effects.
20
- def __init__(self, alpha=0.05):
21
- super().__init__()
22
- self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
23
- self.alpha = alpha
24
-
25
- def forward(self, pred, true):
26
- loss = self.loss_fcn(pred, true)
27
- pred = torch.sigmoid(pred) # prob from logits
28
- dx = pred - true # reduce only missing label effects
29
- # dx = (pred - true).abs() # reduce missing label and false label effects
30
- alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
31
- loss *= alpha_factor
32
- return loss.mean()
33
-
34
-
35
- class FocalLoss(nn.Module):
36
- # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
37
- def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
38
- super().__init__()
39
- self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
40
- self.gamma = gamma
41
- self.alpha = alpha
42
- self.reduction = loss_fcn.reduction
43
- self.loss_fcn.reduction = 'none' # required to apply FL to each element
44
-
45
- def forward(self, pred, true):
46
- loss = self.loss_fcn(pred, true)
47
- # p_t = torch.exp(-loss)
48
- # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
49
-
50
- # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
51
- pred_prob = torch.sigmoid(pred) # prob from logits
52
- p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
53
- alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
54
- modulating_factor = (1.0 - p_t) ** self.gamma
55
- loss *= alpha_factor * modulating_factor
56
-
57
- if self.reduction == 'mean':
58
- return loss.mean()
59
- elif self.reduction == 'sum':
60
- return loss.sum()
61
- else: # 'none'
62
- return loss
63
-
64
-
65
- class QFocalLoss(nn.Module):
66
- # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
67
- def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
68
- super().__init__()
69
- self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
70
- self.gamma = gamma
71
- self.alpha = alpha
72
- self.reduction = loss_fcn.reduction
73
- self.loss_fcn.reduction = 'none' # required to apply FL to each element
74
-
75
- def forward(self, pred, true):
76
- loss = self.loss_fcn(pred, true)
77
-
78
- pred_prob = torch.sigmoid(pred) # prob from logits
79
- alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
80
- modulating_factor = torch.abs(true - pred_prob) ** self.gamma
81
- loss *= alpha_factor * modulating_factor
82
-
83
- if self.reduction == 'mean':
84
- return loss.mean()
85
- elif self.reduction == 'sum':
86
- return loss.sum()
87
- else: # 'none'
88
- return loss
89
-
90
-
91
- class ComputeLoss:
92
- sort_obj_iou = False
93
-
94
- # Compute losses
95
- def __init__(self, model, autobalance=False):
96
- device = next(model.parameters()).device # get model device
97
- h = model.hyp # hyperparameters
98
-
99
- # Define criteria
100
- BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
101
- BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
102
-
103
- # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
104
- self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
105
-
106
- # Focal loss
107
- g = h['fl_gamma'] # focal loss gamma
108
- if g > 0:
109
- BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
110
-
111
- m = de_parallel(model).model[-1] # Detect() module
112
- self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
113
- self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
114
- self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
115
- self.na = m.na # number of anchors
116
- self.nc = m.nc # number of classes
117
- self.nl = m.nl # number of layers
118
- self.anchors = m.anchors
119
- self.device = device
120
-
121
- def __call__(self, p, targets): # predictions, targets
122
- lcls = torch.zeros(1, device=self.device) # class loss
123
- lbox = torch.zeros(1, device=self.device) # box loss
124
- lobj = torch.zeros(1, device=self.device) # object loss
125
- tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
126
-
127
- # Losses
128
- for i, pi in enumerate(p): # layer index, layer predictions
129
- b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
130
- tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
131
-
132
- n = b.shape[0] # number of targets
133
- if n:
134
- # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0
135
- pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions
136
-
137
- # Regression
138
- pxy = pxy.sigmoid() * 2 - 0.5
139
- pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
140
- pbox = torch.cat((pxy, pwh), 1) # predicted box
141
- iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
142
- lbox += (1.0 - iou).mean() # iou loss
143
-
144
- # Objectness
145
- iou = iou.detach().clamp(0).type(tobj.dtype)
146
- if self.sort_obj_iou:
147
- j = iou.argsort()
148
- b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
149
- if self.gr < 1:
150
- iou = (1.0 - self.gr) + self.gr * iou
151
- tobj[b, a, gj, gi] = iou # iou ratio
152
-
153
- # Classification
154
- if self.nc > 1: # cls loss (only if multiple classes)
155
- t = torch.full_like(pcls, self.cn, device=self.device) # targets
156
- t[range(n), tcls[i]] = self.cp
157
- lcls += self.BCEcls(pcls, t) # BCE
158
-
159
- # Append targets to text file
160
- # with open('targets.txt', 'a') as file:
161
- # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
162
-
163
- obji = self.BCEobj(pi[..., 4], tobj)
164
- lobj += obji * self.balance[i] # obj loss
165
- if self.autobalance:
166
- self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
167
-
168
- if self.autobalance:
169
- self.balance = [x / self.balance[self.ssi] for x in self.balance]
170
- lbox *= self.hyp['box']
171
- lobj *= self.hyp['obj']
172
- lcls *= self.hyp['cls']
173
- bs = tobj.shape[0] # batch size
174
-
175
- return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
176
-
177
- def build_targets(self, p, targets):
178
- # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
179
- na, nt = self.na, targets.shape[0] # number of anchors, targets
180
- tcls, tbox, indices, anch = [], [], [], []
181
- gain = torch.ones(7, device=self.device) # normalized to gridspace gain
182
- ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
183
- targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices
184
-
185
- g = 0.5 # bias
186
- off = torch.tensor(
187
- [
188
- [0, 0],
189
- [1, 0],
190
- [0, 1],
191
- [-1, 0],
192
- [0, -1], # j,k,l,m
193
- # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
194
- ],
195
- device=self.device).float() * g # offsets
196
-
197
- for i in range(self.nl):
198
- anchors, shape = self.anchors[i], p[i].shape
199
- gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
200
-
201
- # Match targets to anchors
202
- t = targets * gain # shape(3,n,7)
203
- if nt:
204
- # Matches
205
- r = t[..., 4:6] / anchors[:, None] # wh ratio
206
- j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare
207
- # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
208
- t = t[j] # filter
209
-
210
- # Offsets
211
- gxy = t[:, 2:4] # grid xy
212
- gxi = gain[[2, 3]] - gxy # inverse
213
- j, k = ((gxy % 1 < g) & (gxy > 1)).T
214
- l, m = ((gxi % 1 < g) & (gxi > 1)).T
215
- j = torch.stack((torch.ones_like(j), j, k, l, m))
216
- t = t.repeat((5, 1, 1))[j]
217
- offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
218
- else:
219
- t = targets[0]
220
- offsets = 0
221
-
222
- # Define
223
- bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
224
- a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class
225
- gij = (gxy - offsets).long()
226
- gi, gj = gij.T # grid indices
227
-
228
- # Append
229
- indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
230
- tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
231
- anch.append(anchors[a]) # anchors
232
- tcls.append(c) # class
233
-
234
- return tcls, tbox, indices, anch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Arnx/MusicGenXvAKN/audiocraft/modules/conv.py DELETED
@@ -1,245 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the license found in the
5
- # LICENSE file in the root directory of this source tree.
6
-
7
- import math
8
- import typing as tp
9
- import warnings
10
-
11
- import torch
12
- from torch import nn
13
- from torch.nn import functional as F
14
- from torch.nn.utils import spectral_norm, weight_norm
15
-
16
-
17
- CONV_NORMALIZATIONS = frozenset(['none', 'weight_norm', 'spectral_norm',
18
- 'time_group_norm'])
19
-
20
-
21
- def apply_parametrization_norm(module: nn.Module, norm: str = 'none'):
22
- assert norm in CONV_NORMALIZATIONS
23
- if norm == 'weight_norm':
24
- return weight_norm(module)
25
- elif norm == 'spectral_norm':
26
- return spectral_norm(module)
27
- else:
28
- # We already check was in CONV_NORMALIZATION, so any other choice
29
- # doesn't need reparametrization.
30
- return module
31
-
32
-
33
- def get_norm_module(module: nn.Module, causal: bool = False, norm: str = 'none', **norm_kwargs):
34
- """Return the proper normalization module. If causal is True, this will ensure the returned
35
- module is causal, or return an error if the normalization doesn't support causal evaluation.
36
- """
37
- assert norm in CONV_NORMALIZATIONS
38
- if norm == 'time_group_norm':
39
- if causal:
40
- raise ValueError("GroupNorm doesn't support causal evaluation.")
41
- assert isinstance(module, nn.modules.conv._ConvNd)
42
- return nn.GroupNorm(1, module.out_channels, **norm_kwargs)
43
- else:
44
- return nn.Identity()
45
-
46
-
47
- def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int,
48
- padding_total: int = 0) -> int:
49
- """See `pad_for_conv1d`.
50
- """
51
- length = x.shape[-1]
52
- n_frames = (length - kernel_size + padding_total) / stride + 1
53
- ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
54
- return ideal_length - length
55
-
56
-
57
- def pad_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0):
58
- """Pad for a convolution to make sure that the last window is full.
59
- Extra padding is added at the end. This is required to ensure that we can rebuild
60
- an output of the same length, as otherwise, even with padding, some time steps
61
- might get removed.
62
- For instance, with total padding = 4, kernel size = 4, stride = 2:
63
- 0 0 1 2 3 4 5 0 0 # (0s are padding)
64
- 1 2 3 # (output frames of a convolution, last 0 is never used)
65
- 0 0 1 2 3 4 5 0 # (output of tr. conv., but pos. 5 is going to get removed as padding)
66
- 1 2 3 4 # once you removed padding, we are missing one time step !
67
- """
68
- extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
69
- return F.pad(x, (0, extra_padding))
70
-
71
-
72
- def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'constant', value: float = 0.):
73
- """Tiny wrapper around F.pad, just to allow for reflect padding on small input.
74
- If this is the case, we insert extra 0 padding to the right before the reflection happen.
75
- """
76
- length = x.shape[-1]
77
- padding_left, padding_right = paddings
78
- assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
79
- if mode == 'reflect':
80
- max_pad = max(padding_left, padding_right)
81
- extra_pad = 0
82
- if length <= max_pad:
83
- extra_pad = max_pad - length + 1
84
- x = F.pad(x, (0, extra_pad))
85
- padded = F.pad(x, paddings, mode, value)
86
- end = padded.shape[-1] - extra_pad
87
- return padded[..., :end]
88
- else:
89
- return F.pad(x, paddings, mode, value)
90
-
91
-
92
- def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]):
93
- """Remove padding from x, handling properly zero padding. Only for 1d!
94
- """
95
- padding_left, padding_right = paddings
96
- assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
97
- assert (padding_left + padding_right) <= x.shape[-1]
98
- end = x.shape[-1] - padding_right
99
- return x[..., padding_left: end]
100
-
101
-
102
- class NormConv1d(nn.Module):
103
- """Wrapper around Conv1d and normalization applied to this conv
104
- to provide a uniform interface across normalization approaches.
105
- """
106
- def __init__(self, *args, causal: bool = False, norm: str = 'none',
107
- norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
108
- super().__init__()
109
- self.conv = apply_parametrization_norm(nn.Conv1d(*args, **kwargs), norm)
110
- self.norm = get_norm_module(self.conv, causal, norm, **norm_kwargs)
111
- self.norm_type = norm
112
-
113
- def forward(self, x):
114
- x = self.conv(x)
115
- x = self.norm(x)
116
- return x
117
-
118
-
119
- class NormConv2d(nn.Module):
120
- """Wrapper around Conv2d and normalization applied to this conv
121
- to provide a uniform interface across normalization approaches.
122
- """
123
- def __init__(self, *args, norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
124
- super().__init__()
125
- self.conv = apply_parametrization_norm(nn.Conv2d(*args, **kwargs), norm)
126
- self.norm = get_norm_module(self.conv, causal=False, norm=norm, **norm_kwargs)
127
- self.norm_type = norm
128
-
129
- def forward(self, x):
130
- x = self.conv(x)
131
- x = self.norm(x)
132
- return x
133
-
134
-
135
- class NormConvTranspose1d(nn.Module):
136
- """Wrapper around ConvTranspose1d and normalization applied to this conv
137
- to provide a uniform interface across normalization approaches.
138
- """
139
- def __init__(self, *args, causal: bool = False, norm: str = 'none',
140
- norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
141
- super().__init__()
142
- self.convtr = apply_parametrization_norm(nn.ConvTranspose1d(*args, **kwargs), norm)
143
- self.norm = get_norm_module(self.convtr, causal, norm, **norm_kwargs)
144
- self.norm_type = norm
145
-
146
- def forward(self, x):
147
- x = self.convtr(x)
148
- x = self.norm(x)
149
- return x
150
-
151
-
152
- class NormConvTranspose2d(nn.Module):
153
- """Wrapper around ConvTranspose2d and normalization applied to this conv
154
- to provide a uniform interface across normalization approaches.
155
- """
156
- def __init__(self, *args, norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {}, **kwargs):
157
- super().__init__()
158
- self.convtr = apply_parametrization_norm(nn.ConvTranspose2d(*args, **kwargs), norm)
159
- self.norm = get_norm_module(self.convtr, causal=False, norm=norm, **norm_kwargs)
160
-
161
- def forward(self, x):
162
- x = self.convtr(x)
163
- x = self.norm(x)
164
- return x
165
-
166
-
167
- class StreamableConv1d(nn.Module):
168
- """Conv1d with some builtin handling of asymmetric or causal padding
169
- and normalization.
170
- """
171
- def __init__(self, in_channels: int, out_channels: int,
172
- kernel_size: int, stride: int = 1, dilation: int = 1,
173
- groups: int = 1, bias: bool = True, causal: bool = False,
174
- norm: str = 'none', norm_kwargs: tp.Dict[str, tp.Any] = {},
175
- pad_mode: str = 'reflect'):
176
- super().__init__()
177
- # warn user on unusual setup between dilation and stride
178
- if stride > 1 and dilation > 1:
179
- warnings.warn('StreamableConv1d has been initialized with stride > 1 and dilation > 1'
180
- f' (kernel_size={kernel_size} stride={stride}, dilation={dilation}).')
181
- self.conv = NormConv1d(in_channels, out_channels, kernel_size, stride,
182
- dilation=dilation, groups=groups, bias=bias, causal=causal,
183
- norm=norm, norm_kwargs=norm_kwargs)
184
- self.causal = causal
185
- self.pad_mode = pad_mode
186
-
187
- def forward(self, x):
188
- B, C, T = x.shape
189
- kernel_size = self.conv.conv.kernel_size[0]
190
- stride = self.conv.conv.stride[0]
191
- dilation = self.conv.conv.dilation[0]
192
- kernel_size = (kernel_size - 1) * dilation + 1 # effective kernel size with dilations
193
- padding_total = kernel_size - stride
194
- extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
195
- if self.causal:
196
- # Left padding for causal
197
- x = pad1d(x, (padding_total, extra_padding), mode=self.pad_mode)
198
- else:
199
- # Asymmetric padding required for odd strides
200
- padding_right = padding_total // 2
201
- padding_left = padding_total - padding_right
202
- x = pad1d(x, (padding_left, padding_right + extra_padding), mode=self.pad_mode)
203
- return self.conv(x)
204
-
205
-
206
- class StreamableConvTranspose1d(nn.Module):
207
- """ConvTranspose1d with some builtin handling of asymmetric or causal padding
208
- and normalization.
209
- """
210
- def __init__(self, in_channels: int, out_channels: int,
211
- kernel_size: int, stride: int = 1, causal: bool = False,
212
- norm: str = 'none', trim_right_ratio: float = 1.,
213
- norm_kwargs: tp.Dict[str, tp.Any] = {}):
214
- super().__init__()
215
- self.convtr = NormConvTranspose1d(in_channels, out_channels, kernel_size, stride,
216
- causal=causal, norm=norm, norm_kwargs=norm_kwargs)
217
- self.causal = causal
218
- self.trim_right_ratio = trim_right_ratio
219
- assert self.causal or self.trim_right_ratio == 1., \
220
- "`trim_right_ratio` != 1.0 only makes sense for causal convolutions"
221
- assert self.trim_right_ratio >= 0. and self.trim_right_ratio <= 1.
222
-
223
- def forward(self, x):
224
- kernel_size = self.convtr.convtr.kernel_size[0]
225
- stride = self.convtr.convtr.stride[0]
226
- padding_total = kernel_size - stride
227
-
228
- y = self.convtr(x)
229
-
230
- # We will only trim fixed padding. Extra padding from `pad_for_conv1d` would be
231
- # removed at the very end, when keeping only the right length for the output,
232
- # as removing it here would require also passing the length at the matching layer
233
- # in the encoder.
234
- if self.causal:
235
- # Trim the padding on the right according to the specified ratio
236
- # if trim_right_ratio = 1.0, trim everything from right
237
- padding_right = math.ceil(padding_total * self.trim_right_ratio)
238
- padding_left = padding_total - padding_right
239
- y = unpad1d(y, (padding_left, padding_right))
240
- else:
241
- # Asymmetric padding required for odd strides
242
- padding_right = padding_total // 2
243
- padding_left = padding_total - padding_right
244
- y = unpad1d(y, (padding_left, padding_right))
245
- return y
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ash123/stable-diffusion-nano/share_btn.py DELETED
@@ -1,60 +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
- const gradioEl = document.querySelector('body > gradio-app');
26
- const imgEls = gradioEl.querySelectorAll('#gallery img');
27
- const promptTxt = gradioEl.querySelector('#prompt-text-input input').value;
28
- const shareBtnEl = gradioEl.querySelector('#share-btn');
29
- const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
30
- const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
31
- if(!imgEls.length){
32
- return;
33
- };
34
- shareBtnEl.style.pointerEvents = 'none';
35
- shareIconEl.style.display = 'none';
36
- loadingIconEl.style.removeProperty('display');
37
- const files = await Promise.all(
38
- [...imgEls].map(async (imgEl) => {
39
- const res = await fetch(imgEl.src);
40
- const blob = await res.blob();
41
- const imgId = Date.now() % 200;
42
- const fileName = `diffuse-the-rest-${{imgId}}.jpg`;
43
- return new File([blob], fileName, { type: 'image/jpeg' });
44
- })
45
- );
46
- const urls = await Promise.all(files.map((f) => uploadFile(f)));
47
- const htmlImgs = urls.map(url => `<img src='${url}' width='400' height='400'>`);
48
- const descriptionMd = `<div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>
49
- ${htmlImgs.join(`\n`)}
50
- </div>`;
51
- const params = new URLSearchParams({
52
- title: promptTxt,
53
- description: descriptionMd,
54
- });
55
- const paramsStr = params.toString();
56
- window.open(`https://huggingface.co/spaces/stabilityai/stable-diffusion/discussions/new?${paramsStr}`, '_blank');
57
- shareBtnEl.style.removeProperty('pointer-events');
58
- shareIconEl.style.removeProperty('display');
59
- loadingIconEl.style.display = 'none';
60
- }"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/utils/appdirs.py DELETED
@@ -1,52 +0,0 @@
1
- """
2
- This code wraps the vendored appdirs module to so the return values are
3
- compatible for the current pip code base.
4
-
5
- The intention is to rewrite current usages gradually, keeping the tests pass,
6
- and eventually drop this after all usages are changed.
7
- """
8
-
9
- import os
10
- import sys
11
- from typing import List
12
-
13
- from pip._vendor import platformdirs as _appdirs
14
-
15
-
16
- def user_cache_dir(appname: str) -> str:
17
- return _appdirs.user_cache_dir(appname, appauthor=False)
18
-
19
-
20
- def _macos_user_config_dir(appname: str, roaming: bool = True) -> str:
21
- # Use ~/Application Support/pip, if the directory exists.
22
- path = _appdirs.user_data_dir(appname, appauthor=False, roaming=roaming)
23
- if os.path.isdir(path):
24
- return path
25
-
26
- # Use a Linux-like ~/.config/pip, by default.
27
- linux_like_path = "~/.config/"
28
- if appname:
29
- linux_like_path = os.path.join(linux_like_path, appname)
30
-
31
- return os.path.expanduser(linux_like_path)
32
-
33
-
34
- def user_config_dir(appname: str, roaming: bool = True) -> str:
35
- if sys.platform == "darwin":
36
- return _macos_user_config_dir(appname, roaming)
37
-
38
- return _appdirs.user_config_dir(appname, appauthor=False, roaming=roaming)
39
-
40
-
41
- # for the discussion regarding site_config_dir locations
42
- # see <https://github.com/pypa/pip/issues/1733>
43
- def site_config_dirs(appname: str) -> List[str]:
44
- if sys.platform == "darwin":
45
- return [_appdirs.site_data_dir(appname, appauthor=False, multipath=True)]
46
-
47
- dirval = _appdirs.site_config_dir(appname, appauthor=False, multipath=True)
48
- if sys.platform == "win32":
49
- return [dirval]
50
-
51
- # Unix-y system. Look in /etc as well.
52
- return dirval.split(os.pathsep) + ["/etc"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/tomli/__init__.py DELETED
@@ -1,11 +0,0 @@
1
- # SPDX-License-Identifier: MIT
2
- # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
3
- # Licensed to PSF under a Contributor Agreement.
4
-
5
- __all__ = ("loads", "load", "TOMLDecodeError")
6
- __version__ = "2.0.1" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
7
-
8
- from ._parser import TOMLDecodeError, load, loads
9
-
10
- # Pretend this exception was created here.
11
- TOMLDecodeError.__module__ = __name__
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_400ep_LSJ.py DELETED
@@ -1,14 +0,0 @@
1
- from .mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ import (
2
- dataloader,
3
- lr_multiplier,
4
- model,
5
- optimizer,
6
- train,
7
- )
8
-
9
- train.max_iter *= 4 # 100ep -> 400ep
10
-
11
- lr_multiplier.scheduler.milestones = [
12
- milestone * 4 for milestone in lr_multiplier.scheduler.milestones
13
- ]
14
- lr_multiplier.scheduler.num_updates = train.max_iter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/tests/modeling/test_backbone.py DELETED
@@ -1,34 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
-
3
- import unittest
4
- import torch
5
-
6
- import detectron2.export.torchscript # apply patch # noqa
7
- from detectron2 import model_zoo
8
- from detectron2.config import get_cfg
9
- from detectron2.layers import ShapeSpec
10
- from detectron2.modeling.backbone import build_resnet_backbone
11
- from detectron2.modeling.backbone.fpn import build_resnet_fpn_backbone
12
-
13
-
14
- class TestBackBone(unittest.TestCase):
15
- def test_resnet_scriptability(self):
16
- cfg = get_cfg()
17
- resnet = build_resnet_backbone(cfg, ShapeSpec(channels=3))
18
-
19
- scripted_resnet = torch.jit.script(resnet)
20
-
21
- inp = torch.rand(2, 3, 100, 100)
22
- out1 = resnet(inp)["res4"]
23
- out2 = scripted_resnet(inp)["res4"]
24
- self.assertTrue(torch.allclose(out1, out2))
25
-
26
- def test_fpn_scriptability(self):
27
- cfg = model_zoo.get_config("Misc/scratch_mask_rcnn_R_50_FPN_3x_gn.yaml")
28
- bb = build_resnet_fpn_backbone(cfg, ShapeSpec(channels=3))
29
- bb_s = torch.jit.script(bb)
30
-
31
- inp = torch.rand(2, 3, 128, 128)
32
- out1 = bb(inp)["p5"]
33
- out2 = bb_s(inp)["p5"]
34
- self.assertTrue(torch.allclose(out1, out2))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Bart92/RVC_HF/demucs/__main__.py DELETED
@@ -1,317 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the license found in the
5
- # LICENSE file in the root directory of this source tree.
6
-
7
- import json
8
- import math
9
- import os
10
- import sys
11
- import time
12
- from dataclasses import dataclass, field
13
-
14
- import torch as th
15
- from torch import distributed, nn
16
- from torch.nn.parallel.distributed import DistributedDataParallel
17
-
18
- from .augment import FlipChannels, FlipSign, Remix, Scale, Shift
19
- from .compressed import get_compressed_datasets
20
- from .model import Demucs
21
- from .parser import get_name, get_parser
22
- from .raw import Rawset
23
- from .repitch import RepitchedWrapper
24
- from .pretrained import load_pretrained, SOURCES
25
- from .tasnet import ConvTasNet
26
- from .test import evaluate
27
- from .train import train_model, validate_model
28
- from .utils import (human_seconds, load_model, save_model, get_state,
29
- save_state, sizeof_fmt, get_quantizer)
30
- from .wav import get_wav_datasets, get_musdb_wav_datasets
31
-
32
-
33
- @dataclass
34
- class SavedState:
35
- metrics: list = field(default_factory=list)
36
- last_state: dict = None
37
- best_state: dict = None
38
- optimizer: dict = None
39
-
40
-
41
- def main():
42
- parser = get_parser()
43
- args = parser.parse_args()
44
- name = get_name(parser, args)
45
- print(f"Experiment {name}")
46
-
47
- if args.musdb is None and args.rank == 0:
48
- print(
49
- "You must provide the path to the MusDB dataset with the --musdb flag. "
50
- "To download the MusDB dataset, see https://sigsep.github.io/datasets/musdb.html.",
51
- file=sys.stderr)
52
- sys.exit(1)
53
-
54
- eval_folder = args.evals / name
55
- eval_folder.mkdir(exist_ok=True, parents=True)
56
- args.logs.mkdir(exist_ok=True)
57
- metrics_path = args.logs / f"{name}.json"
58
- eval_folder.mkdir(exist_ok=True, parents=True)
59
- args.checkpoints.mkdir(exist_ok=True, parents=True)
60
- args.models.mkdir(exist_ok=True, parents=True)
61
-
62
- if args.device is None:
63
- device = "cpu"
64
- if th.cuda.is_available():
65
- device = "cuda"
66
- else:
67
- device = args.device
68
-
69
- th.manual_seed(args.seed)
70
- # Prevents too many threads to be started when running `museval` as it can be quite
71
- # inefficient on NUMA architectures.
72
- os.environ["OMP_NUM_THREADS"] = "1"
73
- os.environ["MKL_NUM_THREADS"] = "1"
74
-
75
- if args.world_size > 1:
76
- if device != "cuda" and args.rank == 0:
77
- print("Error: distributed training is only available with cuda device", file=sys.stderr)
78
- sys.exit(1)
79
- th.cuda.set_device(args.rank % th.cuda.device_count())
80
- distributed.init_process_group(backend="nccl",
81
- init_method="tcp://" + args.master,
82
- rank=args.rank,
83
- world_size=args.world_size)
84
-
85
- checkpoint = args.checkpoints / f"{name}.th"
86
- checkpoint_tmp = args.checkpoints / f"{name}.th.tmp"
87
- if args.restart and checkpoint.exists() and args.rank == 0:
88
- checkpoint.unlink()
89
-
90
- if args.test or args.test_pretrained:
91
- args.epochs = 1
92
- args.repeat = 0
93
- if args.test:
94
- model = load_model(args.models / args.test)
95
- else:
96
- model = load_pretrained(args.test_pretrained)
97
- elif args.tasnet:
98
- model = ConvTasNet(audio_channels=args.audio_channels,
99
- samplerate=args.samplerate, X=args.X,
100
- segment_length=4 * args.samples,
101
- sources=SOURCES)
102
- else:
103
- model = Demucs(
104
- audio_channels=args.audio_channels,
105
- channels=args.channels,
106
- context=args.context,
107
- depth=args.depth,
108
- glu=args.glu,
109
- growth=args.growth,
110
- kernel_size=args.kernel_size,
111
- lstm_layers=args.lstm_layers,
112
- rescale=args.rescale,
113
- rewrite=args.rewrite,
114
- stride=args.conv_stride,
115
- resample=args.resample,
116
- normalize=args.normalize,
117
- samplerate=args.samplerate,
118
- segment_length=4 * args.samples,
119
- sources=SOURCES,
120
- )
121
- model.to(device)
122
- if args.init:
123
- model.load_state_dict(load_pretrained(args.init).state_dict())
124
-
125
- if args.show:
126
- print(model)
127
- size = sizeof_fmt(4 * sum(p.numel() for p in model.parameters()))
128
- print(f"Model size {size}")
129
- return
130
-
131
- try:
132
- saved = th.load(checkpoint, map_location='cpu')
133
- except IOError:
134
- saved = SavedState()
135
-
136
- optimizer = th.optim.Adam(model.parameters(), lr=args.lr)
137
-
138
- quantizer = None
139
- quantizer = get_quantizer(model, args, optimizer)
140
-
141
- if saved.last_state is not None:
142
- model.load_state_dict(saved.last_state, strict=False)
143
- if saved.optimizer is not None:
144
- optimizer.load_state_dict(saved.optimizer)
145
-
146
- model_name = f"{name}.th"
147
- if args.save_model:
148
- if args.rank == 0:
149
- model.to("cpu")
150
- model.load_state_dict(saved.best_state)
151
- save_model(model, quantizer, args, args.models / model_name)
152
- return
153
- elif args.save_state:
154
- model_name = f"{args.save_state}.th"
155
- if args.rank == 0:
156
- model.to("cpu")
157
- model.load_state_dict(saved.best_state)
158
- state = get_state(model, quantizer)
159
- save_state(state, args.models / model_name)
160
- return
161
-
162
- if args.rank == 0:
163
- done = args.logs / f"{name}.done"
164
- if done.exists():
165
- done.unlink()
166
-
167
- augment = [Shift(args.data_stride)]
168
- if args.augment:
169
- augment += [FlipSign(), FlipChannels(), Scale(),
170
- Remix(group_size=args.remix_group_size)]
171
- augment = nn.Sequential(*augment).to(device)
172
- print("Agumentation pipeline:", augment)
173
-
174
- if args.mse:
175
- criterion = nn.MSELoss()
176
- else:
177
- criterion = nn.L1Loss()
178
-
179
- # Setting number of samples so that all convolution windows are full.
180
- # Prevents hard to debug mistake with the prediction being shifted compared
181
- # to the input mixture.
182
- samples = model.valid_length(args.samples)
183
- print(f"Number of training samples adjusted to {samples}")
184
- samples = samples + args.data_stride
185
- if args.repitch:
186
- # We need a bit more audio samples, to account for potential
187
- # tempo change.
188
- samples = math.ceil(samples / (1 - 0.01 * args.max_tempo))
189
-
190
- args.metadata.mkdir(exist_ok=True, parents=True)
191
- if args.raw:
192
- train_set = Rawset(args.raw / "train",
193
- samples=samples,
194
- channels=args.audio_channels,
195
- streams=range(1, len(model.sources) + 1),
196
- stride=args.data_stride)
197
-
198
- valid_set = Rawset(args.raw / "valid", channels=args.audio_channels)
199
- elif args.wav:
200
- train_set, valid_set = get_wav_datasets(args, samples, model.sources)
201
- elif args.is_wav:
202
- train_set, valid_set = get_musdb_wav_datasets(args, samples, model.sources)
203
- else:
204
- train_set, valid_set = get_compressed_datasets(args, samples)
205
-
206
- if args.repitch:
207
- train_set = RepitchedWrapper(
208
- train_set,
209
- proba=args.repitch,
210
- max_tempo=args.max_tempo)
211
-
212
- best_loss = float("inf")
213
- for epoch, metrics in enumerate(saved.metrics):
214
- print(f"Epoch {epoch:03d}: "
215
- f"train={metrics['train']:.8f} "
216
- f"valid={metrics['valid']:.8f} "
217
- f"best={metrics['best']:.4f} "
218
- f"ms={metrics.get('true_model_size', 0):.2f}MB "
219
- f"cms={metrics.get('compressed_model_size', 0):.2f}MB "
220
- f"duration={human_seconds(metrics['duration'])}")
221
- best_loss = metrics['best']
222
-
223
- if args.world_size > 1:
224
- dmodel = DistributedDataParallel(model,
225
- device_ids=[th.cuda.current_device()],
226
- output_device=th.cuda.current_device())
227
- else:
228
- dmodel = model
229
-
230
- for epoch in range(len(saved.metrics), args.epochs):
231
- begin = time.time()
232
- model.train()
233
- train_loss, model_size = train_model(
234
- epoch, train_set, dmodel, criterion, optimizer, augment,
235
- quantizer=quantizer,
236
- batch_size=args.batch_size,
237
- device=device,
238
- repeat=args.repeat,
239
- seed=args.seed,
240
- diffq=args.diffq,
241
- workers=args.workers,
242
- world_size=args.world_size)
243
- model.eval()
244
- valid_loss = validate_model(
245
- epoch, valid_set, model, criterion,
246
- device=device,
247
- rank=args.rank,
248
- split=args.split_valid,
249
- overlap=args.overlap,
250
- world_size=args.world_size)
251
-
252
- ms = 0
253
- cms = 0
254
- if quantizer and args.rank == 0:
255
- ms = quantizer.true_model_size()
256
- cms = quantizer.compressed_model_size(num_workers=min(40, args.world_size * 10))
257
-
258
- duration = time.time() - begin
259
- if valid_loss < best_loss and ms <= args.ms_target:
260
- best_loss = valid_loss
261
- saved.best_state = {
262
- key: value.to("cpu").clone()
263
- for key, value in model.state_dict().items()
264
- }
265
-
266
- saved.metrics.append({
267
- "train": train_loss,
268
- "valid": valid_loss,
269
- "best": best_loss,
270
- "duration": duration,
271
- "model_size": model_size,
272
- "true_model_size": ms,
273
- "compressed_model_size": cms,
274
- })
275
- if args.rank == 0:
276
- json.dump(saved.metrics, open(metrics_path, "w"))
277
-
278
- saved.last_state = model.state_dict()
279
- saved.optimizer = optimizer.state_dict()
280
- if args.rank == 0 and not args.test:
281
- th.save(saved, checkpoint_tmp)
282
- checkpoint_tmp.rename(checkpoint)
283
-
284
- print(f"Epoch {epoch:03d}: "
285
- f"train={train_loss:.8f} valid={valid_loss:.8f} best={best_loss:.4f} ms={ms:.2f}MB "
286
- f"cms={cms:.2f}MB "
287
- f"duration={human_seconds(duration)}")
288
-
289
- if args.world_size > 1:
290
- distributed.barrier()
291
-
292
- del dmodel
293
- model.load_state_dict(saved.best_state)
294
- if args.eval_cpu:
295
- device = "cpu"
296
- model.to(device)
297
- model.eval()
298
- evaluate(model, args.musdb, eval_folder,
299
- is_wav=args.is_wav,
300
- rank=args.rank,
301
- world_size=args.world_size,
302
- device=device,
303
- save=args.save,
304
- split=args.split_valid,
305
- shifts=args.shifts,
306
- overlap=args.overlap,
307
- workers=args.eval_workers)
308
- model.to("cpu")
309
- if args.rank == 0:
310
- if not (args.test or args.test_pretrained):
311
- save_model(model, quantizer, args, args.models / model_name)
312
- print("done")
313
- done.write_text("done")
314
-
315
-
316
- if __name__ == "__main__":
317
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Blockman Go Skyblock Hack Apk.md DELETED
@@ -1,86 +0,0 @@
1
- <br />
2
- <h1>Blockman Go Skyblock Hack Apk: Cómo obtener dinero ilimitado y más</h1>
3
- <p>¿Te encanta jugar Blockman Go Skyblock, pero te gustaría tener más recursos y opciones para disfrutar del juego? Si es así, usted podría estar interesado en Blockman Go Skyblock Hack Apk, una versión modificada del juego que le da dinero ilimitado, un menú de mod, y no hay anuncios. En este artículo, le diremos lo que es Blockman Go Skyblock, por qué necesita el hack apk, cómo descargar e instalar, y cómo usarlo. ¡Vamos a empezar! </p>
4
- <h2>blockman go skyblock hack apk</h2><br /><p><b><b>DOWNLOAD</b> &#10042; <a href="https://bltlly.com/2v6Jxq">https://bltlly.com/2v6Jxq</a></b></p><br /><br />
5
- <h2>¿Qué es Blockman Go Skyblock? </h2>
6
- <p>Blockman Go Skyblock es un popular juego móvil que permite a los jugadores construir y gestionar sus propias ciudades virtuales. El juego se basa en el modo Skyblock de Minecraft, donde se comienza con una pequeña isla en el cielo y tiene que expandirse utilizando recursos limitados. También puedes interactuar con otros jugadores, unirte a minijuegos, intercambiar objetos y chatear con amigos. </p>
7
- <p>El juego tiene muchas características que lo hacen divertido y adictivo, como:</p>
8
- <ul>
9
- <li>Varios bloques y elementos para crear y usar</li>
10
- <li>Pieles y trajes personalizables para tu personaje</li>
11
- <li>Diferentes modos y mapas para explorar y jugar</li>
12
- <li>Una comunidad amistosa y activa de jugadores</li>
13
- <li>Actualizaciones y eventos regulares</li>
14
- </ul>
15
- <h2>¿Por qué necesita Blockman Go Skyblock Hack Apk? </h2>
16
- <p>Aunque Blockman Go Skyblock es un gran juego, también tiene algunos inconvenientes que pueden limitar su disfrute. Por ejemplo, necesitas gastar dinero real o ver anuncios para obtener más monedas, que se utilizan para comprar bloques, artículos, pieles y otras cosas. También tienes que lidiar con anuncios molestos que aparecen de vez en cuando. Y algunas de las funciones de mod están bloqueadas o restringidas a menos que pagues por ellas. </p>
17
- <p></p>
18
- <p>Por eso es posible que desee probar Blockman Go Skyblock Hack Apk, una versión modificada del juego que le da acceso a dinero ilimitado, un menú de mod, y sin anuncios. Con este hack apk, usted puede:</p>
19
- <h4>Dinero ilimitado</h4>
20
-
21
- <h4>Menú de mods</h4>
22
- <p>Puedes acceder a un menú mod que te permite personalizar y controlar varios aspectos del juego. Por ejemplo, puedes activar o desactivar la gravedad, el modo volar, el modo velocidad, el modo dios, etc. También puedes cambiar el clima, el tiempo, la dificultad, etc. También puedes generar objetos, turbas, animales, etc. El menú mod te da más libertad y diversión en el juego. </p>
23
- <h4>No hay anuncios</h4>
24
- <p>Puedes disfrutar del juego sin interrupciones ni distracciones de los anuncios. No tienes que ver ningún anuncio para obtener más monedas o desbloquear funciones. Puedes jugar el juego sin problemas y en paz. </p>
25
- <h2>Cómo descargar e instalar Blockman Go Skyblock Hack Apk? </h2>
26
- <p>Si usted está interesado en la descarga y la instalación de Blockman Go Skyblock Hack Apk en su dispositivo, Estos son los pasos que debe seguir:</p>
27
- <h4>Requisitos</h4>
28
- <ul>
29
- <li>Un dispositivo Android con al menos 4 GB de RAM y 100 MB de espacio de almacenamiento gratuito</li>
30
- <li>Una conexión a Internet estable</li>
31
- <li>Una aplicación de administrador de archivos</li>
32
- <li>Permitir la instalación de aplicaciones de fuentes desconocidas en la configuración del dispositivo</li>
33
- </ul>
34
- <h4>Enlace de descarga</h4>
35
- <p>Puede descargar el Blockman Go Skyblock Hack Apk archivo desde este enlace: <a href="">Blockman Go Skyblock Hack Apk Download</a>. Este enlace es seguro y seguro, y le dirigirá a un sitio de buena reputación donde se puede obtener la última versión del archivo apk modded. </p>
36
- <h4>Proceso de instalación</h4>
37
- <p>Una vez que haya descargado el archivo apk, siga estos pasos para instalarlo en su dispositivo:</p>
38
- <ol>
39
- <li>Busque el archivo apk en su aplicación de administrador de archivos y toque en él. </li>
40
- <li>Aparecerá una ventana emergente pidiéndole que confirme la instalación. Toque en "Instalar". </li>
41
- <li>Espere a que se complete la instalación. Puede tardar unos segundos o minutos dependiendo del dispositivo. </li>
42
- <li>Una vez realizada la instalación, toque en "Abrir" para iniciar el juego. </li>
43
- <li> Disfrutar de Blockman Go Skyblock Hack Apk! </li>
44
- </ol>
45
- <h2>Cómo utilizar Blockman Go Skyblock Hack Apk? </h2>
46
-
47
- <h4>Opciones de menú Mod</h4>
48
- <p>Para acceder al menú mod, toque en el icono que parece un engranaje en la esquina superior derecha de la pantalla. Aparecerá una lista de opciones, como:</p>
49
- <ul>
50
- <li>gravedad: puede activar o desactivar la gravedad en el juego. Si lo apaga, puede volar libremente. </li>
51
- <li>Modo mosca: Puede activar o desactivar el modo mosca en el juego. Si lo habilita, puede volar pulsando dos veces el botón de salto. </li>
52
- <li>Modo de velocidad: Puedes aumentar o disminuir la velocidad de tu personaje en el juego. Puedes elegir entre normal, rápido o súper rápido. </li>
53
- <li>Modo Dios: Puedes activar o desactivar el modo dios en el juego. Si lo activas, serás invencible e inmune a cualquier daño. </li>
54
- <li>Tiempo: Puedes cambiar el tiempo en el juego. Puedes elegir entre soleado, lluvioso, nevado o tormentoso. </li>
55
- <li>Tiempo: Puedes cambiar la hora en el juego. Puedes elegir entre día, noche, amanecer o atardecer. </li>
56
- <li>Dificultad: Puedes cambiar el nivel de dificultad en el juego. Puedes elegir entre fácil, normal, duro o extremo. </li>
57
- <li>Spawn: Puedes generar cualquier objeto, mafia, animal o NPC en el juego. Puede elegir entre una amplia gama de opciones y personalizar su cantidad y ubicación. </li>
58
- </ul>
59
- <p>También puede cerrar el menú mod tocando el icono de nuevo. </p>
60
- <h4>Consejos y trucos</h4>
61
- <p>Aquí hay algunos consejos y trucos para sacar el máximo provecho de Blockman Go Skyblock Hack Apk:</p>
62
- <ul>
63
- <li>Usa dinero ilimitado para comprar todo lo que quieras en el juego. También puedes usarlo para actualizar tu isla más rápido y fácil. </li>
64
- <li>Utiliza las opciones de menú mod para personalizar y controlar tu experiencia de juego. También puedes usarlas para divertirte más y desafiarte a ti mismo. </li>
65
- <li>No use anuncios para disfrutar del juego sin interrupciones ni distracciones. También puede guardar sus datos y duración de la batería evitando los anuncios. </li>
66
-
67
- <li>Tenga cuidado de no abusar o abusar de las características de mod en el juego. Es posible que otros jugadores lo prohíban o lo denuncien. </li>
68
- </ul>
69
- <h2>Conclusión</h2>
70
- <p>En conclusión, Blockman Go Skyblock Hack Apk es una gran manera de disfrutar de Blockman Go Skyblock con más características y opciones. Puede obtener dinero ilimitado, un menú de mod, y no hay anuncios con esta versión modificada del juego. También puede descargarlo e instalarlo fácilmente en su dispositivo siguiendo nuestra guía. Y puedes usarlo de forma sencilla y segura siguiendo nuestros consejos y trucos. ¿Qué estás esperando? Descargar Blockman Go Skyblock Hack Apk ahora y divertirse! </p>
71
- <h3>Preguntas frecuentes</h3>
72
- <p>Aquí están algunas de las preguntas más comunes que la gente pregunta acerca de Blockman Go Skyblock Hack Apk:</p>
73
- <ol>
74
- <li><b> ¿Es seguro Blockman Go Skyblock Hack Apk? </b></li>
75
- <p>Sí, Blockman Go Skyblock Hack Apk es seguro de usar, siempre y cuando se descarga desde una fuente de confianza y siga las instrucciones de instalación. El archivo apk modded no contiene ningún virus, malware o spyware que puede dañar su dispositivo o datos. Sin embargo, siempre debe tener cuidado al descargar e instalar cualquier archivo apk desde Internet, y escanearlo con una aplicación antivirus antes de abrirlo. </p>
76
- <li><b>Es Blockman Go Skyblock Hack Apk libre? </b></li>
77
- <p>Sí, Blockman Go Skyblock Hack Apk es libre de descargar y usar. No tienes que pagar dinero o ver ningún anuncio para obtener la versión modificada del juego. Usted puede disfrutar de todas las características y beneficios de la apk hack sin gastar un centavo. </p>
78
- <li><b> ¿Funciona Blockman Go Skyblock Hack Apk en dispositivos iOS? </b></li>
79
- <p>No, Blockman Go Skyblock Hack Apk solo funciona en dispositivos Android. No es compatible con dispositivos iOS, como iPhones o iPads. Si quieres jugar a Blockman Go Skyblock en tu dispositivo iOS, tendrás que descargar la versión original del juego desde la App Store.</p>
80
- <li><b>¿Puedo jugar Blockman Go Skyblock Hack Apk offline? </b></li>
81
-
82
- <li><b> ¿Puedo actualizar Blockman Go Skyblock Hack Apk? </b></li>
83
- <p>Sí, puede actualizar Blockman Go Skyblock Hack Apk siempre que haya una nueva versión disponible. Sin embargo, usted tendrá que descargar e instalar el nuevo archivo apk manualmente, como el juego no se actualizará automáticamente. Puedes consultar las actualizaciones visitando el enlace de descarga o siguiendo nuestro blog. </p>
84
- </ol></p> 64aa2da5cf<br />
85
- <br />
86
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Conseguir Sobre l Descarga Gratuita 2023 Apk.md DELETED
@@ -1,65 +0,0 @@
1
-
2
- <h1>Cómo superar la descarga gratuita 2023 APK: Cómo jugar el juego más frustrante en su dispositivo Android</h1>
3
- <p>Si estás buscando un juego que ponga a prueba tu paciencia, habilidad y cordura, no busques más allá de Cómo superarlo con Bennett Foddy. Este juego es conocido por ser uno de los juegos más difíciles y provocadores de ira jamás creados. Y ahora, se puede jugar en su dispositivo Android de forma gratuita con la ayuda de un archivo APK. En este artículo, te contaremos todo lo que necesitas saber sobre Getting Over It, por qué querrías jugarlo en tu dispositivo móvil y cómo descargarlo e instalarlo gratis en 2023. </p>
4
- <h2>¿Qué es superar con Bennett Foddy? </h2>
5
- <p>Getting Over It with Bennett Foddy es un juego que fue lanzado en 2017 por el desarrollador indie Bennett Foddy. El juego es un homenaje a un juego de 2002 llamado Sexy Hiking, que también era conocido por su extrema dificultad y absurdo. </p>
6
- <h2>conseguir sobre él descarga gratuita 2023 apk</h2><br /><p><b><b>Download File</b> > <a href="https://bltlly.com/2v6JpS">https://bltlly.com/2v6JpS</a></b></p><br /><br />
7
- <h3>El juego de Cómo superarlo</h3>
8
- <p>La jugabilidad de Getting Over es simple pero desafiante. Controlas a un hombre llamado Diógenes, que está atrapado en un caldero y sostiene un martillo. Su objetivo es utilizar el martillo para escalar varios obstáculos, como rocas, árboles, tuberías y muebles. El juego no tiene puntos de control, así que si te caes, tienes que empezar de nuevo desde el principio. El juego tampoco tiene fin, así que puedes seguir escalando todo el tiempo que quieras. </p>
9
- <p>El juego está diseñado para ser frustrante e implacable. La física es realista pero impredecible, por lo que nunca se sabe cómo reaccionará el martillo al medio ambiente. Los controles también son difíciles de dominar, ya que tienes que usar el ratón o la pantalla táctil para balancear el martillo en diferentes direcciones. El juego también cuenta con un comentario de voz en off por el propio Bennett Foddy, quien se burlará, alentará o filosofará sobre su progreso (o falta de él). </p>
10
- <h3>La historia y la recepción de Cómo superarlo</h3>
11
-
12
- <p>A partir de junio de 2023, el juego ha vendido más de 5 millones de copias en varias plataformas, incluyendo Windows, Mac, iOS y Android. El juego también ha ganado varios premios, como el Nuovo Award en el Independent Games Festival en 2018 y el Best Design Award en los Game Developers Choice Awards en 2019. </p>
13
- <h2>¿Por qué quieres jugar a Getting Over It en tu dispositivo Android? </h2>
14
- <p>Superar Es un juego que se puede disfrutar (o sufrir) en cualquier plataforma, pero jugar en su dispositivo Android tiene algunas ventajas y desventajas. </p>
15
- <h3>Los beneficios de jugar Cómo superarlo en el móvil</h3>
16
- <ul>
17
- <li> Se puede jugar en cualquier lugar y en cualquier momento. No necesitas un PC o una consola para experimentar la emoción (o agonía) de Cómo superarlo - Puedes desafiarte a ti mismo con un esquema de control diferente. Usar la pantalla táctil para balancear el martillo puede ser más intuitivo o frustrante, dependiendo de tu preferencia. - Puedes ahorrar algo de dinero. El juego cuesta $7.99 en Steam, pero puedes descargarlo gratis en tu dispositivo Android con un archivo APK. </li>
18
- </ul>
19
- <h3>Los desafíos de jugar Cómo superarlo en el móvil</h3>
20
- <ul>
21
- <li>Necesitas un dispositivo compatible. No todos los dispositivos Android pueden ejecutar el juego sin problemas, por lo que debe verificar las especificaciones y la compatibilidad antes de descargar e instalar el juego. - Necesitas suficiente espacio de almacenamiento. El juego ocupa unos 200 MB de espacio en tu dispositivo, por lo que debes asegurarte de tener suficiente espacio para él. - Necesita una conexión a Internet estable. El juego requiere una conexión a Internet para verificar la licencia y acceder a algunas características, como las tablas de clasificación y el chat. - Usted puede encontrar algunos errores o fallos. El juego no es oficialmente compatible con el desarrollador en dispositivos Android, por lo que puede experimentar algunos problemas o errores al jugar el juego. </li>
22
- </ul>
23
- <h2>Cómo descargar e instalar Getting Over It APK gratis en 2023</h2>
24
-
25
- <h3>Los requisitos para descargar e instalar Cómo superar APK</h3>
26
- <p>Antes de proceder, asegúrese de que tiene los siguientes requisitos:</p>
27
- <ul>
28
- <li>Un dispositivo Android que se ejecuta en Android 5.0 o superior y tiene al menos 1 GB de RAM y 200 MB de espacio de almacenamiento libre. - Una conexión a Internet fiable para descargar el archivo APK y acceder a las características del juego. - Una aplicación de administrador de archivos que puede abrir e instalar archivos APK. - La voluntad de asumir el riesgo de descargar e instalar una versión no oficial del juego que puede contener malware o virus. </li>
29
- </ul>
30
- <h3>Los pasos para descargar e instalar Cómo superarlo APK</h3>
31
- <p>Una vez que haya cumplido con los requisitos, siga estos pasos para descargar e instalar Getting Over It APK:</p>
32
- <p></p>
33
- <h4> Paso 1: Encontrar una fuente confiable para Cómo superarlo APK</h4>
34
- <p>El primer paso es encontrar un sitio web de confianza que ofrece Cómo superar APK gratis. Hay muchos sitios web que afirman proporcionar el juego, pero no todos ellos son seguros o legítimos. Algunos de ellos pueden contener archivos falsos o obsoletos, o peor, malware o virus que pueden dañar su dispositivo o robar sus datos. </p>
35
- <p>Para evitar estos riesgos, usted debe hacer una investigación y comprobar las revisiones y calificaciones del sitio web antes de descargar nada de él. También debe buscar signos de credibilidad, como una URL segura (https), una política de privacidad clara y una información de contacto. </p>
36
- <p>Un ejemplo de una fuente confiable para Getting Over It APK es [APKPure], que es un sitio web popular que ofrece varios archivos APK para los usuarios de Android. Puedes visitar su sitio web y buscar Cómo superarlo con Bennett Foddy en su barra de búsqueda. </p>
37
- <h4>Paso 2: Descargar el archivo APK a su dispositivo</h4>
38
- <p>El siguiente paso es descargar el archivo APK a su dispositivo. Una vez que haya encontrado una fuente confiable, haga clic en el botón de descarga y espere a que se descargue el archivo. El tamaño del archivo es de aproximadamente 200 MB, por lo que puede tomar algún tiempo dependiendo de su velocidad de Internet. </p>
39
-
40
- <h4>Paso 3: Habilitar fuentes desconocidas en la configuración del dispositivo</h4>
41
- <p>El tercer paso es habilitar fuentes desconocidas en la configuración del dispositivo. Esto es necesario porque los dispositivos Android normalmente bloquean la instalación de aplicaciones desde fuentes distintas de Google Play Store. Para permitir la instalación de Getting Over It APK, es necesario cambiar esta configuración. </p>
42
- <p>Para hacer esto, vaya a la configuración del dispositivo y busque la opción de seguridad o privacidad. Entonces, encontrar la opción que dice "Fuentes desconocidas" o "Instalar aplicaciones desconocidas" y alternar en. Es posible que vea un mensaje de advertencia que dice "Su teléfono y los datos personales son más vulnerables a los ataques de aplicaciones de fuentes desconocidas. Usted acepta que usted es el único responsable de cualquier daño a su teléfono o pérdida de datos que pueda resultar del uso de estas aplicaciones." Toque en Aceptar o Permitir proceder. </p> <h4>Paso 4: Instalar el archivo APK y lanzar el juego</h4>
43
- <p>El paso final es instalar el archivo APK y lanzar el juego. Para hacer esto, toque en el archivo APK y siga las instrucciones en la pantalla. Usted puede ver un mensaje que dice "¿Desea instalar esta aplicación? No requiere ningún acceso especial." Toque en Instalar y espere a que termine la instalación. </p>
44
- <p>Después de la instalación se ha completado, usted debe ver un mensaje que dice "App instalado". Toca Abrir para iniciar el juego, o ve al cajón de la aplicación y busca el icono Cómo superarlo. También puedes ver un acceso directo en la pantalla de inicio. </p>
45
- <p>Felicitaciones, que ha descargado con éxito e instalado Cómo Sobre Ella APK de forma gratuita en 2023. Ahora, puedes disfrutar (o soportar) el juego más frustrante en tu dispositivo Android. </p>
46
- <h2>Conclusión</h2>
47
-
48
- <p>En este artículo, hemos explicado qué es Getting Over It, por qué querrías reproducirlo en tu dispositivo móvil y cómo descargarlo e instalarlo gratis en 2023. También le hemos proporcionado una fuente confiable para Getting Over It APK, así como los requisitos y pasos para descargarlo e instalarlo. </p>
49
- <p>Esperamos que haya encontrado este artículo útil e informativo. Si tiene alguna pregunta o comentario, no dude en dejar un comentario a continuación. Y si eres lo suficientemente valiente como para intentar superarlo en tu dispositivo Android, te deseamos buena suerte y que te diviertas (o no). </p>
50
- <h2>Preguntas frecuentes</h2>
51
- <p>Aquí hay algunas preguntas frecuentes sobre cómo superar APK:</p>
52
- <ul>
53
- <li><b>Q: ¿Es Getting Over It APK seguro para descargar e instalar? </b>
54
- - A: Cómo superarlo APK es seguro para descargar e instalar si lo obtiene de una fuente confiable, como [APKPure]. Sin embargo, siempre debe tener cuidado al descargar e instalar cualquier archivo APK de fuentes desconocidas, ya que pueden contener malware o virus que pueden dañar su dispositivo o robar sus datos. También debe escanear el archivo con una aplicación antivirus antes de instalarlo. </li>
55
- <li><b>P: ¿Es legal descargar e instalar APK? </b>
56
- - A: Getting Over It APK no es legal para descargar e instalar, ya que es una versión no oficial del juego que viola los derechos del desarrollador y los términos de servicio. Al descargar e instalar Getting Over It APK, usted está arriesgando la acción legal del desarrollador o las autoridades. También estás privando al desarrollador de sus ingresos legítimos de las ventas del juego. Por lo tanto, no recomendamos o avalar la descarga e instalación de Getting Over It APK.</li>
57
- <li><b>Q: ¿Está superando APK compatible con todos los dispositivos Android? </b>
58
-
59
- <li><b>Q: ¿Cómo puedo actualizar Cómo superarlo APK? </b>
60
- - A: Getting Over It APK no tiene una función de actualización automática, por lo que tendrá que actualizar manualmente cada vez que una nueva versión está disponible. Para ello, tendrá que repetir los pasos para descargar e instalar Getting Over It APK desde una fuente confiable. También es posible que tenga que desinstalar la versión anterior del juego antes de instalar el nuevo. </li>
61
- <li><b>Q: ¿Cómo puedo desinstalar Cómo superar APK? </b>
62
- - A: Si desea desinstalar Getting Over It APK de su dispositivo, puede hacerlo siguiendo estos pasos: - Ir a la configuración de su dispositivo y buscar la opción de aplicaciones o aplicaciones. - Encuentra y toca en Cómo superarlo con Bennett Foddy en la lista de aplicaciones. - Toque en Desinstalar y confirmar su elección. - Espere a que la desinstalación termine y luego elimine el archivo APK de su dispositivo. </li>
63
- </ul></p> 64aa2da5cf<br />
64
- <br />
65
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/distlib/resources.py DELETED
@@ -1,358 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- #
3
- # Copyright (C) 2013-2017 Vinay Sajip.
4
- # Licensed to the Python Software Foundation under a contributor agreement.
5
- # See LICENSE.txt and CONTRIBUTORS.txt.
6
- #
7
- from __future__ import unicode_literals
8
-
9
- import bisect
10
- import io
11
- import logging
12
- import os
13
- import pkgutil
14
- import sys
15
- import types
16
- import zipimport
17
-
18
- from . import DistlibException
19
- from .util import cached_property, get_cache_base, Cache
20
-
21
- logger = logging.getLogger(__name__)
22
-
23
-
24
- cache = None # created when needed
25
-
26
-
27
- class ResourceCache(Cache):
28
- def __init__(self, base=None):
29
- if base is None:
30
- # Use native string to avoid issues on 2.x: see Python #20140.
31
- base = os.path.join(get_cache_base(), str('resource-cache'))
32
- super(ResourceCache, self).__init__(base)
33
-
34
- def is_stale(self, resource, path):
35
- """
36
- Is the cache stale for the given resource?
37
-
38
- :param resource: The :class:`Resource` being cached.
39
- :param path: The path of the resource in the cache.
40
- :return: True if the cache is stale.
41
- """
42
- # Cache invalidation is a hard problem :-)
43
- return True
44
-
45
- def get(self, resource):
46
- """
47
- Get a resource into the cache,
48
-
49
- :param resource: A :class:`Resource` instance.
50
- :return: The pathname of the resource in the cache.
51
- """
52
- prefix, path = resource.finder.get_cache_info(resource)
53
- if prefix is None:
54
- result = path
55
- else:
56
- result = os.path.join(self.base, self.prefix_to_dir(prefix), path)
57
- dirname = os.path.dirname(result)
58
- if not os.path.isdir(dirname):
59
- os.makedirs(dirname)
60
- if not os.path.exists(result):
61
- stale = True
62
- else:
63
- stale = self.is_stale(resource, path)
64
- if stale:
65
- # write the bytes of the resource to the cache location
66
- with open(result, 'wb') as f:
67
- f.write(resource.bytes)
68
- return result
69
-
70
-
71
- class ResourceBase(object):
72
- def __init__(self, finder, name):
73
- self.finder = finder
74
- self.name = name
75
-
76
-
77
- class Resource(ResourceBase):
78
- """
79
- A class representing an in-package resource, such as a data file. This is
80
- not normally instantiated by user code, but rather by a
81
- :class:`ResourceFinder` which manages the resource.
82
- """
83
- is_container = False # Backwards compatibility
84
-
85
- def as_stream(self):
86
- """
87
- Get the resource as a stream.
88
-
89
- This is not a property to make it obvious that it returns a new stream
90
- each time.
91
- """
92
- return self.finder.get_stream(self)
93
-
94
- @cached_property
95
- def file_path(self):
96
- global cache
97
- if cache is None:
98
- cache = ResourceCache()
99
- return cache.get(self)
100
-
101
- @cached_property
102
- def bytes(self):
103
- return self.finder.get_bytes(self)
104
-
105
- @cached_property
106
- def size(self):
107
- return self.finder.get_size(self)
108
-
109
-
110
- class ResourceContainer(ResourceBase):
111
- is_container = True # Backwards compatibility
112
-
113
- @cached_property
114
- def resources(self):
115
- return self.finder.get_resources(self)
116
-
117
-
118
- class ResourceFinder(object):
119
- """
120
- Resource finder for file system resources.
121
- """
122
-
123
- if sys.platform.startswith('java'):
124
- skipped_extensions = ('.pyc', '.pyo', '.class')
125
- else:
126
- skipped_extensions = ('.pyc', '.pyo')
127
-
128
- def __init__(self, module):
129
- self.module = module
130
- self.loader = getattr(module, '__loader__', None)
131
- self.base = os.path.dirname(getattr(module, '__file__', ''))
132
-
133
- def _adjust_path(self, path):
134
- return os.path.realpath(path)
135
-
136
- def _make_path(self, resource_name):
137
- # Issue #50: need to preserve type of path on Python 2.x
138
- # like os.path._get_sep
139
- if isinstance(resource_name, bytes): # should only happen on 2.x
140
- sep = b'/'
141
- else:
142
- sep = '/'
143
- parts = resource_name.split(sep)
144
- parts.insert(0, self.base)
145
- result = os.path.join(*parts)
146
- return self._adjust_path(result)
147
-
148
- def _find(self, path):
149
- return os.path.exists(path)
150
-
151
- def get_cache_info(self, resource):
152
- return None, resource.path
153
-
154
- def find(self, resource_name):
155
- path = self._make_path(resource_name)
156
- if not self._find(path):
157
- result = None
158
- else:
159
- if self._is_directory(path):
160
- result = ResourceContainer(self, resource_name)
161
- else:
162
- result = Resource(self, resource_name)
163
- result.path = path
164
- return result
165
-
166
- def get_stream(self, resource):
167
- return open(resource.path, 'rb')
168
-
169
- def get_bytes(self, resource):
170
- with open(resource.path, 'rb') as f:
171
- return f.read()
172
-
173
- def get_size(self, resource):
174
- return os.path.getsize(resource.path)
175
-
176
- def get_resources(self, resource):
177
- def allowed(f):
178
- return (f != '__pycache__' and not
179
- f.endswith(self.skipped_extensions))
180
- return set([f for f in os.listdir(resource.path) if allowed(f)])
181
-
182
- def is_container(self, resource):
183
- return self._is_directory(resource.path)
184
-
185
- _is_directory = staticmethod(os.path.isdir)
186
-
187
- def iterator(self, resource_name):
188
- resource = self.find(resource_name)
189
- if resource is not None:
190
- todo = [resource]
191
- while todo:
192
- resource = todo.pop(0)
193
- yield resource
194
- if resource.is_container:
195
- rname = resource.name
196
- for name in resource.resources:
197
- if not rname:
198
- new_name = name
199
- else:
200
- new_name = '/'.join([rname, name])
201
- child = self.find(new_name)
202
- if child.is_container:
203
- todo.append(child)
204
- else:
205
- yield child
206
-
207
-
208
- class ZipResourceFinder(ResourceFinder):
209
- """
210
- Resource finder for resources in .zip files.
211
- """
212
- def __init__(self, module):
213
- super(ZipResourceFinder, self).__init__(module)
214
- archive = self.loader.archive
215
- self.prefix_len = 1 + len(archive)
216
- # PyPy doesn't have a _files attr on zipimporter, and you can't set one
217
- if hasattr(self.loader, '_files'):
218
- self._files = self.loader._files
219
- else:
220
- self._files = zipimport._zip_directory_cache[archive]
221
- self.index = sorted(self._files)
222
-
223
- def _adjust_path(self, path):
224
- return path
225
-
226
- def _find(self, path):
227
- path = path[self.prefix_len:]
228
- if path in self._files:
229
- result = True
230
- else:
231
- if path and path[-1] != os.sep:
232
- path = path + os.sep
233
- i = bisect.bisect(self.index, path)
234
- try:
235
- result = self.index[i].startswith(path)
236
- except IndexError:
237
- result = False
238
- if not result:
239
- logger.debug('_find failed: %r %r', path, self.loader.prefix)
240
- else:
241
- logger.debug('_find worked: %r %r', path, self.loader.prefix)
242
- return result
243
-
244
- def get_cache_info(self, resource):
245
- prefix = self.loader.archive
246
- path = resource.path[1 + len(prefix):]
247
- return prefix, path
248
-
249
- def get_bytes(self, resource):
250
- return self.loader.get_data(resource.path)
251
-
252
- def get_stream(self, resource):
253
- return io.BytesIO(self.get_bytes(resource))
254
-
255
- def get_size(self, resource):
256
- path = resource.path[self.prefix_len:]
257
- return self._files[path][3]
258
-
259
- def get_resources(self, resource):
260
- path = resource.path[self.prefix_len:]
261
- if path and path[-1] != os.sep:
262
- path += os.sep
263
- plen = len(path)
264
- result = set()
265
- i = bisect.bisect(self.index, path)
266
- while i < len(self.index):
267
- if not self.index[i].startswith(path):
268
- break
269
- s = self.index[i][plen:]
270
- result.add(s.split(os.sep, 1)[0]) # only immediate children
271
- i += 1
272
- return result
273
-
274
- def _is_directory(self, path):
275
- path = path[self.prefix_len:]
276
- if path and path[-1] != os.sep:
277
- path += os.sep
278
- i = bisect.bisect(self.index, path)
279
- try:
280
- result = self.index[i].startswith(path)
281
- except IndexError:
282
- result = False
283
- return result
284
-
285
-
286
- _finder_registry = {
287
- type(None): ResourceFinder,
288
- zipimport.zipimporter: ZipResourceFinder
289
- }
290
-
291
- try:
292
- # In Python 3.6, _frozen_importlib -> _frozen_importlib_external
293
- try:
294
- import _frozen_importlib_external as _fi
295
- except ImportError:
296
- import _frozen_importlib as _fi
297
- _finder_registry[_fi.SourceFileLoader] = ResourceFinder
298
- _finder_registry[_fi.FileFinder] = ResourceFinder
299
- # See issue #146
300
- _finder_registry[_fi.SourcelessFileLoader] = ResourceFinder
301
- del _fi
302
- except (ImportError, AttributeError):
303
- pass
304
-
305
-
306
- def register_finder(loader, finder_maker):
307
- _finder_registry[type(loader)] = finder_maker
308
-
309
-
310
- _finder_cache = {}
311
-
312
-
313
- def finder(package):
314
- """
315
- Return a resource finder for a package.
316
- :param package: The name of the package.
317
- :return: A :class:`ResourceFinder` instance for the package.
318
- """
319
- if package in _finder_cache:
320
- result = _finder_cache[package]
321
- else:
322
- if package not in sys.modules:
323
- __import__(package)
324
- module = sys.modules[package]
325
- path = getattr(module, '__path__', None)
326
- if path is None:
327
- raise DistlibException('You cannot get a finder for a module, '
328
- 'only for a package')
329
- loader = getattr(module, '__loader__', None)
330
- finder_maker = _finder_registry.get(type(loader))
331
- if finder_maker is None:
332
- raise DistlibException('Unable to locate finder for %r' % package)
333
- result = finder_maker(module)
334
- _finder_cache[package] = result
335
- return result
336
-
337
-
338
- _dummy_module = types.ModuleType(str('__dummy__'))
339
-
340
-
341
- def finder_for_path(path):
342
- """
343
- Return a resource finder for a path, which should represent a container.
344
-
345
- :param path: The path.
346
- :return: A :class:`ResourceFinder` instance for the path.
347
- """
348
- result = None
349
- # calls any path hooks, gets importer into cache
350
- pkgutil.get_importer(path)
351
- loader = sys.path_importer_cache.get(path)
352
- finder = _finder_registry.get(type(loader))
353
- if finder:
354
- module = _dummy_module
355
- module.__file__ = os.path.join(path, '')
356
- module.__loader__ = loader
357
- result = finder(module)
358
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/rich/segment.py DELETED
@@ -1,739 +0,0 @@
1
- from enum import IntEnum
2
- from functools import lru_cache
3
- from itertools import filterfalse
4
- from logging import getLogger
5
- from operator import attrgetter
6
- from typing import (
7
- TYPE_CHECKING,
8
- Dict,
9
- Iterable,
10
- List,
11
- NamedTuple,
12
- Optional,
13
- Sequence,
14
- Tuple,
15
- Type,
16
- Union,
17
- )
18
-
19
- from .cells import (
20
- _is_single_cell_widths,
21
- cached_cell_len,
22
- cell_len,
23
- get_character_cell_size,
24
- set_cell_size,
25
- )
26
- from .repr import Result, rich_repr
27
- from .style import Style
28
-
29
- if TYPE_CHECKING:
30
- from .console import Console, ConsoleOptions, RenderResult
31
-
32
- log = getLogger("rich")
33
-
34
-
35
- class ControlType(IntEnum):
36
- """Non-printable control codes which typically translate to ANSI codes."""
37
-
38
- BELL = 1
39
- CARRIAGE_RETURN = 2
40
- HOME = 3
41
- CLEAR = 4
42
- SHOW_CURSOR = 5
43
- HIDE_CURSOR = 6
44
- ENABLE_ALT_SCREEN = 7
45
- DISABLE_ALT_SCREEN = 8
46
- CURSOR_UP = 9
47
- CURSOR_DOWN = 10
48
- CURSOR_FORWARD = 11
49
- CURSOR_BACKWARD = 12
50
- CURSOR_MOVE_TO_COLUMN = 13
51
- CURSOR_MOVE_TO = 14
52
- ERASE_IN_LINE = 15
53
- SET_WINDOW_TITLE = 16
54
-
55
-
56
- ControlCode = Union[
57
- Tuple[ControlType],
58
- Tuple[ControlType, Union[int, str]],
59
- Tuple[ControlType, int, int],
60
- ]
61
-
62
-
63
- @rich_repr()
64
- class Segment(NamedTuple):
65
- """A piece of text with associated style. Segments are produced by the Console render process and
66
- are ultimately converted in to strings to be written to the terminal.
67
-
68
- Args:
69
- text (str): A piece of text.
70
- style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.
71
- control (Tuple[ControlCode], optional): Optional sequence of control codes.
72
-
73
- Attributes:
74
- cell_length (int): The cell length of this Segment.
75
- """
76
-
77
- text: str
78
- style: Optional[Style] = None
79
- control: Optional[Sequence[ControlCode]] = None
80
-
81
- @property
82
- def cell_length(self) -> int:
83
- """The number of terminal cells required to display self.text.
84
-
85
- Returns:
86
- int: A number of cells.
87
- """
88
- text, _style, control = self
89
- return 0 if control else cell_len(text)
90
-
91
- def __rich_repr__(self) -> Result:
92
- yield self.text
93
- if self.control is None:
94
- if self.style is not None:
95
- yield self.style
96
- else:
97
- yield self.style
98
- yield self.control
99
-
100
- def __bool__(self) -> bool:
101
- """Check if the segment contains text."""
102
- return bool(self.text)
103
-
104
- @property
105
- def is_control(self) -> bool:
106
- """Check if the segment contains control codes."""
107
- return self.control is not None
108
-
109
- @classmethod
110
- @lru_cache(1024 * 16)
111
- def _split_cells(cls, segment: "Segment", cut: int) -> Tuple["Segment", "Segment"]:
112
-
113
- text, style, control = segment
114
- _Segment = Segment
115
-
116
- cell_length = segment.cell_length
117
- if cut >= cell_length:
118
- return segment, _Segment("", style, control)
119
-
120
- cell_size = get_character_cell_size
121
-
122
- pos = int((cut / cell_length) * (len(text) - 1))
123
-
124
- before = text[:pos]
125
- cell_pos = cell_len(before)
126
- if cell_pos == cut:
127
- return (
128
- _Segment(before, style, control),
129
- _Segment(text[pos:], style, control),
130
- )
131
- while pos < len(text):
132
- char = text[pos]
133
- pos += 1
134
- cell_pos += cell_size(char)
135
- before = text[:pos]
136
- if cell_pos == cut:
137
- return (
138
- _Segment(before, style, control),
139
- _Segment(text[pos:], style, control),
140
- )
141
- if cell_pos > cut:
142
- return (
143
- _Segment(before[: pos - 1] + " ", style, control),
144
- _Segment(" " + text[pos:], style, control),
145
- )
146
-
147
- raise AssertionError("Will never reach here")
148
-
149
- def split_cells(self, cut: int) -> Tuple["Segment", "Segment"]:
150
- """Split segment in to two segments at the specified column.
151
-
152
- If the cut point falls in the middle of a 2-cell wide character then it is replaced
153
- by two spaces, to preserve the display width of the parent segment.
154
-
155
- Returns:
156
- Tuple[Segment, Segment]: Two segments.
157
- """
158
- text, style, control = self
159
-
160
- if _is_single_cell_widths(text):
161
- # Fast path with all 1 cell characters
162
- if cut >= len(text):
163
- return self, Segment("", style, control)
164
- return (
165
- Segment(text[:cut], style, control),
166
- Segment(text[cut:], style, control),
167
- )
168
-
169
- return self._split_cells(self, cut)
170
-
171
- @classmethod
172
- def line(cls) -> "Segment":
173
- """Make a new line segment."""
174
- return cls("\n")
175
-
176
- @classmethod
177
- def apply_style(
178
- cls,
179
- segments: Iterable["Segment"],
180
- style: Optional[Style] = None,
181
- post_style: Optional[Style] = None,
182
- ) -> Iterable["Segment"]:
183
- """Apply style(s) to an iterable of segments.
184
-
185
- Returns an iterable of segments where the style is replaced by ``style + segment.style + post_style``.
186
-
187
- Args:
188
- segments (Iterable[Segment]): Segments to process.
189
- style (Style, optional): Base style. Defaults to None.
190
- post_style (Style, optional): Style to apply on top of segment style. Defaults to None.
191
-
192
- Returns:
193
- Iterable[Segments]: A new iterable of segments (possibly the same iterable).
194
- """
195
- result_segments = segments
196
- if style:
197
- apply = style.__add__
198
- result_segments = (
199
- cls(text, None if control else apply(_style), control)
200
- for text, _style, control in result_segments
201
- )
202
- if post_style:
203
- result_segments = (
204
- cls(
205
- text,
206
- (
207
- None
208
- if control
209
- else (_style + post_style if _style else post_style)
210
- ),
211
- control,
212
- )
213
- for text, _style, control in result_segments
214
- )
215
- return result_segments
216
-
217
- @classmethod
218
- def filter_control(
219
- cls, segments: Iterable["Segment"], is_control: bool = False
220
- ) -> Iterable["Segment"]:
221
- """Filter segments by ``is_control`` attribute.
222
-
223
- Args:
224
- segments (Iterable[Segment]): An iterable of Segment instances.
225
- is_control (bool, optional): is_control flag to match in search.
226
-
227
- Returns:
228
- Iterable[Segment]: And iterable of Segment instances.
229
-
230
- """
231
- if is_control:
232
- return filter(attrgetter("control"), segments)
233
- else:
234
- return filterfalse(attrgetter("control"), segments)
235
-
236
- @classmethod
237
- def split_lines(cls, segments: Iterable["Segment"]) -> Iterable[List["Segment"]]:
238
- """Split a sequence of segments in to a list of lines.
239
-
240
- Args:
241
- segments (Iterable[Segment]): Segments potentially containing line feeds.
242
-
243
- Yields:
244
- Iterable[List[Segment]]: Iterable of segment lists, one per line.
245
- """
246
- line: List[Segment] = []
247
- append = line.append
248
-
249
- for segment in segments:
250
- if "\n" in segment.text and not segment.control:
251
- text, style, _ = segment
252
- while text:
253
- _text, new_line, text = text.partition("\n")
254
- if _text:
255
- append(cls(_text, style))
256
- if new_line:
257
- yield line
258
- line = []
259
- append = line.append
260
- else:
261
- append(segment)
262
- if line:
263
- yield line
264
-
265
- @classmethod
266
- def split_and_crop_lines(
267
- cls,
268
- segments: Iterable["Segment"],
269
- length: int,
270
- style: Optional[Style] = None,
271
- pad: bool = True,
272
- include_new_lines: bool = True,
273
- ) -> Iterable[List["Segment"]]:
274
- """Split segments in to lines, and crop lines greater than a given length.
275
-
276
- Args:
277
- segments (Iterable[Segment]): An iterable of segments, probably
278
- generated from console.render.
279
- length (int): Desired line length.
280
- style (Style, optional): Style to use for any padding.
281
- pad (bool): Enable padding of lines that are less than `length`.
282
-
283
- Returns:
284
- Iterable[List[Segment]]: An iterable of lines of segments.
285
- """
286
- line: List[Segment] = []
287
- append = line.append
288
-
289
- adjust_line_length = cls.adjust_line_length
290
- new_line_segment = cls("\n")
291
-
292
- for segment in segments:
293
- if "\n" in segment.text and not segment.control:
294
- text, segment_style, _ = segment
295
- while text:
296
- _text, new_line, text = text.partition("\n")
297
- if _text:
298
- append(cls(_text, segment_style))
299
- if new_line:
300
- cropped_line = adjust_line_length(
301
- line, length, style=style, pad=pad
302
- )
303
- if include_new_lines:
304
- cropped_line.append(new_line_segment)
305
- yield cropped_line
306
- line.clear()
307
- else:
308
- append(segment)
309
- if line:
310
- yield adjust_line_length(line, length, style=style, pad=pad)
311
-
312
- @classmethod
313
- def adjust_line_length(
314
- cls,
315
- line: List["Segment"],
316
- length: int,
317
- style: Optional[Style] = None,
318
- pad: bool = True,
319
- ) -> List["Segment"]:
320
- """Adjust a line to a given width (cropping or padding as required).
321
-
322
- Args:
323
- segments (Iterable[Segment]): A list of segments in a single line.
324
- length (int): The desired width of the line.
325
- style (Style, optional): The style of padding if used (space on the end). Defaults to None.
326
- pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.
327
-
328
- Returns:
329
- List[Segment]: A line of segments with the desired length.
330
- """
331
- line_length = sum(segment.cell_length for segment in line)
332
- new_line: List[Segment]
333
-
334
- if line_length < length:
335
- if pad:
336
- new_line = line + [cls(" " * (length - line_length), style)]
337
- else:
338
- new_line = line[:]
339
- elif line_length > length:
340
- new_line = []
341
- append = new_line.append
342
- line_length = 0
343
- for segment in line:
344
- segment_length = segment.cell_length
345
- if line_length + segment_length < length or segment.control:
346
- append(segment)
347
- line_length += segment_length
348
- else:
349
- text, segment_style, _ = segment
350
- text = set_cell_size(text, length - line_length)
351
- append(cls(text, segment_style))
352
- break
353
- else:
354
- new_line = line[:]
355
- return new_line
356
-
357
- @classmethod
358
- def get_line_length(cls, line: List["Segment"]) -> int:
359
- """Get the length of list of segments.
360
-
361
- Args:
362
- line (List[Segment]): A line encoded as a list of Segments (assumes no '\\\\n' characters),
363
-
364
- Returns:
365
- int: The length of the line.
366
- """
367
- _cell_len = cell_len
368
- return sum(_cell_len(text) for text, style, control in line if not control)
369
-
370
- @classmethod
371
- def get_shape(cls, lines: List[List["Segment"]]) -> Tuple[int, int]:
372
- """Get the shape (enclosing rectangle) of a list of lines.
373
-
374
- Args:
375
- lines (List[List[Segment]]): A list of lines (no '\\\\n' characters).
376
-
377
- Returns:
378
- Tuple[int, int]: Width and height in characters.
379
- """
380
- get_line_length = cls.get_line_length
381
- max_width = max(get_line_length(line) for line in lines) if lines else 0
382
- return (max_width, len(lines))
383
-
384
- @classmethod
385
- def set_shape(
386
- cls,
387
- lines: List[List["Segment"]],
388
- width: int,
389
- height: Optional[int] = None,
390
- style: Optional[Style] = None,
391
- new_lines: bool = False,
392
- ) -> List[List["Segment"]]:
393
- """Set the shape of a list of lines (enclosing rectangle).
394
-
395
- Args:
396
- lines (List[List[Segment]]): A list of lines.
397
- width (int): Desired width.
398
- height (int, optional): Desired height or None for no change.
399
- style (Style, optional): Style of any padding added.
400
- new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
401
-
402
- Returns:
403
- List[List[Segment]]: New list of lines.
404
- """
405
- _height = height or len(lines)
406
-
407
- blank = (
408
- [cls(" " * width + "\n", style)] if new_lines else [cls(" " * width, style)]
409
- )
410
-
411
- adjust_line_length = cls.adjust_line_length
412
- shaped_lines = lines[:_height]
413
- shaped_lines[:] = [
414
- adjust_line_length(line, width, style=style) for line in lines
415
- ]
416
- if len(shaped_lines) < _height:
417
- shaped_lines.extend([blank] * (_height - len(shaped_lines)))
418
- return shaped_lines
419
-
420
- @classmethod
421
- def align_top(
422
- cls: Type["Segment"],
423
- lines: List[List["Segment"]],
424
- width: int,
425
- height: int,
426
- style: Style,
427
- new_lines: bool = False,
428
- ) -> List[List["Segment"]]:
429
- """Aligns lines to top (adds extra lines to bottom as required).
430
-
431
- Args:
432
- lines (List[List[Segment]]): A list of lines.
433
- width (int): Desired width.
434
- height (int, optional): Desired height or None for no change.
435
- style (Style): Style of any padding added.
436
- new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
437
-
438
- Returns:
439
- List[List[Segment]]: New list of lines.
440
- """
441
- extra_lines = height - len(lines)
442
- if not extra_lines:
443
- return lines[:]
444
- lines = lines[:height]
445
- blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
446
- lines = lines + [[blank]] * extra_lines
447
- return lines
448
-
449
- @classmethod
450
- def align_bottom(
451
- cls: Type["Segment"],
452
- lines: List[List["Segment"]],
453
- width: int,
454
- height: int,
455
- style: Style,
456
- new_lines: bool = False,
457
- ) -> List[List["Segment"]]:
458
- """Aligns render to bottom (adds extra lines above as required).
459
-
460
- Args:
461
- lines (List[List[Segment]]): A list of lines.
462
- width (int): Desired width.
463
- height (int, optional): Desired height or None for no change.
464
- style (Style): Style of any padding added. Defaults to None.
465
- new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
466
-
467
- Returns:
468
- List[List[Segment]]: New list of lines.
469
- """
470
- extra_lines = height - len(lines)
471
- if not extra_lines:
472
- return lines[:]
473
- lines = lines[:height]
474
- blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
475
- lines = [[blank]] * extra_lines + lines
476
- return lines
477
-
478
- @classmethod
479
- def align_middle(
480
- cls: Type["Segment"],
481
- lines: List[List["Segment"]],
482
- width: int,
483
- height: int,
484
- style: Style,
485
- new_lines: bool = False,
486
- ) -> List[List["Segment"]]:
487
- """Aligns lines to middle (adds extra lines to above and below as required).
488
-
489
- Args:
490
- lines (List[List[Segment]]): A list of lines.
491
- width (int): Desired width.
492
- height (int, optional): Desired height or None for no change.
493
- style (Style): Style of any padding added.
494
- new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
495
-
496
- Returns:
497
- List[List[Segment]]: New list of lines.
498
- """
499
- extra_lines = height - len(lines)
500
- if not extra_lines:
501
- return lines[:]
502
- lines = lines[:height]
503
- blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
504
- top_lines = extra_lines // 2
505
- bottom_lines = extra_lines - top_lines
506
- lines = [[blank]] * top_lines + lines + [[blank]] * bottom_lines
507
- return lines
508
-
509
- @classmethod
510
- def simplify(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
511
- """Simplify an iterable of segments by combining contiguous segments with the same style.
512
-
513
- Args:
514
- segments (Iterable[Segment]): An iterable of segments.
515
-
516
- Returns:
517
- Iterable[Segment]: A possibly smaller iterable of segments that will render the same way.
518
- """
519
- iter_segments = iter(segments)
520
- try:
521
- last_segment = next(iter_segments)
522
- except StopIteration:
523
- return
524
-
525
- _Segment = Segment
526
- for segment in iter_segments:
527
- if last_segment.style == segment.style and not segment.control:
528
- last_segment = _Segment(
529
- last_segment.text + segment.text, last_segment.style
530
- )
531
- else:
532
- yield last_segment
533
- last_segment = segment
534
- yield last_segment
535
-
536
- @classmethod
537
- def strip_links(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
538
- """Remove all links from an iterable of styles.
539
-
540
- Args:
541
- segments (Iterable[Segment]): An iterable segments.
542
-
543
- Yields:
544
- Segment: Segments with link removed.
545
- """
546
- for segment in segments:
547
- if segment.control or segment.style is None:
548
- yield segment
549
- else:
550
- text, style, _control = segment
551
- yield cls(text, style.update_link(None) if style else None)
552
-
553
- @classmethod
554
- def strip_styles(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
555
- """Remove all styles from an iterable of segments.
556
-
557
- Args:
558
- segments (Iterable[Segment]): An iterable segments.
559
-
560
- Yields:
561
- Segment: Segments with styles replace with None
562
- """
563
- for text, _style, control in segments:
564
- yield cls(text, None, control)
565
-
566
- @classmethod
567
- def remove_color(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
568
- """Remove all color from an iterable of segments.
569
-
570
- Args:
571
- segments (Iterable[Segment]): An iterable segments.
572
-
573
- Yields:
574
- Segment: Segments with colorless style.
575
- """
576
-
577
- cache: Dict[Style, Style] = {}
578
- for text, style, control in segments:
579
- if style:
580
- colorless_style = cache.get(style)
581
- if colorless_style is None:
582
- colorless_style = style.without_color
583
- cache[style] = colorless_style
584
- yield cls(text, colorless_style, control)
585
- else:
586
- yield cls(text, None, control)
587
-
588
- @classmethod
589
- def divide(
590
- cls, segments: Iterable["Segment"], cuts: Iterable[int]
591
- ) -> Iterable[List["Segment"]]:
592
- """Divides an iterable of segments in to portions.
593
-
594
- Args:
595
- cuts (Iterable[int]): Cell positions where to divide.
596
-
597
- Yields:
598
- [Iterable[List[Segment]]]: An iterable of Segments in List.
599
- """
600
- split_segments: List["Segment"] = []
601
- add_segment = split_segments.append
602
-
603
- iter_cuts = iter(cuts)
604
-
605
- while True:
606
- cut = next(iter_cuts, -1)
607
- if cut == -1:
608
- return []
609
- if cut != 0:
610
- break
611
- yield []
612
- pos = 0
613
-
614
- segments_clear = split_segments.clear
615
- segments_copy = split_segments.copy
616
-
617
- _cell_len = cached_cell_len
618
- for segment in segments:
619
- text, _style, control = segment
620
- while text:
621
- end_pos = pos if control else pos + _cell_len(text)
622
- if end_pos < cut:
623
- add_segment(segment)
624
- pos = end_pos
625
- break
626
-
627
- if end_pos == cut:
628
- add_segment(segment)
629
- yield segments_copy()
630
- segments_clear()
631
- pos = end_pos
632
-
633
- cut = next(iter_cuts, -1)
634
- if cut == -1:
635
- if split_segments:
636
- yield segments_copy()
637
- return
638
-
639
- break
640
-
641
- else:
642
- before, segment = segment.split_cells(cut - pos)
643
- text, _style, control = segment
644
- add_segment(before)
645
- yield segments_copy()
646
- segments_clear()
647
- pos = cut
648
-
649
- cut = next(iter_cuts, -1)
650
- if cut == -1:
651
- if split_segments:
652
- yield segments_copy()
653
- return
654
-
655
- yield segments_copy()
656
-
657
-
658
- class Segments:
659
- """A simple renderable to render an iterable of segments. This class may be useful if
660
- you want to print segments outside of a __rich_console__ method.
661
-
662
- Args:
663
- segments (Iterable[Segment]): An iterable of segments.
664
- new_lines (bool, optional): Add new lines between segments. Defaults to False.
665
- """
666
-
667
- def __init__(self, segments: Iterable[Segment], new_lines: bool = False) -> None:
668
- self.segments = list(segments)
669
- self.new_lines = new_lines
670
-
671
- def __rich_console__(
672
- self, console: "Console", options: "ConsoleOptions"
673
- ) -> "RenderResult":
674
- if self.new_lines:
675
- line = Segment.line()
676
- for segment in self.segments:
677
- yield segment
678
- yield line
679
- else:
680
- yield from self.segments
681
-
682
-
683
- class SegmentLines:
684
- def __init__(self, lines: Iterable[List[Segment]], new_lines: bool = False) -> None:
685
- """A simple renderable containing a number of lines of segments. May be used as an intermediate
686
- in rendering process.
687
-
688
- Args:
689
- lines (Iterable[List[Segment]]): Lists of segments forming lines.
690
- new_lines (bool, optional): Insert new lines after each line. Defaults to False.
691
- """
692
- self.lines = list(lines)
693
- self.new_lines = new_lines
694
-
695
- def __rich_console__(
696
- self, console: "Console", options: "ConsoleOptions"
697
- ) -> "RenderResult":
698
- if self.new_lines:
699
- new_line = Segment.line()
700
- for line in self.lines:
701
- yield from line
702
- yield new_line
703
- else:
704
- for line in self.lines:
705
- yield from line
706
-
707
-
708
- if __name__ == "__main__": # pragma: no cover
709
- from pip._vendor.rich.console import Console
710
- from pip._vendor.rich.syntax import Syntax
711
- from pip._vendor.rich.text import Text
712
-
713
- code = """from rich.console import Console
714
- console = Console()
715
- text = Text.from_markup("Hello, [bold magenta]World[/]!")
716
- console.print(text)"""
717
-
718
- text = Text.from_markup("Hello, [bold magenta]World[/]!")
719
-
720
- console = Console()
721
-
722
- console.rule("rich.Segment")
723
- console.print(
724
- "A Segment is the last step in the Rich render process before generating text with ANSI codes."
725
- )
726
- console.print("\nConsider the following code:\n")
727
- console.print(Syntax(code, "python", line_numbers=True))
728
- console.print()
729
- console.print(
730
- "When you call [b]print()[/b], Rich [i]renders[/i] the object in to the following:\n"
731
- )
732
- fragments = list(console.render(text))
733
- console.print(fragments)
734
- console.print()
735
- console.print("The Segments are then processed to produce the following output:\n")
736
- console.print(text)
737
- console.print(
738
- "\nYou will only need to know this if you are implementing your own Rich renderables."
739
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/text_file.py DELETED
@@ -1,287 +0,0 @@
1
- """text_file
2
-
3
- provides the TextFile class, which gives an interface to text files
4
- that (optionally) takes care of stripping comments, ignoring blank
5
- lines, and joining lines with backslashes."""
6
-
7
- import sys
8
-
9
-
10
- class TextFile:
11
- """Provides a file-like object that takes care of all the things you
12
- commonly want to do when processing a text file that has some
13
- line-by-line syntax: strip comments (as long as "#" is your
14
- comment character), skip blank lines, join adjacent lines by
15
- escaping the newline (ie. backslash at end of line), strip
16
- leading and/or trailing whitespace. All of these are optional
17
- and independently controllable.
18
-
19
- Provides a 'warn()' method so you can generate warning messages that
20
- report physical line number, even if the logical line in question
21
- spans multiple physical lines. Also provides 'unreadline()' for
22
- implementing line-at-a-time lookahead.
23
-
24
- Constructor is called as:
25
-
26
- TextFile (filename=None, file=None, **options)
27
-
28
- It bombs (RuntimeError) if both 'filename' and 'file' are None;
29
- 'filename' should be a string, and 'file' a file object (or
30
- something that provides 'readline()' and 'close()' methods). It is
31
- recommended that you supply at least 'filename', so that TextFile
32
- can include it in warning messages. If 'file' is not supplied,
33
- TextFile creates its own using 'io.open()'.
34
-
35
- The options are all boolean, and affect the value returned by
36
- 'readline()':
37
- strip_comments [default: true]
38
- strip from "#" to end-of-line, as well as any whitespace
39
- leading up to the "#" -- unless it is escaped by a backslash
40
- lstrip_ws [default: false]
41
- strip leading whitespace from each line before returning it
42
- rstrip_ws [default: true]
43
- strip trailing whitespace (including line terminator!) from
44
- each line before returning it
45
- skip_blanks [default: true}
46
- skip lines that are empty *after* stripping comments and
47
- whitespace. (If both lstrip_ws and rstrip_ws are false,
48
- then some lines may consist of solely whitespace: these will
49
- *not* be skipped, even if 'skip_blanks' is true.)
50
- join_lines [default: false]
51
- if a backslash is the last non-newline character on a line
52
- after stripping comments and whitespace, join the following line
53
- to it to form one "logical line"; if N consecutive lines end
54
- with a backslash, then N+1 physical lines will be joined to
55
- form one logical line.
56
- collapse_join [default: false]
57
- strip leading whitespace from lines that are joined to their
58
- predecessor; only matters if (join_lines and not lstrip_ws)
59
- errors [default: 'strict']
60
- error handler used to decode the file content
61
-
62
- Note that since 'rstrip_ws' can strip the trailing newline, the
63
- semantics of 'readline()' must differ from those of the builtin file
64
- object's 'readline()' method! In particular, 'readline()' returns
65
- None for end-of-file: an empty string might just be a blank line (or
66
- an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is
67
- not."""
68
-
69
- default_options = {
70
- 'strip_comments': 1,
71
- 'skip_blanks': 1,
72
- 'lstrip_ws': 0,
73
- 'rstrip_ws': 1,
74
- 'join_lines': 0,
75
- 'collapse_join': 0,
76
- 'errors': 'strict',
77
- }
78
-
79
- def __init__(self, filename=None, file=None, **options):
80
- """Construct a new TextFile object. At least one of 'filename'
81
- (a string) and 'file' (a file-like object) must be supplied.
82
- They keyword argument options are described above and affect
83
- the values returned by 'readline()'."""
84
- if filename is None and file is None:
85
- raise RuntimeError(
86
- "you must supply either or both of 'filename' and 'file'"
87
- )
88
-
89
- # set values for all options -- either from client option hash
90
- # or fallback to default_options
91
- for opt in self.default_options.keys():
92
- if opt in options:
93
- setattr(self, opt, options[opt])
94
- else:
95
- setattr(self, opt, self.default_options[opt])
96
-
97
- # sanity check client option hash
98
- for opt in options.keys():
99
- if opt not in self.default_options:
100
- raise KeyError("invalid TextFile option '%s'" % opt)
101
-
102
- if file is None:
103
- self.open(filename)
104
- else:
105
- self.filename = filename
106
- self.file = file
107
- self.current_line = 0 # assuming that file is at BOF!
108
-
109
- # 'linebuf' is a stack of lines that will be emptied before we
110
- # actually read from the file; it's only populated by an
111
- # 'unreadline()' operation
112
- self.linebuf = []
113
-
114
- def open(self, filename):
115
- """Open a new file named 'filename'. This overrides both the
116
- 'filename' and 'file' arguments to the constructor."""
117
- self.filename = filename
118
- self.file = open(self.filename, errors=self.errors)
119
- self.current_line = 0
120
-
121
- def close(self):
122
- """Close the current file and forget everything we know about it
123
- (filename, current line number)."""
124
- file = self.file
125
- self.file = None
126
- self.filename = None
127
- self.current_line = None
128
- file.close()
129
-
130
- def gen_error(self, msg, line=None):
131
- outmsg = []
132
- if line is None:
133
- line = self.current_line
134
- outmsg.append(self.filename + ", ")
135
- if isinstance(line, (list, tuple)):
136
- outmsg.append("lines %d-%d: " % tuple(line))
137
- else:
138
- outmsg.append("line %d: " % line)
139
- outmsg.append(str(msg))
140
- return "".join(outmsg)
141
-
142
- def error(self, msg, line=None):
143
- raise ValueError("error: " + self.gen_error(msg, line))
144
-
145
- def warn(self, msg, line=None):
146
- """Print (to stderr) a warning message tied to the current logical
147
- line in the current file. If the current logical line in the
148
- file spans multiple physical lines, the warning refers to the
149
- whole range, eg. "lines 3-5". If 'line' supplied, it overrides
150
- the current line number; it may be a list or tuple to indicate a
151
- range of physical lines, or an integer for a single physical
152
- line."""
153
- sys.stderr.write("warning: " + self.gen_error(msg, line) + "\n")
154
-
155
- def readline(self): # noqa: C901
156
- """Read and return a single logical line from the current file (or
157
- from an internal buffer if lines have previously been "unread"
158
- with 'unreadline()'). If the 'join_lines' option is true, this
159
- may involve reading multiple physical lines concatenated into a
160
- single string. Updates the current line number, so calling
161
- 'warn()' after 'readline()' emits a warning about the physical
162
- line(s) just read. Returns None on end-of-file, since the empty
163
- string can occur if 'rstrip_ws' is true but 'strip_blanks' is
164
- not."""
165
- # If any "unread" lines waiting in 'linebuf', return the top
166
- # one. (We don't actually buffer read-ahead data -- lines only
167
- # get put in 'linebuf' if the client explicitly does an
168
- # 'unreadline()'.
169
- if self.linebuf:
170
- line = self.linebuf[-1]
171
- del self.linebuf[-1]
172
- return line
173
-
174
- buildup_line = ''
175
-
176
- while True:
177
- # read the line, make it None if EOF
178
- line = self.file.readline()
179
- if line == '':
180
- line = None
181
-
182
- if self.strip_comments and line:
183
-
184
- # Look for the first "#" in the line. If none, never
185
- # mind. If we find one and it's the first character, or
186
- # is not preceded by "\", then it starts a comment --
187
- # strip the comment, strip whitespace before it, and
188
- # carry on. Otherwise, it's just an escaped "#", so
189
- # unescape it (and any other escaped "#"'s that might be
190
- # lurking in there) and otherwise leave the line alone.
191
-
192
- pos = line.find("#")
193
- if pos == -1: # no "#" -- no comments
194
- pass
195
-
196
- # It's definitely a comment -- either "#" is the first
197
- # character, or it's elsewhere and unescaped.
198
- elif pos == 0 or line[pos - 1] != "\\":
199
- # Have to preserve the trailing newline, because it's
200
- # the job of a later step (rstrip_ws) to remove it --
201
- # and if rstrip_ws is false, we'd better preserve it!
202
- # (NB. this means that if the final line is all comment
203
- # and has no trailing newline, we will think that it's
204
- # EOF; I think that's OK.)
205
- eol = (line[-1] == '\n') and '\n' or ''
206
- line = line[0:pos] + eol
207
-
208
- # If all that's left is whitespace, then skip line
209
- # *now*, before we try to join it to 'buildup_line' --
210
- # that way constructs like
211
- # hello \\
212
- # # comment that should be ignored
213
- # there
214
- # result in "hello there".
215
- if line.strip() == "":
216
- continue
217
- else: # it's an escaped "#"
218
- line = line.replace("\\#", "#")
219
-
220
- # did previous line end with a backslash? then accumulate
221
- if self.join_lines and buildup_line:
222
- # oops: end of file
223
- if line is None:
224
- self.warn("continuation line immediately precedes " "end-of-file")
225
- return buildup_line
226
-
227
- if self.collapse_join:
228
- line = line.lstrip()
229
- line = buildup_line + line
230
-
231
- # careful: pay attention to line number when incrementing it
232
- if isinstance(self.current_line, list):
233
- self.current_line[1] = self.current_line[1] + 1
234
- else:
235
- self.current_line = [self.current_line, self.current_line + 1]
236
- # just an ordinary line, read it as usual
237
- else:
238
- if line is None: # eof
239
- return None
240
-
241
- # still have to be careful about incrementing the line number!
242
- if isinstance(self.current_line, list):
243
- self.current_line = self.current_line[1] + 1
244
- else:
245
- self.current_line = self.current_line + 1
246
-
247
- # strip whitespace however the client wants (leading and
248
- # trailing, or one or the other, or neither)
249
- if self.lstrip_ws and self.rstrip_ws:
250
- line = line.strip()
251
- elif self.lstrip_ws:
252
- line = line.lstrip()
253
- elif self.rstrip_ws:
254
- line = line.rstrip()
255
-
256
- # blank line (whether we rstrip'ed or not)? skip to next line
257
- # if appropriate
258
- if (line == '' or line == '\n') and self.skip_blanks:
259
- continue
260
-
261
- if self.join_lines:
262
- if line[-1] == '\\':
263
- buildup_line = line[:-1]
264
- continue
265
-
266
- if line[-2:] == '\\\n':
267
- buildup_line = line[0:-2] + '\n'
268
- continue
269
-
270
- # well, I guess there's some actual content there: return it
271
- return line
272
-
273
- def readlines(self):
274
- """Read and return the list of all logical lines remaining in the
275
- current file."""
276
- lines = []
277
- while True:
278
- line = self.readline()
279
- if line is None:
280
- return lines
281
- lines.append(line)
282
-
283
- def unreadline(self, line):
284
- """Push 'line' (a string) onto an internal buffer that will be
285
- checked by future 'readline()' calls. Handy for implementing
286
- a parser with line-at-a-time lookahead."""
287
- self.linebuf.append(line)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BrianL/CoE197-Fil-DialectTranslator/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: Space2
3
- emoji: 🌍
4
- colorFrom: indigo
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 2.8.14
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CForGETaass/vits-uma-genshin-honkai/modules.py DELETED
@@ -1,388 +0,0 @@
1
- import math
2
- import numpy as np
3
- import torch
4
- from torch import nn
5
- from torch.nn import functional as F
6
-
7
- from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
8
- from torch.nn.utils import weight_norm, remove_weight_norm
9
-
10
- import commons
11
- from commons import init_weights, get_padding
12
- from transforms import piecewise_rational_quadratic_transform
13
-
14
-
15
- LRELU_SLOPE = 0.1
16
-
17
-
18
- class LayerNorm(nn.Module):
19
- def __init__(self, channels, eps=1e-5):
20
- super().__init__()
21
- self.channels = channels
22
- self.eps = eps
23
-
24
- self.gamma = nn.Parameter(torch.ones(channels))
25
- self.beta = nn.Parameter(torch.zeros(channels))
26
-
27
- def forward(self, x):
28
- x = x.transpose(1, -1)
29
- x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
30
- return x.transpose(1, -1)
31
-
32
-
33
- class ConvReluNorm(nn.Module):
34
- def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
35
- super().__init__()
36
- self.in_channels = in_channels
37
- self.hidden_channels = hidden_channels
38
- self.out_channels = out_channels
39
- self.kernel_size = kernel_size
40
- self.n_layers = n_layers
41
- self.p_dropout = p_dropout
42
- assert n_layers > 1, "Number of layers should be larger than 0."
43
-
44
- self.conv_layers = nn.ModuleList()
45
- self.norm_layers = nn.ModuleList()
46
- self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
47
- self.norm_layers.append(LayerNorm(hidden_channels))
48
- self.relu_drop = nn.Sequential(
49
- nn.ReLU(),
50
- nn.Dropout(p_dropout))
51
- for _ in range(n_layers-1):
52
- self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
53
- self.norm_layers.append(LayerNorm(hidden_channels))
54
- self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
55
- self.proj.weight.data.zero_()
56
- self.proj.bias.data.zero_()
57
-
58
- def forward(self, x, x_mask):
59
- x_org = x
60
- for i in range(self.n_layers):
61
- x = self.conv_layers[i](x * x_mask)
62
- x = self.norm_layers[i](x)
63
- x = self.relu_drop(x)
64
- x = x_org + self.proj(x)
65
- return x * x_mask
66
-
67
-
68
- class DDSConv(nn.Module):
69
- """
70
- Dialted and Depth-Separable Convolution
71
- """
72
- def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
73
- super().__init__()
74
- self.channels = channels
75
- self.kernel_size = kernel_size
76
- self.n_layers = n_layers
77
- self.p_dropout = p_dropout
78
-
79
- self.drop = nn.Dropout(p_dropout)
80
- self.convs_sep = nn.ModuleList()
81
- self.convs_1x1 = nn.ModuleList()
82
- self.norms_1 = nn.ModuleList()
83
- self.norms_2 = nn.ModuleList()
84
- for i in range(n_layers):
85
- dilation = kernel_size ** i
86
- padding = (kernel_size * dilation - dilation) // 2
87
- self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
88
- groups=channels, dilation=dilation, padding=padding
89
- ))
90
- self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
91
- self.norms_1.append(LayerNorm(channels))
92
- self.norms_2.append(LayerNorm(channels))
93
-
94
- def forward(self, x, x_mask, g=None):
95
- if g is not None:
96
- x = x + g
97
- for i in range(self.n_layers):
98
- y = self.convs_sep[i](x * x_mask)
99
- y = self.norms_1[i](y)
100
- y = F.gelu(y)
101
- y = self.convs_1x1[i](y)
102
- y = self.norms_2[i](y)
103
- y = F.gelu(y)
104
- y = self.drop(y)
105
- x = x + y
106
- return x * x_mask
107
-
108
-
109
- class WN(torch.nn.Module):
110
- def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
111
- super(WN, self).__init__()
112
- assert(kernel_size % 2 == 1)
113
- self.hidden_channels =hidden_channels
114
- self.kernel_size = kernel_size,
115
- self.dilation_rate = dilation_rate
116
- self.n_layers = n_layers
117
- self.gin_channels = gin_channels
118
- self.p_dropout = p_dropout
119
-
120
- self.in_layers = torch.nn.ModuleList()
121
- self.res_skip_layers = torch.nn.ModuleList()
122
- self.drop = nn.Dropout(p_dropout)
123
-
124
- if gin_channels != 0:
125
- cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
126
- self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
127
-
128
- for i in range(n_layers):
129
- dilation = dilation_rate ** i
130
- padding = int((kernel_size * dilation - dilation) / 2)
131
- in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
132
- dilation=dilation, padding=padding)
133
- in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
134
- self.in_layers.append(in_layer)
135
-
136
- # last one is not necessary
137
- if i < n_layers - 1:
138
- res_skip_channels = 2 * hidden_channels
139
- else:
140
- res_skip_channels = hidden_channels
141
-
142
- res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
143
- res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
144
- self.res_skip_layers.append(res_skip_layer)
145
-
146
- def forward(self, x, x_mask, g=None, **kwargs):
147
- output = torch.zeros_like(x)
148
- n_channels_tensor = torch.IntTensor([self.hidden_channels])
149
-
150
- if g is not None:
151
- g = self.cond_layer(g)
152
-
153
- for i in range(self.n_layers):
154
- x_in = self.in_layers[i](x)
155
- if g is not None:
156
- cond_offset = i * 2 * self.hidden_channels
157
- g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
158
- else:
159
- g_l = torch.zeros_like(x_in)
160
-
161
- acts = commons.fused_add_tanh_sigmoid_multiply(
162
- x_in,
163
- g_l,
164
- n_channels_tensor)
165
- acts = self.drop(acts)
166
-
167
- res_skip_acts = self.res_skip_layers[i](acts)
168
- if i < self.n_layers - 1:
169
- res_acts = res_skip_acts[:,:self.hidden_channels,:]
170
- x = (x + res_acts) * x_mask
171
- output = output + res_skip_acts[:,self.hidden_channels:,:]
172
- else:
173
- output = output + res_skip_acts
174
- return output * x_mask
175
-
176
- def remove_weight_norm(self):
177
- if self.gin_channels != 0:
178
- torch.nn.utils.remove_weight_norm(self.cond_layer)
179
- for l in self.in_layers:
180
- torch.nn.utils.remove_weight_norm(l)
181
- for l in self.res_skip_layers:
182
- torch.nn.utils.remove_weight_norm(l)
183
-
184
-
185
- class ResBlock1(torch.nn.Module):
186
- def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
187
- super(ResBlock1, self).__init__()
188
- self.convs1 = nn.ModuleList([
189
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
190
- padding=get_padding(kernel_size, dilation[0]))),
191
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
192
- padding=get_padding(kernel_size, dilation[1]))),
193
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
194
- padding=get_padding(kernel_size, dilation[2])))
195
- ])
196
- self.convs1.apply(init_weights)
197
-
198
- self.convs2 = nn.ModuleList([
199
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
200
- padding=get_padding(kernel_size, 1))),
201
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
202
- padding=get_padding(kernel_size, 1))),
203
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
204
- padding=get_padding(kernel_size, 1)))
205
- ])
206
- self.convs2.apply(init_weights)
207
-
208
- def forward(self, x, x_mask=None):
209
- for c1, c2 in zip(self.convs1, self.convs2):
210
- xt = F.leaky_relu(x, LRELU_SLOPE)
211
- if x_mask is not None:
212
- xt = xt * x_mask
213
- xt = c1(xt)
214
- xt = F.leaky_relu(xt, LRELU_SLOPE)
215
- if x_mask is not None:
216
- xt = xt * x_mask
217
- xt = c2(xt)
218
- x = xt + x
219
- if x_mask is not None:
220
- x = x * x_mask
221
- return x
222
-
223
- def remove_weight_norm(self):
224
- for l in self.convs1:
225
- remove_weight_norm(l)
226
- for l in self.convs2:
227
- remove_weight_norm(l)
228
-
229
-
230
- class ResBlock2(torch.nn.Module):
231
- def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
232
- super(ResBlock2, self).__init__()
233
- self.convs = nn.ModuleList([
234
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
235
- padding=get_padding(kernel_size, dilation[0]))),
236
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
237
- padding=get_padding(kernel_size, dilation[1])))
238
- ])
239
- self.convs.apply(init_weights)
240
-
241
- def forward(self, x, x_mask=None):
242
- for c in self.convs:
243
- xt = F.leaky_relu(x, LRELU_SLOPE)
244
- if x_mask is not None:
245
- xt = xt * x_mask
246
- xt = c(xt)
247
- x = xt + x
248
- if x_mask is not None:
249
- x = x * x_mask
250
- return x
251
-
252
- def remove_weight_norm(self):
253
- for l in self.convs:
254
- remove_weight_norm(l)
255
-
256
-
257
- class Log(nn.Module):
258
- def forward(self, x, x_mask, reverse=False, **kwargs):
259
- if not reverse:
260
- y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
261
- logdet = torch.sum(-y, [1, 2])
262
- return y, logdet
263
- else:
264
- x = torch.exp(x) * x_mask
265
- return x
266
-
267
-
268
- class Flip(nn.Module):
269
- def forward(self, x, *args, reverse=False, **kwargs):
270
- x = torch.flip(x, [1])
271
- if not reverse:
272
- logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
273
- return x, logdet
274
- else:
275
- return x
276
-
277
-
278
- class ElementwiseAffine(nn.Module):
279
- def __init__(self, channels):
280
- super().__init__()
281
- self.channels = channels
282
- self.m = nn.Parameter(torch.zeros(channels,1))
283
- self.logs = nn.Parameter(torch.zeros(channels,1))
284
-
285
- def forward(self, x, x_mask, reverse=False, **kwargs):
286
- if not reverse:
287
- y = self.m + torch.exp(self.logs) * x
288
- y = y * x_mask
289
- logdet = torch.sum(self.logs * x_mask, [1,2])
290
- return y, logdet
291
- else:
292
- x = (x - self.m) * torch.exp(-self.logs) * x_mask
293
- return x
294
-
295
-
296
- class ResidualCouplingLayer(nn.Module):
297
- def __init__(self,
298
- channels,
299
- hidden_channels,
300
- kernel_size,
301
- dilation_rate,
302
- n_layers,
303
- p_dropout=0,
304
- gin_channels=0,
305
- mean_only=False):
306
- assert channels % 2 == 0, "channels should be divisible by 2"
307
- super().__init__()
308
- self.channels = channels
309
- self.hidden_channels = hidden_channels
310
- self.kernel_size = kernel_size
311
- self.dilation_rate = dilation_rate
312
- self.n_layers = n_layers
313
- self.half_channels = channels // 2
314
- self.mean_only = mean_only
315
-
316
- self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
317
- self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
318
- self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
319
- self.post.weight.data.zero_()
320
- self.post.bias.data.zero_()
321
-
322
- def forward(self, x, x_mask, g=None, reverse=False):
323
- x0, x1 = torch.split(x, [self.half_channels]*2, 1)
324
- h = self.pre(x0) * x_mask
325
- h = self.enc(h, x_mask, g=g)
326
- stats = self.post(h) * x_mask
327
- if not self.mean_only:
328
- m, logs = torch.split(stats, [self.half_channels]*2, 1)
329
- else:
330
- m = stats
331
- logs = torch.zeros_like(m)
332
-
333
- if not reverse:
334
- x1 = m + x1 * torch.exp(logs) * x_mask
335
- x = torch.cat([x0, x1], 1)
336
- logdet = torch.sum(logs, [1,2])
337
- return x, logdet
338
- else:
339
- x1 = (x1 - m) * torch.exp(-logs) * x_mask
340
- x = torch.cat([x0, x1], 1)
341
- return x
342
-
343
-
344
- class ConvFlow(nn.Module):
345
- def __init__(self, in_channels, filter_channels, kernel_size, n_layers, num_bins=10, tail_bound=5.0):
346
- super().__init__()
347
- self.in_channels = in_channels
348
- self.filter_channels = filter_channels
349
- self.kernel_size = kernel_size
350
- self.n_layers = n_layers
351
- self.num_bins = num_bins
352
- self.tail_bound = tail_bound
353
- self.half_channels = in_channels // 2
354
-
355
- self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
356
- self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.)
357
- self.proj = nn.Conv1d(filter_channels, self.half_channels * (num_bins * 3 - 1), 1)
358
- self.proj.weight.data.zero_()
359
- self.proj.bias.data.zero_()
360
-
361
- def forward(self, x, x_mask, g=None, reverse=False):
362
- x0, x1 = torch.split(x, [self.half_channels]*2, 1)
363
- h = self.pre(x0)
364
- h = self.convs(h, x_mask, g=g)
365
- h = self.proj(h) * x_mask
366
-
367
- b, c, t = x0.shape
368
- h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
369
-
370
- unnormalized_widths = h[..., :self.num_bins] / math.sqrt(self.filter_channels)
371
- unnormalized_heights = h[..., self.num_bins:2*self.num_bins] / math.sqrt(self.filter_channels)
372
- unnormalized_derivatives = h[..., 2 * self.num_bins:]
373
-
374
- x1, logabsdet = piecewise_rational_quadratic_transform(x1,
375
- unnormalized_widths,
376
- unnormalized_heights,
377
- unnormalized_derivatives,
378
- inverse=reverse,
379
- tails='linear',
380
- tail_bound=self.tail_bound
381
- )
382
-
383
- x = torch.cat([x0, x1], 1) * x_mask
384
- logdet = torch.sum(logabsdet * x_mask, [1,2])
385
- if not reverse:
386
- return x, logdet
387
- else:
388
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChandraMohanNayal/AutoGPT/autogpt/commands/web_playwright.py DELETED
@@ -1,80 +0,0 @@
1
- """Web scraping commands using Playwright"""
2
- from __future__ import annotations
3
-
4
- try:
5
- from playwright.sync_api import sync_playwright
6
- except ImportError:
7
- print(
8
- "Playwright not installed. Please install it with 'pip install playwright' to use."
9
- )
10
- from bs4 import BeautifulSoup
11
-
12
- from autogpt.processing.html import extract_hyperlinks, format_hyperlinks
13
-
14
-
15
- def scrape_text(url: str) -> str:
16
- """Scrape text from a webpage
17
-
18
- Args:
19
- url (str): The URL to scrape text from
20
-
21
- Returns:
22
- str: The scraped text
23
- """
24
- with sync_playwright() as p:
25
- browser = p.chromium.launch()
26
- page = browser.new_page()
27
-
28
- try:
29
- page.goto(url)
30
- html_content = page.content()
31
- soup = BeautifulSoup(html_content, "html.parser")
32
-
33
- for script in soup(["script", "style"]):
34
- script.extract()
35
-
36
- text = soup.get_text()
37
- lines = (line.strip() for line in text.splitlines())
38
- chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
39
- text = "\n".join(chunk for chunk in chunks if chunk)
40
-
41
- except Exception as e:
42
- text = f"Error: {str(e)}"
43
-
44
- finally:
45
- browser.close()
46
-
47
- return text
48
-
49
-
50
- def scrape_links(url: str) -> str | list[str]:
51
- """Scrape links from a webpage
52
-
53
- Args:
54
- url (str): The URL to scrape links from
55
-
56
- Returns:
57
- Union[str, List[str]]: The scraped links
58
- """
59
- with sync_playwright() as p:
60
- browser = p.chromium.launch()
61
- page = browser.new_page()
62
-
63
- try:
64
- page.goto(url)
65
- html_content = page.content()
66
- soup = BeautifulSoup(html_content, "html.parser")
67
-
68
- for script in soup(["script", "style"]):
69
- script.extract()
70
-
71
- hyperlinks = extract_hyperlinks(soup, url)
72
- formatted_links = format_hyperlinks(hyperlinks)
73
-
74
- except Exception as e:
75
- formatted_links = f"Error: {str(e)}"
76
-
77
- finally:
78
- browser.close()
79
-
80
- return formatted_links
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Codecooker/rvcapi/src/infer_pack/modules.py DELETED
@@ -1,522 +0,0 @@
1
- import copy
2
- import math
3
- import numpy as np
4
- import scipy
5
- import torch
6
- from torch import nn
7
- from torch.nn import functional as F
8
-
9
- from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
10
- from torch.nn.utils import weight_norm, remove_weight_norm
11
-
12
- from infer_pack import commons
13
- from infer_pack.commons import init_weights, get_padding
14
- from infer_pack.transforms import piecewise_rational_quadratic_transform
15
-
16
-
17
- LRELU_SLOPE = 0.1
18
-
19
-
20
- class LayerNorm(nn.Module):
21
- def __init__(self, channels, eps=1e-5):
22
- super().__init__()
23
- self.channels = channels
24
- self.eps = eps
25
-
26
- self.gamma = nn.Parameter(torch.ones(channels))
27
- self.beta = nn.Parameter(torch.zeros(channels))
28
-
29
- def forward(self, x):
30
- x = x.transpose(1, -1)
31
- x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
32
- return x.transpose(1, -1)
33
-
34
-
35
- class ConvReluNorm(nn.Module):
36
- def __init__(
37
- self,
38
- in_channels,
39
- hidden_channels,
40
- out_channels,
41
- kernel_size,
42
- n_layers,
43
- p_dropout,
44
- ):
45
- super().__init__()
46
- self.in_channels = in_channels
47
- self.hidden_channels = hidden_channels
48
- self.out_channels = out_channels
49
- self.kernel_size = kernel_size
50
- self.n_layers = n_layers
51
- self.p_dropout = p_dropout
52
- assert n_layers > 1, "Number of layers should be larger than 0."
53
-
54
- self.conv_layers = nn.ModuleList()
55
- self.norm_layers = nn.ModuleList()
56
- self.conv_layers.append(
57
- nn.Conv1d(
58
- in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
59
- )
60
- )
61
- self.norm_layers.append(LayerNorm(hidden_channels))
62
- self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
63
- for _ in range(n_layers - 1):
64
- self.conv_layers.append(
65
- nn.Conv1d(
66
- hidden_channels,
67
- hidden_channels,
68
- kernel_size,
69
- padding=kernel_size // 2,
70
- )
71
- )
72
- self.norm_layers.append(LayerNorm(hidden_channels))
73
- self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
74
- self.proj.weight.data.zero_()
75
- self.proj.bias.data.zero_()
76
-
77
- def forward(self, x, x_mask):
78
- x_org = x
79
- for i in range(self.n_layers):
80
- x = self.conv_layers[i](x * x_mask)
81
- x = self.norm_layers[i](x)
82
- x = self.relu_drop(x)
83
- x = x_org + self.proj(x)
84
- return x * x_mask
85
-
86
-
87
- class DDSConv(nn.Module):
88
- """
89
- Dialted and Depth-Separable Convolution
90
- """
91
-
92
- def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
93
- super().__init__()
94
- self.channels = channels
95
- self.kernel_size = kernel_size
96
- self.n_layers = n_layers
97
- self.p_dropout = p_dropout
98
-
99
- self.drop = nn.Dropout(p_dropout)
100
- self.convs_sep = nn.ModuleList()
101
- self.convs_1x1 = nn.ModuleList()
102
- self.norms_1 = nn.ModuleList()
103
- self.norms_2 = nn.ModuleList()
104
- for i in range(n_layers):
105
- dilation = kernel_size**i
106
- padding = (kernel_size * dilation - dilation) // 2
107
- self.convs_sep.append(
108
- nn.Conv1d(
109
- channels,
110
- channels,
111
- kernel_size,
112
- groups=channels,
113
- dilation=dilation,
114
- padding=padding,
115
- )
116
- )
117
- self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
118
- self.norms_1.append(LayerNorm(channels))
119
- self.norms_2.append(LayerNorm(channels))
120
-
121
- def forward(self, x, x_mask, g=None):
122
- if g is not None:
123
- x = x + g
124
- for i in range(self.n_layers):
125
- y = self.convs_sep[i](x * x_mask)
126
- y = self.norms_1[i](y)
127
- y = F.gelu(y)
128
- y = self.convs_1x1[i](y)
129
- y = self.norms_2[i](y)
130
- y = F.gelu(y)
131
- y = self.drop(y)
132
- x = x + y
133
- return x * x_mask
134
-
135
-
136
- class WN(torch.nn.Module):
137
- def __init__(
138
- self,
139
- hidden_channels,
140
- kernel_size,
141
- dilation_rate,
142
- n_layers,
143
- gin_channels=0,
144
- p_dropout=0,
145
- ):
146
- super(WN, self).__init__()
147
- assert kernel_size % 2 == 1
148
- self.hidden_channels = hidden_channels
149
- self.kernel_size = (kernel_size,)
150
- self.dilation_rate = dilation_rate
151
- self.n_layers = n_layers
152
- self.gin_channels = gin_channels
153
- self.p_dropout = p_dropout
154
-
155
- self.in_layers = torch.nn.ModuleList()
156
- self.res_skip_layers = torch.nn.ModuleList()
157
- self.drop = nn.Dropout(p_dropout)
158
-
159
- if gin_channels != 0:
160
- cond_layer = torch.nn.Conv1d(
161
- gin_channels, 2 * hidden_channels * n_layers, 1
162
- )
163
- self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
164
-
165
- for i in range(n_layers):
166
- dilation = dilation_rate**i
167
- padding = int((kernel_size * dilation - dilation) / 2)
168
- in_layer = torch.nn.Conv1d(
169
- hidden_channels,
170
- 2 * hidden_channels,
171
- kernel_size,
172
- dilation=dilation,
173
- padding=padding,
174
- )
175
- in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
176
- self.in_layers.append(in_layer)
177
-
178
- # last one is not necessary
179
- if i < n_layers - 1:
180
- res_skip_channels = 2 * hidden_channels
181
- else:
182
- res_skip_channels = hidden_channels
183
-
184
- res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
185
- res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
186
- self.res_skip_layers.append(res_skip_layer)
187
-
188
- def forward(self, x, x_mask, g=None, **kwargs):
189
- output = torch.zeros_like(x)
190
- n_channels_tensor = torch.IntTensor([self.hidden_channels])
191
-
192
- if g is not None:
193
- g = self.cond_layer(g)
194
-
195
- for i in range(self.n_layers):
196
- x_in = self.in_layers[i](x)
197
- if g is not None:
198
- cond_offset = i * 2 * self.hidden_channels
199
- g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
200
- else:
201
- g_l = torch.zeros_like(x_in)
202
-
203
- acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
204
- acts = self.drop(acts)
205
-
206
- res_skip_acts = self.res_skip_layers[i](acts)
207
- if i < self.n_layers - 1:
208
- res_acts = res_skip_acts[:, : self.hidden_channels, :]
209
- x = (x + res_acts) * x_mask
210
- output = output + res_skip_acts[:, self.hidden_channels :, :]
211
- else:
212
- output = output + res_skip_acts
213
- return output * x_mask
214
-
215
- def remove_weight_norm(self):
216
- if self.gin_channels != 0:
217
- torch.nn.utils.remove_weight_norm(self.cond_layer)
218
- for l in self.in_layers:
219
- torch.nn.utils.remove_weight_norm(l)
220
- for l in self.res_skip_layers:
221
- torch.nn.utils.remove_weight_norm(l)
222
-
223
-
224
- class ResBlock1(torch.nn.Module):
225
- def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
226
- super(ResBlock1, self).__init__()
227
- self.convs1 = nn.ModuleList(
228
- [
229
- weight_norm(
230
- Conv1d(
231
- channels,
232
- channels,
233
- kernel_size,
234
- 1,
235
- dilation=dilation[0],
236
- padding=get_padding(kernel_size, dilation[0]),
237
- )
238
- ),
239
- weight_norm(
240
- Conv1d(
241
- channels,
242
- channels,
243
- kernel_size,
244
- 1,
245
- dilation=dilation[1],
246
- padding=get_padding(kernel_size, dilation[1]),
247
- )
248
- ),
249
- weight_norm(
250
- Conv1d(
251
- channels,
252
- channels,
253
- kernel_size,
254
- 1,
255
- dilation=dilation[2],
256
- padding=get_padding(kernel_size, dilation[2]),
257
- )
258
- ),
259
- ]
260
- )
261
- self.convs1.apply(init_weights)
262
-
263
- self.convs2 = nn.ModuleList(
264
- [
265
- weight_norm(
266
- Conv1d(
267
- channels,
268
- channels,
269
- kernel_size,
270
- 1,
271
- dilation=1,
272
- padding=get_padding(kernel_size, 1),
273
- )
274
- ),
275
- weight_norm(
276
- Conv1d(
277
- channels,
278
- channels,
279
- kernel_size,
280
- 1,
281
- dilation=1,
282
- padding=get_padding(kernel_size, 1),
283
- )
284
- ),
285
- weight_norm(
286
- Conv1d(
287
- channels,
288
- channels,
289
- kernel_size,
290
- 1,
291
- dilation=1,
292
- padding=get_padding(kernel_size, 1),
293
- )
294
- ),
295
- ]
296
- )
297
- self.convs2.apply(init_weights)
298
-
299
- def forward(self, x, x_mask=None):
300
- for c1, c2 in zip(self.convs1, self.convs2):
301
- xt = F.leaky_relu(x, LRELU_SLOPE)
302
- if x_mask is not None:
303
- xt = xt * x_mask
304
- xt = c1(xt)
305
- xt = F.leaky_relu(xt, LRELU_SLOPE)
306
- if x_mask is not None:
307
- xt = xt * x_mask
308
- xt = c2(xt)
309
- x = xt + x
310
- if x_mask is not None:
311
- x = x * x_mask
312
- return x
313
-
314
- def remove_weight_norm(self):
315
- for l in self.convs1:
316
- remove_weight_norm(l)
317
- for l in self.convs2:
318
- remove_weight_norm(l)
319
-
320
-
321
- class ResBlock2(torch.nn.Module):
322
- def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
323
- super(ResBlock2, self).__init__()
324
- self.convs = nn.ModuleList(
325
- [
326
- weight_norm(
327
- Conv1d(
328
- channels,
329
- channels,
330
- kernel_size,
331
- 1,
332
- dilation=dilation[0],
333
- padding=get_padding(kernel_size, dilation[0]),
334
- )
335
- ),
336
- weight_norm(
337
- Conv1d(
338
- channels,
339
- channels,
340
- kernel_size,
341
- 1,
342
- dilation=dilation[1],
343
- padding=get_padding(kernel_size, dilation[1]),
344
- )
345
- ),
346
- ]
347
- )
348
- self.convs.apply(init_weights)
349
-
350
- def forward(self, x, x_mask=None):
351
- for c in self.convs:
352
- xt = F.leaky_relu(x, LRELU_SLOPE)
353
- if x_mask is not None:
354
- xt = xt * x_mask
355
- xt = c(xt)
356
- x = xt + x
357
- if x_mask is not None:
358
- x = x * x_mask
359
- return x
360
-
361
- def remove_weight_norm(self):
362
- for l in self.convs:
363
- remove_weight_norm(l)
364
-
365
-
366
- class Log(nn.Module):
367
- def forward(self, x, x_mask, reverse=False, **kwargs):
368
- if not reverse:
369
- y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
370
- logdet = torch.sum(-y, [1, 2])
371
- return y, logdet
372
- else:
373
- x = torch.exp(x) * x_mask
374
- return x
375
-
376
-
377
- class Flip(nn.Module):
378
- def forward(self, x, *args, reverse=False, **kwargs):
379
- x = torch.flip(x, [1])
380
- if not reverse:
381
- logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
382
- return x, logdet
383
- else:
384
- return x
385
-
386
-
387
- class ElementwiseAffine(nn.Module):
388
- def __init__(self, channels):
389
- super().__init__()
390
- self.channels = channels
391
- self.m = nn.Parameter(torch.zeros(channels, 1))
392
- self.logs = nn.Parameter(torch.zeros(channels, 1))
393
-
394
- def forward(self, x, x_mask, reverse=False, **kwargs):
395
- if not reverse:
396
- y = self.m + torch.exp(self.logs) * x
397
- y = y * x_mask
398
- logdet = torch.sum(self.logs * x_mask, [1, 2])
399
- return y, logdet
400
- else:
401
- x = (x - self.m) * torch.exp(-self.logs) * x_mask
402
- return x
403
-
404
-
405
- class ResidualCouplingLayer(nn.Module):
406
- def __init__(
407
- self,
408
- channels,
409
- hidden_channels,
410
- kernel_size,
411
- dilation_rate,
412
- n_layers,
413
- p_dropout=0,
414
- gin_channels=0,
415
- mean_only=False,
416
- ):
417
- assert channels % 2 == 0, "channels should be divisible by 2"
418
- super().__init__()
419
- self.channels = channels
420
- self.hidden_channels = hidden_channels
421
- self.kernel_size = kernel_size
422
- self.dilation_rate = dilation_rate
423
- self.n_layers = n_layers
424
- self.half_channels = channels // 2
425
- self.mean_only = mean_only
426
-
427
- self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
428
- self.enc = WN(
429
- hidden_channels,
430
- kernel_size,
431
- dilation_rate,
432
- n_layers,
433
- p_dropout=p_dropout,
434
- gin_channels=gin_channels,
435
- )
436
- self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
437
- self.post.weight.data.zero_()
438
- self.post.bias.data.zero_()
439
-
440
- def forward(self, x, x_mask, g=None, reverse=False):
441
- x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
442
- h = self.pre(x0) * x_mask
443
- h = self.enc(h, x_mask, g=g)
444
- stats = self.post(h) * x_mask
445
- if not self.mean_only:
446
- m, logs = torch.split(stats, [self.half_channels] * 2, 1)
447
- else:
448
- m = stats
449
- logs = torch.zeros_like(m)
450
-
451
- if not reverse:
452
- x1 = m + x1 * torch.exp(logs) * x_mask
453
- x = torch.cat([x0, x1], 1)
454
- logdet = torch.sum(logs, [1, 2])
455
- return x, logdet
456
- else:
457
- x1 = (x1 - m) * torch.exp(-logs) * x_mask
458
- x = torch.cat([x0, x1], 1)
459
- return x
460
-
461
- def remove_weight_norm(self):
462
- self.enc.remove_weight_norm()
463
-
464
-
465
- class ConvFlow(nn.Module):
466
- def __init__(
467
- self,
468
- in_channels,
469
- filter_channels,
470
- kernel_size,
471
- n_layers,
472
- num_bins=10,
473
- tail_bound=5.0,
474
- ):
475
- super().__init__()
476
- self.in_channels = in_channels
477
- self.filter_channels = filter_channels
478
- self.kernel_size = kernel_size
479
- self.n_layers = n_layers
480
- self.num_bins = num_bins
481
- self.tail_bound = tail_bound
482
- self.half_channels = in_channels // 2
483
-
484
- self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
485
- self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
486
- self.proj = nn.Conv1d(
487
- filter_channels, self.half_channels * (num_bins * 3 - 1), 1
488
- )
489
- self.proj.weight.data.zero_()
490
- self.proj.bias.data.zero_()
491
-
492
- def forward(self, x, x_mask, g=None, reverse=False):
493
- x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
494
- h = self.pre(x0)
495
- h = self.convs(h, x_mask, g=g)
496
- h = self.proj(h) * x_mask
497
-
498
- b, c, t = x0.shape
499
- h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
500
-
501
- unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
502
- unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
503
- self.filter_channels
504
- )
505
- unnormalized_derivatives = h[..., 2 * self.num_bins :]
506
-
507
- x1, logabsdet = piecewise_rational_quadratic_transform(
508
- x1,
509
- unnormalized_widths,
510
- unnormalized_heights,
511
- unnormalized_derivatives,
512
- inverse=reverse,
513
- tails="linear",
514
- tail_bound=self.tail_bound,
515
- )
516
-
517
- x = torch.cat([x0, x1], 1) * x_mask
518
- logdet = torch.sum(logabsdet * x_mask, [1, 2])
519
- if not reverse:
520
- return x, logdet
521
- else:
522
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/PIL/ImageMorph.py DELETED
@@ -1,254 +0,0 @@
1
- # A binary morphology add-on for the Python Imaging Library
2
- #
3
- # History:
4
- # 2014-06-04 Initial version.
5
- #
6
- # Copyright (c) 2014 Dov Grobgeld <[email protected]>
7
-
8
- import re
9
-
10
- from . import Image, _imagingmorph
11
-
12
- LUT_SIZE = 1 << 9
13
-
14
- # fmt: off
15
- ROTATION_MATRIX = [
16
- 6, 3, 0,
17
- 7, 4, 1,
18
- 8, 5, 2,
19
- ]
20
- MIRROR_MATRIX = [
21
- 2, 1, 0,
22
- 5, 4, 3,
23
- 8, 7, 6,
24
- ]
25
- # fmt: on
26
-
27
-
28
- class LutBuilder:
29
- """A class for building a MorphLut from a descriptive language
30
-
31
- The input patterns is a list of a strings sequences like these::
32
-
33
- 4:(...
34
- .1.
35
- 111)->1
36
-
37
- (whitespaces including linebreaks are ignored). The option 4
38
- describes a series of symmetry operations (in this case a
39
- 4-rotation), the pattern is described by:
40
-
41
- - . or X - Ignore
42
- - 1 - Pixel is on
43
- - 0 - Pixel is off
44
-
45
- The result of the operation is described after "->" string.
46
-
47
- The default is to return the current pixel value, which is
48
- returned if no other match is found.
49
-
50
- Operations:
51
-
52
- - 4 - 4 way rotation
53
- - N - Negate
54
- - 1 - Dummy op for no other operation (an op must always be given)
55
- - M - Mirroring
56
-
57
- Example::
58
-
59
- lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])
60
- lut = lb.build_lut()
61
-
62
- """
63
-
64
- def __init__(self, patterns=None, op_name=None):
65
- if patterns is not None:
66
- self.patterns = patterns
67
- else:
68
- self.patterns = []
69
- self.lut = None
70
- if op_name is not None:
71
- known_patterns = {
72
- "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],
73
- "dilation4": ["4:(... .0. .1.)->1"],
74
- "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],
75
- "erosion4": ["4:(... .1. .0.)->0"],
76
- "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],
77
- "edge": [
78
- "1:(... ... ...)->0",
79
- "4:(.0. .1. ...)->1",
80
- "4:(01. .1. ...)->1",
81
- ],
82
- }
83
- if op_name not in known_patterns:
84
- msg = "Unknown pattern " + op_name + "!"
85
- raise Exception(msg)
86
-
87
- self.patterns = known_patterns[op_name]
88
-
89
- def add_patterns(self, patterns):
90
- self.patterns += patterns
91
-
92
- def build_default_lut(self):
93
- symbols = [0, 1]
94
- m = 1 << 4 # pos of current pixel
95
- self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))
96
-
97
- def get_lut(self):
98
- return self.lut
99
-
100
- def _string_permute(self, pattern, permutation):
101
- """string_permute takes a pattern and a permutation and returns the
102
- string permuted according to the permutation list.
103
- """
104
- assert len(permutation) == 9
105
- return "".join(pattern[p] for p in permutation)
106
-
107
- def _pattern_permute(self, basic_pattern, options, basic_result):
108
- """pattern_permute takes a basic pattern and its result and clones
109
- the pattern according to the modifications described in the $options
110
- parameter. It returns a list of all cloned patterns."""
111
- patterns = [(basic_pattern, basic_result)]
112
-
113
- # rotations
114
- if "4" in options:
115
- res = patterns[-1][1]
116
- for i in range(4):
117
- patterns.append(
118
- (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)
119
- )
120
- # mirror
121
- if "M" in options:
122
- n = len(patterns)
123
- for pattern, res in patterns[:n]:
124
- patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))
125
-
126
- # negate
127
- if "N" in options:
128
- n = len(patterns)
129
- for pattern, res in patterns[:n]:
130
- # Swap 0 and 1
131
- pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")
132
- res = 1 - int(res)
133
- patterns.append((pattern, res))
134
-
135
- return patterns
136
-
137
- def build_lut(self):
138
- """Compile all patterns into a morphology lut.
139
-
140
- TBD :Build based on (file) morphlut:modify_lut
141
- """
142
- self.build_default_lut()
143
- patterns = []
144
-
145
- # Parse and create symmetries of the patterns strings
146
- for p in self.patterns:
147
- m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))
148
- if not m:
149
- msg = 'Syntax error in pattern "' + p + '"'
150
- raise Exception(msg)
151
- options = m.group(1)
152
- pattern = m.group(2)
153
- result = int(m.group(3))
154
-
155
- # Get rid of spaces
156
- pattern = pattern.replace(" ", "").replace("\n", "")
157
-
158
- patterns += self._pattern_permute(pattern, options, result)
159
-
160
- # compile the patterns into regular expressions for speed
161
- for i, pattern in enumerate(patterns):
162
- p = pattern[0].replace(".", "X").replace("X", "[01]")
163
- p = re.compile(p)
164
- patterns[i] = (p, pattern[1])
165
-
166
- # Step through table and find patterns that match.
167
- # Note that all the patterns are searched. The last one
168
- # caught overrides
169
- for i in range(LUT_SIZE):
170
- # Build the bit pattern
171
- bitpattern = bin(i)[2:]
172
- bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]
173
-
174
- for p, r in patterns:
175
- if p.match(bitpattern):
176
- self.lut[i] = [0, 1][r]
177
-
178
- return self.lut
179
-
180
-
181
- class MorphOp:
182
- """A class for binary morphological operators"""
183
-
184
- def __init__(self, lut=None, op_name=None, patterns=None):
185
- """Create a binary morphological operator"""
186
- self.lut = lut
187
- if op_name is not None:
188
- self.lut = LutBuilder(op_name=op_name).build_lut()
189
- elif patterns is not None:
190
- self.lut = LutBuilder(patterns=patterns).build_lut()
191
-
192
- def apply(self, image):
193
- """Run a single morphological operation on an image
194
-
195
- Returns a tuple of the number of changed pixels and the
196
- morphed image"""
197
- if self.lut is None:
198
- msg = "No operator loaded"
199
- raise Exception(msg)
200
-
201
- if image.mode != "L":
202
- msg = "Image mode must be L"
203
- raise ValueError(msg)
204
- outimage = Image.new(image.mode, image.size, None)
205
- count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)
206
- return count, outimage
207
-
208
- def match(self, image):
209
- """Get a list of coordinates matching the morphological operation on
210
- an image.
211
-
212
- Returns a list of tuples of (x,y) coordinates
213
- of all matching pixels. See :ref:`coordinate-system`."""
214
- if self.lut is None:
215
- msg = "No operator loaded"
216
- raise Exception(msg)
217
-
218
- if image.mode != "L":
219
- msg = "Image mode must be L"
220
- raise ValueError(msg)
221
- return _imagingmorph.match(bytes(self.lut), image.im.id)
222
-
223
- def get_on_pixels(self, image):
224
- """Get a list of all turned on pixels in a binary image
225
-
226
- Returns a list of tuples of (x,y) coordinates
227
- of all matching pixels. See :ref:`coordinate-system`."""
228
-
229
- if image.mode != "L":
230
- msg = "Image mode must be L"
231
- raise ValueError(msg)
232
- return _imagingmorph.get_on_pixels(image.im.id)
233
-
234
- def load_lut(self, filename):
235
- """Load an operator from an mrl file"""
236
- with open(filename, "rb") as f:
237
- self.lut = bytearray(f.read())
238
-
239
- if len(self.lut) != LUT_SIZE:
240
- self.lut = None
241
- msg = "Wrong size operator file!"
242
- raise Exception(msg)
243
-
244
- def save_lut(self, filename):
245
- """Save an operator to an mrl file"""
246
- if self.lut is None:
247
- msg = "No operator loaded"
248
- raise Exception(msg)
249
- with open(filename, "wb") as f:
250
- f.write(self.lut)
251
-
252
- def set_lut(self, lut):
253
- """Set the lut from an external source"""
254
- self.lut = lut
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fastapi/_compat.py DELETED
@@ -1,616 +0,0 @@
1
- from collections import deque
2
- from copy import copy
3
- from dataclasses import dataclass, is_dataclass
4
- from enum import Enum
5
- from typing import (
6
- Any,
7
- Callable,
8
- Deque,
9
- Dict,
10
- FrozenSet,
11
- List,
12
- Mapping,
13
- Sequence,
14
- Set,
15
- Tuple,
16
- Type,
17
- Union,
18
- )
19
-
20
- from fastapi.exceptions import RequestErrorModel
21
- from fastapi.types import IncEx, ModelNameMap, UnionType
22
- from pydantic import BaseModel, create_model
23
- from pydantic.version import VERSION as PYDANTIC_VERSION
24
- from starlette.datastructures import UploadFile
25
- from typing_extensions import Annotated, Literal, get_args, get_origin
26
-
27
- PYDANTIC_V2 = PYDANTIC_VERSION.startswith("2.")
28
-
29
-
30
- sequence_annotation_to_type = {
31
- Sequence: list,
32
- List: list,
33
- list: list,
34
- Tuple: tuple,
35
- tuple: tuple,
36
- Set: set,
37
- set: set,
38
- FrozenSet: frozenset,
39
- frozenset: frozenset,
40
- Deque: deque,
41
- deque: deque,
42
- }
43
-
44
- sequence_types = tuple(sequence_annotation_to_type.keys())
45
-
46
- if PYDANTIC_V2:
47
- from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError
48
- from pydantic import TypeAdapter
49
- from pydantic import ValidationError as ValidationError
50
- from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined]
51
- GetJsonSchemaHandler as GetJsonSchemaHandler,
52
- )
53
- from pydantic._internal._typing_extra import eval_type_lenient
54
- from pydantic._internal._utils import lenient_issubclass as lenient_issubclass
55
- from pydantic.fields import FieldInfo
56
- from pydantic.json_schema import GenerateJsonSchema as GenerateJsonSchema
57
- from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue
58
- from pydantic_core import CoreSchema as CoreSchema
59
- from pydantic_core import MultiHostUrl as MultiHostUrl
60
- from pydantic_core import PydanticUndefined, PydanticUndefinedType
61
- from pydantic_core import Url as Url
62
- from pydantic_core.core_schema import (
63
- general_plain_validator_function as general_plain_validator_function,
64
- )
65
-
66
- Required = PydanticUndefined
67
- Undefined = PydanticUndefined
68
- UndefinedType = PydanticUndefinedType
69
- evaluate_forwardref = eval_type_lenient
70
- Validator = Any
71
-
72
- class BaseConfig:
73
- pass
74
-
75
- class ErrorWrapper(Exception):
76
- pass
77
-
78
- @dataclass
79
- class ModelField:
80
- field_info: FieldInfo
81
- name: str
82
- mode: Literal["validation", "serialization"] = "validation"
83
-
84
- @property
85
- def alias(self) -> str:
86
- a = self.field_info.alias
87
- return a if a is not None else self.name
88
-
89
- @property
90
- def required(self) -> bool:
91
- return self.field_info.is_required()
92
-
93
- @property
94
- def default(self) -> Any:
95
- return self.get_default()
96
-
97
- @property
98
- def type_(self) -> Any:
99
- return self.field_info.annotation
100
-
101
- def __post_init__(self) -> None:
102
- self._type_adapter: TypeAdapter[Any] = TypeAdapter(
103
- Annotated[self.field_info.annotation, self.field_info]
104
- )
105
-
106
- def get_default(self) -> Any:
107
- if self.field_info.is_required():
108
- return Undefined
109
- return self.field_info.get_default(call_default_factory=True)
110
-
111
- def validate(
112
- self,
113
- value: Any,
114
- values: Dict[str, Any] = {}, # noqa: B006
115
- *,
116
- loc: Tuple[Union[int, str], ...] = (),
117
- ) -> Tuple[Any, Union[List[Dict[str, Any]], None]]:
118
- try:
119
- return (
120
- self._type_adapter.validate_python(value, from_attributes=True),
121
- None,
122
- )
123
- except ValidationError as exc:
124
- return None, _regenerate_error_with_loc(
125
- errors=exc.errors(), loc_prefix=loc
126
- )
127
-
128
- def serialize(
129
- self,
130
- value: Any,
131
- *,
132
- mode: Literal["json", "python"] = "json",
133
- include: Union[IncEx, None] = None,
134
- exclude: Union[IncEx, None] = None,
135
- by_alias: bool = True,
136
- exclude_unset: bool = False,
137
- exclude_defaults: bool = False,
138
- exclude_none: bool = False,
139
- ) -> Any:
140
- # What calls this code passes a value that already called
141
- # self._type_adapter.validate_python(value)
142
- return self._type_adapter.dump_python(
143
- value,
144
- mode=mode,
145
- include=include,
146
- exclude=exclude,
147
- by_alias=by_alias,
148
- exclude_unset=exclude_unset,
149
- exclude_defaults=exclude_defaults,
150
- exclude_none=exclude_none,
151
- )
152
-
153
- def __hash__(self) -> int:
154
- # Each ModelField is unique for our purposes, to allow making a dict from
155
- # ModelField to its JSON Schema.
156
- return id(self)
157
-
158
- def get_annotation_from_field_info(
159
- annotation: Any, field_info: FieldInfo, field_name: str
160
- ) -> Any:
161
- return annotation
162
-
163
- def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:
164
- return errors # type: ignore[return-value]
165
-
166
- def _model_rebuild(model: Type[BaseModel]) -> None:
167
- model.model_rebuild()
168
-
169
- def _model_dump(
170
- model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any
171
- ) -> Any:
172
- return model.model_dump(mode=mode, **kwargs)
173
-
174
- def _get_model_config(model: BaseModel) -> Any:
175
- return model.model_config
176
-
177
- def get_schema_from_model_field(
178
- *,
179
- field: ModelField,
180
- schema_generator: GenerateJsonSchema,
181
- model_name_map: ModelNameMap,
182
- field_mapping: Dict[
183
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
184
- ],
185
- ) -> Dict[str, Any]:
186
- # This expects that GenerateJsonSchema was already used to generate the definitions
187
- json_schema = field_mapping[(field, field.mode)]
188
- if "$ref" not in json_schema:
189
- # TODO remove when deprecating Pydantic v1
190
- # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207
191
- json_schema[
192
- "title"
193
- ] = field.field_info.title or field.alias.title().replace("_", " ")
194
- return json_schema
195
-
196
- def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap:
197
- return {}
198
-
199
- def get_definitions(
200
- *,
201
- fields: List[ModelField],
202
- schema_generator: GenerateJsonSchema,
203
- model_name_map: ModelNameMap,
204
- ) -> Tuple[
205
- Dict[
206
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
207
- ],
208
- Dict[str, Dict[str, Any]],
209
- ]:
210
- inputs = [
211
- (field, field.mode, field._type_adapter.core_schema) for field in fields
212
- ]
213
- field_mapping, definitions = schema_generator.generate_definitions(
214
- inputs=inputs
215
- )
216
- return field_mapping, definitions # type: ignore[return-value]
217
-
218
- def is_scalar_field(field: ModelField) -> bool:
219
- from fastapi import params
220
-
221
- return field_annotation_is_scalar(
222
- field.field_info.annotation
223
- ) and not isinstance(field.field_info, params.Body)
224
-
225
- def is_sequence_field(field: ModelField) -> bool:
226
- return field_annotation_is_sequence(field.field_info.annotation)
227
-
228
- def is_scalar_sequence_field(field: ModelField) -> bool:
229
- return field_annotation_is_scalar_sequence(field.field_info.annotation)
230
-
231
- def is_bytes_field(field: ModelField) -> bool:
232
- return is_bytes_or_nonable_bytes_annotation(field.type_)
233
-
234
- def is_bytes_sequence_field(field: ModelField) -> bool:
235
- return is_bytes_sequence_annotation(field.type_)
236
-
237
- def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:
238
- return type(field_info).from_annotation(annotation)
239
-
240
- def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
241
- origin_type = (
242
- get_origin(field.field_info.annotation) or field.field_info.annotation
243
- )
244
- assert issubclass(origin_type, sequence_types) # type: ignore[arg-type]
245
- return sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return]
246
-
247
- def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
248
- error = ValidationError.from_exception_data(
249
- "Field required", [{"type": "missing", "loc": loc, "input": {}}]
250
- ).errors()[0]
251
- error["input"] = None
252
- return error # type: ignore[return-value]
253
-
254
- def create_body_model(
255
- *, fields: Sequence[ModelField], model_name: str
256
- ) -> Type[BaseModel]:
257
- field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields}
258
- BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload]
259
- return BodyModel
260
-
261
- else:
262
- from fastapi.openapi.constants import REF_PREFIX as REF_PREFIX
263
- from pydantic import AnyUrl as Url # noqa: F401
264
- from pydantic import ( # type: ignore[assignment]
265
- BaseConfig as BaseConfig, # noqa: F401
266
- )
267
- from pydantic import ValidationError as ValidationError # noqa: F401
268
- from pydantic.class_validators import ( # type: ignore[no-redef]
269
- Validator as Validator, # noqa: F401
270
- )
271
- from pydantic.error_wrappers import ( # type: ignore[no-redef]
272
- ErrorWrapper as ErrorWrapper, # noqa: F401
273
- )
274
- from pydantic.errors import MissingError
275
- from pydantic.fields import ( # type: ignore[attr-defined]
276
- SHAPE_FROZENSET,
277
- SHAPE_LIST,
278
- SHAPE_SEQUENCE,
279
- SHAPE_SET,
280
- SHAPE_SINGLETON,
281
- SHAPE_TUPLE,
282
- SHAPE_TUPLE_ELLIPSIS,
283
- )
284
- from pydantic.fields import FieldInfo as FieldInfo
285
- from pydantic.fields import ( # type: ignore[no-redef,attr-defined]
286
- ModelField as ModelField, # noqa: F401
287
- )
288
- from pydantic.fields import ( # type: ignore[no-redef,attr-defined]
289
- Required as Required, # noqa: F401
290
- )
291
- from pydantic.fields import ( # type: ignore[no-redef,attr-defined]
292
- Undefined as Undefined,
293
- )
294
- from pydantic.fields import ( # type: ignore[no-redef, attr-defined]
295
- UndefinedType as UndefinedType, # noqa: F401
296
- )
297
- from pydantic.networks import ( # type: ignore[no-redef]
298
- MultiHostDsn as MultiHostUrl, # noqa: F401
299
- )
300
- from pydantic.schema import (
301
- field_schema,
302
- get_flat_models_from_fields,
303
- get_model_name_map,
304
- model_process_schema,
305
- )
306
- from pydantic.schema import ( # type: ignore[no-redef] # noqa: F401
307
- get_annotation_from_field_info as get_annotation_from_field_info,
308
- )
309
- from pydantic.typing import ( # type: ignore[no-redef]
310
- evaluate_forwardref as evaluate_forwardref, # noqa: F401
311
- )
312
- from pydantic.utils import ( # type: ignore[no-redef]
313
- lenient_issubclass as lenient_issubclass, # noqa: F401
314
- )
315
-
316
- GetJsonSchemaHandler = Any # type: ignore[assignment,misc]
317
- JsonSchemaValue = Dict[str, Any] # type: ignore[misc]
318
- CoreSchema = Any # type: ignore[assignment,misc]
319
-
320
- sequence_shapes = {
321
- SHAPE_LIST,
322
- SHAPE_SET,
323
- SHAPE_FROZENSET,
324
- SHAPE_TUPLE,
325
- SHAPE_SEQUENCE,
326
- SHAPE_TUPLE_ELLIPSIS,
327
- }
328
- sequence_shape_to_type = {
329
- SHAPE_LIST: list,
330
- SHAPE_SET: set,
331
- SHAPE_TUPLE: tuple,
332
- SHAPE_SEQUENCE: list,
333
- SHAPE_TUPLE_ELLIPSIS: list,
334
- }
335
-
336
- @dataclass
337
- class GenerateJsonSchema: # type: ignore[no-redef]
338
- ref_template: str
339
-
340
- class PydanticSchemaGenerationError(Exception): # type: ignore[no-redef]
341
- pass
342
-
343
- def general_plain_validator_function( # type: ignore[misc]
344
- function: Callable[..., Any],
345
- *,
346
- ref: Union[str, None] = None,
347
- metadata: Any = None,
348
- serialization: Any = None,
349
- ) -> Any:
350
- return {}
351
-
352
- def get_model_definitions(
353
- *,
354
- flat_models: Set[Union[Type[BaseModel], Type[Enum]]],
355
- model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
356
- ) -> Dict[str, Any]:
357
- definitions: Dict[str, Dict[str, Any]] = {}
358
- for model in flat_models:
359
- m_schema, m_definitions, m_nested_models = model_process_schema(
360
- model, model_name_map=model_name_map, ref_prefix=REF_PREFIX
361
- )
362
- definitions.update(m_definitions)
363
- model_name = model_name_map[model]
364
- if "description" in m_schema:
365
- m_schema["description"] = m_schema["description"].split("\f")[0]
366
- definitions[model_name] = m_schema
367
- return definitions
368
-
369
- def is_pv1_scalar_field(field: ModelField) -> bool:
370
- from fastapi import params
371
-
372
- field_info = field.field_info
373
- if not (
374
- field.shape == SHAPE_SINGLETON # type: ignore[attr-defined]
375
- and not lenient_issubclass(field.type_, BaseModel)
376
- and not lenient_issubclass(field.type_, dict)
377
- and not field_annotation_is_sequence(field.type_)
378
- and not is_dataclass(field.type_)
379
- and not isinstance(field_info, params.Body)
380
- ):
381
- return False
382
- if field.sub_fields: # type: ignore[attr-defined]
383
- if not all(
384
- is_pv1_scalar_field(f)
385
- for f in field.sub_fields # type: ignore[attr-defined]
386
- ):
387
- return False
388
- return True
389
-
390
- def is_pv1_scalar_sequence_field(field: ModelField) -> bool:
391
- if (field.shape in sequence_shapes) and not lenient_issubclass( # type: ignore[attr-defined]
392
- field.type_, BaseModel
393
- ):
394
- if field.sub_fields is not None: # type: ignore[attr-defined]
395
- for sub_field in field.sub_fields: # type: ignore[attr-defined]
396
- if not is_pv1_scalar_field(sub_field):
397
- return False
398
- return True
399
- if _annotation_is_sequence(field.type_):
400
- return True
401
- return False
402
-
403
- def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:
404
- use_errors: List[Any] = []
405
- for error in errors:
406
- if isinstance(error, ErrorWrapper):
407
- new_errors = ValidationError( # type: ignore[call-arg]
408
- errors=[error], model=RequestErrorModel
409
- ).errors()
410
- use_errors.extend(new_errors)
411
- elif isinstance(error, list):
412
- use_errors.extend(_normalize_errors(error))
413
- else:
414
- use_errors.append(error)
415
- return use_errors
416
-
417
- def _model_rebuild(model: Type[BaseModel]) -> None:
418
- model.update_forward_refs()
419
-
420
- def _model_dump(
421
- model: BaseModel, mode: Literal["json", "python"] = "json", **kwargs: Any
422
- ) -> Any:
423
- return model.dict(**kwargs)
424
-
425
- def _get_model_config(model: BaseModel) -> Any:
426
- return model.__config__ # type: ignore[attr-defined]
427
-
428
- def get_schema_from_model_field(
429
- *,
430
- field: ModelField,
431
- schema_generator: GenerateJsonSchema,
432
- model_name_map: ModelNameMap,
433
- field_mapping: Dict[
434
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
435
- ],
436
- ) -> Dict[str, Any]:
437
- # This expects that GenerateJsonSchema was already used to generate the definitions
438
- return field_schema( # type: ignore[no-any-return]
439
- field, model_name_map=model_name_map, ref_prefix=REF_PREFIX
440
- )[0]
441
-
442
- def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap:
443
- models = get_flat_models_from_fields(fields, known_models=set())
444
- return get_model_name_map(models) # type: ignore[no-any-return]
445
-
446
- def get_definitions(
447
- *,
448
- fields: List[ModelField],
449
- schema_generator: GenerateJsonSchema,
450
- model_name_map: ModelNameMap,
451
- ) -> Tuple[
452
- Dict[
453
- Tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue
454
- ],
455
- Dict[str, Dict[str, Any]],
456
- ]:
457
- models = get_flat_models_from_fields(fields, known_models=set())
458
- return {}, get_model_definitions(
459
- flat_models=models, model_name_map=model_name_map
460
- )
461
-
462
- def is_scalar_field(field: ModelField) -> bool:
463
- return is_pv1_scalar_field(field)
464
-
465
- def is_sequence_field(field: ModelField) -> bool:
466
- return field.shape in sequence_shapes or _annotation_is_sequence(field.type_) # type: ignore[attr-defined]
467
-
468
- def is_scalar_sequence_field(field: ModelField) -> bool:
469
- return is_pv1_scalar_sequence_field(field)
470
-
471
- def is_bytes_field(field: ModelField) -> bool:
472
- return lenient_issubclass(field.type_, bytes)
473
-
474
- def is_bytes_sequence_field(field: ModelField) -> bool:
475
- return field.shape in sequence_shapes and lenient_issubclass(field.type_, bytes) # type: ignore[attr-defined]
476
-
477
- def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:
478
- return copy(field_info)
479
-
480
- def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:
481
- return sequence_shape_to_type[field.shape](value) # type: ignore[no-any-return,attr-defined]
482
-
483
- def get_missing_field_error(loc: Tuple[str, ...]) -> Dict[str, Any]:
484
- missing_field_error = ErrorWrapper(MissingError(), loc=loc) # type: ignore[call-arg]
485
- new_error = ValidationError([missing_field_error], RequestErrorModel)
486
- return new_error.errors()[0] # type: ignore[return-value]
487
-
488
- def create_body_model(
489
- *, fields: Sequence[ModelField], model_name: str
490
- ) -> Type[BaseModel]:
491
- BodyModel = create_model(model_name)
492
- for f in fields:
493
- BodyModel.__fields__[f.name] = f # type: ignore[index]
494
- return BodyModel
495
-
496
-
497
- def _regenerate_error_with_loc(
498
- *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]
499
- ) -> List[Dict[str, Any]]:
500
- updated_loc_errors: List[Any] = [
501
- {**err, "loc": loc_prefix + err.get("loc", ())}
502
- for err in _normalize_errors(errors)
503
- ]
504
-
505
- return updated_loc_errors
506
-
507
-
508
- def _annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
509
- if lenient_issubclass(annotation, (str, bytes)):
510
- return False
511
- return lenient_issubclass(annotation, sequence_types)
512
-
513
-
514
- def field_annotation_is_sequence(annotation: Union[Type[Any], None]) -> bool:
515
- return _annotation_is_sequence(annotation) or _annotation_is_sequence(
516
- get_origin(annotation)
517
- )
518
-
519
-
520
- def value_is_sequence(value: Any) -> bool:
521
- return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) # type: ignore[arg-type]
522
-
523
-
524
- def _annotation_is_complex(annotation: Union[Type[Any], None]) -> bool:
525
- return (
526
- lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile))
527
- or _annotation_is_sequence(annotation)
528
- or is_dataclass(annotation)
529
- )
530
-
531
-
532
- def field_annotation_is_complex(annotation: Union[Type[Any], None]) -> bool:
533
- origin = get_origin(annotation)
534
- if origin is Union or origin is UnionType:
535
- return any(field_annotation_is_complex(arg) for arg in get_args(annotation))
536
-
537
- return (
538
- _annotation_is_complex(annotation)
539
- or _annotation_is_complex(origin)
540
- or hasattr(origin, "__pydantic_core_schema__")
541
- or hasattr(origin, "__get_pydantic_core_schema__")
542
- )
543
-
544
-
545
- def field_annotation_is_scalar(annotation: Any) -> bool:
546
- # handle Ellipsis here to make tuple[int, ...] work nicely
547
- return annotation is Ellipsis or not field_annotation_is_complex(annotation)
548
-
549
-
550
- def field_annotation_is_scalar_sequence(annotation: Union[Type[Any], None]) -> bool:
551
- origin = get_origin(annotation)
552
- if origin is Union or origin is UnionType:
553
- at_least_one_scalar_sequence = False
554
- for arg in get_args(annotation):
555
- if field_annotation_is_scalar_sequence(arg):
556
- at_least_one_scalar_sequence = True
557
- continue
558
- elif not field_annotation_is_scalar(arg):
559
- return False
560
- return at_least_one_scalar_sequence
561
- return field_annotation_is_sequence(annotation) and all(
562
- field_annotation_is_scalar(sub_annotation)
563
- for sub_annotation in get_args(annotation)
564
- )
565
-
566
-
567
- def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool:
568
- if lenient_issubclass(annotation, bytes):
569
- return True
570
- origin = get_origin(annotation)
571
- if origin is Union or origin is UnionType:
572
- for arg in get_args(annotation):
573
- if lenient_issubclass(arg, bytes):
574
- return True
575
- return False
576
-
577
-
578
- def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool:
579
- if lenient_issubclass(annotation, UploadFile):
580
- return True
581
- origin = get_origin(annotation)
582
- if origin is Union or origin is UnionType:
583
- for arg in get_args(annotation):
584
- if lenient_issubclass(arg, UploadFile):
585
- return True
586
- return False
587
-
588
-
589
- def is_bytes_sequence_annotation(annotation: Any) -> bool:
590
- origin = get_origin(annotation)
591
- if origin is Union or origin is UnionType:
592
- at_least_one = False
593
- for arg in get_args(annotation):
594
- if is_bytes_sequence_annotation(arg):
595
- at_least_one = True
596
- continue
597
- return at_least_one
598
- return field_annotation_is_sequence(annotation) and all(
599
- is_bytes_or_nonable_bytes_annotation(sub_annotation)
600
- for sub_annotation in get_args(annotation)
601
- )
602
-
603
-
604
- def is_uploadfile_sequence_annotation(annotation: Any) -> bool:
605
- origin = get_origin(annotation)
606
- if origin is Union or origin is UnionType:
607
- at_least_one = False
608
- for arg in get_args(annotation):
609
- if is_uploadfile_sequence_annotation(arg):
610
- at_least_one = True
611
- continue
612
- return at_least_one
613
- return field_annotation_is_sequence(annotation) and all(
614
- is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation)
615
- for sub_annotation in get_args(annotation)
616
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/colorLib/builder.py DELETED
@@ -1,659 +0,0 @@
1
- """
2
- colorLib.builder: Build COLR/CPAL tables from scratch
3
-
4
- """
5
- import collections
6
- import copy
7
- import enum
8
- from functools import partial
9
- from math import ceil, log
10
- from typing import (
11
- Any,
12
- Dict,
13
- Generator,
14
- Iterable,
15
- List,
16
- Mapping,
17
- Optional,
18
- Sequence,
19
- Tuple,
20
- Type,
21
- TypeVar,
22
- Union,
23
- )
24
- from fontTools.misc.arrayTools import intRect
25
- from fontTools.misc.fixedTools import fixedToFloat
26
- from fontTools.misc.treeTools import build_n_ary_tree
27
- from fontTools.ttLib.tables import C_O_L_R_
28
- from fontTools.ttLib.tables import C_P_A_L_
29
- from fontTools.ttLib.tables import _n_a_m_e
30
- from fontTools.ttLib.tables import otTables as ot
31
- from fontTools.ttLib.tables.otTables import ExtendMode, CompositeMode
32
- from .errors import ColorLibError
33
- from .geometry import round_start_circle_stable_containment
34
- from .table_builder import BuildCallback, TableBuilder
35
-
36
-
37
- # TODO move type aliases to colorLib.types?
38
- T = TypeVar("T")
39
- _Kwargs = Mapping[str, Any]
40
- _PaintInput = Union[int, _Kwargs, ot.Paint, Tuple[str, "_PaintInput"]]
41
- _PaintInputList = Sequence[_PaintInput]
42
- _ColorGlyphsDict = Dict[str, Union[_PaintInputList, _PaintInput]]
43
- _ColorGlyphsV0Dict = Dict[str, Sequence[Tuple[str, int]]]
44
- _ClipBoxInput = Union[
45
- Tuple[int, int, int, int, int], # format 1, variable
46
- Tuple[int, int, int, int], # format 0, non-variable
47
- ot.ClipBox,
48
- ]
49
-
50
-
51
- MAX_PAINT_COLR_LAYER_COUNT = 255
52
- _DEFAULT_ALPHA = 1.0
53
- _MAX_REUSE_LEN = 32
54
-
55
-
56
- def _beforeBuildPaintRadialGradient(paint, source):
57
- x0 = source["x0"]
58
- y0 = source["y0"]
59
- r0 = source["r0"]
60
- x1 = source["x1"]
61
- y1 = source["y1"]
62
- r1 = source["r1"]
63
-
64
- # TODO apparently no builder_test confirms this works (?)
65
-
66
- # avoid abrupt change after rounding when c0 is near c1's perimeter
67
- c = round_start_circle_stable_containment((x0, y0), r0, (x1, y1), r1)
68
- x0, y0 = c.centre
69
- r0 = c.radius
70
-
71
- # update source to ensure paint is built with corrected values
72
- source["x0"] = x0
73
- source["y0"] = y0
74
- source["r0"] = r0
75
- source["x1"] = x1
76
- source["y1"] = y1
77
- source["r1"] = r1
78
-
79
- return paint, source
80
-
81
-
82
- def _defaultColorStop():
83
- colorStop = ot.ColorStop()
84
- colorStop.Alpha = _DEFAULT_ALPHA
85
- return colorStop
86
-
87
-
88
- def _defaultVarColorStop():
89
- colorStop = ot.VarColorStop()
90
- colorStop.Alpha = _DEFAULT_ALPHA
91
- return colorStop
92
-
93
-
94
- def _defaultColorLine():
95
- colorLine = ot.ColorLine()
96
- colorLine.Extend = ExtendMode.PAD
97
- return colorLine
98
-
99
-
100
- def _defaultVarColorLine():
101
- colorLine = ot.VarColorLine()
102
- colorLine.Extend = ExtendMode.PAD
103
- return colorLine
104
-
105
-
106
- def _defaultPaintSolid():
107
- paint = ot.Paint()
108
- paint.Alpha = _DEFAULT_ALPHA
109
- return paint
110
-
111
-
112
- def _buildPaintCallbacks():
113
- return {
114
- (
115
- BuildCallback.BEFORE_BUILD,
116
- ot.Paint,
117
- ot.PaintFormat.PaintRadialGradient,
118
- ): _beforeBuildPaintRadialGradient,
119
- (
120
- BuildCallback.BEFORE_BUILD,
121
- ot.Paint,
122
- ot.PaintFormat.PaintVarRadialGradient,
123
- ): _beforeBuildPaintRadialGradient,
124
- (BuildCallback.CREATE_DEFAULT, ot.ColorStop): _defaultColorStop,
125
- (BuildCallback.CREATE_DEFAULT, ot.VarColorStop): _defaultVarColorStop,
126
- (BuildCallback.CREATE_DEFAULT, ot.ColorLine): _defaultColorLine,
127
- (BuildCallback.CREATE_DEFAULT, ot.VarColorLine): _defaultVarColorLine,
128
- (
129
- BuildCallback.CREATE_DEFAULT,
130
- ot.Paint,
131
- ot.PaintFormat.PaintSolid,
132
- ): _defaultPaintSolid,
133
- (
134
- BuildCallback.CREATE_DEFAULT,
135
- ot.Paint,
136
- ot.PaintFormat.PaintVarSolid,
137
- ): _defaultPaintSolid,
138
- }
139
-
140
-
141
- def populateCOLRv0(
142
- table: ot.COLR,
143
- colorGlyphsV0: _ColorGlyphsV0Dict,
144
- glyphMap: Optional[Mapping[str, int]] = None,
145
- ):
146
- """Build v0 color layers and add to existing COLR table.
147
-
148
- Args:
149
- table: a raw ``otTables.COLR()`` object (not ttLib's ``table_C_O_L_R_``).
150
- colorGlyphsV0: map of base glyph names to lists of (layer glyph names,
151
- color palette index) tuples. Can be empty.
152
- glyphMap: a map from glyph names to glyph indices, as returned from
153
- ``TTFont.getReverseGlyphMap()``, to optionally sort base records by GID.
154
- """
155
- if glyphMap is not None:
156
- colorGlyphItems = sorted(
157
- colorGlyphsV0.items(), key=lambda item: glyphMap[item[0]]
158
- )
159
- else:
160
- colorGlyphItems = colorGlyphsV0.items()
161
- baseGlyphRecords = []
162
- layerRecords = []
163
- for baseGlyph, layers in colorGlyphItems:
164
- baseRec = ot.BaseGlyphRecord()
165
- baseRec.BaseGlyph = baseGlyph
166
- baseRec.FirstLayerIndex = len(layerRecords)
167
- baseRec.NumLayers = len(layers)
168
- baseGlyphRecords.append(baseRec)
169
-
170
- for layerGlyph, paletteIndex in layers:
171
- layerRec = ot.LayerRecord()
172
- layerRec.LayerGlyph = layerGlyph
173
- layerRec.PaletteIndex = paletteIndex
174
- layerRecords.append(layerRec)
175
-
176
- table.BaseGlyphRecordArray = table.LayerRecordArray = None
177
- if baseGlyphRecords:
178
- table.BaseGlyphRecordArray = ot.BaseGlyphRecordArray()
179
- table.BaseGlyphRecordArray.BaseGlyphRecord = baseGlyphRecords
180
- if layerRecords:
181
- table.LayerRecordArray = ot.LayerRecordArray()
182
- table.LayerRecordArray.LayerRecord = layerRecords
183
- table.BaseGlyphRecordCount = len(baseGlyphRecords)
184
- table.LayerRecordCount = len(layerRecords)
185
-
186
-
187
- def buildCOLR(
188
- colorGlyphs: _ColorGlyphsDict,
189
- version: Optional[int] = None,
190
- *,
191
- glyphMap: Optional[Mapping[str, int]] = None,
192
- varStore: Optional[ot.VarStore] = None,
193
- varIndexMap: Optional[ot.DeltaSetIndexMap] = None,
194
- clipBoxes: Optional[Dict[str, _ClipBoxInput]] = None,
195
- allowLayerReuse: bool = True,
196
- ) -> C_O_L_R_.table_C_O_L_R_:
197
- """Build COLR table from color layers mapping.
198
-
199
- Args:
200
-
201
- colorGlyphs: map of base glyph name to, either list of (layer glyph name,
202
- color palette index) tuples for COLRv0; or a single ``Paint`` (dict) or
203
- list of ``Paint`` for COLRv1.
204
- version: the version of COLR table. If None, the version is determined
205
- by the presence of COLRv1 paints or variation data (varStore), which
206
- require version 1; otherwise, if all base glyphs use only simple color
207
- layers, version 0 is used.
208
- glyphMap: a map from glyph names to glyph indices, as returned from
209
- TTFont.getReverseGlyphMap(), to optionally sort base records by GID.
210
- varStore: Optional ItemVarationStore for deltas associated with v1 layer.
211
- varIndexMap: Optional DeltaSetIndexMap for deltas associated with v1 layer.
212
- clipBoxes: Optional map of base glyph name to clip box 4- or 5-tuples:
213
- (xMin, yMin, xMax, yMax) or (xMin, yMin, xMax, yMax, varIndexBase).
214
-
215
- Returns:
216
- A new COLR table.
217
- """
218
- self = C_O_L_R_.table_C_O_L_R_()
219
-
220
- if varStore is not None and version == 0:
221
- raise ValueError("Can't add VarStore to COLRv0")
222
-
223
- if version in (None, 0) and not varStore:
224
- # split color glyphs into v0 and v1 and encode separately
225
- colorGlyphsV0, colorGlyphsV1 = _split_color_glyphs_by_version(colorGlyphs)
226
- if version == 0 and colorGlyphsV1:
227
- raise ValueError("Can't encode COLRv1 glyphs in COLRv0")
228
- else:
229
- # unless explicitly requested for v1 or have variations, in which case
230
- # we encode all color glyph as v1
231
- colorGlyphsV0, colorGlyphsV1 = {}, colorGlyphs
232
-
233
- colr = ot.COLR()
234
-
235
- populateCOLRv0(colr, colorGlyphsV0, glyphMap)
236
-
237
- colr.LayerList, colr.BaseGlyphList = buildColrV1(
238
- colorGlyphsV1,
239
- glyphMap,
240
- allowLayerReuse=allowLayerReuse,
241
- )
242
-
243
- if version is None:
244
- version = 1 if (varStore or colorGlyphsV1) else 0
245
- elif version not in (0, 1):
246
- raise NotImplementedError(version)
247
- self.version = colr.Version = version
248
-
249
- if version == 0:
250
- self.ColorLayers = self._decompileColorLayersV0(colr)
251
- else:
252
- colr.ClipList = buildClipList(clipBoxes) if clipBoxes else None
253
- colr.VarIndexMap = varIndexMap
254
- colr.VarStore = varStore
255
- self.table = colr
256
-
257
- return self
258
-
259
-
260
- def buildClipList(clipBoxes: Dict[str, _ClipBoxInput]) -> ot.ClipList:
261
- clipList = ot.ClipList()
262
- clipList.Format = 1
263
- clipList.clips = {name: buildClipBox(box) for name, box in clipBoxes.items()}
264
- return clipList
265
-
266
-
267
- def buildClipBox(clipBox: _ClipBoxInput) -> ot.ClipBox:
268
- if isinstance(clipBox, ot.ClipBox):
269
- return clipBox
270
- n = len(clipBox)
271
- clip = ot.ClipBox()
272
- if n not in (4, 5):
273
- raise ValueError(f"Invalid ClipBox: expected 4 or 5 values, found {n}")
274
- clip.xMin, clip.yMin, clip.xMax, clip.yMax = intRect(clipBox[:4])
275
- clip.Format = int(n == 5) + 1
276
- if n == 5:
277
- clip.VarIndexBase = int(clipBox[4])
278
- return clip
279
-
280
-
281
- class ColorPaletteType(enum.IntFlag):
282
- USABLE_WITH_LIGHT_BACKGROUND = 0x0001
283
- USABLE_WITH_DARK_BACKGROUND = 0x0002
284
-
285
- @classmethod
286
- def _missing_(cls, value):
287
- # enforce reserved bits
288
- if isinstance(value, int) and (value < 0 or value & 0xFFFC != 0):
289
- raise ValueError(f"{value} is not a valid {cls.__name__}")
290
- return super()._missing_(value)
291
-
292
-
293
- # None, 'abc' or {'en': 'abc', 'de': 'xyz'}
294
- _OptionalLocalizedString = Union[None, str, Dict[str, str]]
295
-
296
-
297
- def buildPaletteLabels(
298
- labels: Iterable[_OptionalLocalizedString], nameTable: _n_a_m_e.table__n_a_m_e
299
- ) -> List[Optional[int]]:
300
- return [
301
- nameTable.addMultilingualName(l, mac=False)
302
- if isinstance(l, dict)
303
- else C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
304
- if l is None
305
- else nameTable.addMultilingualName({"en": l}, mac=False)
306
- for l in labels
307
- ]
308
-
309
-
310
- def buildCPAL(
311
- palettes: Sequence[Sequence[Tuple[float, float, float, float]]],
312
- paletteTypes: Optional[Sequence[ColorPaletteType]] = None,
313
- paletteLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
314
- paletteEntryLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
315
- nameTable: Optional[_n_a_m_e.table__n_a_m_e] = None,
316
- ) -> C_P_A_L_.table_C_P_A_L_:
317
- """Build CPAL table from list of color palettes.
318
-
319
- Args:
320
- palettes: list of lists of colors encoded as tuples of (R, G, B, A) floats
321
- in the range [0..1].
322
- paletteTypes: optional list of ColorPaletteType, one for each palette.
323
- paletteLabels: optional list of palette labels. Each lable can be either:
324
- None (no label), a string (for for default English labels), or a
325
- localized string (as a dict keyed with BCP47 language codes).
326
- paletteEntryLabels: optional list of palette entry labels, one for each
327
- palette entry (see paletteLabels).
328
- nameTable: optional name table where to store palette and palette entry
329
- labels. Required if either paletteLabels or paletteEntryLabels is set.
330
-
331
- Return:
332
- A new CPAL v0 or v1 table, if custom palette types or labels are specified.
333
- """
334
- if len({len(p) for p in palettes}) != 1:
335
- raise ColorLibError("color palettes have different lengths")
336
-
337
- if (paletteLabels or paletteEntryLabels) and not nameTable:
338
- raise TypeError(
339
- "nameTable is required if palette or palette entries have labels"
340
- )
341
-
342
- cpal = C_P_A_L_.table_C_P_A_L_()
343
- cpal.numPaletteEntries = len(palettes[0])
344
-
345
- cpal.palettes = []
346
- for i, palette in enumerate(palettes):
347
- colors = []
348
- for j, color in enumerate(palette):
349
- if not isinstance(color, tuple) or len(color) != 4:
350
- raise ColorLibError(
351
- f"In palette[{i}][{j}]: expected (R, G, B, A) tuple, got {color!r}"
352
- )
353
- if any(v > 1 or v < 0 for v in color):
354
- raise ColorLibError(
355
- f"palette[{i}][{j}] has invalid out-of-range [0..1] color: {color!r}"
356
- )
357
- # input colors are RGBA, CPAL encodes them as BGRA
358
- red, green, blue, alpha = color
359
- colors.append(
360
- C_P_A_L_.Color(*(round(v * 255) for v in (blue, green, red, alpha)))
361
- )
362
- cpal.palettes.append(colors)
363
-
364
- if any(v is not None for v in (paletteTypes, paletteLabels, paletteEntryLabels)):
365
- cpal.version = 1
366
-
367
- if paletteTypes is not None:
368
- if len(paletteTypes) != len(palettes):
369
- raise ColorLibError(
370
- f"Expected {len(palettes)} paletteTypes, got {len(paletteTypes)}"
371
- )
372
- cpal.paletteTypes = [ColorPaletteType(t).value for t in paletteTypes]
373
- else:
374
- cpal.paletteTypes = [C_P_A_L_.table_C_P_A_L_.DEFAULT_PALETTE_TYPE] * len(
375
- palettes
376
- )
377
-
378
- if paletteLabels is not None:
379
- if len(paletteLabels) != len(palettes):
380
- raise ColorLibError(
381
- f"Expected {len(palettes)} paletteLabels, got {len(paletteLabels)}"
382
- )
383
- cpal.paletteLabels = buildPaletteLabels(paletteLabels, nameTable)
384
- else:
385
- cpal.paletteLabels = [C_P_A_L_.table_C_P_A_L_.NO_NAME_ID] * len(palettes)
386
-
387
- if paletteEntryLabels is not None:
388
- if len(paletteEntryLabels) != cpal.numPaletteEntries:
389
- raise ColorLibError(
390
- f"Expected {cpal.numPaletteEntries} paletteEntryLabels, "
391
- f"got {len(paletteEntryLabels)}"
392
- )
393
- cpal.paletteEntryLabels = buildPaletteLabels(paletteEntryLabels, nameTable)
394
- else:
395
- cpal.paletteEntryLabels = [
396
- C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
397
- ] * cpal.numPaletteEntries
398
- else:
399
- cpal.version = 0
400
-
401
- return cpal
402
-
403
-
404
- # COLR v1 tables
405
- # See draft proposal at: https://github.com/googlefonts/colr-gradients-spec
406
-
407
-
408
- def _is_colrv0_layer(layer: Any) -> bool:
409
- # Consider as COLRv0 layer any sequence of length 2 (be it tuple or list) in which
410
- # the first element is a str (the layerGlyph) and the second element is an int
411
- # (CPAL paletteIndex).
412
- # https://github.com/googlefonts/ufo2ft/issues/426
413
- try:
414
- layerGlyph, paletteIndex = layer
415
- except (TypeError, ValueError):
416
- return False
417
- else:
418
- return isinstance(layerGlyph, str) and isinstance(paletteIndex, int)
419
-
420
-
421
- def _split_color_glyphs_by_version(
422
- colorGlyphs: _ColorGlyphsDict,
423
- ) -> Tuple[_ColorGlyphsV0Dict, _ColorGlyphsDict]:
424
- colorGlyphsV0 = {}
425
- colorGlyphsV1 = {}
426
- for baseGlyph, layers in colorGlyphs.items():
427
- if all(_is_colrv0_layer(l) for l in layers):
428
- colorGlyphsV0[baseGlyph] = layers
429
- else:
430
- colorGlyphsV1[baseGlyph] = layers
431
-
432
- # sanity check
433
- assert set(colorGlyphs) == (set(colorGlyphsV0) | set(colorGlyphsV1))
434
-
435
- return colorGlyphsV0, colorGlyphsV1
436
-
437
-
438
- def _reuse_ranges(num_layers: int) -> Generator[Tuple[int, int], None, None]:
439
- # TODO feels like something itertools might have already
440
- for lbound in range(num_layers):
441
- # Reuse of very large #s of layers is relatively unlikely
442
- # +2: we want sequences of at least 2
443
- # otData handles single-record duplication
444
- for ubound in range(
445
- lbound + 2, min(num_layers + 1, lbound + 2 + _MAX_REUSE_LEN)
446
- ):
447
- yield (lbound, ubound)
448
-
449
-
450
- class LayerReuseCache:
451
- reusePool: Mapping[Tuple[Any, ...], int]
452
- tuples: Mapping[int, Tuple[Any, ...]]
453
- keepAlive: List[ot.Paint] # we need id to remain valid
454
-
455
- def __init__(self):
456
- self.reusePool = {}
457
- self.tuples = {}
458
- self.keepAlive = []
459
-
460
- def _paint_tuple(self, paint: ot.Paint):
461
- # start simple, who even cares about cyclic graphs or interesting field types
462
- def _tuple_safe(value):
463
- if isinstance(value, enum.Enum):
464
- return value
465
- elif hasattr(value, "__dict__"):
466
- return tuple(
467
- (k, _tuple_safe(v)) for k, v in sorted(value.__dict__.items())
468
- )
469
- elif isinstance(value, collections.abc.MutableSequence):
470
- return tuple(_tuple_safe(e) for e in value)
471
- return value
472
-
473
- # Cache the tuples for individual Paint instead of the whole sequence
474
- # because the seq could be a transient slice
475
- result = self.tuples.get(id(paint), None)
476
- if result is None:
477
- result = _tuple_safe(paint)
478
- self.tuples[id(paint)] = result
479
- self.keepAlive.append(paint)
480
- return result
481
-
482
- def _as_tuple(self, paints: Sequence[ot.Paint]) -> Tuple[Any, ...]:
483
- return tuple(self._paint_tuple(p) for p in paints)
484
-
485
- def try_reuse(self, layers: List[ot.Paint]) -> List[ot.Paint]:
486
- found_reuse = True
487
- while found_reuse:
488
- found_reuse = False
489
-
490
- ranges = sorted(
491
- _reuse_ranges(len(layers)),
492
- key=lambda t: (t[1] - t[0], t[1], t[0]),
493
- reverse=True,
494
- )
495
- for lbound, ubound in ranges:
496
- reuse_lbound = self.reusePool.get(
497
- self._as_tuple(layers[lbound:ubound]), -1
498
- )
499
- if reuse_lbound == -1:
500
- continue
501
- new_slice = ot.Paint()
502
- new_slice.Format = int(ot.PaintFormat.PaintColrLayers)
503
- new_slice.NumLayers = ubound - lbound
504
- new_slice.FirstLayerIndex = reuse_lbound
505
- layers = layers[:lbound] + [new_slice] + layers[ubound:]
506
- found_reuse = True
507
- break
508
- return layers
509
-
510
- def add(self, layers: List[ot.Paint], first_layer_index: int):
511
- for lbound, ubound in _reuse_ranges(len(layers)):
512
- self.reusePool[self._as_tuple(layers[lbound:ubound])] = (
513
- lbound + first_layer_index
514
- )
515
-
516
-
517
- class LayerListBuilder:
518
- layers: List[ot.Paint]
519
- cache: LayerReuseCache
520
- allowLayerReuse: bool
521
-
522
- def __init__(self, *, allowLayerReuse=True):
523
- self.layers = []
524
- if allowLayerReuse:
525
- self.cache = LayerReuseCache()
526
- else:
527
- self.cache = None
528
-
529
- # We need to intercept construction of PaintColrLayers
530
- callbacks = _buildPaintCallbacks()
531
- callbacks[
532
- (
533
- BuildCallback.BEFORE_BUILD,
534
- ot.Paint,
535
- ot.PaintFormat.PaintColrLayers,
536
- )
537
- ] = self._beforeBuildPaintColrLayers
538
- self.tableBuilder = TableBuilder(callbacks)
539
-
540
- # COLR layers is unusual in that it modifies shared state
541
- # so we need a callback into an object
542
- def _beforeBuildPaintColrLayers(self, dest, source):
543
- # Sketchy gymnastics: a sequence input will have dropped it's layers
544
- # into NumLayers; get it back
545
- if isinstance(source.get("NumLayers", None), collections.abc.Sequence):
546
- layers = source["NumLayers"]
547
- else:
548
- layers = source["Layers"]
549
-
550
- # Convert maps seqs or whatever into typed objects
551
- layers = [self.buildPaint(l) for l in layers]
552
-
553
- # No reason to have a colr layers with just one entry
554
- if len(layers) == 1:
555
- return layers[0], {}
556
-
557
- if self.cache is not None:
558
- # Look for reuse, with preference to longer sequences
559
- # This may make the layer list smaller
560
- layers = self.cache.try_reuse(layers)
561
-
562
- # The layer list is now final; if it's too big we need to tree it
563
- is_tree = len(layers) > MAX_PAINT_COLR_LAYER_COUNT
564
- layers = build_n_ary_tree(layers, n=MAX_PAINT_COLR_LAYER_COUNT)
565
-
566
- # We now have a tree of sequences with Paint leaves.
567
- # Convert the sequences into PaintColrLayers.
568
- def listToColrLayers(layer):
569
- if isinstance(layer, collections.abc.Sequence):
570
- return self.buildPaint(
571
- {
572
- "Format": ot.PaintFormat.PaintColrLayers,
573
- "Layers": [listToColrLayers(l) for l in layer],
574
- }
575
- )
576
- return layer
577
-
578
- layers = [listToColrLayers(l) for l in layers]
579
-
580
- # No reason to have a colr layers with just one entry
581
- if len(layers) == 1:
582
- return layers[0], {}
583
-
584
- paint = ot.Paint()
585
- paint.Format = int(ot.PaintFormat.PaintColrLayers)
586
- paint.NumLayers = len(layers)
587
- paint.FirstLayerIndex = len(self.layers)
588
- self.layers.extend(layers)
589
-
590
- # Register our parts for reuse provided we aren't a tree
591
- # If we are a tree the leaves registered for reuse and that will suffice
592
- if self.cache is not None and not is_tree:
593
- self.cache.add(layers, paint.FirstLayerIndex)
594
-
595
- # we've fully built dest; empty source prevents generalized build from kicking in
596
- return paint, {}
597
-
598
- def buildPaint(self, paint: _PaintInput) -> ot.Paint:
599
- return self.tableBuilder.build(ot.Paint, paint)
600
-
601
- def build(self) -> Optional[ot.LayerList]:
602
- if not self.layers:
603
- return None
604
- layers = ot.LayerList()
605
- layers.LayerCount = len(self.layers)
606
- layers.Paint = self.layers
607
- return layers
608
-
609
-
610
- def buildBaseGlyphPaintRecord(
611
- baseGlyph: str, layerBuilder: LayerListBuilder, paint: _PaintInput
612
- ) -> ot.BaseGlyphList:
613
- self = ot.BaseGlyphPaintRecord()
614
- self.BaseGlyph = baseGlyph
615
- self.Paint = layerBuilder.buildPaint(paint)
616
- return self
617
-
618
-
619
- def _format_glyph_errors(errors: Mapping[str, Exception]) -> str:
620
- lines = []
621
- for baseGlyph, error in sorted(errors.items()):
622
- lines.append(f" {baseGlyph} => {type(error).__name__}: {error}")
623
- return "\n".join(lines)
624
-
625
-
626
- def buildColrV1(
627
- colorGlyphs: _ColorGlyphsDict,
628
- glyphMap: Optional[Mapping[str, int]] = None,
629
- *,
630
- allowLayerReuse: bool = True,
631
- ) -> Tuple[Optional[ot.LayerList], ot.BaseGlyphList]:
632
- if glyphMap is not None:
633
- colorGlyphItems = sorted(
634
- colorGlyphs.items(), key=lambda item: glyphMap[item[0]]
635
- )
636
- else:
637
- colorGlyphItems = colorGlyphs.items()
638
-
639
- errors = {}
640
- baseGlyphs = []
641
- layerBuilder = LayerListBuilder(allowLayerReuse=allowLayerReuse)
642
- for baseGlyph, paint in colorGlyphItems:
643
- try:
644
- baseGlyphs.append(buildBaseGlyphPaintRecord(baseGlyph, layerBuilder, paint))
645
-
646
- except (ColorLibError, OverflowError, ValueError, TypeError) as e:
647
- errors[baseGlyph] = e
648
-
649
- if errors:
650
- failed_glyphs = _format_glyph_errors(errors)
651
- exc = ColorLibError(f"Failed to build BaseGlyphList:\n{failed_glyphs}")
652
- exc.errors = errors
653
- raise exc from next(iter(errors.values()))
654
-
655
- layers = layerBuilder.build()
656
- glyphs = ot.BaseGlyphList()
657
- glyphs.BaseGlyphCount = len(baseGlyphs)
658
- glyphs.BaseGlyphPaintRecord = baseGlyphs
659
- return (layers, glyphs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/h11/_writers.py DELETED
@@ -1,145 +0,0 @@
1
- # Code to read HTTP data
2
- #
3
- # Strategy: each writer takes an event + a write-some-bytes function, which is
4
- # calls.
5
- #
6
- # WRITERS is a dict describing how to pick a reader. It maps states to either:
7
- # - a writer
8
- # - or, for body writers, a dict of framin-dependent writer factories
9
-
10
- from typing import Any, Callable, Dict, List, Tuple, Type, Union
11
-
12
- from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Response
13
- from ._headers import Headers
14
- from ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVER
15
- from ._util import LocalProtocolError, Sentinel
16
-
17
- __all__ = ["WRITERS"]
18
-
19
- Writer = Callable[[bytes], Any]
20
-
21
-
22
- def write_headers(headers: Headers, write: Writer) -> None:
23
- # "Since the Host field-value is critical information for handling a
24
- # request, a user agent SHOULD generate Host as the first header field
25
- # following the request-line." - RFC 7230
26
- raw_items = headers._full_items
27
- for raw_name, name, value in raw_items:
28
- if name == b"host":
29
- write(b"%s: %s\r\n" % (raw_name, value))
30
- for raw_name, name, value in raw_items:
31
- if name != b"host":
32
- write(b"%s: %s\r\n" % (raw_name, value))
33
- write(b"\r\n")
34
-
35
-
36
- def write_request(request: Request, write: Writer) -> None:
37
- if request.http_version != b"1.1":
38
- raise LocalProtocolError("I only send HTTP/1.1")
39
- write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target))
40
- write_headers(request.headers, write)
41
-
42
-
43
- # Shared between InformationalResponse and Response
44
- def write_any_response(
45
- response: Union[InformationalResponse, Response], write: Writer
46
- ) -> None:
47
- if response.http_version != b"1.1":
48
- raise LocalProtocolError("I only send HTTP/1.1")
49
- status_bytes = str(response.status_code).encode("ascii")
50
- # We don't bother sending ascii status messages like "OK"; they're
51
- # optional and ignored by the protocol. (But the space after the numeric
52
- # status code is mandatory.)
53
- #
54
- # XX FIXME: could at least make an effort to pull out the status message
55
- # from stdlib's http.HTTPStatus table. Or maybe just steal their enums
56
- # (either by import or copy/paste). We already accept them as status codes
57
- # since they're of type IntEnum < int.
58
- write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason))
59
- write_headers(response.headers, write)
60
-
61
-
62
- class BodyWriter:
63
- def __call__(self, event: Event, write: Writer) -> None:
64
- if type(event) is Data:
65
- self.send_data(event.data, write)
66
- elif type(event) is EndOfMessage:
67
- self.send_eom(event.headers, write)
68
- else: # pragma: no cover
69
- assert False
70
-
71
- def send_data(self, data: bytes, write: Writer) -> None:
72
- pass
73
-
74
- def send_eom(self, headers: Headers, write: Writer) -> None:
75
- pass
76
-
77
-
78
- #
79
- # These are all careful not to do anything to 'data' except call len(data) and
80
- # write(data). This allows us to transparently pass-through funny objects,
81
- # like placeholder objects referring to files on disk that will be sent via
82
- # sendfile(2).
83
- #
84
- class ContentLengthWriter(BodyWriter):
85
- def __init__(self, length: int) -> None:
86
- self._length = length
87
-
88
- def send_data(self, data: bytes, write: Writer) -> None:
89
- self._length -= len(data)
90
- if self._length < 0:
91
- raise LocalProtocolError("Too much data for declared Content-Length")
92
- write(data)
93
-
94
- def send_eom(self, headers: Headers, write: Writer) -> None:
95
- if self._length != 0:
96
- raise LocalProtocolError("Too little data for declared Content-Length")
97
- if headers:
98
- raise LocalProtocolError("Content-Length and trailers don't mix")
99
-
100
-
101
- class ChunkedWriter(BodyWriter):
102
- def send_data(self, data: bytes, write: Writer) -> None:
103
- # if we encoded 0-length data in the naive way, it would look like an
104
- # end-of-message.
105
- if not data:
106
- return
107
- write(b"%x\r\n" % len(data))
108
- write(data)
109
- write(b"\r\n")
110
-
111
- def send_eom(self, headers: Headers, write: Writer) -> None:
112
- write(b"0\r\n")
113
- write_headers(headers, write)
114
-
115
-
116
- class Http10Writer(BodyWriter):
117
- def send_data(self, data: bytes, write: Writer) -> None:
118
- write(data)
119
-
120
- def send_eom(self, headers: Headers, write: Writer) -> None:
121
- if headers:
122
- raise LocalProtocolError("can't send trailers to HTTP/1.0 client")
123
- # no need to close the socket ourselves, that will be taken care of by
124
- # Connection: close machinery
125
-
126
-
127
- WritersType = Dict[
128
- Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]],
129
- Union[
130
- Dict[str, Type[BodyWriter]],
131
- Callable[[Union[InformationalResponse, Response], Writer], None],
132
- Callable[[Request, Writer], None],
133
- ],
134
- ]
135
-
136
- WRITERS: WritersType = {
137
- (CLIENT, IDLE): write_request,
138
- (SERVER, IDLE): write_any_response,
139
- (SERVER, SEND_RESPONSE): write_any_response,
140
- SEND_BODY: {
141
- "chunked": ChunkedWriter,
142
- "content-length": ContentLengthWriter,
143
- "http/1.0": Http10Writer,
144
- },
145
- }