parquet-converter commited on
Commit
05b7341
·
1 Parent(s): e8d507b

Update parquet files (step 47 of 249)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Clip Paint Studio Cost.md +0 -95
  2. spaces/1gistliPinn/ChatGPT4/Examples/CRACK ThunderSoft Folder Password Lock Pro 11.0.0 Multilingual Full Wi BEST.md +0 -8
  3. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Blockudoku A Relaxing and Stimulating Block Puzzle Game for Everyone - Indir and Experience.md +0 -147
  4. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Dark Bitcoin Miner Pro V7.0 and Join the Crypto Revolution..md +0 -96
  5. spaces/1phancelerku/anime-remove-background/Download GTA 3 1.1 Ultimate Trainer V3 5 and Unlock All Features in Grand Theft Auto III.md +0 -98
  6. spaces/3mrology/Chameleon_Text2Img_Generation_Demo/README.md +0 -14
  7. spaces/7hao/bingo/tests/parse.ts +0 -13
  8. spaces/801artistry/RVC801/mdx.py +0 -228
  9. spaces/801artistry/RVC801/tools/infer_batch_rvc.py +0 -72
  10. spaces/AIConsultant/MusicGen/scripts/mos.py +0 -286
  11. spaces/AIFILMS/StyleGANEX/models/bisenet/model.py +0 -283
  12. spaces/AIGC-Audio/AudioGPT/text_to_speech/tasks/run.py +0 -19
  13. spaces/AbandonedMuse/UnlimitedMusicGen/audiocraft/modules/conv.py +0 -245
  14. spaces/Abubakari/Sepsis-prediction-streamlit-app/app.py +0 -154
  15. spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/midas/midas/__init__.py +0 -0
  16. spaces/Adapting/YouTube-Downloader/app.py +0 -32
  17. spaces/Aditya9790/yolo7-object-tracking/LICENSE.md +0 -674
  18. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/filedropzone/Factory.d.ts +0 -5
  19. spaces/AlexWang/lama/models/ade20k/segm_lib/nn/modules/__init__.py +0 -12
  20. spaces/Andy1621/uniformer_image_detection/configs/instaboost/mask_rcnn_x101_64x4d_fpn_instaboost_4x_coco.py +0 -13
  21. spaces/Andy1621/uniformer_image_detection/mmdet/models/backbones/res2net.py +0 -351
  22. spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/nonlocal_r50-d8.py +0 -46
  23. spaces/Andy1621/uniformer_image_segmentation/configs/nonlocal_net/README.md +0 -48
  24. spaces/AnimaLab/bias-test-gpt-pairs/openAI_manager.py +0 -191
  25. spaces/Anonymous-sub/Rerender/ControlNet/tool_add_control.py +0 -50
  26. spaces/Apex-X/nono/roop/core.py +0 -215
  27. spaces/Ariharasudhan/YoloV5/utils/loggers/__init__.py +0 -404
  28. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/network/download.py +0 -186
  29. spaces/AutoLLM/AutoAgents/setup.py +0 -7
  30. spaces/AzumaSeren100/XuanShen-Bert-VITS2/text/english.py +0 -138
  31. spaces/BAAI/vid2vid-zero/gradio_demo/runner.py +0 -137
  32. spaces/BasToTheMax/22h-vintedois-diffusion-v0-1/app.py +0 -3
  33. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/operations/build/build_tracker.py +0 -124
  34. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/utils/inject_securetransport.py +0 -35
  35. spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/command/sdist.py +0 -210
  36. spaces/BongoCaat/ArtGenerator/README.md +0 -13
  37. spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/modeling/proposal_generator/rpn.py +0 -185
  38. spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/__init__.py +0 -10
  39. spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/tests/test_setup.py +0 -20
  40. spaces/CVPR/LIVE/pybind11/tests/test_stl_binders.py +0 -285
  41. spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/logical.h +0 -23
  42. spaces/CVPR/transfiner/configs/common/models/keypoint_rcnn_fpn.py +0 -33
  43. spaces/ChandraMohanNayal/AutoGPT/autogpt/json_utils/json_fix_general.py +0 -124
  44. spaces/ChrisPreston/diff-svc_minato_aqua/infer_tools/trans_key.py +0 -67
  45. spaces/Codecooker/rvcapi/src/webui.py +0 -309
  46. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/cu2qu/__init__.py +0 -15
  47. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/builder.py +0 -1706
  48. spaces/DaleChen/AutoGPT/autogpt/commands/file_operations.py +0 -267
  49. spaces/Datasculptor/DescriptionGPT/tools/merge_lvis_coco.py +0 -202
  50. spaces/Detomo/ai-comic-generation/src/lib/replaceNonWhiteWithTransparent.ts +0 -46
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Clip Paint Studio Cost.md DELETED
@@ -1,95 +0,0 @@
1
- <br />
2
- <h1>How Much Does Clip Paint Studio Cost and Is It Worth It?</h1>
3
- <p>Clip Paint Studio (also known as Clip Studio Paint or Manga Studio) is a powerful and versatile software for creating digital art, comics, and animation. It offers a wide range of features and tools to help you bring your creative vision to life. But how much does it cost and is it worth the investment? Here are some things to consider before you buy Clip Paint Studio.</p>
4
- <h2>Clip Paint Studio Pricing Plans</h2>
5
- <p>Clip Paint Studio has two main versions: Pro and EX. The Pro version is designed for basic illustration and comic creation, while the EX version has more advanced features for professional comic and animation production. You can compare the features of each version <a href="https://www.clipstudio.net/en/purchase/compare">here</a>.</p>
6
- <h2>clip paint studio cost</h2><br /><p><b><b>DOWNLOAD</b> &middot;&middot;&middot;&middot;&middot; <a href="https://byltly.com/2uKy30">https://byltly.com/2uKy30</a></b></p><br /><br />
7
- <p>The pricing plans for Clip Paint Studio vary depending on the device and the payment method. You can choose to buy a perpetual license or a monthly subscription. Here are the current prices as of May 2023:</p>
8
- <table>
9
- <tr>
10
- <th>Device</th>
11
- <th>Pro License</th>
12
- <th>EX License</th>
13
- <th>Pro Subscription</th>
14
- <th>EX Subscription</th>
15
- </tr>
16
- <tr>
17
- <td>Windows/Mac</td>
18
- <td>$49.99 (one-time)</td>
19
- <td>$219.00 (one-time)</td>
20
- <td>$4.49/month or $24.99/year</td>
21
- <td>$8.99/month or $71.99/year</td>
22
- </tr>
23
- <tr>
24
- <td>iPad/iPhone</td>
25
- <td>N/A</td>
26
- <td>N/A</td>
27
- <td>$4.49/month or $24.99/year</td>
28
- <td>$8.99/month or $71.99/year</td>
29
- </tr>
30
- <tr>
31
- <td>Android/Galaxy</td>
32
- <td>N/A</td>
33
- <td>N/A</td>
34
- <td>$0.99/month or $9.99/year (first 6 months free)</td>
35
- <td>$2.49/month or $24.99/year (first 6 months free)</td>
36
- </tr>
37
- <tr>
38
- <td>Chromebook</td>
39
- <td>N/A</td>
40
- <td>N/A</td>
41
- <td>$0.99/month or $9.99/year (first 3 months free)</td>
42
- <td>$2.49/month or $24.99/year (first 3 months free)</td>
43
- </tr>
44
- </table>
45
-
46
- <p>Note: These prices are subject to change and may vary by region. You can check the latest prices on the <a href="https://www.clipstudio.net/en/purchase">official website</a>.</p>
47
-
48
- <h2>Clip Paint Studio Benefits and Drawbacks</h2>
49
-
50
- <p>Clip Paint Studio is a popular choice among artists and creators for many reasons. Here are some of the benefits and drawbacks of using Clip Paint Studio:</p>
51
-
52
- <h3>Benefits:</h3>
53
-
54
- <ul>
55
-
56
- <li>It has a user-friendly interface and customizable workspace.</li>
57
-
58
- <li>It supports various file formats and devices.</li>
59
-
60
- <li>It has a large and active community of users and resources.</li>
61
-
62
- <li>It has a rich collection of brushes, pens, textures, materials, and assets.</li>
63
-
64
- <li>It has powerful tools for drawing, coloring, editing, vectoring, and animating.</li>
65
-
66
- <li>It has smart features for comic and manga creation, such as panel layout, perspective rulers, word balloons, and 3D models.</li>
67
-
68
- <li>It has frequent updates and improvements based on user feedback.</li>
69
-
70
- <li>It offers a free trial and a money-back guarantee.</li>
71
-
72
- </ul>
73
-
74
- <h3>Drawbacks:</h3>
75
-
76
- <ul>
77
-
78
- <li>It can be overwhelming for beginners or casual users.</li>
79
-
80
- <li>It can be expensive for some users, especially the EX version.</li>
81
-
82
- <li>It can have compatibility issues with some devices or software.</li>
83
-
84
- <li>It can have bugs or glitches sometimes.</li>
85
-
86
- <li>It can have limited support or documentation for some languages or regions.</li>
87
-
88
- </ul>
89
-
90
- <h2>Is Clip Paint Studio Worth It?</h2>
91
-
92
- <p>The answer to this question depends on your needs, preferences, budget, and goals as an artist or creator. Clip Paint Studio is a great software for anyone who wants to create digital art, comics, or animation with high quality and efficiency. However, it may not be the best option for</p>
93
- <p></p> ddb901b051<br />
94
- <br />
95
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/CRACK ThunderSoft Folder Password Lock Pro 11.0.0 Multilingual Full Wi BEST.md DELETED
@@ -1,8 +0,0 @@
1
-
2
- <p>If your computer has an older security system that you no longer want to install an. 0, Code : 110-8601. How to activate the function to display all letters in the password? How to active. CODE : 03-2944. PROGRAM2 - Unlock Folder Password Protection Using File Encryptor PRO 10. . CODE : 03-2944. 0 crack. 23-12-2017 06-20-2014.. .</p>
3
- <p>Hidden files are not encrypted because the file name is not encrypted. Upon infection the cyber criminals will initially try to clear up the malicious files using the registry cleaner. -__hot__-crack-thundersoft-folder-password-lock-pro-11-0-0-multilingual-full-wil -__hot__-crack-thundersoft-folder-password-lock-pro-11-0-0-multilingual-full-wil -__hot__-crack-thundersoft-folder-password-lock-pro-11-0-0-multilingual-full-wil -__hot__-crack-thundersoft-folder-password-lock-pro-11-0-0-multilingual-full-wil. </p>
4
- <h2>CRACK ThunderSoft Folder Password Lock Pro 11.0.0 Multilingual Full Wi</h2><br /><p><b><b>Download</b> &hArr; <a href="https://imgfil.com/2uxZve">https://imgfil.com/2uxZve</a></b></p><br /><br />
5
- <p>You can download and install the folder password unlock without the need for registration. However, it seems to have some performance issues and doesn't seem very secure. While it is now easier to download and install the said software, there are more complex and security related concerns one might be faced with. </p>
6
- <p>To access your encrypted files you need a decryption program, which is available here. The program is called CRACK ThunderSoft and this is the most sophisticated ransomware on the market. The ransomware is unknown and may be created by the hacker group in the past, since it appears to have been used by other groups. It is the first ransomware that can perform a forensic investigation on a computer system, by breaking through all kinds of layer. </p> 899543212b<br />
7
- <br />
8
- <br />
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Blockudoku A Relaxing and Stimulating Block Puzzle Game for Everyone - Indir and Experience.md DELETED
@@ -1,147 +0,0 @@
1
- <br />
2
- <h1>Block Puzzle Indir: How to Download and Play the Best Block Puzzle Games</h1>
3
- <p>Do you love playing puzzle games that challenge your brain and keep you entertained? If so, you might want to try block puzzle games, which are a popular genre of puzzle games that combine elements of Tetris, Sudoku, and jigsaw puzzles. Block puzzle games are simple yet addictive games that require you to fit different shapes of blocks on a grid, either horizontally or vertically, to clear lines or squares. They are fun, relaxing, and rewarding games that can improve your cognitive skills, mental health, and mood.</p>
4
- <h2>block puzzle indir</h2><br /><p><b><b>Download Zip</b> &raquo; <a href="https://urlin.us/2uSUiN">https://urlin.us/2uSUiN</a></b></p><br /><br />
5
- <p>But how can you download and play block puzzle games? What are the best block puzzle games available? And what are some tips and tricks to master them? In this article, we will answer these questions and more. We will explain what block puzzle games are, how they originated and evolved, what benefits they offer, what features they have, how to download and play them, and how to improve your skills. By the end of this article, you will be ready to enjoy block puzzle games like a champ!</p>
6
- <h2>What are Block Puzzle Games?</h2>
7
- <p>Block puzzle games are a type of puzzle games that involve moving and rotating different shapes of blocks on a grid or board. The goal is to fill up the grid with blocks without leaving any gaps or spaces. Depending on the game mode, you may have to clear horizontal or vertical lines, 3x3 squares, or other patterns by placing blocks of the same color or type. You may also have to deal with obstacles, power-ups, timers, or other challenges. The game ends when there is no more space for new blocks or when you reach a certain score or level.</p>
8
- <h3>The Origin and Evolution of Block Puzzle Games</h3>
9
- <p>Block puzzle games have a long history that dates back to the 19th century. One of the earliest examples of block puzzle games is Tangram, a Chinese game that consists of seven flat shapes that can be arranged into various figures. Another example is Pentominoes, a game invented by American mathematician Solomon W. Golomb in 1953, which uses 12 shapes made of five squares each.</p>
10
- <p>block puzzle indir apk<br />
11
- block puzzle indir ücretsiz<br />
12
- block puzzle indir pc<br />
13
- block puzzle indir android<br />
14
- block puzzle indir ios<br />
15
- block puzzle indir oyna<br />
16
- block puzzle indir online<br />
17
- block puzzle indir yükle<br />
18
- block puzzle indir hileli<br />
19
- block puzzle indir mod<br />
20
- block puzzle indir son sürüm<br />
21
- block puzzle indir windows 10<br />
22
- block puzzle indir bilgisayar<br />
23
- block puzzle indir laptop<br />
24
- block puzzle indir tablet<br />
25
- block puzzle indir telefon<br />
26
- block puzzle indir google play<br />
27
- block sudoku indir<br />
28
- block hexa indir<br />
29
- block wood indir<br />
30
- block jewel indir<br />
31
- block legend indir<br />
32
- block master indir<br />
33
- block craft indir<br />
34
- block slide indir<br />
35
- block tower indir<br />
36
- block breaker indir<br />
37
- block shooter indir<br />
38
- block stacker indir<br />
39
- block matcher indir<br />
40
- block blast indir<br />
41
- block mania indir<br />
42
- block star indir<br />
43
- block world indir<br />
44
- block color indir<br />
45
- block twist indir<br />
46
- block drop indir<br />
47
- block fill indir<br />
48
- block rotate indir<br />
49
- block shuffle indir<br />
50
- block swap indir<br />
51
- block merge indir<br />
52
- block explode indir<br />
53
- block connect indir<br />
54
- block fit indir<br />
55
- block move indir<br />
56
- block slide and roll indir</p>
57
- <p>However, the most influential and famous block puzzle game is Tetris, which was created by Soviet engineer Alexey Pajitnov in 1984. Tetris is a game that involves falling blocks of different shapes that can be rotated and moved sideways to fit into a rectangular grid. The game became a worldwide phenomenon and inspired many variations and spin-offs.</p>
58
- <p>Since then, block puzzle games have evolved and diversified into many subgenres and formats. Some examples of modern block puzzle games are Blockudoku, Blockscapes, Woodoku, Block Blast Adventure Master, Blocks: Block Puzzle Games, and many more. These games offer different features, themes, modes, graphics, sounds, and challenges that appeal to different tastes and preferences.</p>
59
- <h3>The Benefits of Playing Block Puzzle Games</h3>
60
- <p>Playing block puzzle games is not only fun but also beneficial for your brain and well-being. Here are some of the benefits of playing block puzzle games:</p>
61
- <ul>
62
- <li>They improve your cognitive skills such as memory, attention, concentration, logic, problem-solving, spatial perception, visual analysis, and synthesis.</li>
63
- <li>They enhance your motor skills such as hand-eye coordination, fine motor control, reaction time, and dexterity.</li>
64
- <li>They reduce stress and anxiety by providing a relaxing and satisfying activity that distracts you from negative thoughts and emotions.</li>
65
- <li>They boost your mood and self-esteem by giving you a sense of achievement and reward when you complete a puzzle or beat a high score.</li>
66
- <li>They stimulate your creativity and imagination by allowing you to create different shapes and patterns with blocks.</li> <h3>The Features of Block Puzzle Games</h3>
67
- <p>Block puzzle games have various features that make them appealing and enjoyable for players of all ages and backgrounds. Some of the common features of block puzzle games are:</p>
68
- <ul>
69
- <li>They have simple and intuitive controls that are easy to learn and use. You can usually move and rotate the blocks with a swipe, a tap, or a drag on your screen.</li>
70
- <li>They have colorful and attractive graphics that create a pleasant and stimulating visual experience. You can choose from different themes and styles that suit your mood and preference.</li>
71
- <li>They have soothing and catchy sounds that enhance the gameplay and create a relaxing and immersive atmosphere. You can listen to different music and sound effects that match the theme and mood of the game.</li>
72
- <li>They have various modes and levels that offer different challenges and goals. You can play classic mode, arcade mode, time mode, endless mode, or other modes that test your skills and strategy. You can also progress through different levels of difficulty and complexity that keep you engaged and motivated.</li>
73
- <li>They have leaderboards and achievements that allow you to compete with yourself and others. You can track your progress and performance, compare your scores and rankings with other players, and unlock new achievements and rewards.</li>
74
- </ul>
75
- <h2>How to Download and Play Block Puzzle Games?</h2>
76
- <p>If you are interested in playing block puzzle games, you may wonder how to download and play them on your device. Here are some steps that you can follow to enjoy block puzzle games:</p>
77
- <h3>Choosing the Right Platform and Device</h3>
78
- <p>The first step is to choose the right platform and device for playing block puzzle games. Block puzzle games are available on various platforms such as web browsers, desktop computers, laptops, tablets, smartphones, consoles, or smart TVs. You can choose the platform that is most convenient and accessible for you.</p>
79
- <p>However, some platforms may have more options and features than others. For example, web browsers may have limited graphics and sounds, while smartphones may have smaller screens and batteries. Therefore, you should consider the pros and cons of each platform before choosing one.</p>
80
- <p>The most popular platform for playing block puzzle games is smartphones, as they are portable, versatile, and easy to use. You can download block puzzle games from various app stores such as Google Play Store, Apple App Store, Amazon Appstore, or Samsung Galaxy Store. You can also play block puzzle games online without downloading them by visiting websites such as Block Puzzle Online or Block Puzzle Games.</p>
81
- <h3>Finding the Best Block Puzzle Games</h3>
82
- <p>The next step is to find the best block puzzle games that suit your taste and preference. There are hundreds of block puzzle games available on different platforms, so you may feel overwhelmed by the choices. However, you can narrow down your options by using some criteria such as:</p>
83
- <ul>
84
- <li>The genre and theme of the game. You can choose from classic block puzzle games, wood block puzzle games, jewel block puzzle games, candy block puzzle games, or other themes that appeal to you.</li>
85
- <li>The features and modes of the game. You can choose from block puzzle games that have different features such as power-ups, obstacles, timers, hints, or other challenges. You can also choose from block puzzle games that have different modes such as classic mode, arcade mode, time mode, endless mode, or other modes that offer different goals.</li>
86
- <li>The ratings and reviews of the game. You can check the ratings and reviews of block puzzle games on app stores or websites to see what other players think about them. You can look for block puzzle games that have high ratings, positive reviews, or large numbers of downloads.</li>
87
- <li>The recommendations and suggestions of the game. You can ask for recommendations and suggestions from your friends, family, or other players who play block puzzle games. You can also look for recommendations and suggestions from online sources such as blogs, forums, social media, or YouTube videos.</li>
88
- </ul>
89
- <h3>Installing and Launching the Games</h3>
90
- <p>The third step is to install and launch the block puzzle games on your device. If you download block puzzle games from app stores or websites, you need to follow the instructions on how to install them on your device. You may need to grant some permissions or accept some terms and conditions before installing them.</p>
91
- <p>If you play block puzzle games online without downloading them, you need to visit the websites that host them on your web browser. You may need to enable some settings or plugins such as Flash Player or JavaScript before playing them.</p>
92
- <p>Once you install or access the block puzzle games on your device, you need to launch them by tapping or clicking on their icons or links. You may need to wait for some loading time before the game starts.</p>
93
- <h3>Learning the Rules and Controls</h3>
94
- <p>The fourth step is The fourth step is to learn the rules and controls of the block puzzle games. Each block puzzle game may have different rules and controls, so you need to read the instructions or tutorials before playing them. You can usually find the instructions or tutorials on the main menu, the settings, or the help section of the game. You can also look for online guides or videos that explain how to play the game. The basic rules and controls of block puzzle games are: - You need to move and rotate the blocks that appear on the top or the side of the screen to fit them into the grid or board. - You can use your finger, your mouse, or your keyboard to move and rotate the blocks. You can swipe, tap, drag, click, or press the arrow keys to control the blocks. - You need to fill up the grid with blocks without leaving any gaps or spaces. You can place the blocks horizontally or vertically, depending on the game mode. - You need to clear lines or squares by placing blocks of the same color or type. You can clear horizontal or vertical lines, 3x3 squares, or other patterns, depending on the game mode. - You need to avoid filling up the grid with blocks that cannot be cleared. If there is no more space for new blocks, the game is over. - You need to score points by clearing lines or squares. The more lines or squares you clear at once, the more points you get. You may also get bonus points for clearing special blocks, using power-ups, or completing achievements. - You need to reach a certain score or level to win the game or advance to the next stage. You may also have a time limit or a move limit to complete the game or stage. <h3>Applying Some Tips and Tricks</h3>
95
- <p>The fifth and final step is to apply some tips and tricks to improve your skills and enjoyment of block puzzle games. Here are some tips and tricks that you can use:</p>
96
- <ul>
97
- <li>Plan ahead and think strategically. Before placing a block, look at the grid and see where it would fit best. Try to create as many lines or squares as possible with each block. Avoid placing blocks randomly or impulsively.</li>
98
- <li>Use power-ups wisely. Some block puzzle games have power-ups that can help you clear more blocks, change the shape or color of blocks, remove obstacles, or extend time. Use them when you are stuck or when you want to boost your score.</li>
99
- <li>Practice regularly and challenge yourself. The more you play block puzzle games, the better you will get at them. Practice different modes and levels to improve your speed, accuracy, and strategy. Challenge yourself by playing harder levels, setting higher goals, or competing with other players.</li>
100
- <li>Have fun and relax. Block puzzle games are meant to be fun and relaxing, not stressful or frustrating. Don't worry too much about your score or performance. Enjoy the process of solving puzzles and creating shapes with blocks. Take breaks when you feel tired or bored.</li>
101
- </ul>
102
- <h2>Conclusion</h2>
103
- <p>Block puzzle games are a great way to spend your free time and exercise your brain. They are simple yet addictive games that require you to fit different shapes of blocks on a grid, either horizontally or vertically, to clear lines or squares. They have various benefits, features, modes, and challenges that make them appealing and enjoyable for players of all ages and backgrounds.</p>
104
- <h3>Summary of the Main Points</h3>
105
- <p>In this article, we have covered:</p>
106
- <ul>
107
- <li>What are block puzzle games and how they originated and evolved.</li>
108
- <li>What benefits they offer for your cognitive skills, motor skills, stress relief, mood enhancement, and creativity.</li>
109
- <li>What features they have such as graphics, sounds, modes, levels, leaderboards, and achievements.</li>
110
- <li>How to download and play them on different platforms and devices.</li>
111
- <li>How to learn the rules and controls of different block puzzle games.</li>
112
- <li>How to apply some tips and tricks to improve your skills and enjoyment of block puzzle games.</li>
113
- </ul>
114
- <h3>Call to Action</h3>
115
- <p>If you are interested in playing block puzzle games, don't hesitate to download them from app stores or websites today. You can also play them online without downloading them by visiting websites such as Block Puzzle Online or Block Puzzle Games. You will find a wide range of block puzzle games that suit your taste and preference.</p>
116
- <p>Block puzzle games are fun, relaxing, and rewarding games that can improve your brain and well-being. They are easy to learn and play but hard to master and put down. They are perfect for killing time, relieving stress, boosting mood, stimulating creativity, and challenging yourself.</p>
117
- <p>So what are you waiting for? Download block puzzle indir now and start playing!</p>
118
- <h3>FAQs</h3>
119
- <p <p>Here are some frequently asked questions (FAQs) about block puzzle games:</p>
120
- <table>
121
- <tr>
122
- <th>Question</th>
123
- <th>Answer</th>
124
- </tr>
125
- <tr>
126
- <td>What is the difference between block puzzle games and Tetris?</td>
127
- <td>Tetris is a specific block puzzle game that involves falling blocks of four squares each that can be rotated and moved sideways to fit into a rectangular grid. Block puzzle games are a broader genre of puzzle games that involve different shapes of blocks that can be moved and rotated to fit into various grids or boards.</td>
128
- </tr>
129
- <tr>
130
- <td>What are some of the best block puzzle games for Android and iOS?</td>
131
- <td>Some of the best block puzzle games for Android and iOS are Blockudoku, Blockscapes, Woodoku, Block Blast Adventure Master, Blocks: Block Puzzle Games, and many more. You can download them from Google Play Store or Apple App Store.</td>
132
- </tr>
133
- <tr>
134
- <td>How can I play block puzzle games online without downloading them?</td>
135
- <td>You can play block puzzle games online without downloading them by visiting websites such as Block Puzzle Online or Block Puzzle Games. You can choose from different block puzzle games and play them on your web browser.</td>
136
- </tr>
137
- <tr>
138
- <td>How can I improve my skills and strategy in block puzzle games?</td>
139
- <td>You can improve your skills and strategy in block puzzle games by practicing regularly, challenging yourself, planning ahead, thinking strategically, using power-ups wisely, and having fun.</td>
140
- </tr>
141
- <tr>
142
- <td>Are block puzzle games suitable for children?</td>
143
- <td>Yes, block puzzle games are suitable for children as they are simple, fun, and educational. They can help children develop their cognitive skills, motor skills, creativity, and concentration. However, parents should supervise their children's screen time and game choices.</td>
144
- </tr>
145
- </table></p> 197e85843d<br />
146
- <br />
147
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Download Dark Bitcoin Miner Pro V7.0 and Join the Crypto Revolution..md DELETED
@@ -1,96 +0,0 @@
1
-
2
- <h1>Dark Bitcoin Miner Pro V7.0 Free Download: What You Need to Know</h1>
3
- <p>Bitcoin mining is a process of creating new bitcoins by solving complex mathematical problems using specialized hardware and software.</p>
4
- <p>There are many types of bitcoin mining software available in the market, but not all of them. <p>One of the most popular and controversial bitcoin mining software is dark bitcoin miner pro v7.0, which claims to be the fastest and most efficient bitcoin miner ever created.</p>
5
- <h2>dark bitcoin miner pro v7.0 free download</h2><br /><p><b><b>Download Zip</b> &#10042; <a href="https://urlin.us/2uSZFd">https://urlin.us/2uSZFd</a></b></p><br /><br />
6
- <p>But what is dark bitcoin miner pro v7.0, why is it so popular, and what are the risks of downloading it?</p>
7
- <p>In this article, we will answer these questions and more, and provide you with some alternatives to dark bitcoin miner pro v7.0 that are safer and more reliable.</p>
8
- <h2>What is Dark Bitcoin Miner Pro V7.0?</h2>
9
- <p>Dark bitcoin miner pro v7.0 is a bitcoin mining software that claims to be able to mine bitcoins using any device, such as CPU, GPU, ASIC, or FPGA.</p>
10
- <p>It also claims to be compatible with various algorithms, such as SHA-256, Scrypt, X11, Ethash, and Equihash, and to support multiple cryptocurrencies, such as Bitcoin, Litecoin, Dash, Ethereum, and Zcash.</p>
11
- <h3>How Does Dark Bitcoin Miner Pro V7.0 Work?</h3>
12
- <p>Dark bitcoin miner pro v7.0 works by using the device's processing power to solve complex mathematical problems that verify transactions on the blockchain.</p>
13
- <p>For every problem solved, the miner receives a reward in the form of newly created bitcoins or other cryptocurrencies.</p>
14
- <p>The more processing power the device has, the faster and more efficient the mining process is.</p>
15
- <h3>What are the Features of Dark Bitcoin Miner Pro V7.0?</h3>
16
- <p>Some of the features of dark bitcoin miner pro v7.0 are:</p>
17
- <p></p>
18
- <ul>
19
- <li>High speed: Dark bitcoin miner pro v7.0 claims to be able to mine bitcoins at a rate of up to 1 BTC per day, depending on the device and the algorithm used.</li>
20
- <li>Low power consumption: Dark bitcoin miner pro v7.0 claims to be able to mine bitcoins using only 10% of the device's power consumption, saving energy and money.</li>
21
- <li>Compatibility: Dark bitcoin miner pro v7.0 claims to be compatible with any device that has a processor, such as laptops, desktops, smartphones, tablets, or even smart TVs.</li>
22
- <li>Versatility: Dark bitcoin miner pro v7.0 claims to be able to mine any cryptocurrency that uses any algorithm, such as Bitcoin, Litecoin, Dash, Ethereum, or Zcash.</li>
23
- <li>User-friendly: Dark bitcoin miner pro v7.0 claims to be easy to install and use, with a simple interface and automatic settings.</li>
24
- </ul>
25
- <h2>Why is Dark Bitcoin Miner Pro V7.0 Popular?</h2>
26
- <p>Dark bitcoin miner pro v7.0 is popular because it appeals to many people who want to mine bitcoins without investing in expensive and complicated hardware or software.</p>
27
- <p>Many beginners and enthusiasts who are interested in bitcoin mining are attracted by the promises of dark bitcoin miner pro v7.0, such as high speed, low power consumption, compatibility, versatility, and user-friendliness.</p>
28
- <p>They also believe that dark bitcoin miner pro v7.0 is a free and easy way to earn bitcoins without any risk or effort.</p>
29
- <h3>How to Download Dark Bitcoin Miner Pro V7.0?</h3>
30
- <p>Dark bitcoin miner pro v7.0 is not available on any official or reputable website or platform.</p>
31
- <p>The only way to download dark bitcoin miner pro v7.0 is through unofficial and unverified sources, such as file-sharing websites, GitHub repositories, or Telegram channels.</p>
32
- <p>These sources are often unreliable and unsafe, as they may contain viruses, malware, spyware, or other harmful programs that can infect your device or steal your data.</p>
33
- <h3>How to Install and Use Dark Bitcoin Miner Pro V7.0?</h3>
34
- <p>If you decide to download dark bitcoin miner pro v7.0 from one of these sources, you will need to follow these steps to install and use it:</p>
35
- <ol>
36
- <li>Disable your antivirus program: Dark bitcoin miner pro v7.0 is detected as a malicious program by most antivirus programs, so you will need to disable your antivirus program before downloading or running it.</li>
37
- <li>Extract the rar file: Dark bitcoin miner pro v7.0 is usually compressed in a rar file that you will need to extract using a program like WinRAR or 7-Zip.</li>
38
- <li>Run the exe file: After extracting the rar file, you will find an exe file that you will need to run as administrator by right-clicking on it and selecting "Run as administrator".</li>
39
- <li>Configure the settings: After running the exe file, you will see a window that will allow you to configure the settings of dark bitcoin miner pro v7.0, such as the algorithm, the cryptocurrency, the wallet address, the mining pool, and the mining speed.</li>
40
- <li>Start mining: After configuring the settings, you will need to click on the "Start" button to start mining bitcoins or other cryptocurrencies with dark bitcoin miner pro v7.0.</li>
41
- </ol>
42
- <h2>What are the Risks of Downloading Dark Bitcoin Miner Pro V7.0?</h2>
43
- <p>Downloading dark bitcoin miner pro v7.0 is not only illegal, but also very risky.</p>
44
- <p>There are many dangers of downloading dark bitcoin miner pro v7.0, such as:</p>
45
- <h3>How to Detect and Remove Malware from Dark Bitcoin Miner Pro V7.0?</h3>
46
- <p>One of the most common and serious dangers of downloading dark bitcoin miner pro v7.0 is malware infection.</p>
47
- <p>Malware is a malicious software that can harm your device or data in various ways, such as deleting or encrypting your files, stealing your passwords or personal information, spying on your online activities, or hijacking your resources.</p>
48
- <p>Dark bitcoin miner pro v7.0 may contain malware that can infect your device when you download or run it, or even when you extract the rar file.</p>
49
- <p>To detect and remove malware from dark bitcoin miner pro v7.0, you will need to follow these steps:</p>
50
- <ol>
51
- <li>Use a malware scanner: A malware scanner is a program that can scan your device for any signs of malware infection, such as suspicious files, processes, or registry entries. You can use a reputable and reliable malware scanner, such as Malwarebytes, to scan your device and remove any malware that it finds.</li>
52
- <li>Delete suspicious files: If you suspect that dark bitcoin miner pro v7.0 has infected your device with malware, you should delete any suspicious files that are related to it, such as the rar file, the exe file, or any other files that have been created or modified by it.</li>
53
- <li>Restore your system: If deleting suspicious files does not solve the problem, you may need to restore your system to a previous state before you downloaded or ran dark bitcoin miner pro v7.0. You can use a system restore point or a backup to restore your system and undo any changes that dark bitcoin miner pro v7.0 may have made.</li>
54
- </ol>
55
- <h3>How to Avoid Legal Issues from Using Dark Bitcoin Miner Pro V7.0?</h3>
56
- <p>Another danger of downloading dark bitcoin miner pro v7.0 is legal issues.</p>
57
- <p>Legal issues are the problems that may arise from breaking the law by using dark bitcoin miner pro v7.0, such as violating the intellectual property rights of the original developers of the software, infringing the terms and conditions of the mining pools or platforms that you use, or engaging in illegal or fraudulent activities with the cryptocurrencies that you mine.</p>
58
- <p>To avoid legal issues from using dark bitcoin miner pro v7.0, you will need to follow these precautions:</p>
59
- <ul>
60
- <li>Check the local laws: Before downloading or using dark bitcoin miner pro v7.0, you should check the local laws of your country or region regarding bitcoin mining and cryptocurrency transactions. Some countries or regions may have strict regulations or prohibitions on these activities, and you may face legal consequences if you violate them.</li>
61
- <li>Use a VPN: A VPN is a virtual private network that can hide your IP address and encrypt your online traffic, making it harder for anyone to track or monitor your online activities. You can use a VPN to protect your privacy and anonymity when using dark bitcoin miner pro v7.0, and to bypass any geo-restrictions or censorship that may prevent you from accessing certain websites or platforms.</li>
62
- <li>Do not disclose personal information: When using dark bitcoin miner pro v7.0, you should not disclose any personal information that can identify you or link you to your activities, such as your name, email address, phone number, bank account number, or social media accounts. You should also avoid using the same wallet address for different transactions, and use a mixer service to anonymize your transactions.</li>
63
- </ul>
64
- <h2>What are the Alternatives to Dark Bitcoin Miner Pro V7.0?</h2>
65
- <p>If you want to mine bitcoins or other cryptocurrencies without risking your device, data, or reputation, you should avoid downloading dark bitcoin miner pro v7.0 and look for some alternatives that are safer and more reliable.</p>
66
- <p>Some of the alternatives to dark bitcoin miner pro v7.0 are:</p>
67
- <h3>How to Choose the Best Alternative to Dark Bitcoin Miner Pro V7.0?</h3>
68
- <p>To choose the best alternative to dark bitcoin miner pro v7.0, you should consider some criteria that can help you evaluate the quality and suitability of the software, such as:</p>
69
- <ul>
70
- <li>Security: The software should be secure and free from any malware, spyware, or viruses that can harm your device or data.</li>
71
- <li>Performance: The software should be fast and efficient, and able to mine bitcoins or other cryptocurrencies at a reasonable rate and with minimal power consumption.</li>
72
- <li>Cost: The software should be affordable and transparent, and not charge any hidden fees or commissions for using it.</li>
73
- <li>Reputation: The software should be reputable and trustworthy, and have positive reviews and feedback from other users and experts.</li>
74
- </ul>
75
- <h3>How to Compare the Alternatives to Dark Bitcoin Miner Pro V7.0?</h3>
76
- <p>To compare the alternatives to dark bitcoin miner pro v7.0 based on the criteria mentioned above, you can use a table like this one:</p>
77
- | Software | Security | Performance | Cost | Reputation | | -------- | -------- | ----------- | ---- | ---------- | | CGMiner | High: Open-source and widely used by miners. | High: Supports various devices and algorithms. | Low: Free to download and use. | High: One of the oldest and most popular mining software. | | NiceHash | Medium: Has been hacked in the past, but has improved its security measures. | Medium: Depends on the market demand and supply of hashing power. | Medium: Charges a small fee for using its service. | Medium: Has a large user base and a good customer support. | | Genesis Mining | High: Uses advanced encryption and security protocols. | Low: Limited by the contracts and plans available. | High: Requires a upfront payment and a maintenance fee. | High: One of the leading cloud mining providers with a good reputation. | | Slush Pool | High: Uses a secure connection and a unique voting system. | Medium: Depends on the pool size and the difficulty level. | Low: Charges a 2% fee for using its service. | High: The first and one of the largest mining pools in the world. | <h2>Conclusion</h2>
78
- <p>In conclusion, dark bitcoin miner pro v7.0 is a bitcoin mining software that claims to be able to mine bitcoins using any device, algorithm, or cryptocurrency.</p>
79
- <p>However, dark bitcoin miner pro v7.0 is also illegal, risky, and unreliable, as it may contain malware, steal your data, damage your device, or cause legal issues.</p>
80
- <p>Therefore, you should avoid downloading dark bitcoin miner pro v7.0 and look for some alternatives that are safer and more reliable, such as legitimate mining software, cloud mining services, or mining pools.</p>
81
- <h3>FAQs</h3>
82
- <p>Here are some frequently asked questions related to the topic of this article:</p>
83
- <ol>
84
- <li><b>Is dark bitcoin miner pro v7.0 a scam?</b></li>
85
- <p>Yes, dark bitcoin miner pro v7.0 is a scam that tries to lure unsuspecting users into downloading malware or giving away their personal information.</p>
86
- <li><b>How much can I earn with dark bitcoin miner pro v7.0?</b></li>
87
- <p>You cannot earn anything with dark bitcoin miner pro v7.0, as it does not actually mine bitcoins or other cryptocurrencies.</p>
88
- <li><b>Is dark bitcoin miner pro v7.0 safe to use?</b></li>
89
- <p>No, dark bitcoin miner pro v7.0 is not safe to use, as it may infect your device with malware, steal your data, damage your device, or cause legal issues.</p>
90
- <li><b>What are the best devices for dark bitcoin miner pro v7.0?</b></li>
91
- <p>There are no best devices for dark bitcoin miner pro v7.0, as it does not work on any device.</p>
92
- <li><b>How can I contact the developers of dark bitcoin miner pro v7.0?</b></li>
93
- <p>You cannot contact the developers of dark bitcoin miner pro v7.0, as they are anonymous and untraceable.</p>
94
- </ol></p> 197e85843d<br />
95
- <br />
96
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download GTA 3 1.1 Ultimate Trainer V3 5 and Unlock All Features in Grand Theft Auto III.md DELETED
@@ -1,98 +0,0 @@
1
-
2
- <h1>How to Download GTA 3 1.1 Ultimate Trainer v3 5</h1>
3
- <p>If you are a fan of Grand Theft Auto III, you may have heard of GTA 3 1.1 Ultimate Trainer v3 5, a powerful tool that allows you to customize and enhance your gameplay experience. With this trainer, you can access dozens of cheats and options that will make your game more fun and exciting. In this article, we will show you how to download, install, and use GTA 3 1.1 Ultimate Trainer v3 5.</p>
4
- <h2>What is GTA 3 1.1 Ultimate Trainer v3 5?</h2>
5
- <p>GTA 3 1.1 Ultimate Trainer v3 5 is a mod for Grand Theft Auto III that adds a menu with various cheats and options that you can activate or deactivate at any time during the game. You can use this trainer to change your character's appearance, spawn vehicles and weapons, manipulate the weather and time, increase your health and money, and much more.</p>
6
- <h2>download gta 3 1.1 ultimate trainer v3 5</h2><br /><p><b><b>DOWNLOAD</b> &#10026; <a href="https://jinyurl.com/2uNMxJ">https://jinyurl.com/2uNMxJ</a></b></p><br /><br />
7
- <h3>Features of GTA 3 1.1 Ultimate Trainer v3 5</h3>
8
- <p>Some of the features of GTA 3 1.1 Ultimate Trainer v3 5 are:</p>
9
- <ul>
10
- <li>43 cheats and options, including infinite health, ammo, armor, money, no police, no damage, flying cars, super speed, etc.</li>
11
- <li>A customizable hotkey system that lets you assign any key to any cheat or option.</li>
12
- <li>A savegame editor that lets you modify your save files with ease.</li>
13
- <li>A screenshot function that lets you capture your gameplay moments.</li>
14
- <li>A teleport function that lets you move to any location on the map.</li>
15
- <li>A vehicle spawner that lets you spawn any vehicle in the game.</li>
16
- <li>A weapon spawner that lets you spawn any weapon in the game.</li>
17
- <li>A skin selector that lets you change your character's appearance.</li>
18
- <li>A weather selector that lets you change the weather and time in the game.</li>
19
- <li>A stats editor that lets you modify your character's stats and skills.</li>
20
- <li>A garage editor that lets you customize your vehicles.</li>
21
- <li>A mission selector that lets you skip or replay any mission in the game.</li>
22
- </ul>
23
- <h3>Requirements for GTA 3 1.1 Ultimate Trainer v3 5</h3>
24
- <p>To use GTA 3 1.1 Ultimate Trainer v3 5, you need:</p>
25
- <ul>
26
- <li>A PC with Windows XP or higher.</li>
27
- <li>Grand Theft Auto III version 1.1 installed on your PC.</li>
28
- <li>WinRAR or any other program that can extract ZIP files.</li>
29
- </ul>
30
- <h2>Where to Download GTA 3 1.1 Ultimate Trainer v3 5?</h2>
31
- <p>You can download GTA 3 1.1 Ultimate Trainer v3 5 from various websites that host mods for Grand Theft Auto III. Here are two of the most popular ones:</p>
32
- <h3>Download from GameFront[^<a href="(^i^)">i</a>] </h4>
33
- <p>GameFront is a website that offers free downloads of mods, patches, demos, and other files for various games. You can download GTA 3 1.1 Ultimate Trainer v3 from this link:</p>
34
- <a href <a href="">https://www.gamefront.com/games/grand-theft-auto-3/file/gta-3-ultimate-trainer</a>
35
- <p>The file size is 222 KB and the download speed depends on your internet connection. To download the file, you need to click on the "Download Now" button and wait for the countdown to finish. Then, you need to click on the "Download" button again and save the file to your PC.</p>
36
- <h3>Download from MegaGames[^<a href="(^i^)">i</a>]</h3>
37
- <p>MegaGames is another website that offers free downloads of mods, patches, trainers, and other files for various games. You can download GTA 3 1.1 Ultimate Trainer v3 5 from this link:</p>
38
- <a href="">https://megagames.com/trainers/grand-theft-auto-3-v11-ultimate-trainer-v35</a>
39
- <p>The file size is 223 KB and the download speed depends on your internet connection. To download the file, you need to click on the "Download" button and save the file to your PC.</p>
40
- <p>How to install gta 3 ultimate trainer v3 5 on pc<br />
41
- Gta 3 ultimate trainer v3 5 cheats and codes<br />
42
- Gta 3 ultimate trainer v3 5 free download full version<br />
43
- Gta 3 ultimate trainer v3 5 mod menu and features<br />
44
- Gta 3 ultimate trainer v3 5 download link and instructions<br />
45
- Gta 3 ultimate trainer v3 5 gameplay and review<br />
46
- Gta 3 ultimate trainer v3 5 compatible with windows 10<br />
47
- Gta 3 ultimate trainer v3 5 best settings and options<br />
48
- Gta 3 ultimate trainer v3 5 unlimited money and health<br />
49
- Gta 3 ultimate trainer v3 5 no virus and no survey<br />
50
- Gta 3 ultimate trainer v3 5 latest update and patch<br />
51
- Gta 3 ultimate trainer v3 5 online multiplayer and co-op<br />
52
- Gta 3 ultimate trainer v3 5 system requirements and specifications<br />
53
- Gta 3 ultimate trainer v3 5 tips and tricks<br />
54
- Gta 3 ultimate trainer v3 5 error fix and troubleshooting<br />
55
- Gta 3 ultimate trainer v3 5 backup and restore<br />
56
- Gta 3 ultimate trainer v3 5 custom missions and maps<br />
57
- Gta 3 ultimate trainer v3 5 hidden secrets and easter eggs<br />
58
- Gta 3 ultimate trainer v3 5 fun and funny moments<br />
59
- Gta 3 ultimate trainer v3 5 comparison with other trainers<br />
60
- Gta 3 ultimate trainer v3 5 pros and cons<br />
61
- Gta 3 ultimate trainer v3 5 download size and speed<br />
62
- Gta 3 ultimate trainer v3 5 support and feedback<br />
63
- Gta 3 ultimate trainer v3 5 alternatives and similar trainers<br />
64
- Gta 3 ultimate trainer v3 5 guide and tutorial</p>
65
- <h2>How to Install GTA 3 1.1 Ultimate Trainer v3 5?</h2>
66
- <p>After you have downloaded GTA 3 1.1 Ultimate Trainer v3 5 from one of the websites above, you need to install it on your PC. The installation process is very simple and straightforward. Here are the steps you need to follow:</p>
67
- <h3>Extract the files to your GTA 3 folder</h3>
68
- <p>The file you have downloaded is a ZIP file that contains several files and folders. You need to extract them to your GTA 3 folder, which is usually located at C:\Program Files\Rockstar Games\GTAIII. To do this, you need to use WinRAR or any other program that can extract ZIP files. Right-click on the ZIP file and select "Extract Here" or "Extract to GTA_3_Ultimate_Trainer_v3_5". This will create a new folder with the same name as the ZIP file. Open this folder and copy all the files and folders inside it to your GTA 3 folder. You may need to overwrite some existing files, so make sure you have a backup of your original files in case something goes wrong.</p>
69
- <h3>Run the trainer and select the options you want</h3>
70
- <p>After you have copied the files to your GTA 3 folder, you can run the trainer by double-clicking on the GTA_III_Ultimate_Trainer_v35.exe file. This will open a window with a menu that shows all the cheats and options available in the trainer. You can use your mouse or keyboard to navigate through the menu and select the options you want. You can also customize the hotkeys for each option by clicking on the "Hotkeys" button at the bottom of the window. You can save your settings by clicking on the "Save Settings" button at the top of the window.</p>
71
- <h2>How to Use GTA 3 1.1 Ultimate Trainer v3 5?</h2>
72
- <p>Once you have installed and run GTA 3 1.1 Ultimate Trainer v3 5, you can use it to enhance your gameplay experience in Grand Theft Auto III. Here are some tips on how to use it:</p>
73
- <h3>Press F12 to activate the trainer</h3>
74
- <p>The trainer works in the background while you play GTA 3. To activate it, you need to press F12 on your keyboard. This will bring up a small window at the top left corner of your screen that shows the status of the trainer and some information about your game. You can press F12 again to hide this window.</p>
75
- <h3>Use the keyboard shortcuts to toggle the cheats</h3>
76
- <p>To use any of the cheats or options in the trainer, you need to press the corresponding keyboard shortcut that you have assigned in the menu. For example, if you want to activate infinite health, you need to press H on your keyboard. You will hear a sound and see a message on your screen that confirms that the cheat is activated or deactivated. You can also see which cheats are active by looking at the small window that appears when you press F12.</p> <h2>Tips and Tricks for GTA 3 1.1 Ultimate Trainer v3 5</h2>
77
- <p>GTA 3 1.1 Ultimate Trainer v3 5 is a great tool that can make your game more enjoyable and easier, but it also comes with some risks and limitations. Here are some tips and tricks that can help you use it safely and effectively:</p>
78
- <h3>Save your game before using the trainer</h3>
79
- <p>Using the trainer can sometimes cause glitches or crashes in your game, especially if you use too many cheats at once or change some settings that are not compatible with your game version. To avoid losing your progress or corrupting your save files, you should always save your game before using the trainer. You can use the savegame editor in the trainer to create multiple save slots and backup your saves.</p>
80
- <h3>Be careful with some cheats that may cause glitches or crashes</h3>
81
- <p>Some of the cheats and options in the trainer may have unintended consequences or side effects that can affect your game performance or stability. For example, using the flying cars cheat may cause your car to fly out of the map or get stuck in the air. Using the super speed cheat may make your game run too fast or slow down. Using the no police cheat may prevent you from completing some missions that require you to get a wanted level. You should use these cheats with caution and turn them off when you don't need them.</p>
82
- <h2>Conclusion</h2>
83
- <p>GTA 3 1.1 Ultimate Trainer v3 5 is a mod that adds a menu with various cheats and options that you can use to customize and enhance your gameplay experience in Grand Theft Auto III. You can download it from various websites that host mods for GTA 3, and install it by extracting the files to your GTA 3 folder. You can activate it by pressing F12 and use the keyboard shortcuts to toggle the cheats and options. You can also use the menu to change your hotkeys, edit your save files, take screenshots, teleport, spawn vehicles and weapons, change your skin, weather, stats, garage, and missions. However, you should also be careful with some cheats that may cause glitches or crashes in your game, and save your game before using the trainer.</p>
84
- <h2>FAQs</h2>
85
- <p>Here are some of the frequently asked questions about GTA 3 1.1 Ultimate Trainer v3 5:</p>
86
- <h4>Q: Does GTA 3 1.1 Ultimate Trainer v3 5 work with other mods?</h4>
87
- <p>A: GTA 3 1.1 Ultimate Trainer v3 5 may work with some other mods that do not modify the same files or features as the trainer. However, it may also cause conflicts or compatibility issues with some mods that do modify the same files or features as the trainer. You should always check the readme files or descriptions of the mods you want to use with the trainer, and make sure they are compatible with each other.</p>
88
- <h4>Q: Does GTA 3 1.1 Ultimate Trainer v3 5 work with Steam version of GTA 3?</h4>
89
- <p>A: GTA 3 1.1 Ultimate Trainer v3 5 works with Steam version of GTA 3, but you need to downgrade your game to version 1.1 first. The Steam version of GTA 3 is version 1.0, which is not compatible with the trainer. You can use a patch or a tool to downgrade your game to version 1.1, which you can find online.</p>
90
- <h4>Q: How do I uninstall GTA 3 1.1 Ultimate Trainer v3 5?</h4>
91
- <p>A: To uninstall GTA 3 1.1 Ultimate Trainer v3 5, you need to delete all the files and folders that you have copied to your GTA 3 folder when you installed the trainer. You may also need to restore your original files if you have overwritten them with the trainer files.</p>
92
- <h4>Q: Where can I find more information about GTA 3 1.1 Ultimate Trainer v3 5?</h4>
93
- <p>A: You can find more information about GTA 3 1.1 Ultimate Trainer v3 5 on the websites where you downloaded it from, or on the forums or communities dedicated to GTA mods. You can also contact the author of the trainer, LithJoe, if you have any questions or feedback.</p>
94
- <h4>Q: Is GTA 3 1.1 Ultimate Trainer v3 5 safe to use?</h4>
95
- <p>A: GTA 3 1.1 Ultimate Trainer v3 is safe to use as long as you download it from a trusted source and scan it for viruses or malware before installing it on your PC. However, you should also be aware that using any mod or trainer may affect your game performance or stability <p>or stability, and that using some cheats or options may be considered cheating or unfair by some players or online servers. You should use the trainer at your own risk and discretion, and respect the rules and preferences of other players and servers.</p>
96
- <p>I hope this article has helped you learn how to download, install, and use GTA 3 1.1 Ultimate Trainer v3 5. If you have any comments or questions, feel free to leave them below. Happy gaming!</p> 401be4b1e0<br />
97
- <br />
98
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/3mrology/Chameleon_Text2Img_Generation_Demo/README.md DELETED
@@ -1,14 +0,0 @@
1
- ---
2
- title: Chameleon Text2Image Demo
3
- emoji: 🦎
4
- colorFrom: green
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 3.12.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- duplicated_from: huggingface-projects/magic-diffusion
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/7hao/bingo/tests/parse.ts DELETED
@@ -1,13 +0,0 @@
1
- import { promises as fs } from 'fs'
2
- import { join } from 'path'
3
- import { parseHeadersFromCurl } from '@/lib/utils'
4
-
5
- (async () => {
6
- const content = await fs.readFile(join(__dirname, './fixtures/curl.txt'), 'utf-8')
7
- const headers = parseHeadersFromCurl(content)
8
- console.log(headers)
9
-
10
- const cmdContent = await fs.readFile(join(__dirname, './fixtures/cmd.txt'), 'utf-8')
11
- const cmdHeaders = parseHeadersFromCurl(cmdContent)
12
- console.log(cmdHeaders)
13
- })()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/801artistry/RVC801/mdx.py DELETED
@@ -1,228 +0,0 @@
1
- import torch
2
- import onnxruntime as ort
3
- from tqdm import tqdm
4
- import warnings
5
- import numpy as np
6
- import hashlib
7
- import queue
8
- import threading
9
-
10
- warnings.filterwarnings("ignore")
11
-
12
- class MDX_Model:
13
- def __init__(self, device, dim_f, dim_t, n_fft, hop=1024, stem_name=None, compensation=1.000):
14
- self.dim_f = dim_f
15
- self.dim_t = dim_t
16
- self.dim_c = 4
17
- self.n_fft = n_fft
18
- self.hop = hop
19
- self.stem_name = stem_name
20
- self.compensation = compensation
21
-
22
- self.n_bins = self.n_fft//2+1
23
- self.chunk_size = hop * (self.dim_t-1)
24
- self.window = torch.hann_window(window_length=self.n_fft, periodic=True).to(device)
25
-
26
- out_c = self.dim_c
27
-
28
- self.freq_pad = torch.zeros([1, out_c, self.n_bins-self.dim_f, self.dim_t]).to(device)
29
-
30
- def stft(self, x):
31
- x = x.reshape([-1, self.chunk_size])
32
- x = torch.stft(x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True, return_complex=True)
33
- x = torch.view_as_real(x)
34
- x = x.permute([0,3,1,2])
35
- x = x.reshape([-1,2,2,self.n_bins,self.dim_t]).reshape([-1,4,self.n_bins,self.dim_t])
36
- return x[:,:,:self.dim_f]
37
-
38
- def istft(self, x, freq_pad=None):
39
- freq_pad = self.freq_pad.repeat([x.shape[0],1,1,1]) if freq_pad is None else freq_pad
40
- x = torch.cat([x, freq_pad], -2)
41
- # c = 4*2 if self.target_name=='*' else 2
42
- x = x.reshape([-1,2,2,self.n_bins,self.dim_t]).reshape([-1,2,self.n_bins,self.dim_t])
43
- x = x.permute([0,2,3,1])
44
- x = x.contiguous()
45
- x = torch.view_as_complex(x)
46
- x = torch.istft(x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True)
47
- return x.reshape([-1,2,self.chunk_size])
48
-
49
-
50
- class MDX:
51
-
52
- DEFAULT_SR = 44100
53
- # Unit: seconds
54
- DEFAULT_CHUNK_SIZE = 0 * DEFAULT_SR
55
- DEFAULT_MARGIN_SIZE = 1 * DEFAULT_SR
56
-
57
- DEFAULT_PROCESSOR = 0
58
-
59
- def __init__(self, model_path:str, params:MDX_Model, processor=DEFAULT_PROCESSOR):
60
-
61
- # Set the device and the provider (CPU or CUDA)
62
- self.device = torch.device(f'cuda:{processor}') if processor >= 0 else torch.device('cpu')
63
- self.provider = ['CUDAExecutionProvider'] if processor >= 0 else ['CPUExecutionProvider']
64
-
65
- self.model = params
66
-
67
- # Load the ONNX model using ONNX Runtime
68
- self.ort = ort.InferenceSession(model_path, providers=self.provider)
69
- # Preload the model for faster performance
70
- self.ort.run(None, {'input':torch.rand(1, 4, params.dim_f, params.dim_t).numpy()})
71
- self.process = lambda spec:self.ort.run(None, {'input': spec.cpu().numpy()})[0]
72
-
73
- self.prog = None
74
-
75
- @staticmethod
76
- def get_hash(model_path):
77
- try:
78
- with open(model_path, 'rb') as f:
79
- f.seek(- 10000 * 1024, 2)
80
- model_hash = hashlib.md5(f.read()).hexdigest()
81
- except:
82
- model_hash = hashlib.md5(open(model_path,'rb').read()).hexdigest()
83
-
84
- return model_hash
85
-
86
- @staticmethod
87
- def segment(wave, combine=True, chunk_size=DEFAULT_CHUNK_SIZE, margin_size=DEFAULT_MARGIN_SIZE):
88
- """
89
- Segment or join segmented wave array
90
-
91
- Args:
92
- wave: (np.array) Wave array to be segmented or joined
93
- combine: (bool) If True, combines segmented wave array. If False, segments wave array.
94
- chunk_size: (int) Size of each segment (in samples)
95
- margin_size: (int) Size of margin between segments (in samples)
96
-
97
- Returns:
98
- numpy array: Segmented or joined wave array
99
- """
100
-
101
- if combine:
102
- processed_wave = None # Initializing as None instead of [] for later numpy array concatenation
103
- for segment_count, segment in enumerate(wave):
104
- start = 0 if segment_count == 0 else margin_size
105
- end = None if segment_count == len(wave)-1 else -margin_size
106
- if margin_size == 0:
107
- end = None
108
- if processed_wave is None: # Create array for first segment
109
- processed_wave = segment[:, start:end]
110
- else: # Concatenate to existing array for subsequent segments
111
- processed_wave = np.concatenate((processed_wave, segment[:, start:end]), axis=-1)
112
-
113
- else:
114
- processed_wave = []
115
- sample_count = wave.shape[-1]
116
-
117
- if chunk_size <= 0 or chunk_size > sample_count:
118
- chunk_size = sample_count
119
-
120
- if margin_size > chunk_size:
121
- margin_size = chunk_size
122
-
123
- for segment_count, skip in enumerate(range(0, sample_count, chunk_size)):
124
-
125
- margin = 0 if segment_count == 0 else margin_size
126
- end = min(skip+chunk_size+margin_size, sample_count)
127
- start = skip-margin
128
-
129
- cut = wave[:,start:end].copy()
130
- processed_wave.append(cut)
131
-
132
- if end == sample_count:
133
- break
134
-
135
- return processed_wave
136
-
137
- def pad_wave(self, wave):
138
- """
139
- Pad the wave array to match the required chunk size
140
-
141
- Args:
142
- wave: (np.array) Wave array to be padded
143
-
144
- Returns:
145
- tuple: (padded_wave, pad, trim)
146
- - padded_wave: Padded wave array
147
- - pad: Number of samples that were padded
148
- - trim: Number of samples that were trimmed
149
- """
150
- n_sample = wave.shape[1]
151
- trim = self.model.n_fft//2
152
- gen_size = self.model.chunk_size-2*trim
153
- pad = gen_size - n_sample%gen_size
154
-
155
- # Padded wave
156
- wave_p = np.concatenate((np.zeros((2,trim)), wave, np.zeros((2,pad)), np.zeros((2,trim))), 1)
157
-
158
- mix_waves = []
159
- for i in range(0, n_sample+pad, gen_size):
160
- waves = np.array(wave_p[:, i:i+self.model.chunk_size])
161
- mix_waves.append(waves)
162
-
163
- mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to(self.device)
164
-
165
- return mix_waves, pad, trim
166
-
167
- def _process_wave(self, mix_waves, trim, pad, q:queue.Queue, _id:int):
168
- """
169
- Process each wave segment in a multi-threaded environment
170
-
171
- Args:
172
- mix_waves: (torch.Tensor) Wave segments to be processed
173
- trim: (int) Number of samples trimmed during padding
174
- pad: (int) Number of samples padded during padding
175
- q: (queue.Queue) Queue to hold the processed wave segments
176
- _id: (int) Identifier of the processed wave segment
177
-
178
- Returns:
179
- numpy array: Processed wave segment
180
- """
181
- mix_waves = mix_waves.split(1)
182
- with torch.no_grad():
183
- pw = []
184
- for mix_wave in mix_waves:
185
- self.prog.update()
186
- spec = self.model.stft(mix_wave)
187
- processed_spec = torch.tensor(self.process(spec))
188
- processed_wav = self.model.istft(processed_spec.to(self.device))
189
- processed_wav = processed_wav[:,:,trim:-trim].transpose(0,1).reshape(2, -1).cpu().numpy()
190
- pw.append(processed_wav)
191
- processed_signal = np.concatenate(pw, axis=-1)[:, :-pad]
192
- q.put({_id:processed_signal})
193
- return processed_signal
194
-
195
- def process_wave(self, wave:np.array, mt_threads=1):
196
- """
197
- Process the wave array in a multi-threaded environment
198
-
199
- Args:
200
- wave: (np.array) Wave array to be processed
201
- mt_threads: (int) Number of threads to be used for processing
202
-
203
- Returns:
204
- numpy array: Processed wave array
205
- """
206
- self.prog = tqdm(total=0)
207
- chunk = wave.shape[-1]//mt_threads
208
- waves = self.segment(wave, False, chunk)
209
-
210
- # Create a queue to hold the processed wave segments
211
- q = queue.Queue()
212
- threads = []
213
- for c, batch in enumerate(waves):
214
- mix_waves, pad, trim = self.pad_wave(batch)
215
- self.prog.total = len(mix_waves)*mt_threads
216
- thread = threading.Thread(target=self._process_wave, args=(mix_waves, trim, pad, q, c))
217
- thread.start()
218
- threads.append(thread)
219
- for thread in threads:
220
- thread.join()
221
- self.prog.close()
222
-
223
- processed_batches = []
224
- while not q.empty():
225
- processed_batches.append(q.get())
226
- processed_batches = [list(wave.values())[0] for wave in sorted(processed_batches, key=lambda d: list(d.keys())[0])]
227
- assert len(processed_batches) == len(waves), 'Incomplete processed batches, please reduce batch size!'
228
- return self.segment(processed_batches, True, chunk)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/801artistry/RVC801/tools/infer_batch_rvc.py DELETED
@@ -1,72 +0,0 @@
1
- import argparse
2
- import os
3
- import sys
4
-
5
- print("Command-line arguments:", sys.argv)
6
-
7
- now_dir = os.getcwd()
8
- sys.path.append(now_dir)
9
- import sys
10
-
11
- import tqdm as tq
12
- from dotenv import load_dotenv
13
- from scipy.io import wavfile
14
-
15
- from configs.config import Config
16
- from infer.modules.vc.modules import VC
17
-
18
-
19
- def arg_parse() -> tuple:
20
- parser = argparse.ArgumentParser()
21
- parser.add_argument("--f0up_key", type=int, default=0)
22
- parser.add_argument("--input_path", type=str, help="input path")
23
- parser.add_argument("--index_path", type=str, help="index path")
24
- parser.add_argument("--f0method", type=str, default="harvest", help="harvest or pm")
25
- parser.add_argument("--opt_path", type=str, help="opt path")
26
- parser.add_argument("--model_name", type=str, help="store in assets/weight_root")
27
- parser.add_argument("--index_rate", type=float, default=0.66, help="index rate")
28
- parser.add_argument("--device", type=str, help="device")
29
- parser.add_argument("--is_half", type=bool, help="use half -> True")
30
- parser.add_argument("--filter_radius", type=int, default=3, help="filter radius")
31
- parser.add_argument("--resample_sr", type=int, default=0, help="resample sr")
32
- parser.add_argument("--rms_mix_rate", type=float, default=1, help="rms mix rate")
33
- parser.add_argument("--protect", type=float, default=0.33, help="protect")
34
-
35
- args = parser.parse_args()
36
- sys.argv = sys.argv[:1]
37
-
38
- return args
39
-
40
-
41
- def main():
42
- load_dotenv()
43
- args = arg_parse()
44
- config = Config()
45
- config.device = args.device if args.device else config.device
46
- config.is_half = args.is_half if args.is_half else config.is_half
47
- vc = VC(config)
48
- vc.get_vc(args.model_name)
49
- audios = os.listdir(args.input_path)
50
- for file in tq.tqdm(audios):
51
- if file.endswith(".wav"):
52
- file_path = os.path.join(args.input_path, file)
53
- _, wav_opt = vc.vc_single(
54
- 0,
55
- file_path,
56
- args.f0up_key,
57
- None,
58
- args.f0method,
59
- args.index_path,
60
- None,
61
- args.index_rate,
62
- args.filter_radius,
63
- args.resample_sr,
64
- args.rms_mix_rate,
65
- args.protect,
66
- )
67
- out_path = os.path.join(args.opt_path, file)
68
- wavfile.write(out_path, wav_opt[0], wav_opt[1])
69
-
70
-
71
- if __name__ == "__main__":
72
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIConsultant/MusicGen/scripts/mos.py DELETED
@@ -1,286 +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
-
8
- """
9
- To run this script, from the root of the repo. Make sure to have Flask installed
10
-
11
- FLASK_DEBUG=1 FLASK_APP=scripts.mos flask run -p 4567
12
- # or if you have gunicorn
13
- gunicorn -w 4 -b 127.0.0.1:8895 -t 120 'scripts.mos:app' --access-logfile -
14
-
15
- """
16
- from collections import defaultdict
17
- from functools import wraps
18
- from hashlib import sha1
19
- import json
20
- import math
21
- from pathlib import Path
22
- import random
23
- import typing as tp
24
-
25
- from flask import Flask, redirect, render_template, request, session, url_for
26
-
27
- from audiocraft import train
28
- from audiocraft.utils.samples.manager import get_samples_for_xps
29
-
30
-
31
- SAMPLES_PER_PAGE = 8
32
- MAX_RATING = 5
33
- storage = Path(train.main.dora.dir / 'mos_storage')
34
- storage.mkdir(exist_ok=True)
35
- surveys = storage / 'surveys'
36
- surveys.mkdir(exist_ok=True)
37
- magma_root = Path(train.__file__).parent.parent
38
- app = Flask('mos', static_folder=str(magma_root / 'scripts/static'),
39
- template_folder=str(magma_root / 'scripts/templates'))
40
- app.secret_key = b'audiocraft makes the best songs'
41
-
42
-
43
- def normalize_path(path: Path):
44
- """Just to make path a bit nicer, make them relative to the Dora root dir.
45
- """
46
- path = path.resolve()
47
- dora_dir = train.main.dora.dir.resolve() / 'xps'
48
- return path.relative_to(dora_dir)
49
-
50
-
51
- def get_full_path(normalized_path: Path):
52
- """Revert `normalize_path`.
53
- """
54
- return train.main.dora.dir.resolve() / 'xps' / normalized_path
55
-
56
-
57
- def get_signature(xps: tp.List[str]):
58
- """Return a signature for a list of XP signatures.
59
- """
60
- return sha1(json.dumps(xps).encode()).hexdigest()[:10]
61
-
62
-
63
- def ensure_logged(func):
64
- """Ensure user is logged in.
65
- """
66
- @wraps(func)
67
- def _wrapped(*args, **kwargs):
68
- user = session.get('user')
69
- if user is None:
70
- return redirect(url_for('login', redirect_to=request.url))
71
- return func(*args, **kwargs)
72
- return _wrapped
73
-
74
-
75
- @app.route('/login', methods=['GET', 'POST'])
76
- def login():
77
- """Login user if not already, then redirect.
78
- """
79
- user = session.get('user')
80
- if user is None:
81
- error = None
82
- if request.method == 'POST':
83
- user = request.form['user']
84
- if not user:
85
- error = 'User cannot be empty'
86
- if user is None or error:
87
- return render_template('login.html', error=error)
88
- assert user
89
- session['user'] = user
90
- redirect_to = request.args.get('redirect_to')
91
- if redirect_to is None:
92
- redirect_to = url_for('index')
93
- return redirect(redirect_to)
94
-
95
-
96
- @app.route('/', methods=['GET', 'POST'])
97
- @ensure_logged
98
- def index():
99
- """Offer to create a new study.
100
- """
101
- errors = []
102
- if request.method == 'POST':
103
- xps_or_grids = [part.strip() for part in request.form['xps'].split()]
104
- xps = set()
105
- for xp_or_grid in xps_or_grids:
106
- xp_path = train.main.dora.dir / 'xps' / xp_or_grid
107
- if xp_path.exists():
108
- xps.add(xp_or_grid)
109
- continue
110
- grid_path = train.main.dora.dir / 'grids' / xp_or_grid
111
- if grid_path.exists():
112
- for child in grid_path.iterdir():
113
- if child.is_symlink():
114
- xps.add(child.name)
115
- continue
116
- errors.append(f'{xp_or_grid} is neither an XP nor a grid!')
117
- assert xps or errors
118
- blind = 'true' if request.form.get('blind') == 'on' else 'false'
119
- xps = list(xps)
120
- if not errors:
121
- signature = get_signature(xps)
122
- manifest = {
123
- 'xps': xps,
124
- }
125
- survey_path = surveys / signature
126
- survey_path.mkdir(exist_ok=True)
127
- with open(survey_path / 'manifest.json', 'w') as f:
128
- json.dump(manifest, f, indent=2)
129
- return redirect(url_for('survey', blind=blind, signature=signature))
130
- return render_template('index.html', errors=errors)
131
-
132
-
133
- @app.route('/survey/<signature>', methods=['GET', 'POST'])
134
- @ensure_logged
135
- def survey(signature):
136
- success = request.args.get('success', False)
137
- seed = int(request.args.get('seed', 4321))
138
- blind = request.args.get('blind', 'false') in ['true', 'on', 'True']
139
- exclude_prompted = request.args.get('exclude_prompted', 'false') in ['true', 'on', 'True']
140
- exclude_unprompted = request.args.get('exclude_unprompted', 'false') in ['true', 'on', 'True']
141
- max_epoch = int(request.args.get('max_epoch', '-1'))
142
- survey_path = surveys / signature
143
- assert survey_path.exists(), survey_path
144
-
145
- user = session['user']
146
- result_folder = survey_path / 'results'
147
- result_folder.mkdir(exist_ok=True)
148
- result_file = result_folder / f'{user}_{seed}.json'
149
-
150
- with open(survey_path / 'manifest.json') as f:
151
- manifest = json.load(f)
152
-
153
- xps = [train.main.get_xp_from_sig(xp) for xp in manifest['xps']]
154
- names, ref_name = train.main.get_names(xps)
155
-
156
- samples_kwargs = {
157
- 'exclude_prompted': exclude_prompted,
158
- 'exclude_unprompted': exclude_unprompted,
159
- 'max_epoch': max_epoch,
160
- }
161
- matched_samples = get_samples_for_xps(xps, epoch=-1, **samples_kwargs) # fetch latest epoch
162
- models_by_id = {
163
- id: [{
164
- 'xp': xps[idx],
165
- 'xp_name': names[idx],
166
- 'model_id': f'{xps[idx].sig}-{sample.id}',
167
- 'sample': sample,
168
- 'is_prompted': sample.prompt is not None,
169
- 'errors': [],
170
- } for idx, sample in enumerate(samples)]
171
- for id, samples in matched_samples.items()
172
- }
173
- experiments = [
174
- {'xp': xp, 'name': names[idx], 'epoch': list(matched_samples.values())[0][idx].epoch}
175
- for idx, xp in enumerate(xps)
176
- ]
177
-
178
- keys = list(matched_samples.keys())
179
- keys.sort()
180
- rng = random.Random(seed)
181
- rng.shuffle(keys)
182
- model_ids = keys[:SAMPLES_PER_PAGE]
183
-
184
- if blind:
185
- for key in model_ids:
186
- rng.shuffle(models_by_id[key])
187
-
188
- ok = True
189
- if request.method == 'POST':
190
- all_samples_results = []
191
- for id in model_ids:
192
- models = models_by_id[id]
193
- result = {
194
- 'id': id,
195
- 'is_prompted': models[0]['is_prompted'],
196
- 'models': {}
197
- }
198
- all_samples_results.append(result)
199
- for model in models:
200
- rating = request.form[model['model_id']]
201
- if rating:
202
- rating = int(rating)
203
- assert rating <= MAX_RATING and rating >= 1
204
- result['models'][model['xp'].sig] = rating
205
- model['rating'] = rating
206
- else:
207
- ok = False
208
- model['errors'].append('Please rate this model.')
209
- if ok:
210
- result = {
211
- 'results': all_samples_results,
212
- 'seed': seed,
213
- 'user': user,
214
- 'blind': blind,
215
- 'exclude_prompted': exclude_prompted,
216
- 'exclude_unprompted': exclude_unprompted,
217
- }
218
- print(result)
219
- with open(result_file, 'w') as f:
220
- json.dump(result, f)
221
- seed = seed + 1
222
- return redirect(url_for(
223
- 'survey', signature=signature, blind=blind, seed=seed,
224
- exclude_prompted=exclude_prompted, exclude_unprompted=exclude_unprompted,
225
- max_epoch=max_epoch, success=True))
226
-
227
- ratings = list(range(1, MAX_RATING + 1))
228
- return render_template(
229
- 'survey.html', ratings=ratings, blind=blind, seed=seed, signature=signature, success=success,
230
- exclude_prompted=exclude_prompted, exclude_unprompted=exclude_unprompted, max_epoch=max_epoch,
231
- experiments=experiments, models_by_id=models_by_id, model_ids=model_ids, errors=[],
232
- ref_name=ref_name, already_filled=result_file.exists())
233
-
234
-
235
- @app.route('/audio/<path:path>')
236
- def audio(path: str):
237
- full_path = Path('/') / path
238
- assert full_path.suffix in [".mp3", ".wav"]
239
- return full_path.read_bytes(), {'Content-Type': 'audio/mpeg'}
240
-
241
-
242
- def mean(x):
243
- return sum(x) / len(x)
244
-
245
-
246
- def std(x):
247
- m = mean(x)
248
- return math.sqrt(sum((i - m)**2 for i in x) / len(x))
249
-
250
-
251
- @app.route('/results/<signature>')
252
- @ensure_logged
253
- def results(signature):
254
-
255
- survey_path = surveys / signature
256
- assert survey_path.exists(), survey_path
257
- result_folder = survey_path / 'results'
258
- result_folder.mkdir(exist_ok=True)
259
-
260
- # ratings per model, then per user.
261
- ratings_per_model = defaultdict(list)
262
- users = []
263
- for result_file in result_folder.iterdir():
264
- if result_file.suffix != '.json':
265
- continue
266
- with open(result_file) as f:
267
- results = json.load(f)
268
- users.append(results['user'])
269
- for result in results['results']:
270
- for sig, rating in result['models'].items():
271
- ratings_per_model[sig].append(rating)
272
-
273
- fmt = '{:.2f}'
274
- models = []
275
- for model in sorted(ratings_per_model.keys()):
276
- ratings = ratings_per_model[model]
277
-
278
- models.append({
279
- 'sig': model,
280
- 'samples': len(ratings),
281
- 'mean_rating': fmt.format(mean(ratings)),
282
- # the value 1.96 was probably chosen to achieve some
283
- # confidence interval assuming gaussianity.
284
- 'std_rating': fmt.format(1.96 * std(ratings) / len(ratings)**0.5),
285
- })
286
- return render_template('results.html', signature=signature, models=models, users=users)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/StyleGANEX/models/bisenet/model.py DELETED
@@ -1,283 +0,0 @@
1
- #!/usr/bin/python
2
- # -*- encoding: utf-8 -*-
3
-
4
-
5
- import torch
6
- import torch.nn as nn
7
- import torch.nn.functional as F
8
- import torchvision
9
-
10
- from models.bisenet.resnet import Resnet18
11
- # from modules.bn import InPlaceABNSync as BatchNorm2d
12
-
13
-
14
- class ConvBNReLU(nn.Module):
15
- def __init__(self, in_chan, out_chan, ks=3, stride=1, padding=1, *args, **kwargs):
16
- super(ConvBNReLU, self).__init__()
17
- self.conv = nn.Conv2d(in_chan,
18
- out_chan,
19
- kernel_size = ks,
20
- stride = stride,
21
- padding = padding,
22
- bias = False)
23
- self.bn = nn.BatchNorm2d(out_chan)
24
- self.init_weight()
25
-
26
- def forward(self, x):
27
- x = self.conv(x)
28
- x = F.relu(self.bn(x))
29
- return x
30
-
31
- def init_weight(self):
32
- for ly in self.children():
33
- if isinstance(ly, nn.Conv2d):
34
- nn.init.kaiming_normal_(ly.weight, a=1)
35
- if not ly.bias is None: nn.init.constant_(ly.bias, 0)
36
-
37
- class BiSeNetOutput(nn.Module):
38
- def __init__(self, in_chan, mid_chan, n_classes, *args, **kwargs):
39
- super(BiSeNetOutput, self).__init__()
40
- self.conv = ConvBNReLU(in_chan, mid_chan, ks=3, stride=1, padding=1)
41
- self.conv_out = nn.Conv2d(mid_chan, n_classes, kernel_size=1, bias=False)
42
- self.init_weight()
43
-
44
- def forward(self, x):
45
- x = self.conv(x)
46
- x = self.conv_out(x)
47
- return x
48
-
49
- def init_weight(self):
50
- for ly in self.children():
51
- if isinstance(ly, nn.Conv2d):
52
- nn.init.kaiming_normal_(ly.weight, a=1)
53
- if not ly.bias is None: nn.init.constant_(ly.bias, 0)
54
-
55
- def get_params(self):
56
- wd_params, nowd_params = [], []
57
- for name, module in self.named_modules():
58
- if isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d):
59
- wd_params.append(module.weight)
60
- if not module.bias is None:
61
- nowd_params.append(module.bias)
62
- elif isinstance(module, nn.BatchNorm2d):
63
- nowd_params += list(module.parameters())
64
- return wd_params, nowd_params
65
-
66
-
67
- class AttentionRefinementModule(nn.Module):
68
- def __init__(self, in_chan, out_chan, *args, **kwargs):
69
- super(AttentionRefinementModule, self).__init__()
70
- self.conv = ConvBNReLU(in_chan, out_chan, ks=3, stride=1, padding=1)
71
- self.conv_atten = nn.Conv2d(out_chan, out_chan, kernel_size= 1, bias=False)
72
- self.bn_atten = nn.BatchNorm2d(out_chan)
73
- self.sigmoid_atten = nn.Sigmoid()
74
- self.init_weight()
75
-
76
- def forward(self, x):
77
- feat = self.conv(x)
78
- atten = F.avg_pool2d(feat, feat.size()[2:])
79
- atten = self.conv_atten(atten)
80
- atten = self.bn_atten(atten)
81
- atten = self.sigmoid_atten(atten)
82
- out = torch.mul(feat, atten)
83
- return out
84
-
85
- def init_weight(self):
86
- for ly in self.children():
87
- if isinstance(ly, nn.Conv2d):
88
- nn.init.kaiming_normal_(ly.weight, a=1)
89
- if not ly.bias is None: nn.init.constant_(ly.bias, 0)
90
-
91
-
92
- class ContextPath(nn.Module):
93
- def __init__(self, *args, **kwargs):
94
- super(ContextPath, self).__init__()
95
- self.resnet = Resnet18()
96
- self.arm16 = AttentionRefinementModule(256, 128)
97
- self.arm32 = AttentionRefinementModule(512, 128)
98
- self.conv_head32 = ConvBNReLU(128, 128, ks=3, stride=1, padding=1)
99
- self.conv_head16 = ConvBNReLU(128, 128, ks=3, stride=1, padding=1)
100
- self.conv_avg = ConvBNReLU(512, 128, ks=1, stride=1, padding=0)
101
-
102
- self.init_weight()
103
-
104
- def forward(self, x):
105
- H0, W0 = x.size()[2:]
106
- feat8, feat16, feat32 = self.resnet(x)
107
- H8, W8 = feat8.size()[2:]
108
- H16, W16 = feat16.size()[2:]
109
- H32, W32 = feat32.size()[2:]
110
-
111
- avg = F.avg_pool2d(feat32, feat32.size()[2:])
112
- avg = self.conv_avg(avg)
113
- avg_up = F.interpolate(avg, (H32, W32), mode='nearest')
114
-
115
- feat32_arm = self.arm32(feat32)
116
- feat32_sum = feat32_arm + avg_up
117
- feat32_up = F.interpolate(feat32_sum, (H16, W16), mode='nearest')
118
- feat32_up = self.conv_head32(feat32_up)
119
-
120
- feat16_arm = self.arm16(feat16)
121
- feat16_sum = feat16_arm + feat32_up
122
- feat16_up = F.interpolate(feat16_sum, (H8, W8), mode='nearest')
123
- feat16_up = self.conv_head16(feat16_up)
124
-
125
- return feat8, feat16_up, feat32_up # x8, x8, x16
126
-
127
- def init_weight(self):
128
- for ly in self.children():
129
- if isinstance(ly, nn.Conv2d):
130
- nn.init.kaiming_normal_(ly.weight, a=1)
131
- if not ly.bias is None: nn.init.constant_(ly.bias, 0)
132
-
133
- def get_params(self):
134
- wd_params, nowd_params = [], []
135
- for name, module in self.named_modules():
136
- if isinstance(module, (nn.Linear, nn.Conv2d)):
137
- wd_params.append(module.weight)
138
- if not module.bias is None:
139
- nowd_params.append(module.bias)
140
- elif isinstance(module, nn.BatchNorm2d):
141
- nowd_params += list(module.parameters())
142
- return wd_params, nowd_params
143
-
144
-
145
- ### This is not used, since I replace this with the resnet feature with the same size
146
- class SpatialPath(nn.Module):
147
- def __init__(self, *args, **kwargs):
148
- super(SpatialPath, self).__init__()
149
- self.conv1 = ConvBNReLU(3, 64, ks=7, stride=2, padding=3)
150
- self.conv2 = ConvBNReLU(64, 64, ks=3, stride=2, padding=1)
151
- self.conv3 = ConvBNReLU(64, 64, ks=3, stride=2, padding=1)
152
- self.conv_out = ConvBNReLU(64, 128, ks=1, stride=1, padding=0)
153
- self.init_weight()
154
-
155
- def forward(self, x):
156
- feat = self.conv1(x)
157
- feat = self.conv2(feat)
158
- feat = self.conv3(feat)
159
- feat = self.conv_out(feat)
160
- return feat
161
-
162
- def init_weight(self):
163
- for ly in self.children():
164
- if isinstance(ly, nn.Conv2d):
165
- nn.init.kaiming_normal_(ly.weight, a=1)
166
- if not ly.bias is None: nn.init.constant_(ly.bias, 0)
167
-
168
- def get_params(self):
169
- wd_params, nowd_params = [], []
170
- for name, module in self.named_modules():
171
- if isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d):
172
- wd_params.append(module.weight)
173
- if not module.bias is None:
174
- nowd_params.append(module.bias)
175
- elif isinstance(module, nn.BatchNorm2d):
176
- nowd_params += list(module.parameters())
177
- return wd_params, nowd_params
178
-
179
-
180
- class FeatureFusionModule(nn.Module):
181
- def __init__(self, in_chan, out_chan, *args, **kwargs):
182
- super(FeatureFusionModule, self).__init__()
183
- self.convblk = ConvBNReLU(in_chan, out_chan, ks=1, stride=1, padding=0)
184
- self.conv1 = nn.Conv2d(out_chan,
185
- out_chan//4,
186
- kernel_size = 1,
187
- stride = 1,
188
- padding = 0,
189
- bias = False)
190
- self.conv2 = nn.Conv2d(out_chan//4,
191
- out_chan,
192
- kernel_size = 1,
193
- stride = 1,
194
- padding = 0,
195
- bias = False)
196
- self.relu = nn.ReLU(inplace=True)
197
- self.sigmoid = nn.Sigmoid()
198
- self.init_weight()
199
-
200
- def forward(self, fsp, fcp):
201
- fcat = torch.cat([fsp, fcp], dim=1)
202
- feat = self.convblk(fcat)
203
- atten = F.avg_pool2d(feat, feat.size()[2:])
204
- atten = self.conv1(atten)
205
- atten = self.relu(atten)
206
- atten = self.conv2(atten)
207
- atten = self.sigmoid(atten)
208
- feat_atten = torch.mul(feat, atten)
209
- feat_out = feat_atten + feat
210
- return feat_out
211
-
212
- def init_weight(self):
213
- for ly in self.children():
214
- if isinstance(ly, nn.Conv2d):
215
- nn.init.kaiming_normal_(ly.weight, a=1)
216
- if not ly.bias is None: nn.init.constant_(ly.bias, 0)
217
-
218
- def get_params(self):
219
- wd_params, nowd_params = [], []
220
- for name, module in self.named_modules():
221
- if isinstance(module, nn.Linear) or isinstance(module, nn.Conv2d):
222
- wd_params.append(module.weight)
223
- if not module.bias is None:
224
- nowd_params.append(module.bias)
225
- elif isinstance(module, nn.BatchNorm2d):
226
- nowd_params += list(module.parameters())
227
- return wd_params, nowd_params
228
-
229
-
230
- class BiSeNet(nn.Module):
231
- def __init__(self, n_classes, *args, **kwargs):
232
- super(BiSeNet, self).__init__()
233
- self.cp = ContextPath()
234
- ## here self.sp is deleted
235
- self.ffm = FeatureFusionModule(256, 256)
236
- self.conv_out = BiSeNetOutput(256, 256, n_classes)
237
- self.conv_out16 = BiSeNetOutput(128, 64, n_classes)
238
- self.conv_out32 = BiSeNetOutput(128, 64, n_classes)
239
- self.init_weight()
240
-
241
- def forward(self, x):
242
- H, W = x.size()[2:]
243
- feat_res8, feat_cp8, feat_cp16 = self.cp(x) # here return res3b1 feature
244
- feat_sp = feat_res8 # use res3b1 feature to replace spatial path feature
245
- feat_fuse = self.ffm(feat_sp, feat_cp8)
246
-
247
- feat_out = self.conv_out(feat_fuse)
248
- feat_out16 = self.conv_out16(feat_cp8)
249
- feat_out32 = self.conv_out32(feat_cp16)
250
-
251
- feat_out = F.interpolate(feat_out, (H, W), mode='bilinear', align_corners=True)
252
- feat_out16 = F.interpolate(feat_out16, (H, W), mode='bilinear', align_corners=True)
253
- feat_out32 = F.interpolate(feat_out32, (H, W), mode='bilinear', align_corners=True)
254
- return feat_out, feat_out16, feat_out32
255
-
256
- def init_weight(self):
257
- for ly in self.children():
258
- if isinstance(ly, nn.Conv2d):
259
- nn.init.kaiming_normal_(ly.weight, a=1)
260
- if not ly.bias is None: nn.init.constant_(ly.bias, 0)
261
-
262
- def get_params(self):
263
- wd_params, nowd_params, lr_mul_wd_params, lr_mul_nowd_params = [], [], [], []
264
- for name, child in self.named_children():
265
- child_wd_params, child_nowd_params = child.get_params()
266
- if isinstance(child, FeatureFusionModule) or isinstance(child, BiSeNetOutput):
267
- lr_mul_wd_params += child_wd_params
268
- lr_mul_nowd_params += child_nowd_params
269
- else:
270
- wd_params += child_wd_params
271
- nowd_params += child_nowd_params
272
- return wd_params, nowd_params, lr_mul_wd_params, lr_mul_nowd_params
273
-
274
-
275
- if __name__ == "__main__":
276
- net = BiSeNet(19)
277
- net.cuda()
278
- net.eval()
279
- in_ten = torch.randn(16, 3, 640, 480).cuda()
280
- out, out16, out32 = net(in_ten)
281
- print(out.shape)
282
-
283
- net.get_params()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/text_to_speech/tasks/run.py DELETED
@@ -1,19 +0,0 @@
1
- import os
2
-
3
- os.environ["OMP_NUM_THREADS"] = "1"
4
-
5
- from text_to_speech.utils.commons.hparams import hparams, set_hparams
6
- import importlib
7
-
8
-
9
- def run_task():
10
- assert hparams['task_cls'] != ''
11
- pkg = ".".join(hparams["task_cls"].split(".")[:-1])
12
- cls_name = hparams["task_cls"].split(".")[-1]
13
- task_cls = getattr(importlib.import_module(pkg), cls_name)
14
- task_cls.start()
15
-
16
-
17
- if __name__ == '__main__':
18
- set_hparams()
19
- run_task()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AbandonedMuse/UnlimitedMusicGen/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/Abubakari/Sepsis-prediction-streamlit-app/app.py DELETED
@@ -1,154 +0,0 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import joblib
4
- import matplotlib.pyplot as plt
5
- import time
6
- import base64
7
-
8
- # Load the pre-trained numerical imputer, scaler, and model using joblib
9
- num_imputer = joblib.load('numerical_imputer.joblib')
10
- scaler = joblib.load('scaler.joblib')
11
- model = joblib.load('Final_model.joblib')
12
-
13
- # Define a function to preprocess the input data
14
- def preprocess_input_data(input_data):
15
- input_data_df = pd.DataFrame(input_data, columns=['PRG', 'PL', 'PR', 'SK', 'TS', 'M11', 'BD2', 'Age', 'Insurance'])
16
- num_columns = input_data_df.select_dtypes(include='number').columns
17
-
18
- input_data_imputed_num = num_imputer.transform(input_data_df[num_columns])
19
- input_scaled_df = pd.DataFrame(scaler.transform(input_data_imputed_num), columns=num_columns)
20
-
21
- return input_scaled_df
22
-
23
-
24
- # Define a function to make the sepsis prediction
25
- def predict_sepsis(input_data):
26
- input_scaled_df = preprocess_input_data(input_data)
27
- prediction = model.predict(input_scaled_df)[0]
28
- probabilities = model.predict_proba(input_scaled_df)[0]
29
- sepsis_status = "Positive" if prediction == 1 else "Negative"
30
-
31
- status_icon = "✔" if prediction == 1 else "✘" # Red 'X' icon for positive sepsis prediction, green checkmark icon for negative sepsis prediction
32
- sepsis_explanation = "Sepsis is a life-threatening condition caused by an infection. A positive prediction suggests that the patient might be exhibiting sepsis symptoms and requires immediate medical attention." if prediction == 1 else "Sepsis is a life-threatening condition caused by an infection. A negative prediction suggests that the patient is not currently exhibiting sepsis symptoms."
33
-
34
- output_df = pd.DataFrame(input_data, columns=['PRG', 'PL', 'PR', 'SK', 'TS', 'M11', 'BD2', 'Age', 'Insurance'])
35
- output_df['Prediction'] = sepsis_status
36
- output_df['Negative Probability'] = probabilities[0]
37
- output_df['Positive Probability'] = probabilities[1]
38
-
39
- return output_df, probabilities, status_icon, sepsis_explanation
40
-
41
- # Create a Streamlit app
42
- def main():
43
- st.title('Sepsis Prediction App')
44
-
45
- st.image("Strealit_.jpg")
46
-
47
- # How to use
48
- st.sidebar.title('How to Use')
49
- st.sidebar.markdown('1. Adjust the input parameters on the left sidebar.')
50
- st.sidebar.markdown('2. Click the "Predict" button to initiate the prediction.')
51
- st.sidebar.markdown('3. The app will simulate a prediction process with a progress bar.')
52
- st.sidebar.markdown('4. Once the prediction is complete, the results will be displayed below.')
53
-
54
-
55
- st.sidebar.title('Input Parameters')
56
-
57
- # Input parameter explanations
58
- st.sidebar.markdown('**PRG:** Plasma Glucose')
59
- PRG = st.sidebar.number_input('PRG', value=0.0)
60
-
61
- st.sidebar.markdown('**PL:** Blood Work Result 1')
62
- PL = st.sidebar.number_input('PL', value=0.0)
63
-
64
- st.sidebar.markdown('**PR:** Blood Pressure Measured')
65
- PR = st.sidebar.number_input('PR', value=0.0)
66
-
67
- st.sidebar.markdown('**SK:** Blood Work Result 2')
68
- SK = st.sidebar.number_input('SK', value=0.0)
69
-
70
- st.sidebar.markdown('**TS:** Blood Work Result 3')
71
- TS = st.sidebar.number_input('TS', value=0.0)
72
-
73
- st.sidebar.markdown('**M11:** BMI')
74
- M11 = st.sidebar.number_input('M11', value=0.0)
75
-
76
- st.sidebar.markdown('**BD2:** Blood Work Result 4')
77
- BD2 = st.sidebar.number_input('BD2', value=0.0)
78
-
79
- st.sidebar.markdown('**Age:** What is the Age of the Patient: ')
80
- Age = st.sidebar.number_input('Age', value=0.0)
81
-
82
- st.sidebar.markdown('**Insurance:** Does the patient have Insurance?')
83
- insurance_options = {0: 'NO', 1: 'YES'}
84
- Insurance = st.sidebar.radio('Insurance', list(insurance_options.keys()), format_func=lambda x: insurance_options[x])
85
-
86
-
87
- input_data = [[PRG, PL, PR, SK, TS, M11, BD2, Age, Insurance]]
88
-
89
- if st.sidebar.button('Predict'):
90
- with st.spinner("Predicting..."):
91
- # Simulate a long-running process
92
- progress_bar = st.progress(0)
93
- step = 20 # A big step will reduce the execution time
94
- for i in range(0, 100, step):
95
- time.sleep(0.1)
96
- progress_bar.progress(i + step)
97
-
98
- output_df, probabilities, status_icon, sepsis_explanation = predict_sepsis(input_data)
99
-
100
- st.subheader('Prediction Result')
101
- prediction_text = "Positive" if status_icon == "✔" else "Negative"
102
- st.markdown(f"Prediction: **{prediction_text}**")
103
- st.markdown(f"{status_icon} {sepsis_explanation}")
104
- st.write(output_df)
105
-
106
- # Add a download button for output_df
107
- csv = output_df.to_csv(index=False)
108
- b64 = base64.b64encode(csv.encode()).decode()
109
- href = f'<a href="data:file/csv;base64,{b64}" download="output.csv">Download Output CSV</a>'
110
- st.markdown(href, unsafe_allow_html=True)
111
-
112
-
113
- # Plot the probabilities
114
- fig, ax = plt.subplots()
115
- ax.bar(['Negative', 'Positive'], probabilities)
116
- ax.set_xlabel('Sepsis Status')
117
- ax.set_ylabel('Probability')
118
- ax.set_title('Sepsis Prediction Probabilities')
119
- st.pyplot(fig)
120
-
121
- # Print feature importance
122
- if hasattr(model, 'coef_'):
123
- feature_importances = model.coef_[0]
124
- feature_names = ['PRG', 'PL', 'PR', 'SK', 'TS', 'M11', 'BD2', 'Age', 'Insurance']
125
-
126
- importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': feature_importances})
127
- importance_df = importance_df.sort_values('Importance', ascending=False)
128
-
129
- st.subheader('Feature Importance')
130
- fig, ax = plt.subplots()
131
- bars = ax.bar(importance_df['Feature'], importance_df['Importance'])
132
- ax.set_xlabel('Feature')
133
- ax.set_ylabel('Importance')
134
- ax.set_title('Feature Importance')
135
- ax.tick_params(axis='x', rotation=45)
136
-
137
- # Add data labels to the bars
138
- for bar in bars:
139
- height = bar.get_height()
140
- ax.annotate(f'{height:.2f}', xy=(bar.get_x() + bar.get_width() / 2, height),
141
- xytext=(0, 3), # 3 points vertical offset
142
- textcoords="offset points",
143
- ha='center', va='bottom')
144
- st.pyplot(fig)
145
-
146
- else:
147
- st.write('Feature importance is not available for this model.')
148
-
149
- #st.subheader('Sepsis Explanation')
150
- #st.markdown(f"{status_icon} {sepsis_explanation}")
151
-
152
-
153
- if __name__ == '__main__':
154
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/midas/midas/__init__.py DELETED
File without changes
spaces/Adapting/YouTube-Downloader/app.py DELETED
@@ -1,32 +0,0 @@
1
- import streamlit as st
2
- import tube as tb
3
-
4
- tb.clear_cache()
5
-
6
-
7
- md = '''
8
- # YouTube Downloader
9
- '''
10
-
11
- st.markdown(md)
12
-
13
-
14
- url = st.text_input(
15
- placeholder="https://www.youtube.com/",
16
- label='**Enter the url of the youtube:**',
17
- key='title'
18
- )
19
-
20
-
21
-
22
- if url is not None and ('https' in url or 'http' in url):
23
- tb.download_yt(url)
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Aditya9790/yolo7-object-tracking/LICENSE.md DELETED
@@ -1,674 +0,0 @@
1
- GNU GENERAL PUBLIC LICENSE
2
- Version 3, 29 June 2007
3
-
4
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
- Everyone is permitted to copy and distribute verbatim copies
6
- of this license document, but changing it is not allowed.
7
-
8
- Preamble
9
-
10
- The GNU General Public License is a free, copyleft license for
11
- software and other kinds of works.
12
-
13
- The licenses for most software and other practical works are designed
14
- to take away your freedom to share and change the works. By contrast,
15
- the GNU General Public License is intended to guarantee your freedom to
16
- share and change all versions of a program--to make sure it remains free
17
- software for all its users. We, the Free Software Foundation, use the
18
- GNU General Public License for most of our software; it applies also to
19
- any other work released this way by its authors. You can apply it to
20
- your programs, too.
21
-
22
- When we speak of free software, we are referring to freedom, not
23
- price. Our General Public Licenses are designed to make sure that you
24
- have the freedom to distribute copies of free software (and charge for
25
- them if you wish), that you receive source code or can get it if you
26
- want it, that you can change the software or use pieces of it in new
27
- free programs, and that you know you can do these things.
28
-
29
- To protect your rights, we need to prevent others from denying you
30
- these rights or asking you to surrender the rights. Therefore, you have
31
- certain responsibilities if you distribute copies of the software, or if
32
- you modify it: responsibilities to respect the freedom of others.
33
-
34
- For example, if you distribute copies of such a program, whether
35
- gratis or for a fee, you must pass on to the recipients the same
36
- freedoms that you received. You must make sure that they, too, receive
37
- or can get the source code. And you must show them these terms so they
38
- know their rights.
39
-
40
- Developers that use the GNU GPL protect your rights with two steps:
41
- (1) assert copyright on the software, and (2) offer you this License
42
- giving you legal permission to copy, distribute and/or modify it.
43
-
44
- For the developers' and authors' protection, the GPL clearly explains
45
- that there is no warranty for this free software. For both users' and
46
- authors' sake, the GPL requires that modified versions be marked as
47
- changed, so that their problems will not be attributed erroneously to
48
- authors of previous versions.
49
-
50
- Some devices are designed to deny users access to install or run
51
- modified versions of the software inside them, although the manufacturer
52
- can do so. This is fundamentally incompatible with the aim of
53
- protecting users' freedom to change the software. The systematic
54
- pattern of such abuse occurs in the area of products for individuals to
55
- use, which is precisely where it is most unacceptable. Therefore, we
56
- have designed this version of the GPL to prohibit the practice for those
57
- products. If such problems arise substantially in other domains, we
58
- stand ready to extend this provision to those domains in future versions
59
- of the GPL, as needed to protect the freedom of users.
60
-
61
- Finally, every program is threatened constantly by software patents.
62
- States should not allow patents to restrict development and use of
63
- software on general-purpose computers, but in those that do, we wish to
64
- avoid the special danger that patents applied to a free program could
65
- make it effectively proprietary. To prevent this, the GPL assures that
66
- patents cannot be used to render the program non-free.
67
-
68
- The precise terms and conditions for copying, distribution and
69
- modification follow.
70
-
71
- TERMS AND CONDITIONS
72
-
73
- 0. Definitions.
74
-
75
- "This License" refers to version 3 of the GNU General Public License.
76
-
77
- "Copyright" also means copyright-like laws that apply to other kinds of
78
- works, such as semiconductor masks.
79
-
80
- "The Program" refers to any copyrightable work licensed under this
81
- License. Each licensee is addressed as "you". "Licensees" and
82
- "recipients" may be individuals or organizations.
83
-
84
- To "modify" a work means to copy from or adapt all or part of the work
85
- in a fashion requiring copyright permission, other than the making of an
86
- exact copy. The resulting work is called a "modified version" of the
87
- earlier work or a work "based on" the earlier work.
88
-
89
- A "covered work" means either the unmodified Program or a work based
90
- on the Program.
91
-
92
- To "propagate" a work means to do anything with it that, without
93
- permission, would make you directly or secondarily liable for
94
- infringement under applicable copyright law, except executing it on a
95
- computer or modifying a private copy. Propagation includes copying,
96
- distribution (with or without modification), making available to the
97
- public, and in some countries other activities as well.
98
-
99
- To "convey" a work means any kind of propagation that enables other
100
- parties to make or receive copies. Mere interaction with a user through
101
- a computer network, with no transfer of a copy, is not conveying.
102
-
103
- An interactive user interface displays "Appropriate Legal Notices"
104
- to the extent that it includes a convenient and prominently visible
105
- feature that (1) displays an appropriate copyright notice, and (2)
106
- tells the user that there is no warranty for the work (except to the
107
- extent that warranties are provided), that licensees may convey the
108
- work under this License, and how to view a copy of this License. If
109
- the interface presents a list of user commands or options, such as a
110
- menu, a prominent item in the list meets this criterion.
111
-
112
- 1. Source Code.
113
-
114
- The "source code" for a work means the preferred form of the work
115
- for making modifications to it. "Object code" means any non-source
116
- form of a work.
117
-
118
- A "Standard Interface" means an interface that either is an official
119
- standard defined by a recognized standards body, or, in the case of
120
- interfaces specified for a particular programming language, one that
121
- is widely used among developers working in that language.
122
-
123
- The "System Libraries" of an executable work include anything, other
124
- than the work as a whole, that (a) is included in the normal form of
125
- packaging a Major Component, but which is not part of that Major
126
- Component, and (b) serves only to enable use of the work with that
127
- Major Component, or to implement a Standard Interface for which an
128
- implementation is available to the public in source code form. A
129
- "Major Component", in this context, means a major essential component
130
- (kernel, window system, and so on) of the specific operating system
131
- (if any) on which the executable work runs, or a compiler used to
132
- produce the work, or an object code interpreter used to run it.
133
-
134
- The "Corresponding Source" for a work in object code form means all
135
- the source code needed to generate, install, and (for an executable
136
- work) run the object code and to modify the work, including scripts to
137
- control those activities. However, it does not include the work's
138
- System Libraries, or general-purpose tools or generally available free
139
- programs which are used unmodified in performing those activities but
140
- which are not part of the work. For example, Corresponding Source
141
- includes interface definition files associated with source files for
142
- the work, and the source code for shared libraries and dynamically
143
- linked subprograms that the work is specifically designed to require,
144
- such as by intimate data communication or control flow between those
145
- subprograms and other parts of the work.
146
-
147
- The Corresponding Source need not include anything that users
148
- can regenerate automatically from other parts of the Corresponding
149
- Source.
150
-
151
- The Corresponding Source for a work in source code form is that
152
- same work.
153
-
154
- 2. Basic Permissions.
155
-
156
- All rights granted under this License are granted for the term of
157
- copyright on the Program, and are irrevocable provided the stated
158
- conditions are met. This License explicitly affirms your unlimited
159
- permission to run the unmodified Program. The output from running a
160
- covered work is covered by this License only if the output, given its
161
- content, constitutes a covered work. This License acknowledges your
162
- rights of fair use or other equivalent, as provided by copyright law.
163
-
164
- You may make, run and propagate covered works that you do not
165
- convey, without conditions so long as your license otherwise remains
166
- in force. You may convey covered works to others for the sole purpose
167
- of having them make modifications exclusively for you, or provide you
168
- with facilities for running those works, provided that you comply with
169
- the terms of this License in conveying all material for which you do
170
- not control copyright. Those thus making or running the covered works
171
- for you must do so exclusively on your behalf, under your direction
172
- and control, on terms that prohibit them from making any copies of
173
- your copyrighted material outside their relationship with you.
174
-
175
- Conveying under any other circumstances is permitted solely under
176
- the conditions stated below. Sublicensing is not allowed; section 10
177
- makes it unnecessary.
178
-
179
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
-
181
- No covered work shall be deemed part of an effective technological
182
- measure under any applicable law fulfilling obligations under article
183
- 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
- similar laws prohibiting or restricting circumvention of such
185
- measures.
186
-
187
- When you convey a covered work, you waive any legal power to forbid
188
- circumvention of technological measures to the extent such circumvention
189
- is effected by exercising rights under this License with respect to
190
- the covered work, and you disclaim any intention to limit operation or
191
- modification of the work as a means of enforcing, against the work's
192
- users, your or third parties' legal rights to forbid circumvention of
193
- technological measures.
194
-
195
- 4. Conveying Verbatim Copies.
196
-
197
- You may convey verbatim copies of the Program's source code as you
198
- receive it, in any medium, provided that you conspicuously and
199
- appropriately publish on each copy an appropriate copyright notice;
200
- keep intact all notices stating that this License and any
201
- non-permissive terms added in accord with section 7 apply to the code;
202
- keep intact all notices of the absence of any warranty; and give all
203
- recipients a copy of this License along with the Program.
204
-
205
- You may charge any price or no price for each copy that you convey,
206
- and you may offer support or warranty protection for a fee.
207
-
208
- 5. Conveying Modified Source Versions.
209
-
210
- You may convey a work based on the Program, or the modifications to
211
- produce it from the Program, in the form of source code under the
212
- terms of section 4, provided that you also meet all of these conditions:
213
-
214
- a) The work must carry prominent notices stating that you modified
215
- it, and giving a relevant date.
216
-
217
- b) The work must carry prominent notices stating that it is
218
- released under this License and any conditions added under section
219
- 7. This requirement modifies the requirement in section 4 to
220
- "keep intact all notices".
221
-
222
- c) You must license the entire work, as a whole, under this
223
- License to anyone who comes into possession of a copy. This
224
- License will therefore apply, along with any applicable section 7
225
- additional terms, to the whole of the work, and all its parts,
226
- regardless of how they are packaged. This License gives no
227
- permission to license the work in any other way, but it does not
228
- invalidate such permission if you have separately received it.
229
-
230
- d) If the work has interactive user interfaces, each must display
231
- Appropriate Legal Notices; however, if the Program has interactive
232
- interfaces that do not display Appropriate Legal Notices, your
233
- work need not make them do so.
234
-
235
- A compilation of a covered work with other separate and independent
236
- works, which are not by their nature extensions of the covered work,
237
- and which are not combined with it such as to form a larger program,
238
- in or on a volume of a storage or distribution medium, is called an
239
- "aggregate" if the compilation and its resulting copyright are not
240
- used to limit the access or legal rights of the compilation's users
241
- beyond what the individual works permit. Inclusion of a covered work
242
- in an aggregate does not cause this License to apply to the other
243
- parts of the aggregate.
244
-
245
- 6. Conveying Non-Source Forms.
246
-
247
- You may convey a covered work in object code form under the terms
248
- of sections 4 and 5, provided that you also convey the
249
- machine-readable Corresponding Source under the terms of this License,
250
- in one of these ways:
251
-
252
- a) Convey the object code in, or embodied in, a physical product
253
- (including a physical distribution medium), accompanied by the
254
- Corresponding Source fixed on a durable physical medium
255
- customarily used for software interchange.
256
-
257
- b) Convey the object code in, or embodied in, a physical product
258
- (including a physical distribution medium), accompanied by a
259
- written offer, valid for at least three years and valid for as
260
- long as you offer spare parts or customer support for that product
261
- model, to give anyone who possesses the object code either (1) a
262
- copy of the Corresponding Source for all the software in the
263
- product that is covered by this License, on a durable physical
264
- medium customarily used for software interchange, for a price no
265
- more than your reasonable cost of physically performing this
266
- conveying of source, or (2) access to copy the
267
- Corresponding Source from a network server at no charge.
268
-
269
- c) Convey individual copies of the object code with a copy of the
270
- written offer to provide the Corresponding Source. This
271
- alternative is allowed only occasionally and noncommercially, and
272
- only if you received the object code with such an offer, in accord
273
- with subsection 6b.
274
-
275
- d) Convey the object code by offering access from a designated
276
- place (gratis or for a charge), and offer equivalent access to the
277
- Corresponding Source in the same way through the same place at no
278
- further charge. You need not require recipients to copy the
279
- Corresponding Source along with the object code. If the place to
280
- copy the object code is a network server, the Corresponding Source
281
- may be on a different server (operated by you or a third party)
282
- that supports equivalent copying facilities, provided you maintain
283
- clear directions next to the object code saying where to find the
284
- Corresponding Source. Regardless of what server hosts the
285
- Corresponding Source, you remain obligated to ensure that it is
286
- available for as long as needed to satisfy these requirements.
287
-
288
- e) Convey the object code using peer-to-peer transmission, provided
289
- you inform other peers where the object code and Corresponding
290
- Source of the work are being offered to the general public at no
291
- charge under subsection 6d.
292
-
293
- A separable portion of the object code, whose source code is excluded
294
- from the Corresponding Source as a System Library, need not be
295
- included in conveying the object code work.
296
-
297
- A "User Product" is either (1) a "consumer product", which means any
298
- tangible personal property which is normally used for personal, family,
299
- or household purposes, or (2) anything designed or sold for incorporation
300
- into a dwelling. In determining whether a product is a consumer product,
301
- doubtful cases shall be resolved in favor of coverage. For a particular
302
- product received by a particular user, "normally used" refers to a
303
- typical or common use of that class of product, regardless of the status
304
- of the particular user or of the way in which the particular user
305
- actually uses, or expects or is expected to use, the product. A product
306
- is a consumer product regardless of whether the product has substantial
307
- commercial, industrial or non-consumer uses, unless such uses represent
308
- the only significant mode of use of the product.
309
-
310
- "Installation Information" for a User Product means any methods,
311
- procedures, authorization keys, or other information required to install
312
- and execute modified versions of a covered work in that User Product from
313
- a modified version of its Corresponding Source. The information must
314
- suffice to ensure that the continued functioning of the modified object
315
- code is in no case prevented or interfered with solely because
316
- modification has been made.
317
-
318
- If you convey an object code work under this section in, or with, or
319
- specifically for use in, a User Product, and the conveying occurs as
320
- part of a transaction in which the right of possession and use of the
321
- User Product is transferred to the recipient in perpetuity or for a
322
- fixed term (regardless of how the transaction is characterized), the
323
- Corresponding Source conveyed under this section must be accompanied
324
- by the Installation Information. But this requirement does not apply
325
- if neither you nor any third party retains the ability to install
326
- modified object code on the User Product (for example, the work has
327
- been installed in ROM).
328
-
329
- The requirement to provide Installation Information does not include a
330
- requirement to continue to provide support service, warranty, or updates
331
- for a work that has been modified or installed by the recipient, or for
332
- the User Product in which it has been modified or installed. Access to a
333
- network may be denied when the modification itself materially and
334
- adversely affects the operation of the network or violates the rules and
335
- protocols for communication across the network.
336
-
337
- Corresponding Source conveyed, and Installation Information provided,
338
- in accord with this section must be in a format that is publicly
339
- documented (and with an implementation available to the public in
340
- source code form), and must require no special password or key for
341
- unpacking, reading or copying.
342
-
343
- 7. Additional Terms.
344
-
345
- "Additional permissions" are terms that supplement the terms of this
346
- License by making exceptions from one or more of its conditions.
347
- Additional permissions that are applicable to the entire Program shall
348
- be treated as though they were included in this License, to the extent
349
- that they are valid under applicable law. If additional permissions
350
- apply only to part of the Program, that part may be used separately
351
- under those permissions, but the entire Program remains governed by
352
- this License without regard to the additional permissions.
353
-
354
- When you convey a copy of a covered work, you may at your option
355
- remove any additional permissions from that copy, or from any part of
356
- it. (Additional permissions may be written to require their own
357
- removal in certain cases when you modify the work.) You may place
358
- additional permissions on material, added by you to a covered work,
359
- for which you have or can give appropriate copyright permission.
360
-
361
- Notwithstanding any other provision of this License, for material you
362
- add to a covered work, you may (if authorized by the copyright holders of
363
- that material) supplement the terms of this License with terms:
364
-
365
- a) Disclaiming warranty or limiting liability differently from the
366
- terms of sections 15 and 16 of this License; or
367
-
368
- b) Requiring preservation of specified reasonable legal notices or
369
- author attributions in that material or in the Appropriate Legal
370
- Notices displayed by works containing it; or
371
-
372
- c) Prohibiting misrepresentation of the origin of that material, or
373
- requiring that modified versions of such material be marked in
374
- reasonable ways as different from the original version; or
375
-
376
- d) Limiting the use for publicity purposes of names of licensors or
377
- authors of the material; or
378
-
379
- e) Declining to grant rights under trademark law for use of some
380
- trade names, trademarks, or service marks; or
381
-
382
- f) Requiring indemnification of licensors and authors of that
383
- material by anyone who conveys the material (or modified versions of
384
- it) with contractual assumptions of liability to the recipient, for
385
- any liability that these contractual assumptions directly impose on
386
- those licensors and authors.
387
-
388
- All other non-permissive additional terms are considered "further
389
- restrictions" within the meaning of section 10. If the Program as you
390
- received it, or any part of it, contains a notice stating that it is
391
- governed by this License along with a term that is a further
392
- restriction, you may remove that term. If a license document contains
393
- a further restriction but permits relicensing or conveying under this
394
- License, you may add to a covered work material governed by the terms
395
- of that license document, provided that the further restriction does
396
- not survive such relicensing or conveying.
397
-
398
- If you add terms to a covered work in accord with this section, you
399
- must place, in the relevant source files, a statement of the
400
- additional terms that apply to those files, or a notice indicating
401
- where to find the applicable terms.
402
-
403
- Additional terms, permissive or non-permissive, may be stated in the
404
- form of a separately written license, or stated as exceptions;
405
- the above requirements apply either way.
406
-
407
- 8. Termination.
408
-
409
- You may not propagate or modify a covered work except as expressly
410
- provided under this License. Any attempt otherwise to propagate or
411
- modify it is void, and will automatically terminate your rights under
412
- this License (including any patent licenses granted under the third
413
- paragraph of section 11).
414
-
415
- However, if you cease all violation of this License, then your
416
- license from a particular copyright holder is reinstated (a)
417
- provisionally, unless and until the copyright holder explicitly and
418
- finally terminates your license, and (b) permanently, if the copyright
419
- holder fails to notify you of the violation by some reasonable means
420
- prior to 60 days after the cessation.
421
-
422
- Moreover, your license from a particular copyright holder is
423
- reinstated permanently if the copyright holder notifies you of the
424
- violation by some reasonable means, this is the first time you have
425
- received notice of violation of this License (for any work) from that
426
- copyright holder, and you cure the violation prior to 30 days after
427
- your receipt of the notice.
428
-
429
- Termination of your rights under this section does not terminate the
430
- licenses of parties who have received copies or rights from you under
431
- this License. If your rights have been terminated and not permanently
432
- reinstated, you do not qualify to receive new licenses for the same
433
- material under section 10.
434
-
435
- 9. Acceptance Not Required for Having Copies.
436
-
437
- You are not required to accept this License in order to receive or
438
- run a copy of the Program. Ancillary propagation of a covered work
439
- occurring solely as a consequence of using peer-to-peer transmission
440
- to receive a copy likewise does not require acceptance. However,
441
- nothing other than this License grants you permission to propagate or
442
- modify any covered work. These actions infringe copyright if you do
443
- not accept this License. Therefore, by modifying or propagating a
444
- covered work, you indicate your acceptance of this License to do so.
445
-
446
- 10. Automatic Licensing of Downstream Recipients.
447
-
448
- Each time you convey a covered work, the recipient automatically
449
- receives a license from the original licensors, to run, modify and
450
- propagate that work, subject to this License. You are not responsible
451
- for enforcing compliance by third parties with this License.
452
-
453
- An "entity transaction" is a transaction transferring control of an
454
- organization, or substantially all assets of one, or subdividing an
455
- organization, or merging organizations. If propagation of a covered
456
- work results from an entity transaction, each party to that
457
- transaction who receives a copy of the work also receives whatever
458
- licenses to the work the party's predecessor in interest had or could
459
- give under the previous paragraph, plus a right to possession of the
460
- Corresponding Source of the work from the predecessor in interest, if
461
- the predecessor has it or can get it with reasonable efforts.
462
-
463
- You may not impose any further restrictions on the exercise of the
464
- rights granted or affirmed under this License. For example, you may
465
- not impose a license fee, royalty, or other charge for exercise of
466
- rights granted under this License, and you may not initiate litigation
467
- (including a cross-claim or counterclaim in a lawsuit) alleging that
468
- any patent claim is infringed by making, using, selling, offering for
469
- sale, or importing the Program or any portion of it.
470
-
471
- 11. Patents.
472
-
473
- A "contributor" is a copyright holder who authorizes use under this
474
- License of the Program or a work on which the Program is based. The
475
- work thus licensed is called the contributor's "contributor version".
476
-
477
- A contributor's "essential patent claims" are all patent claims
478
- owned or controlled by the contributor, whether already acquired or
479
- hereafter acquired, that would be infringed by some manner, permitted
480
- by this License, of making, using, or selling its contributor version,
481
- but do not include claims that would be infringed only as a
482
- consequence of further modification of the contributor version. For
483
- purposes of this definition, "control" includes the right to grant
484
- patent sublicenses in a manner consistent with the requirements of
485
- this License.
486
-
487
- Each contributor grants you a non-exclusive, worldwide, royalty-free
488
- patent license under the contributor's essential patent claims, to
489
- make, use, sell, offer for sale, import and otherwise run, modify and
490
- propagate the contents of its contributor version.
491
-
492
- In the following three paragraphs, a "patent license" is any express
493
- agreement or commitment, however denominated, not to enforce a patent
494
- (such as an express permission to practice a patent or covenant not to
495
- sue for patent infringement). To "grant" such a patent license to a
496
- party means to make such an agreement or commitment not to enforce a
497
- patent against the party.
498
-
499
- If you convey a covered work, knowingly relying on a patent license,
500
- and the Corresponding Source of the work is not available for anyone
501
- to copy, free of charge and under the terms of this License, through a
502
- publicly available network server or other readily accessible means,
503
- then you must either (1) cause the Corresponding Source to be so
504
- available, or (2) arrange to deprive yourself of the benefit of the
505
- patent license for this particular work, or (3) arrange, in a manner
506
- consistent with the requirements of this License, to extend the patent
507
- license to downstream recipients. "Knowingly relying" means you have
508
- actual knowledge that, but for the patent license, your conveying the
509
- covered work in a country, or your recipient's use of the covered work
510
- in a country, would infringe one or more identifiable patents in that
511
- country that you have reason to believe are valid.
512
-
513
- If, pursuant to or in connection with a single transaction or
514
- arrangement, you convey, or propagate by procuring conveyance of, a
515
- covered work, and grant a patent license to some of the parties
516
- receiving the covered work authorizing them to use, propagate, modify
517
- or convey a specific copy of the covered work, then the patent license
518
- you grant is automatically extended to all recipients of the covered
519
- work and works based on it.
520
-
521
- A patent license is "discriminatory" if it does not include within
522
- the scope of its coverage, prohibits the exercise of, or is
523
- conditioned on the non-exercise of one or more of the rights that are
524
- specifically granted under this License. You may not convey a covered
525
- work if you are a party to an arrangement with a third party that is
526
- in the business of distributing software, under which you make payment
527
- to the third party based on the extent of your activity of conveying
528
- the work, and under which the third party grants, to any of the
529
- parties who would receive the covered work from you, a discriminatory
530
- patent license (a) in connection with copies of the covered work
531
- conveyed by you (or copies made from those copies), or (b) primarily
532
- for and in connection with specific products or compilations that
533
- contain the covered work, unless you entered into that arrangement,
534
- or that patent license was granted, prior to 28 March 2007.
535
-
536
- Nothing in this License shall be construed as excluding or limiting
537
- any implied license or other defenses to infringement that may
538
- otherwise be available to you under applicable patent law.
539
-
540
- 12. No Surrender of Others' Freedom.
541
-
542
- If conditions are imposed on you (whether by court order, agreement or
543
- otherwise) that contradict the conditions of this License, they do not
544
- excuse you from the conditions of this License. If you cannot convey a
545
- covered work so as to satisfy simultaneously your obligations under this
546
- License and any other pertinent obligations, then as a consequence you may
547
- not convey it at all. For example, if you agree to terms that obligate you
548
- to collect a royalty for further conveying from those to whom you convey
549
- the Program, the only way you could satisfy both those terms and this
550
- License would be to refrain entirely from conveying the Program.
551
-
552
- 13. Use with the GNU Affero General Public License.
553
-
554
- Notwithstanding any other provision of this License, you have
555
- permission to link or combine any covered work with a work licensed
556
- under version 3 of the GNU Affero General Public License into a single
557
- combined work, and to convey the resulting work. The terms of this
558
- License will continue to apply to the part which is the covered work,
559
- but the special requirements of the GNU Affero General Public License,
560
- section 13, concerning interaction through a network will apply to the
561
- combination as such.
562
-
563
- 14. Revised Versions of this License.
564
-
565
- The Free Software Foundation may publish revised and/or new versions of
566
- the GNU General Public License from time to time. Such new versions will
567
- be similar in spirit to the present version, but may differ in detail to
568
- address new problems or concerns.
569
-
570
- Each version is given a distinguishing version number. If the
571
- Program specifies that a certain numbered version of the GNU General
572
- Public License "or any later version" applies to it, you have the
573
- option of following the terms and conditions either of that numbered
574
- version or of any later version published by the Free Software
575
- Foundation. If the Program does not specify a version number of the
576
- GNU General Public License, you may choose any version ever published
577
- by the Free Software Foundation.
578
-
579
- If the Program specifies that a proxy can decide which future
580
- versions of the GNU General Public License can be used, that proxy's
581
- public statement of acceptance of a version permanently authorizes you
582
- to choose that version for the Program.
583
-
584
- Later license versions may give you additional or different
585
- permissions. However, no additional obligations are imposed on any
586
- author or copyright holder as a result of your choosing to follow a
587
- later version.
588
-
589
- 15. Disclaimer of Warranty.
590
-
591
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
- APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
- HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
- OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
- PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
- IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
- ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
-
600
- 16. Limitation of Liability.
601
-
602
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
- WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
- THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
- GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
- USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
- DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
- PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
- EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
- SUCH DAMAGES.
611
-
612
- 17. Interpretation of Sections 15 and 16.
613
-
614
- If the disclaimer of warranty and limitation of liability provided
615
- above cannot be given local legal effect according to their terms,
616
- reviewing courts shall apply local law that most closely approximates
617
- an absolute waiver of all civil liability in connection with the
618
- Program, unless a warranty or assumption of liability accompanies a
619
- copy of the Program in return for a fee.
620
-
621
- END OF TERMS AND CONDITIONS
622
-
623
- How to Apply These Terms to Your New Programs
624
-
625
- If you develop a new program, and you want it to be of the greatest
626
- possible use to the public, the best way to achieve this is to make it
627
- free software which everyone can redistribute and change under these terms.
628
-
629
- To do so, attach the following notices to the program. It is safest
630
- to attach them to the start of each source file to most effectively
631
- state the exclusion of warranty; and each file should have at least
632
- the "copyright" line and a pointer to where the full notice is found.
633
-
634
- <one line to give the program's name and a brief idea of what it does.>
635
- Copyright (C) <year> <name of author>
636
-
637
- This program is free software: you can redistribute it and/or modify
638
- it under the terms of the GNU General Public License as published by
639
- the Free Software Foundation, either version 3 of the License, or
640
- (at your option) any later version.
641
-
642
- This program is distributed in the hope that it will be useful,
643
- but WITHOUT ANY WARRANTY; without even the implied warranty of
644
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
- GNU General Public License for more details.
646
-
647
- You should have received a copy of the GNU General Public License
648
- along with this program. If not, see <https://www.gnu.org/licenses/>.
649
-
650
- Also add information on how to contact you by electronic and paper mail.
651
-
652
- If the program does terminal interaction, make it output a short
653
- notice like this when it starts in an interactive mode:
654
-
655
- <program> Copyright (C) <year> <name of author>
656
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
- This is free software, and you are welcome to redistribute it
658
- under certain conditions; type `show c' for details.
659
-
660
- The hypothetical commands `show w' and `show c' should show the appropriate
661
- parts of the General Public License. Of course, your program's commands
662
- might be different; for a GUI interface, you would use an "about box".
663
-
664
- You should also get your employer (if you work as a programmer) or school,
665
- if any, to sign a "copyright disclaimer" for the program, if necessary.
666
- For more information on this, and how to apply and follow the GNU GPL, see
667
- <https://www.gnu.org/licenses/>.
668
-
669
- The GNU General Public License does not permit incorporating your program
670
- into proprietary programs. If your program is a subroutine library, you
671
- may consider it more useful to permit linking proprietary applications with
672
- the library. If this is what you want to do, use the GNU Lesser General
673
- Public License instead of this License. But first, please read
674
- <https://www.gnu.org/licenses/why-not-lgpl.html>.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/filedropzone/Factory.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import FileDropZone from './FileDropZone.js';
2
-
3
- export default function (
4
- config?: FileDropZone.IConfig
5
- ): FileDropZone;
 
 
 
 
 
 
spaces/AlexWang/lama/models/ade20k/segm_lib/nn/modules/__init__.py DELETED
@@ -1,12 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- # File : __init__.py
3
- # Author : Jiayuan Mao
4
- # Email : [email protected]
5
- # Date : 27/01/2018
6
- #
7
- # This file is part of Synchronized-BatchNorm-PyTorch.
8
- # https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
9
- # Distributed under MIT License.
10
-
11
- from .batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d
12
- from .replicate import DataParallelWithCallback, patch_replication_callback
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_detection/configs/instaboost/mask_rcnn_x101_64x4d_fpn_instaboost_4x_coco.py DELETED
@@ -1,13 +0,0 @@
1
- _base_ = './mask_rcnn_r50_fpn_instaboost_4x_coco.py'
2
- model = dict(
3
- pretrained='open-mmlab://resnext101_64x4d',
4
- backbone=dict(
5
- type='ResNeXt',
6
- depth=101,
7
- groups=64,
8
- base_width=4,
9
- num_stages=4,
10
- out_indices=(0, 1, 2, 3),
11
- frozen_stages=1,
12
- norm_cfg=dict(type='BN', requires_grad=True),
13
- style='pytorch'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_detection/mmdet/models/backbones/res2net.py DELETED
@@ -1,351 +0,0 @@
1
- import math
2
-
3
- import torch
4
- import torch.nn as nn
5
- import torch.utils.checkpoint as cp
6
- from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
7
- kaiming_init)
8
- from mmcv.runner import load_checkpoint
9
- from torch.nn.modules.batchnorm import _BatchNorm
10
-
11
- from mmdet.utils import get_root_logger
12
- from ..builder import BACKBONES
13
- from .resnet import Bottleneck as _Bottleneck
14
- from .resnet import ResNet
15
-
16
-
17
- class Bottle2neck(_Bottleneck):
18
- expansion = 4
19
-
20
- def __init__(self,
21
- inplanes,
22
- planes,
23
- scales=4,
24
- base_width=26,
25
- base_channels=64,
26
- stage_type='normal',
27
- **kwargs):
28
- """Bottle2neck block for Res2Net.
29
-
30
- If style is "pytorch", the stride-two layer is the 3x3 conv layer, if
31
- it is "caffe", the stride-two layer is the first 1x1 conv layer.
32
- """
33
- super(Bottle2neck, self).__init__(inplanes, planes, **kwargs)
34
- assert scales > 1, 'Res2Net degenerates to ResNet when scales = 1.'
35
- width = int(math.floor(self.planes * (base_width / base_channels)))
36
-
37
- self.norm1_name, norm1 = build_norm_layer(
38
- self.norm_cfg, width * scales, postfix=1)
39
- self.norm3_name, norm3 = build_norm_layer(
40
- self.norm_cfg, self.planes * self.expansion, postfix=3)
41
-
42
- self.conv1 = build_conv_layer(
43
- self.conv_cfg,
44
- self.inplanes,
45
- width * scales,
46
- kernel_size=1,
47
- stride=self.conv1_stride,
48
- bias=False)
49
- self.add_module(self.norm1_name, norm1)
50
-
51
- if stage_type == 'stage' and self.conv2_stride != 1:
52
- self.pool = nn.AvgPool2d(
53
- kernel_size=3, stride=self.conv2_stride, padding=1)
54
- convs = []
55
- bns = []
56
-
57
- fallback_on_stride = False
58
- if self.with_dcn:
59
- fallback_on_stride = self.dcn.pop('fallback_on_stride', False)
60
- if not self.with_dcn or fallback_on_stride:
61
- for i in range(scales - 1):
62
- convs.append(
63
- build_conv_layer(
64
- self.conv_cfg,
65
- width,
66
- width,
67
- kernel_size=3,
68
- stride=self.conv2_stride,
69
- padding=self.dilation,
70
- dilation=self.dilation,
71
- bias=False))
72
- bns.append(
73
- build_norm_layer(self.norm_cfg, width, postfix=i + 1)[1])
74
- self.convs = nn.ModuleList(convs)
75
- self.bns = nn.ModuleList(bns)
76
- else:
77
- assert self.conv_cfg is None, 'conv_cfg must be None for DCN'
78
- for i in range(scales - 1):
79
- convs.append(
80
- build_conv_layer(
81
- self.dcn,
82
- width,
83
- width,
84
- kernel_size=3,
85
- stride=self.conv2_stride,
86
- padding=self.dilation,
87
- dilation=self.dilation,
88
- bias=False))
89
- bns.append(
90
- build_norm_layer(self.norm_cfg, width, postfix=i + 1)[1])
91
- self.convs = nn.ModuleList(convs)
92
- self.bns = nn.ModuleList(bns)
93
-
94
- self.conv3 = build_conv_layer(
95
- self.conv_cfg,
96
- width * scales,
97
- self.planes * self.expansion,
98
- kernel_size=1,
99
- bias=False)
100
- self.add_module(self.norm3_name, norm3)
101
-
102
- self.stage_type = stage_type
103
- self.scales = scales
104
- self.width = width
105
- delattr(self, 'conv2')
106
- delattr(self, self.norm2_name)
107
-
108
- def forward(self, x):
109
- """Forward function."""
110
-
111
- def _inner_forward(x):
112
- identity = x
113
-
114
- out = self.conv1(x)
115
- out = self.norm1(out)
116
- out = self.relu(out)
117
-
118
- if self.with_plugins:
119
- out = self.forward_plugin(out, self.after_conv1_plugin_names)
120
-
121
- spx = torch.split(out, self.width, 1)
122
- sp = self.convs[0](spx[0].contiguous())
123
- sp = self.relu(self.bns[0](sp))
124
- out = sp
125
- for i in range(1, self.scales - 1):
126
- if self.stage_type == 'stage':
127
- sp = spx[i]
128
- else:
129
- sp = sp + spx[i]
130
- sp = self.convs[i](sp.contiguous())
131
- sp = self.relu(self.bns[i](sp))
132
- out = torch.cat((out, sp), 1)
133
-
134
- if self.stage_type == 'normal' or self.conv2_stride == 1:
135
- out = torch.cat((out, spx[self.scales - 1]), 1)
136
- elif self.stage_type == 'stage':
137
- out = torch.cat((out, self.pool(spx[self.scales - 1])), 1)
138
-
139
- if self.with_plugins:
140
- out = self.forward_plugin(out, self.after_conv2_plugin_names)
141
-
142
- out = self.conv3(out)
143
- out = self.norm3(out)
144
-
145
- if self.with_plugins:
146
- out = self.forward_plugin(out, self.after_conv3_plugin_names)
147
-
148
- if self.downsample is not None:
149
- identity = self.downsample(x)
150
-
151
- out += identity
152
-
153
- return out
154
-
155
- if self.with_cp and x.requires_grad:
156
- out = cp.checkpoint(_inner_forward, x)
157
- else:
158
- out = _inner_forward(x)
159
-
160
- out = self.relu(out)
161
-
162
- return out
163
-
164
-
165
- class Res2Layer(nn.Sequential):
166
- """Res2Layer to build Res2Net style backbone.
167
-
168
- Args:
169
- block (nn.Module): block used to build ResLayer.
170
- inplanes (int): inplanes of block.
171
- planes (int): planes of block.
172
- num_blocks (int): number of blocks.
173
- stride (int): stride of the first block. Default: 1
174
- avg_down (bool): Use AvgPool instead of stride conv when
175
- downsampling in the bottle2neck. Default: False
176
- conv_cfg (dict): dictionary to construct and config conv layer.
177
- Default: None
178
- norm_cfg (dict): dictionary to construct and config norm layer.
179
- Default: dict(type='BN')
180
- scales (int): Scales used in Res2Net. Default: 4
181
- base_width (int): Basic width of each scale. Default: 26
182
- """
183
-
184
- def __init__(self,
185
- block,
186
- inplanes,
187
- planes,
188
- num_blocks,
189
- stride=1,
190
- avg_down=True,
191
- conv_cfg=None,
192
- norm_cfg=dict(type='BN'),
193
- scales=4,
194
- base_width=26,
195
- **kwargs):
196
- self.block = block
197
-
198
- downsample = None
199
- if stride != 1 or inplanes != planes * block.expansion:
200
- downsample = nn.Sequential(
201
- nn.AvgPool2d(
202
- kernel_size=stride,
203
- stride=stride,
204
- ceil_mode=True,
205
- count_include_pad=False),
206
- build_conv_layer(
207
- conv_cfg,
208
- inplanes,
209
- planes * block.expansion,
210
- kernel_size=1,
211
- stride=1,
212
- bias=False),
213
- build_norm_layer(norm_cfg, planes * block.expansion)[1],
214
- )
215
-
216
- layers = []
217
- layers.append(
218
- block(
219
- inplanes=inplanes,
220
- planes=planes,
221
- stride=stride,
222
- downsample=downsample,
223
- conv_cfg=conv_cfg,
224
- norm_cfg=norm_cfg,
225
- scales=scales,
226
- base_width=base_width,
227
- stage_type='stage',
228
- **kwargs))
229
- inplanes = planes * block.expansion
230
- for i in range(1, num_blocks):
231
- layers.append(
232
- block(
233
- inplanes=inplanes,
234
- planes=planes,
235
- stride=1,
236
- conv_cfg=conv_cfg,
237
- norm_cfg=norm_cfg,
238
- scales=scales,
239
- base_width=base_width,
240
- **kwargs))
241
- super(Res2Layer, self).__init__(*layers)
242
-
243
-
244
- @BACKBONES.register_module()
245
- class Res2Net(ResNet):
246
- """Res2Net backbone.
247
-
248
- Args:
249
- scales (int): Scales used in Res2Net. Default: 4
250
- base_width (int): Basic width of each scale. Default: 26
251
- depth (int): Depth of res2net, from {50, 101, 152}.
252
- in_channels (int): Number of input image channels. Default: 3.
253
- num_stages (int): Res2net stages. Default: 4.
254
- strides (Sequence[int]): Strides of the first block of each stage.
255
- dilations (Sequence[int]): Dilation of each stage.
256
- out_indices (Sequence[int]): Output from which stages.
257
- style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
258
- layer is the 3x3 conv layer, otherwise the stride-two layer is
259
- the first 1x1 conv layer.
260
- deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv
261
- avg_down (bool): Use AvgPool instead of stride conv when
262
- downsampling in the bottle2neck.
263
- frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
264
- -1 means not freezing any parameters.
265
- norm_cfg (dict): Dictionary to construct and config norm layer.
266
- norm_eval (bool): Whether to set norm layers to eval mode, namely,
267
- freeze running stats (mean and var). Note: Effect on Batch Norm
268
- and its variants only.
269
- plugins (list[dict]): List of plugins for stages, each dict contains:
270
-
271
- - cfg (dict, required): Cfg dict to build plugin.
272
- - position (str, required): Position inside block to insert
273
- plugin, options are 'after_conv1', 'after_conv2', 'after_conv3'.
274
- - stages (tuple[bool], optional): Stages to apply plugin, length
275
- should be same as 'num_stages'.
276
- with_cp (bool): Use checkpoint or not. Using checkpoint will save some
277
- memory while slowing down the training speed.
278
- zero_init_residual (bool): Whether to use zero init for last norm layer
279
- in resblocks to let them behave as identity.
280
-
281
- Example:
282
- >>> from mmdet.models import Res2Net
283
- >>> import torch
284
- >>> self = Res2Net(depth=50, scales=4, base_width=26)
285
- >>> self.eval()
286
- >>> inputs = torch.rand(1, 3, 32, 32)
287
- >>> level_outputs = self.forward(inputs)
288
- >>> for level_out in level_outputs:
289
- ... print(tuple(level_out.shape))
290
- (1, 256, 8, 8)
291
- (1, 512, 4, 4)
292
- (1, 1024, 2, 2)
293
- (1, 2048, 1, 1)
294
- """
295
-
296
- arch_settings = {
297
- 50: (Bottle2neck, (3, 4, 6, 3)),
298
- 101: (Bottle2neck, (3, 4, 23, 3)),
299
- 152: (Bottle2neck, (3, 8, 36, 3))
300
- }
301
-
302
- def __init__(self,
303
- scales=4,
304
- base_width=26,
305
- style='pytorch',
306
- deep_stem=True,
307
- avg_down=True,
308
- **kwargs):
309
- self.scales = scales
310
- self.base_width = base_width
311
- super(Res2Net, self).__init__(
312
- style='pytorch', deep_stem=True, avg_down=True, **kwargs)
313
-
314
- def make_res_layer(self, **kwargs):
315
- return Res2Layer(
316
- scales=self.scales,
317
- base_width=self.base_width,
318
- base_channels=self.base_channels,
319
- **kwargs)
320
-
321
- def init_weights(self, pretrained=None):
322
- """Initialize the weights in backbone.
323
-
324
- Args:
325
- pretrained (str, optional): Path to pre-trained weights.
326
- Defaults to None.
327
- """
328
- if isinstance(pretrained, str):
329
- logger = get_root_logger()
330
- load_checkpoint(self, pretrained, strict=False, logger=logger)
331
- elif pretrained is None:
332
- for m in self.modules():
333
- if isinstance(m, nn.Conv2d):
334
- kaiming_init(m)
335
- elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
336
- constant_init(m, 1)
337
-
338
- if self.dcn is not None:
339
- for m in self.modules():
340
- if isinstance(m, Bottle2neck):
341
- # dcn in Res2Net bottle2neck is in ModuleList
342
- for n in m.convs:
343
- if hasattr(n, 'conv_offset'):
344
- constant_init(n.conv_offset, 0)
345
-
346
- if self.zero_init_residual:
347
- for m in self.modules():
348
- if isinstance(m, Bottle2neck):
349
- constant_init(m.norm3, 0)
350
- else:
351
- raise TypeError('pretrained must be a str or None')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_segmentation/configs/_base_/models/nonlocal_r50-d8.py DELETED
@@ -1,46 +0,0 @@
1
- # model settings
2
- norm_cfg = dict(type='SyncBN', requires_grad=True)
3
- model = dict(
4
- type='EncoderDecoder',
5
- pretrained='open-mmlab://resnet50_v1c',
6
- backbone=dict(
7
- type='ResNetV1c',
8
- depth=50,
9
- num_stages=4,
10
- out_indices=(0, 1, 2, 3),
11
- dilations=(1, 1, 2, 4),
12
- strides=(1, 2, 1, 1),
13
- norm_cfg=norm_cfg,
14
- norm_eval=False,
15
- style='pytorch',
16
- contract_dilation=True),
17
- decode_head=dict(
18
- type='NLHead',
19
- in_channels=2048,
20
- in_index=3,
21
- channels=512,
22
- dropout_ratio=0.1,
23
- reduction=2,
24
- use_scale=True,
25
- mode='embedded_gaussian',
26
- num_classes=19,
27
- norm_cfg=norm_cfg,
28
- align_corners=False,
29
- loss_decode=dict(
30
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
31
- auxiliary_head=dict(
32
- type='FCNHead',
33
- in_channels=1024,
34
- in_index=2,
35
- channels=256,
36
- num_convs=1,
37
- concat_input=False,
38
- dropout_ratio=0.1,
39
- num_classes=19,
40
- norm_cfg=norm_cfg,
41
- align_corners=False,
42
- loss_decode=dict(
43
- type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),
44
- # model training and testing settings
45
- train_cfg=dict(),
46
- test_cfg=dict(mode='whole'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_segmentation/configs/nonlocal_net/README.md DELETED
@@ -1,48 +0,0 @@
1
- # Non-local Neural Networks
2
-
3
- ## Introduction
4
-
5
- <!-- [ALGORITHM] -->
6
-
7
- ```latex
8
- @inproceedings{wang2018non,
9
- title={Non-local neural networks},
10
- author={Wang, Xiaolong and Girshick, Ross and Gupta, Abhinav and He, Kaiming},
11
- booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition},
12
- pages={7794--7803},
13
- year={2018}
14
- }
15
- ```
16
-
17
- ## Results and models
18
-
19
- ### Cityscapes
20
-
21
- | Method | Backbone | Crop Size | Lr schd | Mem (GB) | Inf time (fps) | mIoU | mIoU(ms+flip) | config | download |
22
- | -------- | -------- | --------- | ------: | -------- | -------------- | ----: | ------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
23
- | NonLocal | R-50-D8 | 512x1024 | 40000 | 7.4 | 2.72 | 78.24 | - | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_512x1024_40k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x1024_40k_cityscapes/nonlocal_r50-d8_512x1024_40k_cityscapes_20200605_210748-c75e81e3.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x1024_40k_cityscapes/nonlocal_r50-d8_512x1024_40k_cityscapes_20200605_210748.log.json) |
24
- | NonLocal | R-101-D8 | 512x1024 | 40000 | 10.9 | 1.95 | 78.66 | - | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_512x1024_40k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x1024_40k_cityscapes/nonlocal_r101-d8_512x1024_40k_cityscapes_20200605_210748-d63729fa.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x1024_40k_cityscapes/nonlocal_r101-d8_512x1024_40k_cityscapes_20200605_210748.log.json) |
25
- | NonLocal | R-50-D8 | 769x769 | 40000 | 8.9 | 1.52 | 78.33 | 79.92 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_769x769_40k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_769x769_40k_cityscapes/nonlocal_r50-d8_769x769_40k_cityscapes_20200530_045243-82ef6749.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_769x769_40k_cityscapes/nonlocal_r50-d8_769x769_40k_cityscapes_20200530_045243.log.json) |
26
- | NonLocal | R-101-D8 | 769x769 | 40000 | 12.8 | 1.05 | 78.57 | 80.29 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_769x769_40k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_769x769_40k_cityscapes/nonlocal_r101-d8_769x769_40k_cityscapes_20200530_045348-8fe9a9dc.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_769x769_40k_cityscapes/nonlocal_r101-d8_769x769_40k_cityscapes_20200530_045348.log.json) |
27
- | NonLocal | R-50-D8 | 512x1024 | 80000 | - | - | 78.01 | - | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_512x1024_80k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x1024_80k_cityscapes/nonlocal_r50-d8_512x1024_80k_cityscapes_20200607_193518-d6839fae.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x1024_80k_cityscapes/nonlocal_r50-d8_512x1024_80k_cityscapes_20200607_193518.log.json) |
28
- | NonLocal | R-101-D8 | 512x1024 | 80000 | - | - | 78.93 | - | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_512x1024_80k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x1024_80k_cityscapes/nonlocal_r101-d8_512x1024_80k_cityscapes_20200607_183411-32700183.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x1024_80k_cityscapes/nonlocal_r101-d8_512x1024_80k_cityscapes_20200607_183411.log.json) |
29
- | NonLocal | R-50-D8 | 769x769 | 80000 | - | - | 79.05 | 80.68 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_769x769_80k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_769x769_80k_cityscapes/nonlocal_r50-d8_769x769_80k_cityscapes_20200607_193506-1f9792f6.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_769x769_80k_cityscapes/nonlocal_r50-d8_769x769_80k_cityscapes_20200607_193506.log.json) |
30
- | NonLocal | R-101-D8 | 769x769 | 80000 | - | - | 79.40 | 80.85 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_769x769_80k_cityscapes.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_769x769_80k_cityscapes/nonlocal_r101-d8_769x769_80k_cityscapes_20200607_183428-0e1fa4f9.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_769x769_80k_cityscapes/nonlocal_r101-d8_769x769_80k_cityscapes_20200607_183428.log.json) |
31
-
32
- ### ADE20K
33
-
34
- | Method | Backbone | Crop Size | Lr schd | Mem (GB) | Inf time (fps) | mIoU | mIoU(ms+flip) | config | download |
35
- | -------- | -------- | --------- | ------: | -------- | -------------- | ----: | ------------: | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
- | NonLocal | R-50-D8 | 512x512 | 80000 | 9.1 | 21.37 | 40.75 | 42.05 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_512x512_80k_ade20k.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_80k_ade20k/nonlocal_r50-d8_512x512_80k_ade20k_20200615_015801-5ae0aa33.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_80k_ade20k/nonlocal_r50-d8_512x512_80k_ade20k_20200615_015801.log.json) |
37
- | NonLocal | R-101-D8 | 512x512 | 80000 | 12.6 | 13.97 | 42.90 | 44.27 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_512x512_80k_ade20k.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_80k_ade20k/nonlocal_r101-d8_512x512_80k_ade20k_20200615_015758-24105919.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_80k_ade20k/nonlocal_r101-d8_512x512_80k_ade20k_20200615_015758.log.json) |
38
- | NonLocal | R-50-D8 | 512x512 | 160000 | - | - | 42.03 | 43.04 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_512x512_160k_ade20k.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_160k_ade20k/nonlocal_r50-d8_512x512_160k_ade20k_20200616_005410-baef45e3.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_160k_ade20k/nonlocal_r50-d8_512x512_160k_ade20k_20200616_005410.log.json) |
39
- | NonLocal | R-101-D8 | 512x512 | 160000 | - | - | 43.36 | 44.83 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_512x512_160k_ade20k.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_160k_ade20k/nonlocal_r101-d8_512x512_160k_ade20k_20200616_003422-affd0f8d.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_160k_ade20k/nonlocal_r101-d8_512x512_160k_ade20k_20200616_003422.log.json) |
40
-
41
- ### Pascal VOC 2012 + Aug
42
-
43
- | Method | Backbone | Crop Size | Lr schd | Mem (GB) | Inf time (fps) | mIoU | mIoU(ms+flip) | config | download |
44
- | -------- | -------- | --------- | ------: | -------- | -------------- | ----: | ------------: | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
- | NonLocal | R-50-D8 | 512x512 | 20000 | 6.4 | 21.21 | 76.20 | 77.12 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_512x512_20k_voc12aug.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_20k_voc12aug/nonlocal_r50-d8_512x512_20k_voc12aug_20200617_222613-07f2a57c.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_20k_voc12aug/nonlocal_r50-d8_512x512_20k_voc12aug_20200617_222613.log.json) |
46
- | NonLocal | R-101-D8 | 512x512 | 20000 | 9.8 | 14.01 | 78.15 | 78.86 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_512x512_20k_voc12aug.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_20k_voc12aug/nonlocal_r101-d8_512x512_20k_voc12aug_20200617_222615-948c68ab.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_20k_voc12aug/nonlocal_r101-d8_512x512_20k_voc12aug_20200617_222615.log.json) |
47
- | NonLocal | R-50-D8 | 512x512 | 40000 | - | - | 76.65 | 77.47 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r50-d8_512x512_40k_voc12aug.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_40k_voc12aug/nonlocal_r50-d8_512x512_40k_voc12aug_20200614_000028-0139d4a9.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r50-d8_512x512_40k_voc12aug/nonlocal_r50-d8_512x512_40k_voc12aug_20200614_000028.log.json) |
48
- | NonLocal | R-101-D8 | 512x512 | 40000 | - | - | 78.27 | 79.12 | [config](https://github.com/open-mmlab/mmsegmentation/blob/master/configs/nonlocal_net/nonlocal_r101-d8_512x512_40k_voc12aug.py) | [model](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_40k_voc12aug/nonlocal_r101-d8_512x512_40k_voc12aug_20200614_000028-7e5ff470.pth) &#124; [log](https://download.openmmlab.com/mmsegmentation/v0.5/nonlocal_net/nonlocal_r101-d8_512x512_40k_voc12aug/nonlocal_r101-d8_512x512_40k_voc12aug_20200614_000028.log.json) |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AnimaLab/bias-test-gpt-pairs/openAI_manager.py DELETED
@@ -1,191 +0,0 @@
1
- import openai
2
- import backoff
3
- import json
4
- import re
5
- import random
6
-
7
- import mgr_bias_scoring as bt_mgr
8
-
9
- def initOpenAI(key):
10
- openai.api_key = key
11
-
12
- # list models
13
- models = openai.Model.list()
14
-
15
- return models
16
-
17
- # construct prompts from example_shots
18
- def examples_to_prompt(example_shots, kwd_pair):
19
- prompt = ""
20
- for shot in example_shots:
21
- prompt += "Keywords: "+', '.join(shot['Keywords'])+" ## Sentence: "+ \
22
- shot['Sentence']+" ##\n"
23
- prompt += f"Keywords: {kwd_pair[0]}, {kwd_pair[1]} ## Sentence: "
24
- return prompt
25
-
26
- def genChatGPT(model_name, kwd_pair, bias_spec, num2gen, numTries, temperature=0.8):
27
- t1, t2, a1, a2 = bt_mgr.get_words(bias_spec)
28
- att_terms_str = ','.join([f"'{t}'" for t in random.sample(a1+a2, min(8, len(a1+a2)))])
29
- t_terms_str = ','.join([f"'{t}'" for t in random.sample(t1+t2, min(8, len(t1+t2)))])
30
-
31
- # find out which social group the generator term belongs to
32
- grp_term = kwd_pair[0]
33
- if grp_term in t1:
34
- grp_term_idx = t1.index(grp_term)
35
- grp_term_pair = [grp_term, t2[grp_term_idx]]
36
- else:
37
- grp_term_idx = t2.index(grp_term)
38
- grp_term_pair = [grp_term, t1[grp_term_idx]]
39
-
40
- # construct prompt
41
- #instruction = f"Write a sentence including terms \"{kwd_pair[0]}\" and \"{kwd_pair[1]}\"."# Use examples as guide for the type of sentences to write."
42
- #prompt = examples_to_prompt(example_shots, kwd_pair)
43
- instruction = f"Write a sentence including target term \"{kwd_pair[0]}\" and attribute term \"{kwd_pair[1]}\".\n \
44
- Other target terms in this context are: {t_terms_str}. Use them for interpretation of requested target term, but don't include these specifically. \
45
- Other attribute terms in this context are: {att_terms_str}. Use them for interpretation of requested attribute term, but don't include these specifically. "# Use examples as guide for the type of sentences to write."
46
-
47
- #print(f"Prompt: {prompt}")
48
- #print(f"Instruction: {instruction}")
49
-
50
- # https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb
51
- @backoff.on_exception(backoff.expo, (openai.error.RateLimitError,
52
- openai.error.APIError,
53
- openai.error.ServiceUnavailableError,
54
- ConnectionResetError,
55
- json.decoder.JSONDecodeError))#,
56
- #max_time=300,
57
- #raise_on_giveup=False,
58
- #giveup=fatal_code)
59
-
60
- def completions_with_backoff(**kwargs):
61
- return openai.ChatCompletion.create(**kwargs)
62
-
63
- resp = []
64
- tries = 0
65
- while len(resp) < num2gen and tries < numTries:
66
- # Prompt OpenAI
67
- # https://platform.openai.com/docs/api-reference/chat/create
68
- response = completions_with_backoff(model=model_name,
69
- temperature=temperature,
70
- messages=[{"role": "system", "content": instruction}])
71
- # ,{"role": "user", "content": prompt}
72
-
73
- sentence = response["choices"][0]["message"]["content"]
74
-
75
- fnd_kwd_0 = list(re.finditer(f'{kwd_pair[0].lower()}[ .,!]+', sentence.lower()))
76
- fnd_kwd_1 = list(re.finditer(f'{kwd_pair[1].lower()}[ .,!]+', sentence.lower()))
77
- if len(fnd_kwd_0)>0 and len(fnd_kwd_1)>0:
78
- resp.append([kwd_pair[0], kwd_pair[1], sentence, grp_term_pair[0], grp_term_pair[1]])
79
-
80
- tries += 1
81
-
82
- return resp, instruction
83
-
84
- # Prompt ChatGPT to write a sentence alternaitve for the other social group term
85
- def promptChatGPTTemplate(model_name, term1, term2, sentence, temperature=0.0):
86
- instruction = f"Rewrite the sentence to replace {term1} with {term2}. Make only minimal changes to preserve grammar."
87
- prompt = f"Sentence: {sentence}, Rewrite: "
88
-
89
- # https://github.com/openai/openai-cookbook/blob/main/examples/How_to_handle_rate_limits.ipynb
90
- @backoff.on_exception(backoff.expo, (openai.error.RateLimitError,
91
- openai.error.APIError,
92
- openai.error.ServiceUnavailableError,
93
- ConnectionResetError,
94
- json.decoder.JSONDecodeError))
95
-
96
- def completions_with_backoff(**kwargs):
97
- return openai.ChatCompletion.create(**kwargs)
98
-
99
- # Prompt OpenAI
100
- # https://platform.openai.com/docs/api-reference/chat/create
101
- response = completions_with_backoff(model=model_name,
102
- temperature=temperature,
103
- messages=[{"role": "system", "content": instruction},
104
- {"role": "user", "content": prompt}])
105
-
106
- return response["choices"][0]["message"]["content"]
107
-
108
- # turn generated sentence into a test templates
109
- def chatgpt_sentence_alternative(row, model_name):
110
- sentence = row['Sentence']
111
- grp_term = row['org_grp_term']
112
- att_term = row['Attribute term']
113
- grp_term1 = row['Group term 1']
114
- grp_term2 = row['Group term 2']
115
-
116
- rewrite = promptChatGPTTemplate(model_name, grp_term1, grp_term2, sentence)
117
-
118
- #template, grp_refs = maskDifferences(sentence, rewrite, grp_term_pair, att_term)
119
- return rewrite
120
-
121
- def generateTestSentencesCustom(model_name, gr1_kwds, gr2_kwds, attribute_kwds, att_counts, bias_spec, progress):
122
- print(f"Running Custom Sentence Generator, Counts:\n {att_counts}")
123
- print(f"Groups: [{gr1_kwds}, {gr2_kwds}]\nAttributes: {attribute_kwds}")
124
-
125
- numGlobTries = 5
126
- numTries = 10
127
- all_gens = []
128
- show_instr = False
129
- num_steps = len(attribute_kwds)
130
- for ai, att_kwd in enumerate(attribute_kwds):
131
- print(f'Running att: {att_kwd}..')
132
- att_count = 0
133
- if att_kwd in att_counts:
134
- att_count = att_counts[att_kwd]
135
- elif att_kwd.replace(' ','-') in att_counts:
136
- att_count = att_counts[att_kwd.replace(' ','-')]
137
- else:
138
- print(f"Missing count for attribute: <{att_kwd}>")
139
-
140
- if att_count != 0:
141
- print(f"For {att_kwd} generate {att_count}")
142
-
143
- att_gens = []
144
- glob_tries = 0
145
- while len(att_gens) < att_count and glob_tries < att_count*numGlobTries:
146
- gr1_kwd = random.sample(gr1_kwds, 1)[0]
147
- gr2_kwd = random.sample(gr2_kwds, 1)[0]
148
-
149
- for kwd_pair in [[gr1_kwd.strip(), att_kwd.strip()], [gr2_kwd.strip(), att_kwd.strip()]]:
150
- progress((ai)/num_steps, desc=f"Generating {kwd_pair[0]}<>{att_kwd}...")
151
-
152
- gens, instruction = genChatGPT(model_name, kwd_pair, bias_spec, 1, numTries, temperature=0.8)
153
- att_gens.extend(gens)
154
-
155
- if show_instr == False:
156
- print(f"Instruction: {instruction}")
157
- show_instr = True
158
-
159
- glob_tries += 1
160
- print(".", end="", flush=True)
161
- print()
162
-
163
- if len(att_gens) > att_count:
164
- print(f"Downsampling from {len(att_gens)} to {att_count}...")
165
- att_gens = random.sample(att_gens, att_count)
166
-
167
- print(f"Num generated: {len(att_gens)}")
168
- all_gens.extend(att_gens)
169
-
170
- return all_gens
171
-
172
-
173
- # generate sentences
174
- def generateTestSentences(model_name, group_kwds, attribute_kwds, num2gen, progress):
175
- print(f"Groups: [{group_kwds}]\nAttributes: [{attribute_kwds}]")
176
-
177
- numTries = 5
178
- #num2gen = 2
179
- all_gens = []
180
- num_steps = len(group_kwds)*len(attribute_kwds)
181
- for gi, grp_kwd in enumerate(group_kwds):
182
- for ai, att_kwd in enumerate(attribute_kwds):
183
- progress((gi*len(attribute_kwds)+ai)/num_steps, desc=f"Generating {grp_kwd}<>{att_kwd}...")
184
-
185
- kwd_pair = [grp_kwd.strip(), att_kwd.strip()]
186
-
187
- gens = genChatGPT(model_name, kwd_pair, num2gen, numTries, temperature=0.8)
188
- #print(f"Gens for pair: <{kwd_pair}> -> {gens}")
189
- all_gens.extend(gens)
190
-
191
- return all_gens
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/tool_add_control.py DELETED
@@ -1,50 +0,0 @@
1
- import sys
2
- import os
3
-
4
- assert len(sys.argv) == 3, 'Args are wrong.'
5
-
6
- input_path = sys.argv[1]
7
- output_path = sys.argv[2]
8
-
9
- assert os.path.exists(input_path), 'Input model does not exist.'
10
- assert not os.path.exists(output_path), 'Output filename already exists.'
11
- assert os.path.exists(os.path.dirname(output_path)), 'Output path is not valid.'
12
-
13
- import torch
14
- from share import *
15
- from cldm.model import create_model
16
-
17
-
18
- def get_node_name(name, parent_name):
19
- if len(name) <= len(parent_name):
20
- return False, ''
21
- p = name[:len(parent_name)]
22
- if p != parent_name:
23
- return False, ''
24
- return True, name[len(parent_name):]
25
-
26
-
27
- model = create_model(config_path='./models/cldm_v15.yaml')
28
-
29
- pretrained_weights = torch.load(input_path)
30
- if 'state_dict' in pretrained_weights:
31
- pretrained_weights = pretrained_weights['state_dict']
32
-
33
- scratch_dict = model.state_dict()
34
-
35
- target_dict = {}
36
- for k in scratch_dict.keys():
37
- is_control, name = get_node_name(k, 'control_')
38
- if is_control:
39
- copy_k = 'model.diffusion_' + name
40
- else:
41
- copy_k = k
42
- if copy_k in pretrained_weights:
43
- target_dict[k] = pretrained_weights[copy_k].clone()
44
- else:
45
- target_dict[k] = scratch_dict[k].clone()
46
- print(f'These weights are newly added: {k}')
47
-
48
- model.load_state_dict(target_dict, strict=True)
49
- torch.save(model.state_dict(), output_path)
50
- print('Done.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Apex-X/nono/roop/core.py DELETED
@@ -1,215 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import os
4
- import sys
5
- # single thread doubles cuda performance - needs to be set before torch import
6
- if any(arg.startswith('--execution-provider') for arg in sys.argv):
7
- os.environ['OMP_NUM_THREADS'] = '1'
8
- # reduce tensorflow log level
9
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
10
- import warnings
11
- from typing import List
12
- import platform
13
- import signal
14
- import shutil
15
- import argparse
16
- import torch
17
- import onnxruntime
18
- import tensorflow
19
-
20
- import roop.globals
21
- import roop.metadata
22
- import roop.ui as ui
23
- from roop.predicter import predict_image, predict_video
24
- from roop.processors.frame.core import get_frame_processors_modules
25
- from roop.utilities import has_image_extension, is_image, is_video, detect_fps, create_video, extract_frames, get_temp_frame_paths, restore_audio, create_temp, move_temp, clean_temp, normalize_output_path
26
-
27
- if 'ROCMExecutionProvider' in roop.globals.execution_providers:
28
- del torch
29
-
30
- warnings.filterwarnings('ignore', category=FutureWarning, module='insightface')
31
- warnings.filterwarnings('ignore', category=UserWarning, module='torchvision')
32
-
33
-
34
- def parse_args() -> None:
35
- signal.signal(signal.SIGINT, lambda signal_number, frame: destroy())
36
- program = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=100))
37
- program.add_argument('-s', '--source', help='select an source image', dest='source_path')
38
- program.add_argument('-t', '--target', help='select an target image or video', dest='target_path')
39
- program.add_argument('-o', '--output', help='select output file or directory', dest='output_path')
40
- program.add_argument('--frame-processor', help='frame processors (choices: face_swapper, face_enhancer, ...)', dest='frame_processor', default=['face_swapper'], nargs='+')
41
- program.add_argument('--keep-fps', help='keep original fps', dest='keep_fps', action='store_true', default=False)
42
- program.add_argument('--keep-audio', help='keep original audio', dest='keep_audio', action='store_true', default=True)
43
- program.add_argument('--keep-frames', help='keep temporary frames', dest='keep_frames', action='store_true', default=False)
44
- program.add_argument('--many-faces', help='process every face', dest='many_faces', action='store_true', default=False)
45
- program.add_argument('--video-encoder', help='adjust output video encoder', dest='video_encoder', default='libx264', choices=['libx264', 'libx265', 'libvpx-vp9'])
46
- program.add_argument('--video-quality', help='adjust output video quality', dest='video_quality', type=int, default=18, choices=range(52), metavar='[0-51]')
47
- program.add_argument('--max-memory', help='maximum amount of RAM in GB', dest='max_memory', type=int, default=suggest_max_memory())
48
- program.add_argument('--execution-provider', help='available execution provider (choices: cpu, ...)', dest='execution_provider', default=['cpu'], choices=suggest_execution_providers(), nargs='+')
49
- program.add_argument('--execution-threads', help='number of execution threads', dest='execution_threads', type=int, default=suggest_execution_threads())
50
- program.add_argument('-v', '--version', action='version', version=f'{roop.metadata.name} {roop.metadata.version}')
51
-
52
- args = program.parse_args()
53
-
54
- roop.globals.source_path = args.source_path
55
- roop.globals.target_path = args.target_path
56
- roop.globals.output_path = normalize_output_path(roop.globals.source_path, roop.globals.target_path, args.output_path)
57
- roop.globals.frame_processors = args.frame_processor
58
- roop.globals.headless = args.source_path or args.target_path or args.output_path
59
- roop.globals.keep_fps = args.keep_fps
60
- roop.globals.keep_audio = args.keep_audio
61
- roop.globals.keep_frames = args.keep_frames
62
- roop.globals.many_faces = args.many_faces
63
- roop.globals.video_encoder = args.video_encoder
64
- roop.globals.video_quality = args.video_quality
65
- roop.globals.max_memory = args.max_memory
66
- roop.globals.execution_providers = decode_execution_providers(args.execution_provider)
67
- roop.globals.execution_threads = args.execution_threads
68
-
69
-
70
- def encode_execution_providers(execution_providers: List[str]) -> List[str]:
71
- return [execution_provider.replace('ExecutionProvider', '').lower() for execution_provider in execution_providers]
72
-
73
-
74
- def decode_execution_providers(execution_providers: List[str]) -> List[str]:
75
- return [provider for provider, encoded_execution_provider in zip(onnxruntime.get_available_providers(), encode_execution_providers(onnxruntime.get_available_providers()))
76
- if any(execution_provider in encoded_execution_provider for execution_provider in execution_providers)]
77
-
78
-
79
- def suggest_max_memory() -> int:
80
- if platform.system().lower() == 'darwin':
81
- return 4
82
- return 16
83
-
84
-
85
- def suggest_execution_providers() -> List[str]:
86
- return encode_execution_providers(onnxruntime.get_available_providers())
87
-
88
-
89
- def suggest_execution_threads() -> int:
90
- if 'DmlExecutionProvider' in roop.globals.execution_providers:
91
- return 1
92
- if 'ROCMExecutionProvider' in roop.globals.execution_providers:
93
- return 1
94
- return 8
95
-
96
-
97
- def limit_resources() -> None:
98
- # prevent tensorflow memory leak
99
- gpus = tensorflow.config.experimental.list_physical_devices('GPU')
100
- for gpu in gpus:
101
- tensorflow.config.experimental.set_virtual_device_configuration(gpu, [
102
- tensorflow.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)
103
- ])
104
- # limit memory usage
105
- if roop.globals.max_memory:
106
- memory = roop.globals.max_memory * 1024 ** 3
107
- if platform.system().lower() == 'darwin':
108
- memory = roop.globals.max_memory * 1024 ** 6
109
- if platform.system().lower() == 'windows':
110
- import ctypes
111
- kernel32 = ctypes.windll.kernel32
112
- kernel32.SetProcessWorkingSetSize(-1, ctypes.c_size_t(memory), ctypes.c_size_t(memory))
113
- else:
114
- import resource
115
- resource.setrlimit(resource.RLIMIT_DATA, (memory, memory))
116
-
117
-
118
- def release_resources() -> None:
119
- if 'CUDAExecutionProvider' in roop.globals.execution_providers:
120
- torch.cuda.empty_cache()
121
-
122
-
123
- def pre_check() -> bool:
124
- if sys.version_info < (3, 9):
125
- update_status('Python version is not supported - please upgrade to 3.9 or higher.')
126
- return False
127
- if not shutil.which('ffmpeg'):
128
- update_status('ffmpeg is not installed.')
129
- return False
130
- return True
131
-
132
-
133
- def update_status(message: str, scope: str = 'ROOP.CORE') -> None:
134
- print(f'[{scope}] {message}')
135
- if not roop.globals.headless:
136
- ui.update_status(message)
137
-
138
-
139
- def start() -> None:
140
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
141
- if not frame_processor.pre_start():
142
- return
143
- # process image to image
144
- if has_image_extension(roop.globals.target_path):
145
- if predict_image(roop.globals.target_path):
146
- destroy()
147
- shutil.copy2(roop.globals.target_path, roop.globals.output_path)
148
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
149
- update_status('Progressing...', frame_processor.NAME)
150
- frame_processor.process_image(roop.globals.source_path, roop.globals.output_path, roop.globals.output_path)
151
- frame_processor.post_process()
152
- release_resources()
153
- if is_image(roop.globals.target_path):
154
- update_status('Processing to image succeed!')
155
- else:
156
- update_status('Processing to image failed!')
157
- return
158
- # process image to videos
159
- if predict_video(roop.globals.target_path):
160
- destroy()
161
- update_status('Creating temp resources...')
162
- create_temp(roop.globals.target_path)
163
- update_status('Extracting frames...')
164
- extract_frames(roop.globals.target_path)
165
- temp_frame_paths = get_temp_frame_paths(roop.globals.target_path)
166
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
167
- update_status('Progressing...', frame_processor.NAME)
168
- frame_processor.process_video(roop.globals.source_path, temp_frame_paths)
169
- frame_processor.post_process()
170
- release_resources()
171
- # handles fps
172
- if roop.globals.keep_fps:
173
- update_status('Detecting fps...')
174
- fps = detect_fps(roop.globals.target_path)
175
- update_status(f'Creating video with {fps} fps...')
176
- create_video(roop.globals.target_path, fps)
177
- else:
178
- update_status('Creating video with 30.0 fps...')
179
- create_video(roop.globals.target_path)
180
- # handle audio
181
- if roop.globals.keep_audio:
182
- if roop.globals.keep_fps:
183
- update_status('Restoring audio...')
184
- else:
185
- update_status('Restoring audio might cause issues as fps are not kept...')
186
- restore_audio(roop.globals.target_path, roop.globals.output_path)
187
- else:
188
- move_temp(roop.globals.target_path, roop.globals.output_path)
189
- # clean and validate
190
- clean_temp(roop.globals.target_path)
191
- if is_video(roop.globals.target_path):
192
- update_status('Processing to video succeed!')
193
- else:
194
- update_status('Processing to video failed!')
195
-
196
-
197
- def destroy() -> None:
198
- if roop.globals.target_path:
199
- clean_temp(roop.globals.target_path)
200
- quit()
201
-
202
-
203
- def run() -> None:
204
- parse_args()
205
- if not pre_check():
206
- return
207
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
208
- if not frame_processor.pre_check():
209
- return
210
- limit_resources()
211
- if roop.globals.headless:
212
- start()
213
- else:
214
- window = ui.init(start, destroy)
215
- window.mainloop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ariharasudhan/YoloV5/utils/loggers/__init__.py DELETED
@@ -1,404 +0,0 @@
1
- # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
- """
3
- Logging utils
4
- """
5
-
6
- import os
7
- import warnings
8
- from pathlib import Path
9
-
10
- import pkg_resources as pkg
11
- import torch
12
- from torch.utils.tensorboard import SummaryWriter
13
-
14
- from utils.general import LOGGER, colorstr, cv2
15
- from utils.loggers.clearml.clearml_utils import ClearmlLogger
16
- from utils.loggers.wandb.wandb_utils import WandbLogger
17
- from utils.plots import plot_images, plot_labels, plot_results
18
- from utils.torch_utils import de_parallel
19
-
20
- LOGGERS = ('csv', 'tb', 'wandb', 'clearml', 'comet') # *.csv, TensorBoard, Weights & Biases, ClearML
21
- RANK = int(os.getenv('RANK', -1))
22
-
23
- try:
24
- import wandb
25
-
26
- assert hasattr(wandb, '__version__') # verify package import not local dir
27
- if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in {0, -1}:
28
- try:
29
- wandb_login_success = wandb.login(timeout=30)
30
- except wandb.errors.UsageError: # known non-TTY terminal issue
31
- wandb_login_success = False
32
- if not wandb_login_success:
33
- wandb = None
34
- except (ImportError, AssertionError):
35
- wandb = None
36
-
37
- try:
38
- import clearml
39
-
40
- assert hasattr(clearml, '__version__') # verify package import not local dir
41
- except (ImportError, AssertionError):
42
- clearml = None
43
-
44
- try:
45
- if RANK not in [0, -1]:
46
- comet_ml = None
47
- else:
48
- import comet_ml
49
-
50
- assert hasattr(comet_ml, '__version__') # verify package import not local dir
51
- from utils.loggers.comet import CometLogger
52
-
53
- except (ModuleNotFoundError, ImportError, AssertionError):
54
- comet_ml = None
55
-
56
-
57
- class Loggers():
58
- # YOLOv5 Loggers class
59
- def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
60
- self.save_dir = save_dir
61
- self.weights = weights
62
- self.opt = opt
63
- self.hyp = hyp
64
- self.plots = not opt.noplots # plot results
65
- self.logger = logger # for printing results to console
66
- self.include = include
67
- self.keys = [
68
- 'train/box_loss',
69
- 'train/obj_loss',
70
- 'train/cls_loss', # train loss
71
- 'metrics/precision',
72
- 'metrics/recall',
73
- 'metrics/mAP_0.5',
74
- 'metrics/mAP_0.5:0.95', # metrics
75
- 'val/box_loss',
76
- 'val/obj_loss',
77
- 'val/cls_loss', # val loss
78
- 'x/lr0',
79
- 'x/lr1',
80
- 'x/lr2'] # params
81
- self.best_keys = ['best/epoch', 'best/precision', 'best/recall', 'best/mAP_0.5', 'best/mAP_0.5:0.95']
82
- for k in LOGGERS:
83
- setattr(self, k, None) # init empty logger dictionary
84
- self.csv = True # always log to csv
85
-
86
- # Messages
87
- # if not wandb:
88
- # prefix = colorstr('Weights & Biases: ')
89
- # s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs in Weights & Biases"
90
- # self.logger.info(s)
91
- if not clearml:
92
- prefix = colorstr('ClearML: ')
93
- s = f"{prefix}run 'pip install clearml' to automatically track, visualize and remotely train YOLOv5 🚀 in ClearML"
94
- self.logger.info(s)
95
- if not comet_ml:
96
- prefix = colorstr('Comet: ')
97
- s = f"{prefix}run 'pip install comet_ml' to automatically track and visualize YOLOv5 🚀 runs in Comet"
98
- self.logger.info(s)
99
- # TensorBoard
100
- s = self.save_dir
101
- if 'tb' in self.include and not self.opt.evolve:
102
- prefix = colorstr('TensorBoard: ')
103
- self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
104
- self.tb = SummaryWriter(str(s))
105
-
106
- # W&B
107
- if wandb and 'wandb' in self.include:
108
- wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')
109
- run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None
110
- self.opt.hyp = self.hyp # add hyperparameters
111
- self.wandb = WandbLogger(self.opt, run_id)
112
- # temp warn. because nested artifacts not supported after 0.12.10
113
- # if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.11'):
114
- # s = "YOLOv5 temporarily requires wandb version 0.12.10 or below. Some features may not work as expected."
115
- # self.logger.warning(s)
116
- else:
117
- self.wandb = None
118
-
119
- # ClearML
120
- if clearml and 'clearml' in self.include:
121
- self.clearml = ClearmlLogger(self.opt, self.hyp)
122
- else:
123
- self.clearml = None
124
-
125
- # Comet
126
- if comet_ml and 'comet' in self.include:
127
- if isinstance(self.opt.resume, str) and self.opt.resume.startswith("comet://"):
128
- run_id = self.opt.resume.split("/")[-1]
129
- self.comet_logger = CometLogger(self.opt, self.hyp, run_id=run_id)
130
-
131
- else:
132
- self.comet_logger = CometLogger(self.opt, self.hyp)
133
-
134
- else:
135
- self.comet_logger = None
136
-
137
- @property
138
- def remote_dataset(self):
139
- # Get data_dict if custom dataset artifact link is provided
140
- data_dict = None
141
- if self.clearml:
142
- data_dict = self.clearml.data_dict
143
- if self.wandb:
144
- data_dict = self.wandb.data_dict
145
- if self.comet_logger:
146
- data_dict = self.comet_logger.data_dict
147
-
148
- return data_dict
149
-
150
- def on_train_start(self):
151
- if self.comet_logger:
152
- self.comet_logger.on_train_start()
153
-
154
- def on_pretrain_routine_start(self):
155
- if self.comet_logger:
156
- self.comet_logger.on_pretrain_routine_start()
157
-
158
- def on_pretrain_routine_end(self, labels, names):
159
- # Callback runs on pre-train routine end
160
- if self.plots:
161
- plot_labels(labels, names, self.save_dir)
162
- paths = self.save_dir.glob('*labels*.jpg') # training labels
163
- if self.wandb:
164
- self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})
165
- # if self.clearml:
166
- # pass # ClearML saves these images automatically using hooks
167
- if self.comet_logger:
168
- self.comet_logger.on_pretrain_routine_end(paths)
169
-
170
- def on_train_batch_end(self, model, ni, imgs, targets, paths, vals):
171
- log_dict = dict(zip(self.keys[0:3], vals))
172
- # Callback runs on train batch end
173
- # ni: number integrated batches (since train start)
174
- if self.plots:
175
- if ni < 3:
176
- f = self.save_dir / f'train_batch{ni}.jpg' # filename
177
- plot_images(imgs, targets, paths, f)
178
- if ni == 0 and self.tb and not self.opt.sync_bn:
179
- log_tensorboard_graph(self.tb, model, imgsz=(self.opt.imgsz, self.opt.imgsz))
180
- if ni == 10 and (self.wandb or self.clearml):
181
- files = sorted(self.save_dir.glob('train*.jpg'))
182
- if self.wandb:
183
- self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
184
- if self.clearml:
185
- self.clearml.log_debug_samples(files, title='Mosaics')
186
-
187
- if self.comet_logger:
188
- self.comet_logger.on_train_batch_end(log_dict, step=ni)
189
-
190
- def on_train_epoch_end(self, epoch):
191
- # Callback runs on train epoch end
192
- if self.wandb:
193
- self.wandb.current_epoch = epoch + 1
194
-
195
- if self.comet_logger:
196
- self.comet_logger.on_train_epoch_end(epoch)
197
-
198
- def on_val_start(self):
199
- if self.comet_logger:
200
- self.comet_logger.on_val_start()
201
-
202
- def on_val_image_end(self, pred, predn, path, names, im):
203
- # Callback runs on val image end
204
- if self.wandb:
205
- self.wandb.val_one_image(pred, predn, path, names, im)
206
- if self.clearml:
207
- self.clearml.log_image_with_boxes(path, pred, names, im)
208
-
209
- def on_val_batch_end(self, batch_i, im, targets, paths, shapes, out):
210
- if self.comet_logger:
211
- self.comet_logger.on_val_batch_end(batch_i, im, targets, paths, shapes, out)
212
-
213
- def on_val_end(self, nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix):
214
- # Callback runs on val end
215
- if self.wandb or self.clearml:
216
- files = sorted(self.save_dir.glob('val*.jpg'))
217
- if self.wandb:
218
- self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})
219
- if self.clearml:
220
- self.clearml.log_debug_samples(files, title='Validation')
221
-
222
- if self.comet_logger:
223
- self.comet_logger.on_val_end(nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix)
224
-
225
- def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
226
- # Callback runs at the end of each fit (train+val) epoch
227
- x = dict(zip(self.keys, vals))
228
- if self.csv:
229
- file = self.save_dir / 'results.csv'
230
- n = len(x) + 1 # number of cols
231
- s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header
232
- with open(file, 'a') as f:
233
- f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
234
-
235
- if self.tb:
236
- for k, v in x.items():
237
- self.tb.add_scalar(k, v, epoch)
238
- elif self.clearml: # log to ClearML if TensorBoard not used
239
- for k, v in x.items():
240
- title, series = k.split('/')
241
- self.clearml.task.get_logger().report_scalar(title, series, v, epoch)
242
-
243
- if self.wandb:
244
- if best_fitness == fi:
245
- best_results = [epoch] + vals[3:7]
246
- for i, name in enumerate(self.best_keys):
247
- self.wandb.wandb_run.summary[name] = best_results[i] # log best results in the summary
248
- self.wandb.log(x)
249
- self.wandb.end_epoch(best_result=best_fitness == fi)
250
-
251
- if self.clearml:
252
- self.clearml.current_epoch_logged_images = set() # reset epoch image limit
253
- self.clearml.current_epoch += 1
254
-
255
- if self.comet_logger:
256
- self.comet_logger.on_fit_epoch_end(x, epoch=epoch)
257
-
258
- def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
259
- # Callback runs on model save event
260
- if (epoch + 1) % self.opt.save_period == 0 and not final_epoch and self.opt.save_period != -1:
261
- if self.wandb:
262
- self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
263
- if self.clearml:
264
- self.clearml.task.update_output_model(model_path=str(last),
265
- model_name='Latest Model',
266
- auto_delete_file=False)
267
-
268
- if self.comet_logger:
269
- self.comet_logger.on_model_save(last, epoch, final_epoch, best_fitness, fi)
270
-
271
- def on_train_end(self, last, best, epoch, results):
272
- # Callback runs on training end, i.e. saving best model
273
- if self.plots:
274
- plot_results(file=self.save_dir / 'results.csv') # save results.png
275
- files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]
276
- files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter
277
- self.logger.info(f"Results saved to {colorstr('bold', self.save_dir)}")
278
-
279
- if self.tb and not self.clearml: # These images are already captured by ClearML by now, we don't want doubles
280
- for f in files:
281
- self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
282
-
283
- if self.wandb:
284
- self.wandb.log(dict(zip(self.keys[3:10], results)))
285
- self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
286
- # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
287
- if not self.opt.evolve:
288
- wandb.log_artifact(str(best if best.exists() else last),
289
- type='model',
290
- name=f'run_{self.wandb.wandb_run.id}_model',
291
- aliases=['latest', 'best', 'stripped'])
292
- self.wandb.finish_run()
293
-
294
- if self.clearml and not self.opt.evolve:
295
- self.clearml.task.update_output_model(model_path=str(best if best.exists() else last),
296
- name='Best Model',
297
- auto_delete_file=False)
298
-
299
- if self.comet_logger:
300
- final_results = dict(zip(self.keys[3:10], results))
301
- self.comet_logger.on_train_end(files, self.save_dir, last, best, epoch, final_results)
302
-
303
- def on_params_update(self, params: dict):
304
- # Update hyperparams or configs of the experiment
305
- if self.wandb:
306
- self.wandb.wandb_run.config.update(params, allow_val_change=True)
307
- if self.comet_logger:
308
- self.comet_logger.on_params_update(params)
309
-
310
-
311
- class GenericLogger:
312
- """
313
- YOLOv5 General purpose logger for non-task specific logging
314
- Usage: from utils.loggers import GenericLogger; logger = GenericLogger(...)
315
- Arguments
316
- opt: Run arguments
317
- console_logger: Console logger
318
- include: loggers to include
319
- """
320
-
321
- def __init__(self, opt, console_logger, include=('tb', 'wandb')):
322
- # init default loggers
323
- self.save_dir = Path(opt.save_dir)
324
- self.include = include
325
- self.console_logger = console_logger
326
- self.csv = self.save_dir / 'results.csv' # CSV logger
327
- if 'tb' in self.include:
328
- prefix = colorstr('TensorBoard: ')
329
- self.console_logger.info(
330
- f"{prefix}Start with 'tensorboard --logdir {self.save_dir.parent}', view at http://localhost:6006/")
331
- self.tb = SummaryWriter(str(self.save_dir))
332
-
333
- if wandb and 'wandb' in self.include:
334
- self.wandb = wandb.init(project=web_project_name(str(opt.project)),
335
- name=None if opt.name == "exp" else opt.name,
336
- config=opt)
337
- else:
338
- self.wandb = None
339
-
340
- def log_metrics(self, metrics, epoch):
341
- # Log metrics dictionary to all loggers
342
- if self.csv:
343
- keys, vals = list(metrics.keys()), list(metrics.values())
344
- n = len(metrics) + 1 # number of cols
345
- s = '' if self.csv.exists() else (('%23s,' * n % tuple(['epoch'] + keys)).rstrip(',') + '\n') # header
346
- with open(self.csv, 'a') as f:
347
- f.write(s + ('%23.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
348
-
349
- if self.tb:
350
- for k, v in metrics.items():
351
- self.tb.add_scalar(k, v, epoch)
352
-
353
- if self.wandb:
354
- self.wandb.log(metrics, step=epoch)
355
-
356
- def log_images(self, files, name='Images', epoch=0):
357
- # Log images to all loggers
358
- files = [Path(f) for f in (files if isinstance(files, (tuple, list)) else [files])] # to Path
359
- files = [f for f in files if f.exists()] # filter by exists
360
-
361
- if self.tb:
362
- for f in files:
363
- self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
364
-
365
- if self.wandb:
366
- self.wandb.log({name: [wandb.Image(str(f), caption=f.name) for f in files]}, step=epoch)
367
-
368
- def log_graph(self, model, imgsz=(640, 640)):
369
- # Log model graph to all loggers
370
- if self.tb:
371
- log_tensorboard_graph(self.tb, model, imgsz)
372
-
373
- def log_model(self, model_path, epoch=0, metadata={}):
374
- # Log model to all loggers
375
- if self.wandb:
376
- art = wandb.Artifact(name=f"run_{wandb.run.id}_model", type="model", metadata=metadata)
377
- art.add_file(str(model_path))
378
- wandb.log_artifact(art)
379
-
380
- def update_params(self, params):
381
- # Update the paramters logged
382
- if self.wandb:
383
- wandb.run.config.update(params, allow_val_change=True)
384
-
385
-
386
- def log_tensorboard_graph(tb, model, imgsz=(640, 640)):
387
- # Log model graph to TensorBoard
388
- try:
389
- p = next(model.parameters()) # for device, type
390
- imgsz = (imgsz, imgsz) if isinstance(imgsz, int) else imgsz # expand
391
- im = torch.zeros((1, 3, *imgsz)).to(p.device).type_as(p) # input image (WARNING: must be zeros, not empty)
392
- with warnings.catch_warnings():
393
- warnings.simplefilter('ignore') # suppress jit trace warning
394
- tb.add_graph(torch.jit.trace(de_parallel(model), im, strict=False), [])
395
- except Exception as e:
396
- LOGGER.warning(f'WARNING ⚠️ TensorBoard graph visualization failure {e}')
397
-
398
-
399
- def web_project_name(project):
400
- # Convert local project name to web project name
401
- if not project.startswith('runs/train'):
402
- return project
403
- suffix = '-Classify' if project.endswith('-cls') else '-Segment' if project.endswith('-seg') else ''
404
- return f'YOLOv5{suffix}'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/network/download.py DELETED
@@ -1,186 +0,0 @@
1
- """Download files with progress indicators.
2
- """
3
- import email.message
4
- import logging
5
- import mimetypes
6
- import os
7
- from typing import Iterable, Optional, Tuple
8
-
9
- from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
10
-
11
- from pip._internal.cli.progress_bars import get_download_progress_renderer
12
- from pip._internal.exceptions import NetworkConnectionError
13
- from pip._internal.models.index import PyPI
14
- from pip._internal.models.link import Link
15
- from pip._internal.network.cache import is_from_cache
16
- from pip._internal.network.session import PipSession
17
- from pip._internal.network.utils import HEADERS, raise_for_status, response_chunks
18
- from pip._internal.utils.misc import format_size, redact_auth_from_url, splitext
19
-
20
- logger = logging.getLogger(__name__)
21
-
22
-
23
- def _get_http_response_size(resp: Response) -> Optional[int]:
24
- try:
25
- return int(resp.headers["content-length"])
26
- except (ValueError, KeyError, TypeError):
27
- return None
28
-
29
-
30
- def _prepare_download(
31
- resp: Response,
32
- link: Link,
33
- progress_bar: str,
34
- ) -> Iterable[bytes]:
35
- total_length = _get_http_response_size(resp)
36
-
37
- if link.netloc == PyPI.file_storage_domain:
38
- url = link.show_url
39
- else:
40
- url = link.url_without_fragment
41
-
42
- logged_url = redact_auth_from_url(url)
43
-
44
- if total_length:
45
- logged_url = "{} ({})".format(logged_url, format_size(total_length))
46
-
47
- if is_from_cache(resp):
48
- logger.info("Using cached %s", logged_url)
49
- else:
50
- logger.info("Downloading %s", logged_url)
51
-
52
- if logger.getEffectiveLevel() > logging.INFO:
53
- show_progress = False
54
- elif is_from_cache(resp):
55
- show_progress = False
56
- elif not total_length:
57
- show_progress = True
58
- elif total_length > (40 * 1000):
59
- show_progress = True
60
- else:
61
- show_progress = False
62
-
63
- chunks = response_chunks(resp, CONTENT_CHUNK_SIZE)
64
-
65
- if not show_progress:
66
- return chunks
67
-
68
- renderer = get_download_progress_renderer(bar_type=progress_bar, size=total_length)
69
- return renderer(chunks)
70
-
71
-
72
- def sanitize_content_filename(filename: str) -> str:
73
- """
74
- Sanitize the "filename" value from a Content-Disposition header.
75
- """
76
- return os.path.basename(filename)
77
-
78
-
79
- def parse_content_disposition(content_disposition: str, default_filename: str) -> str:
80
- """
81
- Parse the "filename" value from a Content-Disposition header, and
82
- return the default filename if the result is empty.
83
- """
84
- m = email.message.Message()
85
- m["content-type"] = content_disposition
86
- filename = m.get_param("filename")
87
- if filename:
88
- # We need to sanitize the filename to prevent directory traversal
89
- # in case the filename contains ".." path parts.
90
- filename = sanitize_content_filename(str(filename))
91
- return filename or default_filename
92
-
93
-
94
- def _get_http_response_filename(resp: Response, link: Link) -> str:
95
- """Get an ideal filename from the given HTTP response, falling back to
96
- the link filename if not provided.
97
- """
98
- filename = link.filename # fallback
99
- # Have a look at the Content-Disposition header for a better guess
100
- content_disposition = resp.headers.get("content-disposition")
101
- if content_disposition:
102
- filename = parse_content_disposition(content_disposition, filename)
103
- ext: Optional[str] = splitext(filename)[1]
104
- if not ext:
105
- ext = mimetypes.guess_extension(resp.headers.get("content-type", ""))
106
- if ext:
107
- filename += ext
108
- if not ext and link.url != resp.url:
109
- ext = os.path.splitext(resp.url)[1]
110
- if ext:
111
- filename += ext
112
- return filename
113
-
114
-
115
- def _http_get_download(session: PipSession, link: Link) -> Response:
116
- target_url = link.url.split("#", 1)[0]
117
- resp = session.get(target_url, headers=HEADERS, stream=True)
118
- raise_for_status(resp)
119
- return resp
120
-
121
-
122
- class Downloader:
123
- def __init__(
124
- self,
125
- session: PipSession,
126
- progress_bar: str,
127
- ) -> None:
128
- self._session = session
129
- self._progress_bar = progress_bar
130
-
131
- def __call__(self, link: Link, location: str) -> Tuple[str, str]:
132
- """Download the file given by link into location."""
133
- try:
134
- resp = _http_get_download(self._session, link)
135
- except NetworkConnectionError as e:
136
- assert e.response is not None
137
- logger.critical(
138
- "HTTP error %s while getting %s", e.response.status_code, link
139
- )
140
- raise
141
-
142
- filename = _get_http_response_filename(resp, link)
143
- filepath = os.path.join(location, filename)
144
-
145
- chunks = _prepare_download(resp, link, self._progress_bar)
146
- with open(filepath, "wb") as content_file:
147
- for chunk in chunks:
148
- content_file.write(chunk)
149
- content_type = resp.headers.get("Content-Type", "")
150
- return filepath, content_type
151
-
152
-
153
- class BatchDownloader:
154
- def __init__(
155
- self,
156
- session: PipSession,
157
- progress_bar: str,
158
- ) -> None:
159
- self._session = session
160
- self._progress_bar = progress_bar
161
-
162
- def __call__(
163
- self, links: Iterable[Link], location: str
164
- ) -> Iterable[Tuple[Link, Tuple[str, str]]]:
165
- """Download the files given by links into location."""
166
- for link in links:
167
- try:
168
- resp = _http_get_download(self._session, link)
169
- except NetworkConnectionError as e:
170
- assert e.response is not None
171
- logger.critical(
172
- "HTTP error %s while getting %s",
173
- e.response.status_code,
174
- link,
175
- )
176
- raise
177
-
178
- filename = _get_http_response_filename(resp, link)
179
- filepath = os.path.join(location, filename)
180
-
181
- chunks = _prepare_download(resp, link, self._progress_bar)
182
- with open(filepath, "wb") as content_file:
183
- for chunk in chunks:
184
- content_file.write(chunk)
185
- content_type = resp.headers.get("Content-Type", "")
186
- yield link, (filepath, content_type)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AutoLLM/AutoAgents/setup.py DELETED
@@ -1,7 +0,0 @@
1
- from setuptools import setup, find_packages
2
-
3
- setup(
4
- name='autoagents',
5
- version='0.1.0',
6
- packages=find_packages(include=['autoagents', 'autoagents.*'])
7
- )
 
 
 
 
 
 
 
 
spaces/AzumaSeren100/XuanShen-Bert-VITS2/text/english.py DELETED
@@ -1,138 +0,0 @@
1
- import pickle
2
- import os
3
- import re
4
- from g2p_en import G2p
5
- from string import punctuation
6
-
7
- from text import symbols
8
-
9
- current_file_path = os.path.dirname(__file__)
10
- CMU_DICT_PATH = os.path.join(current_file_path, 'cmudict.rep')
11
- CACHE_PATH = os.path.join(current_file_path, 'cmudict_cache.pickle')
12
- _g2p = G2p()
13
-
14
- arpa = {'AH0', 'S', 'AH1', 'EY2', 'AE2', 'EH0', 'OW2', 'UH0', 'NG', 'B', 'G', 'AY0', 'M', 'AA0', 'F', 'AO0', 'ER2', 'UH1', 'IY1', 'AH2', 'DH', 'IY0', 'EY1', 'IH0', 'K', 'N', 'W', 'IY2', 'T', 'AA1', 'ER1', 'EH2', 'OY0', 'UH2', 'UW1', 'Z', 'AW2', 'AW1', 'V', 'UW2', 'AA2', 'ER', 'AW0', 'UW0', 'R', 'OW1', 'EH1', 'ZH', 'AE0', 'IH2', 'IH', 'Y', 'JH', 'P', 'AY1', 'EY0', 'OY2', 'TH', 'HH', 'D', 'ER0', 'CH', 'AO1', 'AE1', 'AO2', 'OY1', 'AY2', 'IH1', 'OW0', 'L', 'SH'}
15
-
16
-
17
- def post_replace_ph(ph):
18
- rep_map = {
19
- ':': ',',
20
- ';': ',',
21
- ',': ',',
22
- '。': '.',
23
- '!': '!',
24
- '?': '?',
25
- '\n': '.',
26
- "·": ",",
27
- '、': ",",
28
- '...': '…',
29
- 'v': "V"
30
- }
31
- if ph in rep_map.keys():
32
- ph = rep_map[ph]
33
- if ph in symbols:
34
- return ph
35
- if ph not in symbols:
36
- ph = 'UNK'
37
- return ph
38
-
39
- def read_dict():
40
- g2p_dict = {}
41
- start_line = 49
42
- with open(CMU_DICT_PATH) as f:
43
- line = f.readline()
44
- line_index = 1
45
- while line:
46
- if line_index >= start_line:
47
- line = line.strip()
48
- word_split = line.split(' ')
49
- word = word_split[0]
50
-
51
- syllable_split = word_split[1].split(' - ')
52
- g2p_dict[word] = []
53
- for syllable in syllable_split:
54
- phone_split = syllable.split(' ')
55
- g2p_dict[word].append(phone_split)
56
-
57
- line_index = line_index + 1
58
- line = f.readline()
59
-
60
- return g2p_dict
61
-
62
-
63
- def cache_dict(g2p_dict, file_path):
64
- with open(file_path, 'wb') as pickle_file:
65
- pickle.dump(g2p_dict, pickle_file)
66
-
67
-
68
- def get_dict():
69
- if os.path.exists(CACHE_PATH):
70
- with open(CACHE_PATH, 'rb') as pickle_file:
71
- g2p_dict = pickle.load(pickle_file)
72
- else:
73
- g2p_dict = read_dict()
74
- cache_dict(g2p_dict, CACHE_PATH)
75
-
76
- return g2p_dict
77
-
78
- eng_dict = get_dict()
79
-
80
- def refine_ph(phn):
81
- tone = 0
82
- if re.search(r'\d$', phn):
83
- tone = int(phn[-1]) + 1
84
- phn = phn[:-1]
85
- return phn.lower(), tone
86
-
87
- def refine_syllables(syllables):
88
- tones = []
89
- phonemes = []
90
- for phn_list in syllables:
91
- for i in range(len(phn_list)):
92
- phn = phn_list[i]
93
- phn, tone = refine_ph(phn)
94
- phonemes.append(phn)
95
- tones.append(tone)
96
- return phonemes, tones
97
-
98
-
99
- def text_normalize(text):
100
- # todo: eng text normalize
101
- return text
102
-
103
- def g2p(text):
104
-
105
- phones = []
106
- tones = []
107
- words = re.split(r"([,;.\-\?\!\s+])", text)
108
- for w in words:
109
- if w.upper() in eng_dict:
110
- phns, tns = refine_syllables(eng_dict[w.upper()])
111
- phones += phns
112
- tones += tns
113
- else:
114
- phone_list = list(filter(lambda p: p != " ", _g2p(w)))
115
- for ph in phone_list:
116
- if ph in arpa:
117
- ph, tn = refine_ph(ph)
118
- phones.append(ph)
119
- tones.append(tn)
120
- else:
121
- phones.append(ph)
122
- tones.append(0)
123
- # todo: implement word2ph
124
- word2ph = [1 for i in phones]
125
-
126
- phones = [post_replace_ph(i) for i in phones]
127
- return phones, tones, word2ph
128
-
129
- if __name__ == "__main__":
130
- # print(get_dict())
131
- # print(eng_word_to_phoneme("hello"))
132
- print(g2p("In this paper, we propose 1 DSPGAN, a GAN-based universal vocoder."))
133
- # all_phones = set()
134
- # for k, syllables in eng_dict.items():
135
- # for group in syllables:
136
- # for ph in group:
137
- # all_phones.add(ph)
138
- # print(all_phones)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BAAI/vid2vid-zero/gradio_demo/runner.py DELETED
@@ -1,137 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import datetime
4
- import os
5
- import pathlib
6
- import shlex
7
- import shutil
8
- import subprocess
9
- import sys
10
-
11
- import gradio as gr
12
- import slugify
13
- import torch
14
- import huggingface_hub
15
- from huggingface_hub import HfApi
16
- from omegaconf import OmegaConf
17
-
18
-
19
- ORIGINAL_SPACE_ID = 'BAAI/vid2vid-zero'
20
- SPACE_ID = os.getenv('SPACE_ID', ORIGINAL_SPACE_ID)
21
-
22
-
23
- class Runner:
24
- def __init__(self, hf_token: str | None = None):
25
- self.hf_token = hf_token
26
-
27
- self.checkpoint_dir = pathlib.Path('checkpoints')
28
- self.checkpoint_dir.mkdir(exist_ok=True)
29
-
30
- def download_base_model(self, base_model_id: str, token=None) -> str:
31
- model_dir = self.checkpoint_dir / base_model_id
32
- org_name = base_model_id.split('/')[0]
33
- org_dir = self.checkpoint_dir / org_name
34
- if not model_dir.exists():
35
- org_dir.mkdir(exist_ok=True)
36
- print(f'https://huggingface.co/{base_model_id}')
37
- if token == None:
38
- subprocess.run(shlex.split(f'git lfs install'), cwd=org_dir)
39
- subprocess.run(shlex.split(
40
- f'git lfs clone https://huggingface.co/{base_model_id}'),
41
- cwd=org_dir)
42
- return model_dir.as_posix()
43
- else:
44
- temp_path = huggingface_hub.snapshot_download(base_model_id, use_auth_token=token)
45
- print(temp_path, org_dir)
46
- # subprocess.run(shlex.split(f'mv {temp_path} {model_dir.as_posix()}'))
47
- # return model_dir.as_posix()
48
- return temp_path
49
-
50
- def join_model_library_org(self, token: str) -> None:
51
- subprocess.run(
52
- shlex.split(
53
- f'curl -X POST -H "Authorization: Bearer {token}" -H "Content-Type: application/json" {URL_TO_JOIN_MODEL_LIBRARY_ORG}'
54
- ))
55
-
56
- def run_vid2vid_zero(
57
- self,
58
- model_path: str,
59
- input_video: str,
60
- prompt: str,
61
- n_sample_frames: int,
62
- sample_start_idx: int,
63
- sample_frame_rate: int,
64
- validation_prompt: str,
65
- guidance_scale: float,
66
- resolution: str,
67
- seed: int,
68
- remove_gpu_after_running: bool,
69
- input_token: str = None,
70
- ) -> str:
71
-
72
- if not torch.cuda.is_available():
73
- raise gr.Error('CUDA is not available.')
74
- if input_video is None:
75
- raise gr.Error('You need to upload a video.')
76
- if not prompt:
77
- raise gr.Error('The input prompt is missing.')
78
- if not validation_prompt:
79
- raise gr.Error('The validation prompt is missing.')
80
-
81
- resolution = int(resolution)
82
- n_sample_frames = int(n_sample_frames)
83
- sample_start_idx = int(sample_start_idx)
84
- sample_frame_rate = int(sample_frame_rate)
85
-
86
- repo_dir = pathlib.Path(__file__).parent
87
- prompt_path = prompt.replace(' ', '_')
88
- output_dir = repo_dir / 'outputs' / prompt_path
89
- output_dir.mkdir(parents=True, exist_ok=True)
90
-
91
- config = OmegaConf.load('configs/black-swan.yaml')
92
- config.pretrained_model_path = self.download_base_model(model_path, token=input_token)
93
-
94
- # we remove null-inversion & use fp16 for fast inference on web demo
95
- config.mixed_precision = "fp16"
96
- config.validation_data.use_null_inv = False
97
-
98
- config.output_dir = output_dir.as_posix()
99
- config.input_data.video_path = input_video.name # type: ignore
100
- config.input_data.prompt = prompt
101
- config.input_data.n_sample_frames = n_sample_frames
102
- config.input_data.width = resolution
103
- config.input_data.height = resolution
104
- config.input_data.sample_start_idx = sample_start_idx
105
- config.input_data.sample_frame_rate = sample_frame_rate
106
-
107
- config.validation_data.prompts = [validation_prompt]
108
- config.validation_data.video_length = 8
109
- config.validation_data.width = resolution
110
- config.validation_data.height = resolution
111
- config.validation_data.num_inference_steps = 50
112
- config.validation_data.guidance_scale = guidance_scale
113
-
114
- config.input_batch_size = 1
115
- config.seed = seed
116
-
117
- config_path = output_dir / 'config.yaml'
118
- with open(config_path, 'w') as f:
119
- OmegaConf.save(config, f)
120
-
121
- command = f'accelerate launch test_vid2vid_zero.py --config {config_path}'
122
- subprocess.run(shlex.split(command))
123
-
124
- output_video_path = os.path.join(output_dir, "sample-all.mp4")
125
- print(f"video path for gradio: {output_video_path}")
126
- message = 'Running completed!'
127
- print(message)
128
-
129
- if remove_gpu_after_running:
130
- space_id = os.getenv('SPACE_ID')
131
- if space_id:
132
- api = HfApi(
133
- token=self.hf_token if self.hf_token else input_token)
134
- api.request_space_hardware(repo_id=space_id,
135
- hardware='cpu-basic')
136
-
137
- return output_video_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BasToTheMax/22h-vintedois-diffusion-v0-1/app.py DELETED
@@ -1,3 +0,0 @@
1
- import gradio as gr
2
-
3
- gr.Interface.load("models/22h/vintedois-diffusion-v0-1").launch()
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/operations/build/build_tracker.py DELETED
@@ -1,124 +0,0 @@
1
- import contextlib
2
- import hashlib
3
- import logging
4
- import os
5
- from types import TracebackType
6
- from typing import Dict, Generator, Optional, Set, Type, Union
7
-
8
- from pip._internal.models.link import Link
9
- from pip._internal.req.req_install import InstallRequirement
10
- from pip._internal.utils.temp_dir import TempDirectory
11
-
12
- logger = logging.getLogger(__name__)
13
-
14
-
15
- @contextlib.contextmanager
16
- def update_env_context_manager(**changes: str) -> Generator[None, None, None]:
17
- target = os.environ
18
-
19
- # Save values from the target and change them.
20
- non_existent_marker = object()
21
- saved_values: Dict[str, Union[object, str]] = {}
22
- for name, new_value in changes.items():
23
- try:
24
- saved_values[name] = target[name]
25
- except KeyError:
26
- saved_values[name] = non_existent_marker
27
- target[name] = new_value
28
-
29
- try:
30
- yield
31
- finally:
32
- # Restore original values in the target.
33
- for name, original_value in saved_values.items():
34
- if original_value is non_existent_marker:
35
- del target[name]
36
- else:
37
- assert isinstance(original_value, str) # for mypy
38
- target[name] = original_value
39
-
40
-
41
- @contextlib.contextmanager
42
- def get_build_tracker() -> Generator["BuildTracker", None, None]:
43
- root = os.environ.get("PIP_BUILD_TRACKER")
44
- with contextlib.ExitStack() as ctx:
45
- if root is None:
46
- root = ctx.enter_context(TempDirectory(kind="build-tracker")).path
47
- ctx.enter_context(update_env_context_manager(PIP_BUILD_TRACKER=root))
48
- logger.debug("Initialized build tracking at %s", root)
49
-
50
- with BuildTracker(root) as tracker:
51
- yield tracker
52
-
53
-
54
- class BuildTracker:
55
- def __init__(self, root: str) -> None:
56
- self._root = root
57
- self._entries: Set[InstallRequirement] = set()
58
- logger.debug("Created build tracker: %s", self._root)
59
-
60
- def __enter__(self) -> "BuildTracker":
61
- logger.debug("Entered build tracker: %s", self._root)
62
- return self
63
-
64
- def __exit__(
65
- self,
66
- exc_type: Optional[Type[BaseException]],
67
- exc_val: Optional[BaseException],
68
- exc_tb: Optional[TracebackType],
69
- ) -> None:
70
- self.cleanup()
71
-
72
- def _entry_path(self, link: Link) -> str:
73
- hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest()
74
- return os.path.join(self._root, hashed)
75
-
76
- def add(self, req: InstallRequirement) -> None:
77
- """Add an InstallRequirement to build tracking."""
78
-
79
- assert req.link
80
- # Get the file to write information about this requirement.
81
- entry_path = self._entry_path(req.link)
82
-
83
- # Try reading from the file. If it exists and can be read from, a build
84
- # is already in progress, so a LookupError is raised.
85
- try:
86
- with open(entry_path) as fp:
87
- contents = fp.read()
88
- except FileNotFoundError:
89
- pass
90
- else:
91
- message = "{} is already being built: {}".format(req.link, contents)
92
- raise LookupError(message)
93
-
94
- # If we're here, req should really not be building already.
95
- assert req not in self._entries
96
-
97
- # Start tracking this requirement.
98
- with open(entry_path, "w", encoding="utf-8") as fp:
99
- fp.write(str(req))
100
- self._entries.add(req)
101
-
102
- logger.debug("Added %s to build tracker %r", req, self._root)
103
-
104
- def remove(self, req: InstallRequirement) -> None:
105
- """Remove an InstallRequirement from build tracking."""
106
-
107
- assert req.link
108
- # Delete the created file and the corresponding entries.
109
- os.unlink(self._entry_path(req.link))
110
- self._entries.remove(req)
111
-
112
- logger.debug("Removed %s from build tracker %r", req, self._root)
113
-
114
- def cleanup(self) -> None:
115
- for req in set(self._entries):
116
- self.remove(req)
117
-
118
- logger.debug("Removed build tracker: %r", self._root)
119
-
120
- @contextlib.contextmanager
121
- def track(self, req: InstallRequirement) -> Generator[None, None, None]:
122
- self.add(req)
123
- yield
124
- self.remove(req)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/utils/inject_securetransport.py DELETED
@@ -1,35 +0,0 @@
1
- """A helper module that injects SecureTransport, on import.
2
-
3
- The import should be done as early as possible, to ensure all requests and
4
- sessions (or whatever) are created after injecting SecureTransport.
5
-
6
- Note that we only do the injection on macOS, when the linked OpenSSL is too
7
- old to handle TLSv1.2.
8
- """
9
-
10
- import sys
11
-
12
-
13
- def inject_securetransport() -> None:
14
- # Only relevant on macOS
15
- if sys.platform != "darwin":
16
- return
17
-
18
- try:
19
- import ssl
20
- except ImportError:
21
- return
22
-
23
- # Checks for OpenSSL 1.0.1
24
- if ssl.OPENSSL_VERSION_NUMBER >= 0x1000100F:
25
- return
26
-
27
- try:
28
- from pip._vendor.urllib3.contrib import securetransport
29
- except (ImportError, OSError):
30
- return
31
-
32
- securetransport.inject_into_urllib3()
33
-
34
-
35
- inject_securetransport()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/command/sdist.py DELETED
@@ -1,210 +0,0 @@
1
- from distutils import log
2
- import distutils.command.sdist as orig
3
- import os
4
- import sys
5
- import io
6
- import contextlib
7
- from itertools import chain
8
-
9
- from .py36compat import sdist_add_defaults
10
-
11
- from .._importlib import metadata
12
- from .build import _ORIGINAL_SUBCOMMANDS
13
-
14
- _default_revctrl = list
15
-
16
-
17
- def walk_revctrl(dirname=''):
18
- """Find all files under revision control"""
19
- for ep in metadata.entry_points(group='setuptools.file_finders'):
20
- for item in ep.load()(dirname):
21
- yield item
22
-
23
-
24
- class sdist(sdist_add_defaults, orig.sdist):
25
- """Smart sdist that finds anything supported by revision control"""
26
-
27
- user_options = [
28
- ('formats=', None,
29
- "formats for source distribution (comma-separated list)"),
30
- ('keep-temp', 'k',
31
- "keep the distribution tree around after creating " +
32
- "archive file(s)"),
33
- ('dist-dir=', 'd',
34
- "directory to put the source distribution archive(s) in "
35
- "[default: dist]"),
36
- ('owner=', 'u',
37
- "Owner name used when creating a tar file [default: current user]"),
38
- ('group=', 'g',
39
- "Group name used when creating a tar file [default: current group]"),
40
- ]
41
-
42
- negative_opt = {}
43
-
44
- README_EXTENSIONS = ['', '.rst', '.txt', '.md']
45
- READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS)
46
-
47
- def run(self):
48
- self.run_command('egg_info')
49
- ei_cmd = self.get_finalized_command('egg_info')
50
- self.filelist = ei_cmd.filelist
51
- self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))
52
- self.check_readme()
53
-
54
- # Run sub commands
55
- for cmd_name in self.get_sub_commands():
56
- self.run_command(cmd_name)
57
-
58
- self.make_distribution()
59
-
60
- dist_files = getattr(self.distribution, 'dist_files', [])
61
- for file in self.archive_files:
62
- data = ('sdist', '', file)
63
- if data not in dist_files:
64
- dist_files.append(data)
65
-
66
- def initialize_options(self):
67
- orig.sdist.initialize_options(self)
68
-
69
- self._default_to_gztar()
70
-
71
- def _default_to_gztar(self):
72
- # only needed on Python prior to 3.6.
73
- if sys.version_info >= (3, 6, 0, 'beta', 1):
74
- return
75
- self.formats = ['gztar']
76
-
77
- def make_distribution(self):
78
- """
79
- Workaround for #516
80
- """
81
- with self._remove_os_link():
82
- orig.sdist.make_distribution(self)
83
-
84
- @staticmethod
85
- @contextlib.contextmanager
86
- def _remove_os_link():
87
- """
88
- In a context, remove and restore os.link if it exists
89
- """
90
-
91
- class NoValue:
92
- pass
93
-
94
- orig_val = getattr(os, 'link', NoValue)
95
- try:
96
- del os.link
97
- except Exception:
98
- pass
99
- try:
100
- yield
101
- finally:
102
- if orig_val is not NoValue:
103
- setattr(os, 'link', orig_val)
104
-
105
- def add_defaults(self):
106
- super().add_defaults()
107
- self._add_defaults_build_sub_commands()
108
-
109
- def _add_defaults_optional(self):
110
- super()._add_defaults_optional()
111
- if os.path.isfile('pyproject.toml'):
112
- self.filelist.append('pyproject.toml')
113
-
114
- def _add_defaults_python(self):
115
- """getting python files"""
116
- if self.distribution.has_pure_modules():
117
- build_py = self.get_finalized_command('build_py')
118
- self.filelist.extend(build_py.get_source_files())
119
- self._add_data_files(self._safe_data_files(build_py))
120
-
121
- def _add_defaults_build_sub_commands(self):
122
- build = self.get_finalized_command("build")
123
- missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS
124
- # ^-- the original built-in sub-commands are already handled by default.
125
- cmds = (self.get_finalized_command(c) for c in missing_cmds)
126
- files = (c.get_source_files() for c in cmds if hasattr(c, "get_source_files"))
127
- self.filelist.extend(chain.from_iterable(files))
128
-
129
- def _safe_data_files(self, build_py):
130
- """
131
- Since the ``sdist`` class is also used to compute the MANIFEST
132
- (via :obj:`setuptools.command.egg_info.manifest_maker`),
133
- there might be recursion problems when trying to obtain the list of
134
- data_files and ``include_package_data=True`` (which in turn depends on
135
- the files included in the MANIFEST).
136
-
137
- To avoid that, ``manifest_maker`` should be able to overwrite this
138
- method and avoid recursive attempts to build/analyze the MANIFEST.
139
- """
140
- return build_py.data_files
141
-
142
- def _add_data_files(self, data_files):
143
- """
144
- Add data files as found in build_py.data_files.
145
- """
146
- self.filelist.extend(
147
- os.path.join(src_dir, name)
148
- for _, src_dir, _, filenames in data_files
149
- for name in filenames
150
- )
151
-
152
- def _add_defaults_data_files(self):
153
- try:
154
- super()._add_defaults_data_files()
155
- except TypeError:
156
- log.warn("data_files contains unexpected objects")
157
-
158
- def check_readme(self):
159
- for f in self.READMES:
160
- if os.path.exists(f):
161
- return
162
- else:
163
- self.warn(
164
- "standard file not found: should have one of " +
165
- ', '.join(self.READMES)
166
- )
167
-
168
- def make_release_tree(self, base_dir, files):
169
- orig.sdist.make_release_tree(self, base_dir, files)
170
-
171
- # Save any egg_info command line options used to create this sdist
172
- dest = os.path.join(base_dir, 'setup.cfg')
173
- if hasattr(os, 'link') and os.path.exists(dest):
174
- # unlink and re-copy, since it might be hard-linked, and
175
- # we don't want to change the source version
176
- os.unlink(dest)
177
- self.copy_file('setup.cfg', dest)
178
-
179
- self.get_finalized_command('egg_info').save_version_info(dest)
180
-
181
- def _manifest_is_not_generated(self):
182
- # check for special comment used in 2.7.1 and higher
183
- if not os.path.isfile(self.manifest):
184
- return False
185
-
186
- with io.open(self.manifest, 'rb') as fp:
187
- first_line = fp.readline()
188
- return (first_line !=
189
- '# file GENERATED by distutils, do NOT edit\n'.encode())
190
-
191
- def read_manifest(self):
192
- """Read the manifest file (named by 'self.manifest') and use it to
193
- fill in 'self.filelist', the list of files to include in the source
194
- distribution.
195
- """
196
- log.info("reading manifest file '%s'", self.manifest)
197
- manifest = open(self.manifest, 'rb')
198
- for line in manifest:
199
- # The manifest must contain UTF-8. See #303.
200
- try:
201
- line = line.decode('UTF-8')
202
- except UnicodeDecodeError:
203
- log.warn("%r not UTF-8 decodable -- skipping" % line)
204
- continue
205
- # ignore comments and blank lines
206
- line = line.strip()
207
- if line.startswith('#') or not line:
208
- continue
209
- self.filelist.append(line)
210
- manifest.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BongoCaat/ArtGenerator/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: ArtGenerator
3
- emoji: 🏃
4
- colorFrom: red
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 3.29.0
8
- app_file: app.py
9
- pinned: false
10
- license: gpl-3.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/modeling/proposal_generator/rpn.py DELETED
@@ -1,185 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
- from typing import Dict, List
3
- import torch
4
- import torch.nn.functional as F
5
- from torch import nn
6
-
7
- from detectron2.layers import ShapeSpec
8
- from detectron2.utils.registry import Registry
9
-
10
- from ..anchor_generator import build_anchor_generator
11
- from ..box_regression import Box2BoxTransform
12
- from ..matcher import Matcher
13
- from .build import PROPOSAL_GENERATOR_REGISTRY
14
- from .rpn_outputs import RPNOutputs, find_top_rpn_proposals
15
-
16
- RPN_HEAD_REGISTRY = Registry("RPN_HEAD")
17
- RPN_HEAD_REGISTRY.__doc__ = """
18
- Registry for RPN heads, which take feature maps and perform
19
- objectness classification and bounding box regression for anchors.
20
-
21
- The registered object will be called with `obj(cfg, input_shape)`.
22
- The call should return a `nn.Module` object.
23
- """
24
-
25
-
26
- def build_rpn_head(cfg, input_shape):
27
- """
28
- Build an RPN head defined by `cfg.MODEL.RPN.HEAD_NAME`.
29
- """
30
- name = cfg.MODEL.RPN.HEAD_NAME
31
- return RPN_HEAD_REGISTRY.get(name)(cfg, input_shape)
32
-
33
-
34
- @RPN_HEAD_REGISTRY.register()
35
- class StandardRPNHead(nn.Module):
36
- """
37
- RPN classification and regression heads. Uses a 3x3 conv to produce a shared
38
- hidden state from which one 1x1 conv predicts objectness logits for each anchor
39
- and a second 1x1 conv predicts bounding-box deltas specifying how to deform
40
- each anchor into an object proposal.
41
- """
42
-
43
- def __init__(self, cfg, input_shape: List[ShapeSpec]):
44
- super().__init__()
45
-
46
- # Standard RPN is shared across levels:
47
- in_channels = [s.channels for s in input_shape]
48
- assert len(set(in_channels)) == 1, "Each level must have the same channel!"
49
- in_channels = in_channels[0]
50
-
51
- # RPNHead should take the same input as anchor generator
52
- # NOTE: it assumes that creating an anchor generator does not have unwanted side effect.
53
- anchor_generator = build_anchor_generator(cfg, input_shape)
54
- num_cell_anchors = anchor_generator.num_cell_anchors
55
- box_dim = anchor_generator.box_dim
56
- assert (
57
- len(set(num_cell_anchors)) == 1
58
- ), "Each level must have the same number of cell anchors"
59
- num_cell_anchors = num_cell_anchors[0]
60
-
61
- # 3x3 conv for the hidden representation
62
- self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
63
- # 1x1 conv for predicting objectness logits
64
- self.objectness_logits = nn.Conv2d(in_channels, num_cell_anchors, kernel_size=1, stride=1)
65
- # 1x1 conv for predicting box2box transform deltas
66
- self.anchor_deltas = nn.Conv2d(
67
- in_channels, num_cell_anchors * box_dim, kernel_size=1, stride=1
68
- )
69
-
70
- for l in [self.conv, self.objectness_logits, self.anchor_deltas]:
71
- nn.init.normal_(l.weight, std=0.01)
72
- nn.init.constant_(l.bias, 0)
73
-
74
- def forward(self, features):
75
- """
76
- Args:
77
- features (list[Tensor]): list of feature maps
78
- """
79
- pred_objectness_logits = []
80
- pred_anchor_deltas = []
81
- for x in features:
82
- t = F.relu(self.conv(x))
83
- pred_objectness_logits.append(self.objectness_logits(t))
84
- pred_anchor_deltas.append(self.anchor_deltas(t))
85
- return pred_objectness_logits, pred_anchor_deltas
86
-
87
-
88
- @PROPOSAL_GENERATOR_REGISTRY.register()
89
- class RPN(nn.Module):
90
- """
91
- Region Proposal Network, introduced by the Faster R-CNN paper.
92
- """
93
-
94
- def __init__(self, cfg, input_shape: Dict[str, ShapeSpec]):
95
- super().__init__()
96
-
97
- # fmt: off
98
- self.min_box_side_len = cfg.MODEL.PROPOSAL_GENERATOR.MIN_SIZE
99
- self.in_features = cfg.MODEL.RPN.IN_FEATURES
100
- self.nms_thresh = cfg.MODEL.RPN.NMS_THRESH
101
- self.batch_size_per_image = cfg.MODEL.RPN.BATCH_SIZE_PER_IMAGE
102
- self.positive_fraction = cfg.MODEL.RPN.POSITIVE_FRACTION
103
- self.smooth_l1_beta = cfg.MODEL.RPN.SMOOTH_L1_BETA
104
- self.loss_weight = cfg.MODEL.RPN.LOSS_WEIGHT
105
- # fmt: on
106
-
107
- # Map from self.training state to train/test settings
108
- self.pre_nms_topk = {
109
- True: cfg.MODEL.RPN.PRE_NMS_TOPK_TRAIN,
110
- False: cfg.MODEL.RPN.PRE_NMS_TOPK_TEST,
111
- }
112
- self.post_nms_topk = {
113
- True: cfg.MODEL.RPN.POST_NMS_TOPK_TRAIN,
114
- False: cfg.MODEL.RPN.POST_NMS_TOPK_TEST,
115
- }
116
- self.boundary_threshold = cfg.MODEL.RPN.BOUNDARY_THRESH
117
-
118
- self.anchor_generator = build_anchor_generator(
119
- cfg, [input_shape[f] for f in self.in_features]
120
- )
121
- self.box2box_transform = Box2BoxTransform(weights=cfg.MODEL.RPN.BBOX_REG_WEIGHTS)
122
- self.anchor_matcher = Matcher(
123
- cfg.MODEL.RPN.IOU_THRESHOLDS, cfg.MODEL.RPN.IOU_LABELS, allow_low_quality_matches=True
124
- )
125
- self.rpn_head = build_rpn_head(cfg, [input_shape[f] for f in self.in_features])
126
-
127
- def forward(self, images, features, gt_instances=None):
128
- """
129
- Args:
130
- images (ImageList): input images of length `N`
131
- features (dict[str: Tensor]): input data as a mapping from feature
132
- map name to tensor. Axis 0 represents the number of images `N` in
133
- the input data; axes 1-3 are channels, height, and width, which may
134
- vary between feature maps (e.g., if a feature pyramid is used).
135
- gt_instances (list[Instances], optional): a length `N` list of `Instances`s.
136
- Each `Instances` stores ground-truth instances for the corresponding image.
137
-
138
- Returns:
139
- proposals: list[Instances]: contains fields "proposal_boxes", "objectness_logits"
140
- loss: dict[Tensor] or None
141
- """
142
- gt_boxes = [x.gt_boxes for x in gt_instances] if gt_instances is not None else None
143
- del gt_instances
144
- features = [features[f] for f in self.in_features]
145
- pred_objectness_logits, pred_anchor_deltas = self.rpn_head(features)
146
- anchors = self.anchor_generator(features)
147
- # TODO: The anchors only depend on the feature map shape; there's probably
148
- # an opportunity for some optimizations (e.g., caching anchors).
149
- outputs = RPNOutputs(
150
- self.box2box_transform,
151
- self.anchor_matcher,
152
- self.batch_size_per_image,
153
- self.positive_fraction,
154
- images,
155
- pred_objectness_logits,
156
- pred_anchor_deltas,
157
- anchors,
158
- self.boundary_threshold,
159
- gt_boxes,
160
- self.smooth_l1_beta,
161
- )
162
-
163
- if self.training:
164
- losses = {k: v * self.loss_weight for k, v in outputs.losses().items()}
165
- else:
166
- losses = {}
167
-
168
- with torch.no_grad():
169
- # Find the top proposals by applying NMS and removing boxes that
170
- # are too small. The proposals are treated as fixed for approximate
171
- # joint training with roi heads. This approach ignores the derivative
172
- # w.r.t. the proposal boxes’ coordinates that are also network
173
- # responses, so is approximate.
174
- proposals = find_top_rpn_proposals(
175
- outputs.predict_proposals(),
176
- outputs.predict_objectness_logits(),
177
- images,
178
- self.nms_thresh,
179
- self.pre_nms_topk[self.training],
180
- self.post_nms_topk[self.training],
181
- self.min_box_side_len,
182
- self.training,
183
- )
184
-
185
- return proposals, losses
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/densepose/__init__.py DELETED
@@ -1,10 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
- from . import dataset # just to register data
3
- from .config import add_densepose_config
4
- from .dataset_mapper import DatasetMapper
5
- from .densepose_head import ROI_DENSEPOSE_HEAD_REGISTRY
6
- from .evaluator import DensePoseCOCOEvaluator
7
- from .roi_head import DensePoseROIHeads
8
- from .structures import DensePoseDataRelative, DensePoseList, DensePoseTransformData
9
- from .modeling.test_time_augmentation import DensePoseGeneralizedRCNNWithTTA
10
- from .utils.transform import load_from_cfg
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/projects/DensePose/tests/test_setup.py DELETED
@@ -1,20 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2
-
3
- import unittest
4
-
5
- from .common import get_config_files, get_quick_schedules_config_files, setup
6
-
7
-
8
- class TestSetup(unittest.TestCase):
9
- def _test_setup(self, config_file):
10
- setup(config_file)
11
-
12
- def test_setup_configs(self):
13
- config_files = get_config_files()
14
- for config_file in config_files:
15
- self._test_setup(config_file)
16
-
17
- def test_setup_quick_schedules_configs(self):
18
- config_files = get_quick_schedules_config_files()
19
- for config_file in config_files:
20
- self._test_setup(config_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/pybind11/tests/test_stl_binders.py DELETED
@@ -1,285 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- import pytest
3
-
4
- import env # noqa: F401
5
-
6
- from pybind11_tests import stl_binders as m
7
-
8
-
9
- def test_vector_int():
10
- v_int = m.VectorInt([0, 0])
11
- assert len(v_int) == 2
12
- assert bool(v_int) is True
13
-
14
- # test construction from a generator
15
- v_int1 = m.VectorInt(x for x in range(5))
16
- assert v_int1 == m.VectorInt([0, 1, 2, 3, 4])
17
-
18
- v_int2 = m.VectorInt([0, 0])
19
- assert v_int == v_int2
20
- v_int2[1] = 1
21
- assert v_int != v_int2
22
-
23
- v_int2.append(2)
24
- v_int2.insert(0, 1)
25
- v_int2.insert(0, 2)
26
- v_int2.insert(0, 3)
27
- v_int2.insert(6, 3)
28
- assert str(v_int2) == "VectorInt[3, 2, 1, 0, 1, 2, 3]"
29
- with pytest.raises(IndexError):
30
- v_int2.insert(8, 4)
31
-
32
- v_int.append(99)
33
- v_int2[2:-2] = v_int
34
- assert v_int2 == m.VectorInt([3, 2, 0, 0, 99, 2, 3])
35
- del v_int2[1:3]
36
- assert v_int2 == m.VectorInt([3, 0, 99, 2, 3])
37
- del v_int2[0]
38
- assert v_int2 == m.VectorInt([0, 99, 2, 3])
39
-
40
- v_int2.extend(m.VectorInt([4, 5]))
41
- assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5])
42
-
43
- v_int2.extend([6, 7])
44
- assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7])
45
-
46
- # test error handling, and that the vector is unchanged
47
- with pytest.raises(RuntimeError):
48
- v_int2.extend([8, 'a'])
49
-
50
- assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7])
51
-
52
- # test extending from a generator
53
- v_int2.extend(x for x in range(5))
54
- assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4])
55
-
56
- # test negative indexing
57
- assert v_int2[-1] == 4
58
-
59
- # insert with negative index
60
- v_int2.insert(-1, 88)
61
- assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88, 4])
62
-
63
- # delete negative index
64
- del v_int2[-1]
65
- assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88])
66
-
67
- v_int2.clear()
68
- assert len(v_int2) == 0
69
-
70
-
71
- # Older PyPy's failed here, related to the PyPy's buffer protocol.
72
- def test_vector_buffer():
73
- b = bytearray([1, 2, 3, 4])
74
- v = m.VectorUChar(b)
75
- assert v[1] == 2
76
- v[2] = 5
77
- mv = memoryview(v) # We expose the buffer interface
78
- if not env.PY2:
79
- assert mv[2] == 5
80
- mv[2] = 6
81
- else:
82
- assert mv[2] == '\x05'
83
- mv[2] = '\x06'
84
- assert v[2] == 6
85
-
86
- if not env.PY2:
87
- mv = memoryview(b)
88
- v = m.VectorUChar(mv[::2])
89
- assert v[1] == 3
90
-
91
- with pytest.raises(RuntimeError) as excinfo:
92
- m.create_undeclstruct() # Undeclared struct contents, no buffer interface
93
- assert "NumPy type info missing for " in str(excinfo.value)
94
-
95
-
96
- def test_vector_buffer_numpy():
97
- np = pytest.importorskip("numpy")
98
- a = np.array([1, 2, 3, 4], dtype=np.int32)
99
- with pytest.raises(TypeError):
100
- m.VectorInt(a)
101
-
102
- a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.uintc)
103
- v = m.VectorInt(a[0, :])
104
- assert len(v) == 4
105
- assert v[2] == 3
106
- ma = np.asarray(v)
107
- ma[2] = 5
108
- assert v[2] == 5
109
-
110
- v = m.VectorInt(a[:, 1])
111
- assert len(v) == 3
112
- assert v[2] == 10
113
-
114
- v = m.get_vectorstruct()
115
- assert v[0].x == 5
116
- ma = np.asarray(v)
117
- ma[1]['x'] = 99
118
- assert v[1].x == 99
119
-
120
- v = m.VectorStruct(np.zeros(3, dtype=np.dtype([('w', 'bool'), ('x', 'I'),
121
- ('y', 'float64'), ('z', 'bool')], align=True)))
122
- assert len(v) == 3
123
-
124
- b = np.array([1, 2, 3, 4], dtype=np.uint8)
125
- v = m.VectorUChar(b[::2])
126
- assert v[1] == 3
127
-
128
-
129
- def test_vector_bool():
130
- import pybind11_cross_module_tests as cm
131
-
132
- vv_c = cm.VectorBool()
133
- for i in range(10):
134
- vv_c.append(i % 2 == 0)
135
- for i in range(10):
136
- assert vv_c[i] == (i % 2 == 0)
137
- assert str(vv_c) == "VectorBool[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]"
138
-
139
-
140
- def test_vector_custom():
141
- v_a = m.VectorEl()
142
- v_a.append(m.El(1))
143
- v_a.append(m.El(2))
144
- assert str(v_a) == "VectorEl[El{1}, El{2}]"
145
-
146
- vv_a = m.VectorVectorEl()
147
- vv_a.append(v_a)
148
- vv_b = vv_a[0]
149
- assert str(vv_b) == "VectorEl[El{1}, El{2}]"
150
-
151
-
152
- def test_map_string_double():
153
- mm = m.MapStringDouble()
154
- mm['a'] = 1
155
- mm['b'] = 2.5
156
-
157
- assert list(mm) == ['a', 'b']
158
- assert list(mm.items()) == [('a', 1), ('b', 2.5)]
159
- assert str(mm) == "MapStringDouble{a: 1, b: 2.5}"
160
-
161
- um = m.UnorderedMapStringDouble()
162
- um['ua'] = 1.1
163
- um['ub'] = 2.6
164
-
165
- assert sorted(list(um)) == ['ua', 'ub']
166
- assert sorted(list(um.items())) == [('ua', 1.1), ('ub', 2.6)]
167
- assert "UnorderedMapStringDouble" in str(um)
168
-
169
-
170
- def test_map_string_double_const():
171
- mc = m.MapStringDoubleConst()
172
- mc['a'] = 10
173
- mc['b'] = 20.5
174
- assert str(mc) == "MapStringDoubleConst{a: 10, b: 20.5}"
175
-
176
- umc = m.UnorderedMapStringDoubleConst()
177
- umc['a'] = 11
178
- umc['b'] = 21.5
179
-
180
- str(umc)
181
-
182
-
183
- def test_noncopyable_containers():
184
- # std::vector
185
- vnc = m.get_vnc(5)
186
- for i in range(0, 5):
187
- assert vnc[i].value == i + 1
188
-
189
- for i, j in enumerate(vnc, start=1):
190
- assert j.value == i
191
-
192
- # std::deque
193
- dnc = m.get_dnc(5)
194
- for i in range(0, 5):
195
- assert dnc[i].value == i + 1
196
-
197
- i = 1
198
- for j in dnc:
199
- assert(j.value == i)
200
- i += 1
201
-
202
- # std::map
203
- mnc = m.get_mnc(5)
204
- for i in range(1, 6):
205
- assert mnc[i].value == 10 * i
206
-
207
- vsum = 0
208
- for k, v in mnc.items():
209
- assert v.value == 10 * k
210
- vsum += v.value
211
-
212
- assert vsum == 150
213
-
214
- # std::unordered_map
215
- mnc = m.get_umnc(5)
216
- for i in range(1, 6):
217
- assert mnc[i].value == 10 * i
218
-
219
- vsum = 0
220
- for k, v in mnc.items():
221
- assert v.value == 10 * k
222
- vsum += v.value
223
-
224
- assert vsum == 150
225
-
226
- # nested std::map<std::vector>
227
- nvnc = m.get_nvnc(5)
228
- for i in range(1, 6):
229
- for j in range(0, 5):
230
- assert nvnc[i][j].value == j + 1
231
-
232
- # Note: maps do not have .values()
233
- for _, v in nvnc.items():
234
- for i, j in enumerate(v, start=1):
235
- assert j.value == i
236
-
237
- # nested std::map<std::map>
238
- nmnc = m.get_nmnc(5)
239
- for i in range(1, 6):
240
- for j in range(10, 60, 10):
241
- assert nmnc[i][j].value == 10 * j
242
-
243
- vsum = 0
244
- for _, v_o in nmnc.items():
245
- for k_i, v_i in v_o.items():
246
- assert v_i.value == 10 * k_i
247
- vsum += v_i.value
248
-
249
- assert vsum == 7500
250
-
251
- # nested std::unordered_map<std::unordered_map>
252
- numnc = m.get_numnc(5)
253
- for i in range(1, 6):
254
- for j in range(10, 60, 10):
255
- assert numnc[i][j].value == 10 * j
256
-
257
- vsum = 0
258
- for _, v_o in numnc.items():
259
- for k_i, v_i in v_o.items():
260
- assert v_i.value == 10 * k_i
261
- vsum += v_i.value
262
-
263
- assert vsum == 7500
264
-
265
-
266
- def test_map_delitem():
267
- mm = m.MapStringDouble()
268
- mm['a'] = 1
269
- mm['b'] = 2.5
270
-
271
- assert list(mm) == ['a', 'b']
272
- assert list(mm.items()) == [('a', 1), ('b', 2.5)]
273
- del mm['a']
274
- assert list(mm) == ['b']
275
- assert list(mm.items()) == [('b', 2.5)]
276
-
277
- um = m.UnorderedMapStringDouble()
278
- um['ua'] = 1.1
279
- um['ub'] = 2.6
280
-
281
- assert sorted(list(um)) == ['ua', 'ub']
282
- assert sorted(list(um.items())) == [('ua', 1.1), ('ub', 2.6)]
283
- del um['ua']
284
- assert sorted(list(um)) == ['ub']
285
- assert sorted(list(um.items())) == [('ub', 2.6)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/logical.h DELETED
@@ -1,23 +0,0 @@
1
- /*
2
- * Copyright 2008-2013 NVIDIA Corporation
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- #pragma once
18
-
19
- #include <thrust/detail/config.h>
20
-
21
- // this system inherits logical
22
- #include <thrust/system/cpp/detail/logical.h>
23
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/transfiner/configs/common/models/keypoint_rcnn_fpn.py DELETED
@@ -1,33 +0,0 @@
1
- from detectron2.config import LazyCall as L
2
- from detectron2.layers import ShapeSpec
3
- from detectron2.modeling.poolers import ROIPooler
4
- from detectron2.modeling.roi_heads import KRCNNConvDeconvUpsampleHead
5
-
6
- from .mask_rcnn_fpn import model
7
-
8
- [model.roi_heads.pop(x) for x in ["mask_in_features", "mask_pooler", "mask_head"]]
9
-
10
- model.roi_heads.update(
11
- num_classes=1,
12
- keypoint_in_features=["p2", "p3", "p4", "p5"],
13
- keypoint_pooler=L(ROIPooler)(
14
- output_size=14,
15
- scales=(1.0 / 4, 1.0 / 8, 1.0 / 16, 1.0 / 32),
16
- sampling_ratio=0,
17
- pooler_type="ROIAlignV2",
18
- ),
19
- keypoint_head=L(KRCNNConvDeconvUpsampleHead)(
20
- input_shape=ShapeSpec(channels=256, width=14, height=14),
21
- num_keypoints=17,
22
- conv_dims=[512] * 8,
23
- loss_normalizer="visible",
24
- ),
25
- )
26
-
27
- # Detectron1 uses 2000 proposals per-batch, but this option is per-image in detectron2.
28
- # 1000 proposals per-image is found to hurt box AP.
29
- # Therefore we increase it to 1500 per-image.
30
- model.proposal_generator.post_nms_topk = (1500, 1000)
31
-
32
- # Keypoint AP degrades (though box AP improves) when using plain L1 loss
33
- model.roi_heads.box_predictor.smooth_l1_beta = 0.5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChandraMohanNayal/AutoGPT/autogpt/json_utils/json_fix_general.py DELETED
@@ -1,124 +0,0 @@
1
- """This module contains functions to fix JSON strings using general programmatic approaches, suitable for addressing
2
- common JSON formatting issues."""
3
- from __future__ import annotations
4
-
5
- import contextlib
6
- import json
7
- import re
8
- from typing import Optional
9
-
10
- from autogpt.config import Config
11
- from autogpt.json_utils.utilities import extract_char_position
12
-
13
- CFG = Config()
14
-
15
-
16
- def fix_invalid_escape(json_to_load: str, error_message: str) -> str:
17
- """Fix invalid escape sequences in JSON strings.
18
-
19
- Args:
20
- json_to_load (str): The JSON string.
21
- error_message (str): The error message from the JSONDecodeError
22
- exception.
23
-
24
- Returns:
25
- str: The JSON string with invalid escape sequences fixed.
26
- """
27
- while error_message.startswith("Invalid \\escape"):
28
- bad_escape_location = extract_char_position(error_message)
29
- json_to_load = (
30
- json_to_load[:bad_escape_location] + json_to_load[bad_escape_location + 1 :]
31
- )
32
- try:
33
- json.loads(json_to_load)
34
- return json_to_load
35
- except json.JSONDecodeError as e:
36
- if CFG.debug_mode:
37
- print("json loads error - fix invalid escape", e)
38
- error_message = str(e)
39
- return json_to_load
40
-
41
-
42
- def balance_braces(json_string: str) -> Optional[str]:
43
- """
44
- Balance the braces in a JSON string.
45
-
46
- Args:
47
- json_string (str): The JSON string.
48
-
49
- Returns:
50
- str: The JSON string with braces balanced.
51
- """
52
-
53
- open_braces_count = json_string.count("{")
54
- close_braces_count = json_string.count("}")
55
-
56
- while open_braces_count > close_braces_count:
57
- json_string += "}"
58
- close_braces_count += 1
59
-
60
- while close_braces_count > open_braces_count:
61
- json_string = json_string.rstrip("}")
62
- close_braces_count -= 1
63
-
64
- with contextlib.suppress(json.JSONDecodeError):
65
- json.loads(json_string)
66
- return json_string
67
-
68
-
69
- def add_quotes_to_property_names(json_string: str) -> str:
70
- """
71
- Add quotes to property names in a JSON string.
72
-
73
- Args:
74
- json_string (str): The JSON string.
75
-
76
- Returns:
77
- str: The JSON string with quotes added to property names.
78
- """
79
-
80
- def replace_func(match: re.Match) -> str:
81
- return f'"{match[1]}":'
82
-
83
- property_name_pattern = re.compile(r"(\w+):")
84
- corrected_json_string = property_name_pattern.sub(replace_func, json_string)
85
-
86
- try:
87
- json.loads(corrected_json_string)
88
- return corrected_json_string
89
- except json.JSONDecodeError as e:
90
- raise e
91
-
92
-
93
- def correct_json(json_to_load: str) -> str:
94
- """
95
- Correct common JSON errors.
96
- Args:
97
- json_to_load (str): The JSON string.
98
- """
99
-
100
- try:
101
- if CFG.debug_mode:
102
- print("json", json_to_load)
103
- json.loads(json_to_load)
104
- return json_to_load
105
- except json.JSONDecodeError as e:
106
- if CFG.debug_mode:
107
- print("json loads error", e)
108
- error_message = str(e)
109
- if error_message.startswith("Invalid \\escape"):
110
- json_to_load = fix_invalid_escape(json_to_load, error_message)
111
- if error_message.startswith(
112
- "Expecting property name enclosed in double quotes"
113
- ):
114
- json_to_load = add_quotes_to_property_names(json_to_load)
115
- try:
116
- json.loads(json_to_load)
117
- return json_to_load
118
- except json.JSONDecodeError as e:
119
- if CFG.debug_mode:
120
- print("json loads error - add quotes", e)
121
- error_message = str(e)
122
- if balanced_str := balance_braces(json_to_load):
123
- return balanced_str
124
- return json_to_load
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChrisPreston/diff-svc_minato_aqua/infer_tools/trans_key.py DELETED
@@ -1,67 +0,0 @@
1
- import os
2
- head_list = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
3
-
4
-
5
- def trans_f0_seq(feature_pit, transform):
6
- feature_pit = feature_pit * 2 ** (transform / 12)
7
- return round(feature_pit, 1)
8
-
9
-
10
- def move_key(raw_data, mv_key):
11
- head = raw_data[:-1]
12
- body = int(raw_data[-1])
13
- new_head_index = head_list.index(head) + mv_key
14
- while new_head_index < 0:
15
- body -= 1
16
- new_head_index += 12
17
- while new_head_index > 11:
18
- body += 1
19
- new_head_index -= 12
20
- result_data = head_list[new_head_index] + str(body)
21
- return result_data
22
-
23
-
24
- def trans_key(raw_data, key):
25
- for i in raw_data:
26
- note_seq_list = i["note_seq"].split(" ")
27
- new_note_seq_list = []
28
- for note_seq in note_seq_list:
29
- if note_seq != "rest":
30
- new_note_seq = move_key(note_seq, key)
31
- new_note_seq_list.append(new_note_seq)
32
- else:
33
- new_note_seq_list.append(note_seq)
34
- i["note_seq"] = " ".join(new_note_seq_list)
35
-
36
- f0_seq_list = i["f0_seq"].split(" ")
37
- f0_seq_list = [float(x) for x in f0_seq_list]
38
- new_f0_seq_list = []
39
- for f0_seq in f0_seq_list:
40
- new_f0_seq = trans_f0_seq(f0_seq, key)
41
- new_f0_seq_list.append(str(new_f0_seq))
42
- i["f0_seq"] = " ".join(new_f0_seq_list)
43
- return raw_data
44
-
45
-
46
- def trans_opencpop(raw_txt, res_txt, key):
47
- if os.path.exists(raw_txt):
48
- f_w = open(res_txt, "w", encoding='utf-8')
49
- with open(raw_txt, "r", encoding='utf-8') as f:
50
- raw_data = f.readlines()
51
- for raw in raw_data:
52
- raw_list = raw.split("|")
53
- new_note_seq_list = []
54
- for note_seq in raw_list[3].split(" "):
55
- if note_seq != "rest":
56
- note_seq = note_seq.split("/")[0] if "/" in note_seq else note_seq
57
- new_note_seq = move_key(note_seq, key)
58
- new_note_seq_list.append(new_note_seq)
59
- else:
60
- new_note_seq_list.append(note_seq)
61
- raw_list[3] = " ".join(new_note_seq_list)
62
- f_w.write("|".join(raw_list))
63
- f_w.close()
64
- print("opencpop标注文件转换完毕")
65
- else:
66
- print("未发现opencpop标注文件,请检查路径")
67
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Codecooker/rvcapi/src/webui.py DELETED
@@ -1,309 +0,0 @@
1
- import json
2
- import os
3
- os.system("pip install torchcrepe")
4
- os.system("pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu")
5
- import shutil
6
- import urllib.request
7
- import zipfile
8
- from argparse import ArgumentParser
9
-
10
- import gradio as gr
11
-
12
- from main import song_cover_pipeline
13
-
14
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
-
16
- mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models')
17
- rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models')
18
- output_dir = os.path.join(BASE_DIR, 'song_output')
19
-
20
-
21
- def get_current_models(models_dir):
22
- models_list = os.listdir(models_dir)
23
- items_to_remove = ['hubert_base.pt', 'MODELS.txt', 'public_models.json', 'rmvpe.pt']
24
- return [item for item in models_list if item not in items_to_remove]
25
-
26
-
27
- def update_models_list():
28
- models_l = get_current_models(rvc_models_dir)
29
- return gr.Dropdown.update(choices=models_l)
30
-
31
-
32
- def load_public_models():
33
- models_table = []
34
- for model in public_models['voice_models']:
35
- if not model['name'] in voice_models:
36
- model = [model['name'], model['description'], model['credit'], model['url'], ', '.join(model['tags'])]
37
- models_table.append(model)
38
-
39
- tags = list(public_models['tags'].keys())
40
- return gr.DataFrame.update(value=models_table), gr.CheckboxGroup.update(choices=tags)
41
-
42
-
43
- def extract_zip(extraction_folder, zip_name):
44
- os.makedirs(extraction_folder)
45
- with zipfile.ZipFile(zip_name, 'r') as zip_ref:
46
- zip_ref.extractall(extraction_folder)
47
- os.remove(zip_name)
48
-
49
- index_filepath, model_filepath = None, None
50
- for root, dirs, files in os.walk(extraction_folder):
51
- for name in files:
52
- if name.endswith('.index'):
53
- index_filepath = os.path.join(root, name)
54
-
55
- if name.endswith('.pth'):
56
- model_filepath = os.path.join(root, name)
57
-
58
- if not model_filepath:
59
- raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.')
60
-
61
- # move model and index file to extraction folder
62
- os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath)))
63
- if index_filepath:
64
- os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath)))
65
-
66
- # remove any unnecessary nested folders
67
- for filepath in os.listdir(extraction_folder):
68
- if os.path.isdir(os.path.join(extraction_folder, filepath)):
69
- shutil.rmtree(os.path.join(extraction_folder, filepath))
70
-
71
-
72
- def download_online_model(url, dir_name, progress=gr.Progress()):
73
- try:
74
- progress(0, desc=f'[~] Downloading voice model with name {dir_name}...')
75
- zip_name = url.split('/')[-1]
76
- extraction_folder = os.path.join(rvc_models_dir, dir_name)
77
- if os.path.exists(extraction_folder):
78
- raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
79
-
80
- if 'pixeldrain.com' in url:
81
- url = f'https://pixeldrain.com/api/file/{zip_name}'
82
-
83
- urllib.request.urlretrieve(url, zip_name)
84
-
85
- progress(0.5, desc='[~] Extracting zip...')
86
- extract_zip(extraction_folder, zip_name)
87
- return f'[+] {dir_name} Model successfully downloaded!'
88
-
89
- except Exception as e:
90
- raise gr.Error(str(e))
91
-
92
-
93
- def upload_local_model(zip_path, dir_name, progress=gr.Progress()):
94
- try:
95
- extraction_folder = os.path.join(rvc_models_dir, dir_name)
96
- if os.path.exists(extraction_folder):
97
- raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.')
98
-
99
- zip_name = zip_path.name
100
- progress(0.5, desc='[~] Extracting zip...')
101
- extract_zip(extraction_folder, zip_name)
102
- return f'[+] {dir_name} Model successfully uploaded!'
103
-
104
- except Exception as e:
105
- raise gr.Error(str(e))
106
-
107
-
108
- def filter_models(tags, query):
109
- models_table = []
110
-
111
- # no filter
112
- if len(tags) == 0 and len(query) == 0:
113
- for model in public_models['voice_models']:
114
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
115
-
116
- # filter based on tags and query
117
- elif len(tags) > 0 and len(query) > 0:
118
- for model in public_models['voice_models']:
119
- if all(tag in model['tags'] for tag in tags):
120
- model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
121
- if query.lower() in model_attributes:
122
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
123
-
124
- # filter based on only tags
125
- elif len(tags) > 0:
126
- for model in public_models['voice_models']:
127
- if all(tag in model['tags'] for tag in tags):
128
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
129
-
130
- # filter based on only query
131
- else:
132
- for model in public_models['voice_models']:
133
- model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower()
134
- if query.lower() in model_attributes:
135
- models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']])
136
-
137
- return gr.DataFrame.update(value=models_table)
138
-
139
-
140
- def pub_dl_autofill(pub_models, event: gr.SelectData):
141
- return gr.Text.update(value=pub_models.loc[event.index[0], 'URL']), gr.Text.update(value=pub_models.loc[event.index[0], 'Model Name'])
142
-
143
-
144
- def swap_visibility():
145
- return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None)
146
-
147
-
148
- def process_file_upload(file):
149
- return file.name, gr.update(value=file.name)
150
-
151
-
152
- if __name__ == '__main__':
153
- os.system("pip install torchcrepe")
154
- os.system("pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu")
155
- parser = ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
156
- parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Enable sharing")
157
- parser.add_argument("--listen", action="store_true", default=False, help="Make the WebUI reachable from your local network.")
158
- parser.add_argument('--listen-host', type=str, help='The hostname that the server will use.')
159
- parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
160
- args = parser.parse_args()
161
-
162
- voice_models = get_current_models(rvc_models_dir)
163
- with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile:
164
- public_models = json.load(infile)
165
-
166
- with gr.Blocks(title='AICoverGenWebUI') as app:
167
-
168
- gr.Label('AICoverGen WebUI created with ❤️', show_label=False)
169
-
170
- # main tab
171
- with gr.Tab("Generate"):
172
-
173
- with gr.Accordion('Main Options'):
174
- with gr.Row():
175
- with gr.Column():
176
- rvc_model = gr.Dropdown(voice_models, label='Voice Models', info='Models folder "AICoverGen --> rvc_models". After new models are added into this folder, click the refresh button')
177
- ref_btn = gr.Button('Refresh Models 🔁', variant='primary')
178
-
179
- with gr.Column() as yt_link_col:
180
- song_input = gr.Text(label='Song input', info='Link to a song on YouTube or full path to a local file. For file upload, click the button below.')
181
- show_file_upload_button = gr.Button('Upload file instead')
182
-
183
- with gr.Column(visible=False) as file_upload_col:
184
- local_file = gr.File(label='Audio file')
185
- song_input_file = gr.UploadButton('Upload 📂', file_types=['audio'], variant='primary')
186
- show_yt_link_button = gr.Button('Paste YouTube link/Path to local file instead')
187
- song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input])
188
-
189
- pitch = gr.Slider(-24, 24, value=0, step=1, label='Pitch Change', info='Pitch Change should be set to either -12, 0, or 12 (multiples of 12) to ensure the vocals are not out of tune')
190
- show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file])
191
- show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file])
192
-
193
- with gr.Accordion('Voice conversion options', open=False):
194
- with gr.Row():
195
- index_rate = gr.Slider(0, 1, value=0.5, label='Index Rate', info="Controls how much of the AI voice's accent to keep in the vocals")
196
- filter_radius = gr.Slider(0, 7, value=3, step=1, label='Filter radius', info='If >=3: apply median filtering median filtering to the harvested pitch results. Can reduce breathiness')
197
- rms_mix_rate = gr.Slider(0, 1, value=0.25, label='RMS mix rate', info="Control how much to use the original vocal's loudness (0) or a fixed loudness (1)")
198
- protect = gr.Slider(0, 0.5, value=0.33, label='Protect rate', info='Protect voiceless consonants and breath sounds. Set to 0.5 to disable.')
199
- keep_files = gr.Checkbox(label='Keep intermediate files',
200
- info='Keep all audio files generated in the song_output/id directory, e.g. Isolated Vocals/Instrumentals. Leave unchecked to save space')
201
-
202
- with gr.Accordion('Audio mixing options', open=False):
203
- gr.Markdown('### Volume Change (decibels)')
204
- with gr.Row():
205
- main_gain = gr.Slider(-20, 20, value=0, step=1, label='Main Vocals')
206
- backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Backup Vocals')
207
- inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Music')
208
-
209
- gr.Markdown('### Reverb Control on AI Vocals')
210
- with gr.Row():
211
- reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='The larger the room, the longer the reverb time')
212
- reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Level of AI vocals with reverb')
213
- reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Level of AI vocals without reverb')
214
- reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Absorption of high frequencies in the reverb')
215
-
216
- with gr.Row():
217
- clear_btn = gr.ClearButton(value='Clear', components=[song_input, rvc_model, keep_files, local_file])
218
- generate_btn = gr.Button("Generate", variant='primary')
219
- ai_cover = gr.Audio(label='AI Cover', show_share_button=False)
220
-
221
- ref_btn.click(update_models_list, None, outputs=rvc_model)
222
- is_webui = gr.Number(value=1, visible=False)
223
- generate_btn.click(song_cover_pipeline,
224
- inputs=[song_input, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain,
225
- inst_gain, index_rate, filter_radius, rms_mix_rate, protect, reverb_rm_size,
226
- reverb_wet, reverb_dry, reverb_damping],
227
- outputs=[ai_cover])
228
- clear_btn.click(lambda: [0, 0, 0, 0, 0.5, 3, 0.25, 0.33, 0.15, 0.2, 0.8, 0.7, None],
229
- outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate,
230
- protect, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, ai_cover])
231
-
232
- # Download tab
233
- with gr.Tab('Download model'):
234
-
235
- with gr.Tab('From HuggingFace/Pixeldrain URL'):
236
- with gr.Row():
237
- model_zip_link = gr.Text(label='Download link to model', info='Should be a zip file containing a .pth model file and an optional .index file.')
238
- model_name = gr.Text(label='Name your model', info='Give your new model a unique name from your other voice models.')
239
-
240
- with gr.Row():
241
- download_btn = gr.Button('Download 🌐', variant='primary', scale=19)
242
- dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
243
-
244
- download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message)
245
-
246
- gr.Markdown('## Input Examples')
247
- gr.Examples(
248
- [
249
- ['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'],
250
- ['https://pixeldrain.com/u/3tJmABXA', 'Gura'],
251
- ['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki']
252
- ],
253
- [model_zip_link, model_name],
254
- [],
255
- download_online_model,
256
- )
257
-
258
- with gr.Tab('From Public Index'):
259
-
260
- gr.Markdown('## How to use')
261
- gr.Markdown('- Click Initialize public models table')
262
- gr.Markdown('- Filter models using tags or search bar')
263
- gr.Markdown('- Select a row to autofill the download link and model name')
264
- gr.Markdown('- Click Download')
265
-
266
- with gr.Row():
267
- pub_zip_link = gr.Text(label='Download link to model')
268
- pub_model_name = gr.Text(label='Model name')
269
-
270
- with gr.Row():
271
- download_pub_btn = gr.Button('Download 🌐', variant='primary', scale=19)
272
- pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
273
-
274
- filter_tags = gr.CheckboxGroup(value=[], label='Show voice models with tags', choices=[])
275
- search_query = gr.Text(label='Search')
276
- load_public_models_button = gr.Button(value='Initialize public models table', variant='primary')
277
-
278
- public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False)
279
- public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name])
280
- load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags])
281
- search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
282
- filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table)
283
- download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message)
284
-
285
- # Upload tab
286
- with gr.Tab('Upload model'):
287
- gr.Markdown('## Upload locally trained RVC v2 model and index file')
288
- gr.Markdown('- Find model file (weights folder) and optional index file (logs/[name] folder)')
289
- gr.Markdown('- Compress files into zip file')
290
- gr.Markdown('- Upload zip file and give unique name for voice')
291
- gr.Markdown('- Click Upload model')
292
-
293
- with gr.Row():
294
- with gr.Column():
295
- zip_file = gr.File(label='Zip file')
296
-
297
- local_model_name = gr.Text(label='Model name')
298
-
299
- with gr.Row():
300
- model_upload_button = gr.Button('Upload model', variant='primary', scale=19)
301
- local_upload_output_message = gr.Text(label='Output Message', interactive=False, scale=20)
302
- model_upload_button.click(upload_local_model, inputs=[zip_file, local_model_name], outputs=local_upload_output_message)
303
-
304
- app.launch(
305
- share=args.share_enabled,
306
- enable_queue=True,
307
- server_name=None if not args.listen else (args.listen_host or '0.0.0.0'),
308
- server_port=args.listen_port,
309
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/cu2qu/__init__.py DELETED
@@ -1,15 +0,0 @@
1
- # Copyright 2016 Google Inc. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from .cu2qu import *
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/feaLib/builder.py DELETED
@@ -1,1706 +0,0 @@
1
- from fontTools.misc import sstruct
2
- from fontTools.misc.textTools import Tag, tostr, binary2num, safeEval
3
- from fontTools.feaLib.error import FeatureLibError
4
- from fontTools.feaLib.lookupDebugInfo import (
5
- LookupDebugInfo,
6
- LOOKUP_DEBUG_INFO_KEY,
7
- LOOKUP_DEBUG_ENV_VAR,
8
- )
9
- from fontTools.feaLib.parser import Parser
10
- from fontTools.feaLib.ast import FeatureFile
11
- from fontTools.feaLib.variableScalar import VariableScalar
12
- from fontTools.otlLib import builder as otl
13
- from fontTools.otlLib.maxContextCalc import maxCtxFont
14
- from fontTools.ttLib import newTable, getTableModule
15
- from fontTools.ttLib.tables import otBase, otTables
16
- from fontTools.otlLib.builder import (
17
- AlternateSubstBuilder,
18
- ChainContextPosBuilder,
19
- ChainContextSubstBuilder,
20
- LigatureSubstBuilder,
21
- MultipleSubstBuilder,
22
- CursivePosBuilder,
23
- MarkBasePosBuilder,
24
- MarkLigPosBuilder,
25
- MarkMarkPosBuilder,
26
- ReverseChainSingleSubstBuilder,
27
- SingleSubstBuilder,
28
- ClassPairPosSubtableBuilder,
29
- PairPosBuilder,
30
- SinglePosBuilder,
31
- ChainContextualRule,
32
- )
33
- from fontTools.otlLib.error import OpenTypeLibError
34
- from fontTools.varLib.varStore import OnlineVarStoreBuilder
35
- from fontTools.varLib.builder import buildVarDevTable
36
- from fontTools.varLib.featureVars import addFeatureVariationsRaw
37
- from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
38
- from collections import defaultdict
39
- import itertools
40
- from io import StringIO
41
- import logging
42
- import warnings
43
- import os
44
-
45
-
46
- log = logging.getLogger(__name__)
47
-
48
-
49
- def addOpenTypeFeatures(font, featurefile, tables=None, debug=False):
50
- """Add features from a file to a font. Note that this replaces any features
51
- currently present.
52
-
53
- Args:
54
- font (feaLib.ttLib.TTFont): The font object.
55
- featurefile: Either a path or file object (in which case we
56
- parse it into an AST), or a pre-parsed AST instance.
57
- tables: If passed, restrict the set of affected tables to those in the
58
- list.
59
- debug: Whether to add source debugging information to the font in the
60
- ``Debg`` table
61
-
62
- """
63
- builder = Builder(font, featurefile)
64
- builder.build(tables=tables, debug=debug)
65
-
66
-
67
- def addOpenTypeFeaturesFromString(
68
- font, features, filename=None, tables=None, debug=False
69
- ):
70
- """Add features from a string to a font. Note that this replaces any
71
- features currently present.
72
-
73
- Args:
74
- font (feaLib.ttLib.TTFont): The font object.
75
- features: A string containing feature code.
76
- filename: The directory containing ``filename`` is used as the root of
77
- relative ``include()`` paths; if ``None`` is provided, the current
78
- directory is assumed.
79
- tables: If passed, restrict the set of affected tables to those in the
80
- list.
81
- debug: Whether to add source debugging information to the font in the
82
- ``Debg`` table
83
-
84
- """
85
-
86
- featurefile = StringIO(tostr(features))
87
- if filename:
88
- featurefile.name = filename
89
- addOpenTypeFeatures(font, featurefile, tables=tables, debug=debug)
90
-
91
-
92
- class Builder(object):
93
- supportedTables = frozenset(
94
- Tag(tag)
95
- for tag in [
96
- "BASE",
97
- "GDEF",
98
- "GPOS",
99
- "GSUB",
100
- "OS/2",
101
- "head",
102
- "hhea",
103
- "name",
104
- "vhea",
105
- "STAT",
106
- ]
107
- )
108
-
109
- def __init__(self, font, featurefile):
110
- self.font = font
111
- # 'featurefile' can be either a path or file object (in which case we
112
- # parse it into an AST), or a pre-parsed AST instance
113
- if isinstance(featurefile, FeatureFile):
114
- self.parseTree, self.file = featurefile, None
115
- else:
116
- self.parseTree, self.file = None, featurefile
117
- self.glyphMap = font.getReverseGlyphMap()
118
- self.varstorebuilder = None
119
- if "fvar" in font:
120
- self.axes = font["fvar"].axes
121
- self.varstorebuilder = OnlineVarStoreBuilder(
122
- [ax.axisTag for ax in self.axes]
123
- )
124
- self.default_language_systems_ = set()
125
- self.script_ = None
126
- self.lookupflag_ = 0
127
- self.lookupflag_markFilterSet_ = None
128
- self.language_systems = set()
129
- self.seen_non_DFLT_script_ = False
130
- self.named_lookups_ = {}
131
- self.cur_lookup_ = None
132
- self.cur_lookup_name_ = None
133
- self.cur_feature_name_ = None
134
- self.lookups_ = []
135
- self.lookup_locations = {"GSUB": {}, "GPOS": {}}
136
- self.features_ = {} # ('latn', 'DEU ', 'smcp') --> [LookupBuilder*]
137
- self.required_features_ = {} # ('latn', 'DEU ') --> 'scmp'
138
- self.feature_variations_ = {}
139
- # for feature 'aalt'
140
- self.aalt_features_ = [] # [(location, featureName)*], for 'aalt'
141
- self.aalt_location_ = None
142
- self.aalt_alternates_ = {}
143
- # for 'featureNames'
144
- self.featureNames_ = set()
145
- self.featureNames_ids_ = {}
146
- # for 'cvParameters'
147
- self.cv_parameters_ = set()
148
- self.cv_parameters_ids_ = {}
149
- self.cv_num_named_params_ = {}
150
- self.cv_characters_ = defaultdict(list)
151
- # for feature 'size'
152
- self.size_parameters_ = None
153
- # for table 'head'
154
- self.fontRevision_ = None # 2.71
155
- # for table 'name'
156
- self.names_ = []
157
- # for table 'BASE'
158
- self.base_horiz_axis_ = None
159
- self.base_vert_axis_ = None
160
- # for table 'GDEF'
161
- self.attachPoints_ = {} # "a" --> {3, 7}
162
- self.ligCaretCoords_ = {} # "f_f_i" --> {300, 600}
163
- self.ligCaretPoints_ = {} # "f_f_i" --> {3, 7}
164
- self.glyphClassDefs_ = {} # "fi" --> (2, (file, line, column))
165
- self.markAttach_ = {} # "acute" --> (4, (file, line, column))
166
- self.markAttachClassID_ = {} # frozenset({"acute", "grave"}) --> 4
167
- self.markFilterSets_ = {} # frozenset({"acute", "grave"}) --> 4
168
- # for table 'OS/2'
169
- self.os2_ = {}
170
- # for table 'hhea'
171
- self.hhea_ = {}
172
- # for table 'vhea'
173
- self.vhea_ = {}
174
- # for table 'STAT'
175
- self.stat_ = {}
176
- # for conditionsets
177
- self.conditionsets_ = {}
178
- # We will often use exactly the same locations (i.e. the font's masters)
179
- # for a large number of variable scalars. Instead of creating a model
180
- # for each, let's share the models.
181
- self.model_cache = {}
182
-
183
- def build(self, tables=None, debug=False):
184
- if self.parseTree is None:
185
- self.parseTree = Parser(self.file, self.glyphMap).parse()
186
- self.parseTree.build(self)
187
- # by default, build all the supported tables
188
- if tables is None:
189
- tables = self.supportedTables
190
- else:
191
- tables = frozenset(tables)
192
- unsupported = tables - self.supportedTables
193
- if unsupported:
194
- unsupported_string = ", ".join(sorted(unsupported))
195
- raise NotImplementedError(
196
- "The following tables were requested but are unsupported: "
197
- f"{unsupported_string}."
198
- )
199
- if "GSUB" in tables:
200
- self.build_feature_aalt_()
201
- if "head" in tables:
202
- self.build_head()
203
- if "hhea" in tables:
204
- self.build_hhea()
205
- if "vhea" in tables:
206
- self.build_vhea()
207
- if "name" in tables:
208
- self.build_name()
209
- if "OS/2" in tables:
210
- self.build_OS_2()
211
- if "STAT" in tables:
212
- self.build_STAT()
213
- for tag in ("GPOS", "GSUB"):
214
- if tag not in tables:
215
- continue
216
- table = self.makeTable(tag)
217
- if self.feature_variations_:
218
- self.makeFeatureVariations(table, tag)
219
- if (
220
- table.ScriptList.ScriptCount > 0
221
- or table.FeatureList.FeatureCount > 0
222
- or table.LookupList.LookupCount > 0
223
- ):
224
- fontTable = self.font[tag] = newTable(tag)
225
- fontTable.table = table
226
- elif tag in self.font:
227
- del self.font[tag]
228
- if any(tag in self.font for tag in ("GPOS", "GSUB")) and "OS/2" in self.font:
229
- self.font["OS/2"].usMaxContext = maxCtxFont(self.font)
230
- if "GDEF" in tables:
231
- gdef = self.buildGDEF()
232
- if gdef:
233
- self.font["GDEF"] = gdef
234
- elif "GDEF" in self.font:
235
- del self.font["GDEF"]
236
- if "BASE" in tables:
237
- base = self.buildBASE()
238
- if base:
239
- self.font["BASE"] = base
240
- elif "BASE" in self.font:
241
- del self.font["BASE"]
242
- if debug or os.environ.get(LOOKUP_DEBUG_ENV_VAR):
243
- self.buildDebg()
244
-
245
- def get_chained_lookup_(self, location, builder_class):
246
- result = builder_class(self.font, location)
247
- result.lookupflag = self.lookupflag_
248
- result.markFilterSet = self.lookupflag_markFilterSet_
249
- self.lookups_.append(result)
250
- return result
251
-
252
- def add_lookup_to_feature_(self, lookup, feature_name):
253
- for script, lang in self.language_systems:
254
- key = (script, lang, feature_name)
255
- self.features_.setdefault(key, []).append(lookup)
256
-
257
- def get_lookup_(self, location, builder_class):
258
- if (
259
- self.cur_lookup_
260
- and type(self.cur_lookup_) == builder_class
261
- and self.cur_lookup_.lookupflag == self.lookupflag_
262
- and self.cur_lookup_.markFilterSet == self.lookupflag_markFilterSet_
263
- ):
264
- return self.cur_lookup_
265
- if self.cur_lookup_name_ and self.cur_lookup_:
266
- raise FeatureLibError(
267
- "Within a named lookup block, all rules must be of "
268
- "the same lookup type and flag",
269
- location,
270
- )
271
- self.cur_lookup_ = builder_class(self.font, location)
272
- self.cur_lookup_.lookupflag = self.lookupflag_
273
- self.cur_lookup_.markFilterSet = self.lookupflag_markFilterSet_
274
- self.lookups_.append(self.cur_lookup_)
275
- if self.cur_lookup_name_:
276
- # We are starting a lookup rule inside a named lookup block.
277
- self.named_lookups_[self.cur_lookup_name_] = self.cur_lookup_
278
- if self.cur_feature_name_:
279
- # We are starting a lookup rule inside a feature. This includes
280
- # lookup rules inside named lookups inside features.
281
- self.add_lookup_to_feature_(self.cur_lookup_, self.cur_feature_name_)
282
- return self.cur_lookup_
283
-
284
- def build_feature_aalt_(self):
285
- if not self.aalt_features_ and not self.aalt_alternates_:
286
- return
287
- alternates = {g: set(a) for g, a in self.aalt_alternates_.items()}
288
- for location, name in self.aalt_features_ + [(None, "aalt")]:
289
- feature = [
290
- (script, lang, feature, lookups)
291
- for (script, lang, feature), lookups in self.features_.items()
292
- if feature == name
293
- ]
294
- # "aalt" does not have to specify its own lookups, but it might.
295
- if not feature and name != "aalt":
296
- warnings.warn("%s: Feature %s has not been defined" % (location, name))
297
- continue
298
- for script, lang, feature, lookups in feature:
299
- for lookuplist in lookups:
300
- if not isinstance(lookuplist, list):
301
- lookuplist = [lookuplist]
302
- for lookup in lookuplist:
303
- for glyph, alts in lookup.getAlternateGlyphs().items():
304
- alternates.setdefault(glyph, set()).update(alts)
305
- single = {
306
- glyph: list(repl)[0] for glyph, repl in alternates.items() if len(repl) == 1
307
- }
308
- # TODO: Figure out the glyph alternate ordering used by makeotf.
309
- # https://github.com/fonttools/fonttools/issues/836
310
- multi = {
311
- glyph: sorted(repl, key=self.font.getGlyphID)
312
- for glyph, repl in alternates.items()
313
- if len(repl) > 1
314
- }
315
- if not single and not multi:
316
- return
317
- self.features_ = {
318
- (script, lang, feature): lookups
319
- for (script, lang, feature), lookups in self.features_.items()
320
- if feature != "aalt"
321
- }
322
- old_lookups = self.lookups_
323
- self.lookups_ = []
324
- self.start_feature(self.aalt_location_, "aalt")
325
- if single:
326
- single_lookup = self.get_lookup_(location, SingleSubstBuilder)
327
- single_lookup.mapping = single
328
- if multi:
329
- multi_lookup = self.get_lookup_(location, AlternateSubstBuilder)
330
- multi_lookup.alternates = multi
331
- self.end_feature()
332
- self.lookups_.extend(old_lookups)
333
-
334
- def build_head(self):
335
- if not self.fontRevision_:
336
- return
337
- table = self.font.get("head")
338
- if not table: # this only happens for unit tests
339
- table = self.font["head"] = newTable("head")
340
- table.decompile(b"\0" * 54, self.font)
341
- table.tableVersion = 1.0
342
- table.created = table.modified = 3406620153 # 2011-12-13 11:22:33
343
- table.fontRevision = self.fontRevision_
344
-
345
- def build_hhea(self):
346
- if not self.hhea_:
347
- return
348
- table = self.font.get("hhea")
349
- if not table: # this only happens for unit tests
350
- table = self.font["hhea"] = newTable("hhea")
351
- table.decompile(b"\0" * 36, self.font)
352
- table.tableVersion = 0x00010000
353
- if "caretoffset" in self.hhea_:
354
- table.caretOffset = self.hhea_["caretoffset"]
355
- if "ascender" in self.hhea_:
356
- table.ascent = self.hhea_["ascender"]
357
- if "descender" in self.hhea_:
358
- table.descent = self.hhea_["descender"]
359
- if "linegap" in self.hhea_:
360
- table.lineGap = self.hhea_["linegap"]
361
-
362
- def build_vhea(self):
363
- if not self.vhea_:
364
- return
365
- table = self.font.get("vhea")
366
- if not table: # this only happens for unit tests
367
- table = self.font["vhea"] = newTable("vhea")
368
- table.decompile(b"\0" * 36, self.font)
369
- table.tableVersion = 0x00011000
370
- if "verttypoascender" in self.vhea_:
371
- table.ascent = self.vhea_["verttypoascender"]
372
- if "verttypodescender" in self.vhea_:
373
- table.descent = self.vhea_["verttypodescender"]
374
- if "verttypolinegap" in self.vhea_:
375
- table.lineGap = self.vhea_["verttypolinegap"]
376
-
377
- def get_user_name_id(self, table):
378
- # Try to find first unused font-specific name id
379
- nameIDs = [name.nameID for name in table.names]
380
- for user_name_id in range(256, 32767):
381
- if user_name_id not in nameIDs:
382
- return user_name_id
383
-
384
- def buildFeatureParams(self, tag):
385
- params = None
386
- if tag == "size":
387
- params = otTables.FeatureParamsSize()
388
- (
389
- params.DesignSize,
390
- params.SubfamilyID,
391
- params.RangeStart,
392
- params.RangeEnd,
393
- ) = self.size_parameters_
394
- if tag in self.featureNames_ids_:
395
- params.SubfamilyNameID = self.featureNames_ids_[tag]
396
- else:
397
- params.SubfamilyNameID = 0
398
- elif tag in self.featureNames_:
399
- if not self.featureNames_ids_:
400
- # name table wasn't selected among the tables to build; skip
401
- pass
402
- else:
403
- assert tag in self.featureNames_ids_
404
- params = otTables.FeatureParamsStylisticSet()
405
- params.Version = 0
406
- params.UINameID = self.featureNames_ids_[tag]
407
- elif tag in self.cv_parameters_:
408
- params = otTables.FeatureParamsCharacterVariants()
409
- params.Format = 0
410
- params.FeatUILabelNameID = self.cv_parameters_ids_.get(
411
- (tag, "FeatUILabelNameID"), 0
412
- )
413
- params.FeatUITooltipTextNameID = self.cv_parameters_ids_.get(
414
- (tag, "FeatUITooltipTextNameID"), 0
415
- )
416
- params.SampleTextNameID = self.cv_parameters_ids_.get(
417
- (tag, "SampleTextNameID"), 0
418
- )
419
- params.NumNamedParameters = self.cv_num_named_params_.get(tag, 0)
420
- params.FirstParamUILabelNameID = self.cv_parameters_ids_.get(
421
- (tag, "ParamUILabelNameID_0"), 0
422
- )
423
- params.CharCount = len(self.cv_characters_[tag])
424
- params.Character = self.cv_characters_[tag]
425
- return params
426
-
427
- def build_name(self):
428
- if not self.names_:
429
- return
430
- table = self.font.get("name")
431
- if not table: # this only happens for unit tests
432
- table = self.font["name"] = newTable("name")
433
- table.names = []
434
- for name in self.names_:
435
- nameID, platformID, platEncID, langID, string = name
436
- # For featureNames block, nameID is 'feature tag'
437
- # For cvParameters blocks, nameID is ('feature tag', 'block name')
438
- if not isinstance(nameID, int):
439
- tag = nameID
440
- if tag in self.featureNames_:
441
- if tag not in self.featureNames_ids_:
442
- self.featureNames_ids_[tag] = self.get_user_name_id(table)
443
- assert self.featureNames_ids_[tag] is not None
444
- nameID = self.featureNames_ids_[tag]
445
- elif tag[0] in self.cv_parameters_:
446
- if tag not in self.cv_parameters_ids_:
447
- self.cv_parameters_ids_[tag] = self.get_user_name_id(table)
448
- assert self.cv_parameters_ids_[tag] is not None
449
- nameID = self.cv_parameters_ids_[tag]
450
- table.setName(string, nameID, platformID, platEncID, langID)
451
- table.names.sort()
452
-
453
- def build_OS_2(self):
454
- if not self.os2_:
455
- return
456
- table = self.font.get("OS/2")
457
- if not table: # this only happens for unit tests
458
- table = self.font["OS/2"] = newTable("OS/2")
459
- data = b"\0" * sstruct.calcsize(getTableModule("OS/2").OS2_format_0)
460
- table.decompile(data, self.font)
461
- version = 0
462
- if "fstype" in self.os2_:
463
- table.fsType = self.os2_["fstype"]
464
- if "panose" in self.os2_:
465
- panose = getTableModule("OS/2").Panose()
466
- (
467
- panose.bFamilyType,
468
- panose.bSerifStyle,
469
- panose.bWeight,
470
- panose.bProportion,
471
- panose.bContrast,
472
- panose.bStrokeVariation,
473
- panose.bArmStyle,
474
- panose.bLetterForm,
475
- panose.bMidline,
476
- panose.bXHeight,
477
- ) = self.os2_["panose"]
478
- table.panose = panose
479
- if "typoascender" in self.os2_:
480
- table.sTypoAscender = self.os2_["typoascender"]
481
- if "typodescender" in self.os2_:
482
- table.sTypoDescender = self.os2_["typodescender"]
483
- if "typolinegap" in self.os2_:
484
- table.sTypoLineGap = self.os2_["typolinegap"]
485
- if "winascent" in self.os2_:
486
- table.usWinAscent = self.os2_["winascent"]
487
- if "windescent" in self.os2_:
488
- table.usWinDescent = self.os2_["windescent"]
489
- if "vendor" in self.os2_:
490
- table.achVendID = safeEval("'''" + self.os2_["vendor"] + "'''")
491
- if "weightclass" in self.os2_:
492
- table.usWeightClass = self.os2_["weightclass"]
493
- if "widthclass" in self.os2_:
494
- table.usWidthClass = self.os2_["widthclass"]
495
- if "unicoderange" in self.os2_:
496
- table.setUnicodeRanges(self.os2_["unicoderange"])
497
- if "codepagerange" in self.os2_:
498
- pages = self.build_codepages_(self.os2_["codepagerange"])
499
- table.ulCodePageRange1, table.ulCodePageRange2 = pages
500
- version = 1
501
- if "xheight" in self.os2_:
502
- table.sxHeight = self.os2_["xheight"]
503
- version = 2
504
- if "capheight" in self.os2_:
505
- table.sCapHeight = self.os2_["capheight"]
506
- version = 2
507
- if "loweropsize" in self.os2_:
508
- table.usLowerOpticalPointSize = self.os2_["loweropsize"]
509
- version = 5
510
- if "upperopsize" in self.os2_:
511
- table.usUpperOpticalPointSize = self.os2_["upperopsize"]
512
- version = 5
513
-
514
- def checkattr(table, attrs):
515
- for attr in attrs:
516
- if not hasattr(table, attr):
517
- setattr(table, attr, 0)
518
-
519
- table.version = max(version, table.version)
520
- # this only happens for unit tests
521
- if version >= 1:
522
- checkattr(table, ("ulCodePageRange1", "ulCodePageRange2"))
523
- if version >= 2:
524
- checkattr(
525
- table,
526
- (
527
- "sxHeight",
528
- "sCapHeight",
529
- "usDefaultChar",
530
- "usBreakChar",
531
- "usMaxContext",
532
- ),
533
- )
534
- if version >= 5:
535
- checkattr(table, ("usLowerOpticalPointSize", "usUpperOpticalPointSize"))
536
-
537
- def setElidedFallbackName(self, value, location):
538
- # ElidedFallbackName is a convenience method for setting
539
- # ElidedFallbackNameID so only one can be allowed
540
- for token in ("ElidedFallbackName", "ElidedFallbackNameID"):
541
- if token in self.stat_:
542
- raise FeatureLibError(
543
- f"{token} is already set.",
544
- location,
545
- )
546
- if isinstance(value, int):
547
- self.stat_["ElidedFallbackNameID"] = value
548
- elif isinstance(value, list):
549
- self.stat_["ElidedFallbackName"] = value
550
- else:
551
- raise AssertionError(value)
552
-
553
- def addDesignAxis(self, designAxis, location):
554
- if "DesignAxes" not in self.stat_:
555
- self.stat_["DesignAxes"] = []
556
- if designAxis.tag in (r.tag for r in self.stat_["DesignAxes"]):
557
- raise FeatureLibError(
558
- f'DesignAxis already defined for tag "{designAxis.tag}".',
559
- location,
560
- )
561
- if designAxis.axisOrder in (r.axisOrder for r in self.stat_["DesignAxes"]):
562
- raise FeatureLibError(
563
- f"DesignAxis already defined for axis number {designAxis.axisOrder}.",
564
- location,
565
- )
566
- self.stat_["DesignAxes"].append(designAxis)
567
-
568
- def addAxisValueRecord(self, axisValueRecord, location):
569
- if "AxisValueRecords" not in self.stat_:
570
- self.stat_["AxisValueRecords"] = []
571
- # Check for duplicate AxisValueRecords
572
- for record_ in self.stat_["AxisValueRecords"]:
573
- if (
574
- {n.asFea() for n in record_.names}
575
- == {n.asFea() for n in axisValueRecord.names}
576
- and {n.asFea() for n in record_.locations}
577
- == {n.asFea() for n in axisValueRecord.locations}
578
- and record_.flags == axisValueRecord.flags
579
- ):
580
- raise FeatureLibError(
581
- "An AxisValueRecord with these values is already defined.",
582
- location,
583
- )
584
- self.stat_["AxisValueRecords"].append(axisValueRecord)
585
-
586
- def build_STAT(self):
587
- if not self.stat_:
588
- return
589
-
590
- axes = self.stat_.get("DesignAxes")
591
- if not axes:
592
- raise FeatureLibError("DesignAxes not defined", None)
593
- axisValueRecords = self.stat_.get("AxisValueRecords")
594
- axisValues = {}
595
- format4_locations = []
596
- for tag in axes:
597
- axisValues[tag.tag] = []
598
- if axisValueRecords is not None:
599
- for avr in axisValueRecords:
600
- valuesDict = {}
601
- if avr.flags > 0:
602
- valuesDict["flags"] = avr.flags
603
- if len(avr.locations) == 1:
604
- location = avr.locations[0]
605
- values = location.values
606
- if len(values) == 1: # format1
607
- valuesDict.update({"value": values[0], "name": avr.names})
608
- if len(values) == 2: # format3
609
- valuesDict.update(
610
- {
611
- "value": values[0],
612
- "linkedValue": values[1],
613
- "name": avr.names,
614
- }
615
- )
616
- if len(values) == 3: # format2
617
- nominal, minVal, maxVal = values
618
- valuesDict.update(
619
- {
620
- "nominalValue": nominal,
621
- "rangeMinValue": minVal,
622
- "rangeMaxValue": maxVal,
623
- "name": avr.names,
624
- }
625
- )
626
- axisValues[location.tag].append(valuesDict)
627
- else:
628
- valuesDict.update(
629
- {
630
- "location": {i.tag: i.values[0] for i in avr.locations},
631
- "name": avr.names,
632
- }
633
- )
634
- format4_locations.append(valuesDict)
635
-
636
- designAxes = [
637
- {
638
- "ordering": a.axisOrder,
639
- "tag": a.tag,
640
- "name": a.names,
641
- "values": axisValues[a.tag],
642
- }
643
- for a in axes
644
- ]
645
-
646
- nameTable = self.font.get("name")
647
- if not nameTable: # this only happens for unit tests
648
- nameTable = self.font["name"] = newTable("name")
649
- nameTable.names = []
650
-
651
- if "ElidedFallbackNameID" in self.stat_:
652
- nameID = self.stat_["ElidedFallbackNameID"]
653
- name = nameTable.getDebugName(nameID)
654
- if not name:
655
- raise FeatureLibError(
656
- f"ElidedFallbackNameID {nameID} points "
657
- "to a nameID that does not exist in the "
658
- '"name" table',
659
- None,
660
- )
661
- elif "ElidedFallbackName" in self.stat_:
662
- nameID = self.stat_["ElidedFallbackName"]
663
-
664
- otl.buildStatTable(
665
- self.font,
666
- designAxes,
667
- locations=format4_locations,
668
- elidedFallbackName=nameID,
669
- )
670
-
671
- def build_codepages_(self, pages):
672
- pages2bits = {
673
- 1252: 0,
674
- 1250: 1,
675
- 1251: 2,
676
- 1253: 3,
677
- 1254: 4,
678
- 1255: 5,
679
- 1256: 6,
680
- 1257: 7,
681
- 1258: 8,
682
- 874: 16,
683
- 932: 17,
684
- 936: 18,
685
- 949: 19,
686
- 950: 20,
687
- 1361: 21,
688
- 869: 48,
689
- 866: 49,
690
- 865: 50,
691
- 864: 51,
692
- 863: 52,
693
- 862: 53,
694
- 861: 54,
695
- 860: 55,
696
- 857: 56,
697
- 855: 57,
698
- 852: 58,
699
- 775: 59,
700
- 737: 60,
701
- 708: 61,
702
- 850: 62,
703
- 437: 63,
704
- }
705
- bits = [pages2bits[p] for p in pages if p in pages2bits]
706
- pages = []
707
- for i in range(2):
708
- pages.append("")
709
- for j in range(i * 32, (i + 1) * 32):
710
- if j in bits:
711
- pages[i] += "1"
712
- else:
713
- pages[i] += "0"
714
- return [binary2num(p[::-1]) for p in pages]
715
-
716
- def buildBASE(self):
717
- if not self.base_horiz_axis_ and not self.base_vert_axis_:
718
- return None
719
- base = otTables.BASE()
720
- base.Version = 0x00010000
721
- base.HorizAxis = self.buildBASEAxis(self.base_horiz_axis_)
722
- base.VertAxis = self.buildBASEAxis(self.base_vert_axis_)
723
-
724
- result = newTable("BASE")
725
- result.table = base
726
- return result
727
-
728
- def buildBASEAxis(self, axis):
729
- if not axis:
730
- return
731
- bases, scripts = axis
732
- axis = otTables.Axis()
733
- axis.BaseTagList = otTables.BaseTagList()
734
- axis.BaseTagList.BaselineTag = bases
735
- axis.BaseTagList.BaseTagCount = len(bases)
736
- axis.BaseScriptList = otTables.BaseScriptList()
737
- axis.BaseScriptList.BaseScriptRecord = []
738
- axis.BaseScriptList.BaseScriptCount = len(scripts)
739
- for script in sorted(scripts):
740
- record = otTables.BaseScriptRecord()
741
- record.BaseScriptTag = script[0]
742
- record.BaseScript = otTables.BaseScript()
743
- record.BaseScript.BaseLangSysCount = 0
744
- record.BaseScript.BaseValues = otTables.BaseValues()
745
- record.BaseScript.BaseValues.DefaultIndex = bases.index(script[1])
746
- record.BaseScript.BaseValues.BaseCoord = []
747
- record.BaseScript.BaseValues.BaseCoordCount = len(script[2])
748
- for c in script[2]:
749
- coord = otTables.BaseCoord()
750
- coord.Format = 1
751
- coord.Coordinate = c
752
- record.BaseScript.BaseValues.BaseCoord.append(coord)
753
- axis.BaseScriptList.BaseScriptRecord.append(record)
754
- return axis
755
-
756
- def buildGDEF(self):
757
- gdef = otTables.GDEF()
758
- gdef.GlyphClassDef = self.buildGDEFGlyphClassDef_()
759
- gdef.AttachList = otl.buildAttachList(self.attachPoints_, self.glyphMap)
760
- gdef.LigCaretList = otl.buildLigCaretList(
761
- self.ligCaretCoords_, self.ligCaretPoints_, self.glyphMap
762
- )
763
- gdef.MarkAttachClassDef = self.buildGDEFMarkAttachClassDef_()
764
- gdef.MarkGlyphSetsDef = self.buildGDEFMarkGlyphSetsDef_()
765
- gdef.Version = 0x00010002 if gdef.MarkGlyphSetsDef else 0x00010000
766
- if self.varstorebuilder:
767
- store = self.varstorebuilder.finish()
768
- if store:
769
- gdef.Version = 0x00010003
770
- gdef.VarStore = store
771
- varidx_map = store.optimize()
772
-
773
- gdef.remap_device_varidxes(varidx_map)
774
- if "GPOS" in self.font:
775
- self.font["GPOS"].table.remap_device_varidxes(varidx_map)
776
- self.model_cache.clear()
777
- if any(
778
- (
779
- gdef.GlyphClassDef,
780
- gdef.AttachList,
781
- gdef.LigCaretList,
782
- gdef.MarkAttachClassDef,
783
- gdef.MarkGlyphSetsDef,
784
- )
785
- ) or hasattr(gdef, "VarStore"):
786
- result = newTable("GDEF")
787
- result.table = gdef
788
- return result
789
- else:
790
- return None
791
-
792
- def buildGDEFGlyphClassDef_(self):
793
- if self.glyphClassDefs_:
794
- classes = {g: c for (g, (c, _)) in self.glyphClassDefs_.items()}
795
- else:
796
- classes = {}
797
- for lookup in self.lookups_:
798
- classes.update(lookup.inferGlyphClasses())
799
- for markClass in self.parseTree.markClasses.values():
800
- for markClassDef in markClass.definitions:
801
- for glyph in markClassDef.glyphSet():
802
- classes[glyph] = 3
803
- if classes:
804
- result = otTables.GlyphClassDef()
805
- result.classDefs = classes
806
- return result
807
- else:
808
- return None
809
-
810
- def buildGDEFMarkAttachClassDef_(self):
811
- classDefs = {g: c for g, (c, _) in self.markAttach_.items()}
812
- if not classDefs:
813
- return None
814
- result = otTables.MarkAttachClassDef()
815
- result.classDefs = classDefs
816
- return result
817
-
818
- def buildGDEFMarkGlyphSetsDef_(self):
819
- sets = []
820
- for glyphs, id_ in sorted(
821
- self.markFilterSets_.items(), key=lambda item: item[1]
822
- ):
823
- sets.append(glyphs)
824
- return otl.buildMarkGlyphSetsDef(sets, self.glyphMap)
825
-
826
- def buildDebg(self):
827
- if "Debg" not in self.font:
828
- self.font["Debg"] = newTable("Debg")
829
- self.font["Debg"].data = {}
830
- self.font["Debg"].data[LOOKUP_DEBUG_INFO_KEY] = self.lookup_locations
831
-
832
- def buildLookups_(self, tag):
833
- assert tag in ("GPOS", "GSUB"), tag
834
- for lookup in self.lookups_:
835
- lookup.lookup_index = None
836
- lookups = []
837
- for lookup in self.lookups_:
838
- if lookup.table != tag:
839
- continue
840
- lookup.lookup_index = len(lookups)
841
- self.lookup_locations[tag][str(lookup.lookup_index)] = LookupDebugInfo(
842
- location=str(lookup.location),
843
- name=self.get_lookup_name_(lookup),
844
- feature=None,
845
- )
846
- lookups.append(lookup)
847
- try:
848
- otLookups = [l.build() for l in lookups]
849
- except OpenTypeLibError as e:
850
- raise FeatureLibError(str(e), e.location) from e
851
- return otLookups
852
-
853
- def makeTable(self, tag):
854
- table = getattr(otTables, tag, None)()
855
- table.Version = 0x00010000
856
- table.ScriptList = otTables.ScriptList()
857
- table.ScriptList.ScriptRecord = []
858
- table.FeatureList = otTables.FeatureList()
859
- table.FeatureList.FeatureRecord = []
860
- table.LookupList = otTables.LookupList()
861
- table.LookupList.Lookup = self.buildLookups_(tag)
862
-
863
- # Build a table for mapping (tag, lookup_indices) to feature_index.
864
- # For example, ('liga', (2,3,7)) --> 23.
865
- feature_indices = {}
866
- required_feature_indices = {} # ('latn', 'DEU') --> 23
867
- scripts = {} # 'latn' --> {'DEU': [23, 24]} for feature #23,24
868
- # Sort the feature table by feature tag:
869
- # https://github.com/fonttools/fonttools/issues/568
870
- sortFeatureTag = lambda f: (f[0][2], f[0][1], f[0][0], f[1])
871
- for key, lookups in sorted(self.features_.items(), key=sortFeatureTag):
872
- script, lang, feature_tag = key
873
- # l.lookup_index will be None when a lookup is not needed
874
- # for the table under construction. For example, substitution
875
- # rules will have no lookup_index while building GPOS tables.
876
- lookup_indices = tuple(
877
- [l.lookup_index for l in lookups if l.lookup_index is not None]
878
- )
879
-
880
- size_feature = tag == "GPOS" and feature_tag == "size"
881
- force_feature = self.any_feature_variations(feature_tag, tag)
882
- if len(lookup_indices) == 0 and not size_feature and not force_feature:
883
- continue
884
-
885
- for ix in lookup_indices:
886
- try:
887
- self.lookup_locations[tag][str(ix)] = self.lookup_locations[tag][
888
- str(ix)
889
- ]._replace(feature=key)
890
- except KeyError:
891
- warnings.warn(
892
- "feaLib.Builder subclass needs upgrading to "
893
- "stash debug information. See fonttools#2065."
894
- )
895
-
896
- feature_key = (feature_tag, lookup_indices)
897
- feature_index = feature_indices.get(feature_key)
898
- if feature_index is None:
899
- feature_index = len(table.FeatureList.FeatureRecord)
900
- frec = otTables.FeatureRecord()
901
- frec.FeatureTag = feature_tag
902
- frec.Feature = otTables.Feature()
903
- frec.Feature.FeatureParams = self.buildFeatureParams(feature_tag)
904
- frec.Feature.LookupListIndex = list(lookup_indices)
905
- frec.Feature.LookupCount = len(lookup_indices)
906
- table.FeatureList.FeatureRecord.append(frec)
907
- feature_indices[feature_key] = feature_index
908
- scripts.setdefault(script, {}).setdefault(lang, []).append(feature_index)
909
- if self.required_features_.get((script, lang)) == feature_tag:
910
- required_feature_indices[(script, lang)] = feature_index
911
-
912
- # Build ScriptList.
913
- for script, lang_features in sorted(scripts.items()):
914
- srec = otTables.ScriptRecord()
915
- srec.ScriptTag = script
916
- srec.Script = otTables.Script()
917
- srec.Script.DefaultLangSys = None
918
- srec.Script.LangSysRecord = []
919
- for lang, feature_indices in sorted(lang_features.items()):
920
- langrec = otTables.LangSysRecord()
921
- langrec.LangSys = otTables.LangSys()
922
- langrec.LangSys.LookupOrder = None
923
-
924
- req_feature_index = required_feature_indices.get((script, lang))
925
- if req_feature_index is None:
926
- langrec.LangSys.ReqFeatureIndex = 0xFFFF
927
- else:
928
- langrec.LangSys.ReqFeatureIndex = req_feature_index
929
-
930
- langrec.LangSys.FeatureIndex = [
931
- i for i in feature_indices if i != req_feature_index
932
- ]
933
- langrec.LangSys.FeatureCount = len(langrec.LangSys.FeatureIndex)
934
-
935
- if lang == "dflt":
936
- srec.Script.DefaultLangSys = langrec.LangSys
937
- else:
938
- langrec.LangSysTag = lang
939
- srec.Script.LangSysRecord.append(langrec)
940
- srec.Script.LangSysCount = len(srec.Script.LangSysRecord)
941
- table.ScriptList.ScriptRecord.append(srec)
942
-
943
- table.ScriptList.ScriptCount = len(table.ScriptList.ScriptRecord)
944
- table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord)
945
- table.LookupList.LookupCount = len(table.LookupList.Lookup)
946
- return table
947
-
948
- def makeFeatureVariations(self, table, table_tag):
949
- feature_vars = {}
950
- has_any_variations = False
951
- # Sort out which lookups to build, gather their indices
952
- for (_, _, feature_tag), variations in self.feature_variations_.items():
953
- feature_vars[feature_tag] = []
954
- for conditionset, builders in variations.items():
955
- raw_conditionset = self.conditionsets_[conditionset]
956
- indices = []
957
- for b in builders:
958
- if b.table != table_tag:
959
- continue
960
- assert b.lookup_index is not None
961
- indices.append(b.lookup_index)
962
- has_any_variations = True
963
- feature_vars[feature_tag].append((raw_conditionset, indices))
964
-
965
- if has_any_variations:
966
- for feature_tag, conditions_and_lookups in feature_vars.items():
967
- addFeatureVariationsRaw(
968
- self.font, table, conditions_and_lookups, feature_tag
969
- )
970
-
971
- def any_feature_variations(self, feature_tag, table_tag):
972
- for (_, _, feature), variations in self.feature_variations_.items():
973
- if feature != feature_tag:
974
- continue
975
- for conditionset, builders in variations.items():
976
- if any(b.table == table_tag for b in builders):
977
- return True
978
- return False
979
-
980
- def get_lookup_name_(self, lookup):
981
- rev = {v: k for k, v in self.named_lookups_.items()}
982
- if lookup in rev:
983
- return rev[lookup]
984
- return None
985
-
986
- def add_language_system(self, location, script, language):
987
- # OpenType Feature File Specification, section 4.b.i
988
- if script == "DFLT" and language == "dflt" and self.default_language_systems_:
989
- raise FeatureLibError(
990
- 'If "languagesystem DFLT dflt" is present, it must be '
991
- "the first of the languagesystem statements",
992
- location,
993
- )
994
- if script == "DFLT":
995
- if self.seen_non_DFLT_script_:
996
- raise FeatureLibError(
997
- 'languagesystems using the "DFLT" script tag must '
998
- "precede all other languagesystems",
999
- location,
1000
- )
1001
- else:
1002
- self.seen_non_DFLT_script_ = True
1003
- if (script, language) in self.default_language_systems_:
1004
- raise FeatureLibError(
1005
- '"languagesystem %s %s" has already been specified'
1006
- % (script.strip(), language.strip()),
1007
- location,
1008
- )
1009
- self.default_language_systems_.add((script, language))
1010
-
1011
- def get_default_language_systems_(self):
1012
- # OpenType Feature File specification, 4.b.i. languagesystem:
1013
- # If no "languagesystem" statement is present, then the
1014
- # implementation must behave exactly as though the following
1015
- # statement were present at the beginning of the feature file:
1016
- # languagesystem DFLT dflt;
1017
- if self.default_language_systems_:
1018
- return frozenset(self.default_language_systems_)
1019
- else:
1020
- return frozenset({("DFLT", "dflt")})
1021
-
1022
- def start_feature(self, location, name):
1023
- self.language_systems = self.get_default_language_systems_()
1024
- self.script_ = "DFLT"
1025
- self.cur_lookup_ = None
1026
- self.cur_feature_name_ = name
1027
- self.lookupflag_ = 0
1028
- self.lookupflag_markFilterSet_ = None
1029
- if name == "aalt":
1030
- self.aalt_location_ = location
1031
-
1032
- def end_feature(self):
1033
- assert self.cur_feature_name_ is not None
1034
- self.cur_feature_name_ = None
1035
- self.language_systems = None
1036
- self.cur_lookup_ = None
1037
- self.lookupflag_ = 0
1038
- self.lookupflag_markFilterSet_ = None
1039
-
1040
- def start_lookup_block(self, location, name):
1041
- if name in self.named_lookups_:
1042
- raise FeatureLibError(
1043
- 'Lookup "%s" has already been defined' % name, location
1044
- )
1045
- if self.cur_feature_name_ == "aalt":
1046
- raise FeatureLibError(
1047
- "Lookup blocks cannot be placed inside 'aalt' features; "
1048
- "move it out, and then refer to it with a lookup statement",
1049
- location,
1050
- )
1051
- self.cur_lookup_name_ = name
1052
- self.named_lookups_[name] = None
1053
- self.cur_lookup_ = None
1054
- if self.cur_feature_name_ is None:
1055
- self.lookupflag_ = 0
1056
- self.lookupflag_markFilterSet_ = None
1057
-
1058
- def end_lookup_block(self):
1059
- assert self.cur_lookup_name_ is not None
1060
- self.cur_lookup_name_ = None
1061
- self.cur_lookup_ = None
1062
- if self.cur_feature_name_ is None:
1063
- self.lookupflag_ = 0
1064
- self.lookupflag_markFilterSet_ = None
1065
-
1066
- def add_lookup_call(self, lookup_name):
1067
- assert lookup_name in self.named_lookups_, lookup_name
1068
- self.cur_lookup_ = None
1069
- lookup = self.named_lookups_[lookup_name]
1070
- if lookup is not None: # skip empty named lookup
1071
- self.add_lookup_to_feature_(lookup, self.cur_feature_name_)
1072
-
1073
- def set_font_revision(self, location, revision):
1074
- self.fontRevision_ = revision
1075
-
1076
- def set_language(self, location, language, include_default, required):
1077
- assert len(language) == 4
1078
- if self.cur_feature_name_ in ("aalt", "size"):
1079
- raise FeatureLibError(
1080
- "Language statements are not allowed "
1081
- 'within "feature %s"' % self.cur_feature_name_,
1082
- location,
1083
- )
1084
- if self.cur_feature_name_ is None:
1085
- raise FeatureLibError(
1086
- "Language statements are not allowed "
1087
- "within standalone lookup blocks",
1088
- location,
1089
- )
1090
- self.cur_lookup_ = None
1091
-
1092
- key = (self.script_, language, self.cur_feature_name_)
1093
- lookups = self.features_.get((key[0], "dflt", key[2]))
1094
- if (language == "dflt" or include_default) and lookups:
1095
- self.features_[key] = lookups[:]
1096
- else:
1097
- self.features_[key] = []
1098
- self.language_systems = frozenset([(self.script_, language)])
1099
-
1100
- if required:
1101
- key = (self.script_, language)
1102
- if key in self.required_features_:
1103
- raise FeatureLibError(
1104
- "Language %s (script %s) has already "
1105
- "specified feature %s as its required feature"
1106
- % (
1107
- language.strip(),
1108
- self.script_.strip(),
1109
- self.required_features_[key].strip(),
1110
- ),
1111
- location,
1112
- )
1113
- self.required_features_[key] = self.cur_feature_name_
1114
-
1115
- def getMarkAttachClass_(self, location, glyphs):
1116
- glyphs = frozenset(glyphs)
1117
- id_ = self.markAttachClassID_.get(glyphs)
1118
- if id_ is not None:
1119
- return id_
1120
- id_ = len(self.markAttachClassID_) + 1
1121
- self.markAttachClassID_[glyphs] = id_
1122
- for glyph in glyphs:
1123
- if glyph in self.markAttach_:
1124
- _, loc = self.markAttach_[glyph]
1125
- raise FeatureLibError(
1126
- "Glyph %s already has been assigned "
1127
- "a MarkAttachmentType at %s" % (glyph, loc),
1128
- location,
1129
- )
1130
- self.markAttach_[glyph] = (id_, location)
1131
- return id_
1132
-
1133
- def getMarkFilterSet_(self, location, glyphs):
1134
- glyphs = frozenset(glyphs)
1135
- id_ = self.markFilterSets_.get(glyphs)
1136
- if id_ is not None:
1137
- return id_
1138
- id_ = len(self.markFilterSets_)
1139
- self.markFilterSets_[glyphs] = id_
1140
- return id_
1141
-
1142
- def set_lookup_flag(self, location, value, markAttach, markFilter):
1143
- value = value & 0xFF
1144
- if markAttach:
1145
- markAttachClass = self.getMarkAttachClass_(location, markAttach)
1146
- value = value | (markAttachClass << 8)
1147
- if markFilter:
1148
- markFilterSet = self.getMarkFilterSet_(location, markFilter)
1149
- value = value | 0x10
1150
- self.lookupflag_markFilterSet_ = markFilterSet
1151
- else:
1152
- self.lookupflag_markFilterSet_ = None
1153
- self.lookupflag_ = value
1154
-
1155
- def set_script(self, location, script):
1156
- if self.cur_feature_name_ in ("aalt", "size"):
1157
- raise FeatureLibError(
1158
- "Script statements are not allowed "
1159
- 'within "feature %s"' % self.cur_feature_name_,
1160
- location,
1161
- )
1162
- if self.cur_feature_name_ is None:
1163
- raise FeatureLibError(
1164
- "Script statements are not allowed " "within standalone lookup blocks",
1165
- location,
1166
- )
1167
- if self.language_systems == {(script, "dflt")}:
1168
- # Nothing to do.
1169
- return
1170
- self.cur_lookup_ = None
1171
- self.script_ = script
1172
- self.lookupflag_ = 0
1173
- self.lookupflag_markFilterSet_ = None
1174
- self.set_language(location, "dflt", include_default=True, required=False)
1175
-
1176
- def find_lookup_builders_(self, lookups):
1177
- """Helper for building chain contextual substitutions
1178
-
1179
- Given a list of lookup names, finds the LookupBuilder for each name.
1180
- If an input name is None, it gets mapped to a None LookupBuilder.
1181
- """
1182
- lookup_builders = []
1183
- for lookuplist in lookups:
1184
- if lookuplist is not None:
1185
- lookup_builders.append(
1186
- [self.named_lookups_.get(l.name) for l in lookuplist]
1187
- )
1188
- else:
1189
- lookup_builders.append(None)
1190
- return lookup_builders
1191
-
1192
- def add_attach_points(self, location, glyphs, contourPoints):
1193
- for glyph in glyphs:
1194
- self.attachPoints_.setdefault(glyph, set()).update(contourPoints)
1195
-
1196
- def add_feature_reference(self, location, featureName):
1197
- if self.cur_feature_name_ != "aalt":
1198
- raise FeatureLibError(
1199
- 'Feature references are only allowed inside "feature aalt"', location
1200
- )
1201
- self.aalt_features_.append((location, featureName))
1202
-
1203
- def add_featureName(self, tag):
1204
- self.featureNames_.add(tag)
1205
-
1206
- def add_cv_parameter(self, tag):
1207
- self.cv_parameters_.add(tag)
1208
-
1209
- def add_to_cv_num_named_params(self, tag):
1210
- """Adds new items to ``self.cv_num_named_params_``
1211
- or increments the count of existing items."""
1212
- if tag in self.cv_num_named_params_:
1213
- self.cv_num_named_params_[tag] += 1
1214
- else:
1215
- self.cv_num_named_params_[tag] = 1
1216
-
1217
- def add_cv_character(self, character, tag):
1218
- self.cv_characters_[tag].append(character)
1219
-
1220
- def set_base_axis(self, bases, scripts, vertical):
1221
- if vertical:
1222
- self.base_vert_axis_ = (bases, scripts)
1223
- else:
1224
- self.base_horiz_axis_ = (bases, scripts)
1225
-
1226
- def set_size_parameters(
1227
- self, location, DesignSize, SubfamilyID, RangeStart, RangeEnd
1228
- ):
1229
- if self.cur_feature_name_ != "size":
1230
- raise FeatureLibError(
1231
- "Parameters statements are not allowed "
1232
- 'within "feature %s"' % self.cur_feature_name_,
1233
- location,
1234
- )
1235
- self.size_parameters_ = [DesignSize, SubfamilyID, RangeStart, RangeEnd]
1236
- for script, lang in self.language_systems:
1237
- key = (script, lang, self.cur_feature_name_)
1238
- self.features_.setdefault(key, [])
1239
-
1240
- # GSUB rules
1241
-
1242
- # GSUB 1
1243
- def add_single_subst(self, location, prefix, suffix, mapping, forceChain):
1244
- if self.cur_feature_name_ == "aalt":
1245
- for from_glyph, to_glyph in mapping.items():
1246
- alts = self.aalt_alternates_.setdefault(from_glyph, set())
1247
- alts.add(to_glyph)
1248
- return
1249
- if prefix or suffix or forceChain:
1250
- self.add_single_subst_chained_(location, prefix, suffix, mapping)
1251
- return
1252
- lookup = self.get_lookup_(location, SingleSubstBuilder)
1253
- for from_glyph, to_glyph in mapping.items():
1254
- if from_glyph in lookup.mapping:
1255
- if to_glyph == lookup.mapping[from_glyph]:
1256
- log.info(
1257
- "Removing duplicate single substitution from glyph"
1258
- ' "%s" to "%s" at %s',
1259
- from_glyph,
1260
- to_glyph,
1261
- location,
1262
- )
1263
- else:
1264
- raise FeatureLibError(
1265
- 'Already defined rule for replacing glyph "%s" by "%s"'
1266
- % (from_glyph, lookup.mapping[from_glyph]),
1267
- location,
1268
- )
1269
- lookup.mapping[from_glyph] = to_glyph
1270
-
1271
- # GSUB 2
1272
- def add_multiple_subst(
1273
- self, location, prefix, glyph, suffix, replacements, forceChain=False
1274
- ):
1275
- if prefix or suffix or forceChain:
1276
- chain = self.get_lookup_(location, ChainContextSubstBuilder)
1277
- sub = self.get_chained_lookup_(location, MultipleSubstBuilder)
1278
- sub.mapping[glyph] = replacements
1279
- chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [sub]))
1280
- return
1281
- lookup = self.get_lookup_(location, MultipleSubstBuilder)
1282
- if glyph in lookup.mapping:
1283
- if replacements == lookup.mapping[glyph]:
1284
- log.info(
1285
- "Removing duplicate multiple substitution from glyph"
1286
- ' "%s" to %s%s',
1287
- glyph,
1288
- replacements,
1289
- f" at {location}" if location else "",
1290
- )
1291
- else:
1292
- raise FeatureLibError(
1293
- 'Already defined substitution for glyph "%s"' % glyph, location
1294
- )
1295
- lookup.mapping[glyph] = replacements
1296
-
1297
- # GSUB 3
1298
- def add_alternate_subst(self, location, prefix, glyph, suffix, replacement):
1299
- if self.cur_feature_name_ == "aalt":
1300
- alts = self.aalt_alternates_.setdefault(glyph, set())
1301
- alts.update(replacement)
1302
- return
1303
- if prefix or suffix:
1304
- chain = self.get_lookup_(location, ChainContextSubstBuilder)
1305
- lookup = self.get_chained_lookup_(location, AlternateSubstBuilder)
1306
- chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [lookup]))
1307
- else:
1308
- lookup = self.get_lookup_(location, AlternateSubstBuilder)
1309
- if glyph in lookup.alternates:
1310
- raise FeatureLibError(
1311
- 'Already defined alternates for glyph "%s"' % glyph, location
1312
- )
1313
- # We allow empty replacement glyphs here.
1314
- lookup.alternates[glyph] = replacement
1315
-
1316
- # GSUB 4
1317
- def add_ligature_subst(
1318
- self, location, prefix, glyphs, suffix, replacement, forceChain
1319
- ):
1320
- if prefix or suffix or forceChain:
1321
- chain = self.get_lookup_(location, ChainContextSubstBuilder)
1322
- lookup = self.get_chained_lookup_(location, LigatureSubstBuilder)
1323
- chain.rules.append(ChainContextualRule(prefix, glyphs, suffix, [lookup]))
1324
- else:
1325
- lookup = self.get_lookup_(location, LigatureSubstBuilder)
1326
-
1327
- if not all(glyphs):
1328
- raise FeatureLibError("Empty glyph class in substitution", location)
1329
-
1330
- # OpenType feature file syntax, section 5.d, "Ligature substitution":
1331
- # "Since the OpenType specification does not allow ligature
1332
- # substitutions to be specified on target sequences that contain
1333
- # glyph classes, the implementation software will enumerate
1334
- # all specific glyph sequences if glyph classes are detected"
1335
- for g in sorted(itertools.product(*glyphs)):
1336
- lookup.ligatures[g] = replacement
1337
-
1338
- # GSUB 5/6
1339
- def add_chain_context_subst(self, location, prefix, glyphs, suffix, lookups):
1340
- if not all(glyphs) or not all(prefix) or not all(suffix):
1341
- raise FeatureLibError(
1342
- "Empty glyph class in contextual substitution", location
1343
- )
1344
- lookup = self.get_lookup_(location, ChainContextSubstBuilder)
1345
- lookup.rules.append(
1346
- ChainContextualRule(
1347
- prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
1348
- )
1349
- )
1350
-
1351
- def add_single_subst_chained_(self, location, prefix, suffix, mapping):
1352
- if not mapping or not all(prefix) or not all(suffix):
1353
- raise FeatureLibError(
1354
- "Empty glyph class in contextual substitution", location
1355
- )
1356
- # https://github.com/fonttools/fonttools/issues/512
1357
- # https://github.com/fonttools/fonttools/issues/2150
1358
- chain = self.get_lookup_(location, ChainContextSubstBuilder)
1359
- sub = chain.find_chainable_single_subst(mapping)
1360
- if sub is None:
1361
- sub = self.get_chained_lookup_(location, SingleSubstBuilder)
1362
- sub.mapping.update(mapping)
1363
- chain.rules.append(
1364
- ChainContextualRule(prefix, [list(mapping.keys())], suffix, [sub])
1365
- )
1366
-
1367
- # GSUB 8
1368
- def add_reverse_chain_single_subst(self, location, old_prefix, old_suffix, mapping):
1369
- if not mapping:
1370
- raise FeatureLibError("Empty glyph class in substitution", location)
1371
- lookup = self.get_lookup_(location, ReverseChainSingleSubstBuilder)
1372
- lookup.rules.append((old_prefix, old_suffix, mapping))
1373
-
1374
- # GPOS rules
1375
-
1376
- # GPOS 1
1377
- def add_single_pos(self, location, prefix, suffix, pos, forceChain):
1378
- if prefix or suffix or forceChain:
1379
- self.add_single_pos_chained_(location, prefix, suffix, pos)
1380
- else:
1381
- lookup = self.get_lookup_(location, SinglePosBuilder)
1382
- for glyphs, value in pos:
1383
- if not glyphs:
1384
- raise FeatureLibError(
1385
- "Empty glyph class in positioning rule", location
1386
- )
1387
- otValueRecord = self.makeOpenTypeValueRecord(
1388
- location, value, pairPosContext=False
1389
- )
1390
- for glyph in glyphs:
1391
- try:
1392
- lookup.add_pos(location, glyph, otValueRecord)
1393
- except OpenTypeLibError as e:
1394
- raise FeatureLibError(str(e), e.location) from e
1395
-
1396
- # GPOS 2
1397
- def add_class_pair_pos(self, location, glyphclass1, value1, glyphclass2, value2):
1398
- if not glyphclass1 or not glyphclass2:
1399
- raise FeatureLibError("Empty glyph class in positioning rule", location)
1400
- lookup = self.get_lookup_(location, PairPosBuilder)
1401
- v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
1402
- v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
1403
- lookup.addClassPair(location, glyphclass1, v1, glyphclass2, v2)
1404
-
1405
- def add_specific_pair_pos(self, location, glyph1, value1, glyph2, value2):
1406
- if not glyph1 or not glyph2:
1407
- raise FeatureLibError("Empty glyph class in positioning rule", location)
1408
- lookup = self.get_lookup_(location, PairPosBuilder)
1409
- v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
1410
- v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
1411
- lookup.addGlyphPair(location, glyph1, v1, glyph2, v2)
1412
-
1413
- # GPOS 3
1414
- def add_cursive_pos(self, location, glyphclass, entryAnchor, exitAnchor):
1415
- if not glyphclass:
1416
- raise FeatureLibError("Empty glyph class in positioning rule", location)
1417
- lookup = self.get_lookup_(location, CursivePosBuilder)
1418
- lookup.add_attachment(
1419
- location,
1420
- glyphclass,
1421
- self.makeOpenTypeAnchor(location, entryAnchor),
1422
- self.makeOpenTypeAnchor(location, exitAnchor),
1423
- )
1424
-
1425
- # GPOS 4
1426
- def add_mark_base_pos(self, location, bases, marks):
1427
- builder = self.get_lookup_(location, MarkBasePosBuilder)
1428
- self.add_marks_(location, builder, marks)
1429
- if not bases:
1430
- raise FeatureLibError("Empty glyph class in positioning rule", location)
1431
- for baseAnchor, markClass in marks:
1432
- otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
1433
- for base in bases:
1434
- builder.bases.setdefault(base, {})[markClass.name] = otBaseAnchor
1435
-
1436
- # GPOS 5
1437
- def add_mark_lig_pos(self, location, ligatures, components):
1438
- builder = self.get_lookup_(location, MarkLigPosBuilder)
1439
- componentAnchors = []
1440
- if not ligatures:
1441
- raise FeatureLibError("Empty glyph class in positioning rule", location)
1442
- for marks in components:
1443
- anchors = {}
1444
- self.add_marks_(location, builder, marks)
1445
- for ligAnchor, markClass in marks:
1446
- anchors[markClass.name] = self.makeOpenTypeAnchor(location, ligAnchor)
1447
- componentAnchors.append(anchors)
1448
- for glyph in ligatures:
1449
- builder.ligatures[glyph] = componentAnchors
1450
-
1451
- # GPOS 6
1452
- def add_mark_mark_pos(self, location, baseMarks, marks):
1453
- builder = self.get_lookup_(location, MarkMarkPosBuilder)
1454
- self.add_marks_(location, builder, marks)
1455
- if not baseMarks:
1456
- raise FeatureLibError("Empty glyph class in positioning rule", location)
1457
- for baseAnchor, markClass in marks:
1458
- otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
1459
- for baseMark in baseMarks:
1460
- builder.baseMarks.setdefault(baseMark, {})[
1461
- markClass.name
1462
- ] = otBaseAnchor
1463
-
1464
- # GPOS 7/8
1465
- def add_chain_context_pos(self, location, prefix, glyphs, suffix, lookups):
1466
- if not all(glyphs) or not all(prefix) or not all(suffix):
1467
- raise FeatureLibError(
1468
- "Empty glyph class in contextual positioning rule", location
1469
- )
1470
- lookup = self.get_lookup_(location, ChainContextPosBuilder)
1471
- lookup.rules.append(
1472
- ChainContextualRule(
1473
- prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
1474
- )
1475
- )
1476
-
1477
- def add_single_pos_chained_(self, location, prefix, suffix, pos):
1478
- if not pos or not all(prefix) or not all(suffix):
1479
- raise FeatureLibError(
1480
- "Empty glyph class in contextual positioning rule", location
1481
- )
1482
- # https://github.com/fonttools/fonttools/issues/514
1483
- chain = self.get_lookup_(location, ChainContextPosBuilder)
1484
- targets = []
1485
- for _, _, _, lookups in chain.rules:
1486
- targets.extend(lookups)
1487
- subs = []
1488
- for glyphs, value in pos:
1489
- if value is None:
1490
- subs.append(None)
1491
- continue
1492
- otValue = self.makeOpenTypeValueRecord(
1493
- location, value, pairPosContext=False
1494
- )
1495
- sub = chain.find_chainable_single_pos(targets, glyphs, otValue)
1496
- if sub is None:
1497
- sub = self.get_chained_lookup_(location, SinglePosBuilder)
1498
- targets.append(sub)
1499
- for glyph in glyphs:
1500
- sub.add_pos(location, glyph, otValue)
1501
- subs.append(sub)
1502
- assert len(pos) == len(subs), (pos, subs)
1503
- chain.rules.append(
1504
- ChainContextualRule(prefix, [g for g, v in pos], suffix, subs)
1505
- )
1506
-
1507
- def add_marks_(self, location, lookupBuilder, marks):
1508
- """Helper for add_mark_{base,liga,mark}_pos."""
1509
- for _, markClass in marks:
1510
- for markClassDef in markClass.definitions:
1511
- for mark in markClassDef.glyphs.glyphSet():
1512
- if mark not in lookupBuilder.marks:
1513
- otMarkAnchor = self.makeOpenTypeAnchor(
1514
- location, markClassDef.anchor
1515
- )
1516
- lookupBuilder.marks[mark] = (markClass.name, otMarkAnchor)
1517
- else:
1518
- existingMarkClass = lookupBuilder.marks[mark][0]
1519
- if markClass.name != existingMarkClass:
1520
- raise FeatureLibError(
1521
- "Glyph %s cannot be in both @%s and @%s"
1522
- % (mark, existingMarkClass, markClass.name),
1523
- location,
1524
- )
1525
-
1526
- def add_subtable_break(self, location):
1527
- self.cur_lookup_.add_subtable_break(location)
1528
-
1529
- def setGlyphClass_(self, location, glyph, glyphClass):
1530
- oldClass, oldLocation = self.glyphClassDefs_.get(glyph, (None, None))
1531
- if oldClass and oldClass != glyphClass:
1532
- raise FeatureLibError(
1533
- "Glyph %s was assigned to a different class at %s"
1534
- % (glyph, oldLocation),
1535
- location,
1536
- )
1537
- self.glyphClassDefs_[glyph] = (glyphClass, location)
1538
-
1539
- def add_glyphClassDef(
1540
- self, location, baseGlyphs, ligatureGlyphs, markGlyphs, componentGlyphs
1541
- ):
1542
- for glyph in baseGlyphs:
1543
- self.setGlyphClass_(location, glyph, 1)
1544
- for glyph in ligatureGlyphs:
1545
- self.setGlyphClass_(location, glyph, 2)
1546
- for glyph in markGlyphs:
1547
- self.setGlyphClass_(location, glyph, 3)
1548
- for glyph in componentGlyphs:
1549
- self.setGlyphClass_(location, glyph, 4)
1550
-
1551
- def add_ligatureCaretByIndex_(self, location, glyphs, carets):
1552
- for glyph in glyphs:
1553
- if glyph not in self.ligCaretPoints_:
1554
- self.ligCaretPoints_[glyph] = carets
1555
-
1556
- def makeLigCaret(self, location, caret):
1557
- if not isinstance(caret, VariableScalar):
1558
- return caret
1559
- default, device = self.makeVariablePos(location, caret)
1560
- if device is not None:
1561
- return (default, device)
1562
- return default
1563
-
1564
- def add_ligatureCaretByPos_(self, location, glyphs, carets):
1565
- carets = [self.makeLigCaret(location, caret) for caret in carets]
1566
- for glyph in glyphs:
1567
- if glyph not in self.ligCaretCoords_:
1568
- self.ligCaretCoords_[glyph] = carets
1569
-
1570
- def add_name_record(self, location, nameID, platformID, platEncID, langID, string):
1571
- self.names_.append([nameID, platformID, platEncID, langID, string])
1572
-
1573
- def add_os2_field(self, key, value):
1574
- self.os2_[key] = value
1575
-
1576
- def add_hhea_field(self, key, value):
1577
- self.hhea_[key] = value
1578
-
1579
- def add_vhea_field(self, key, value):
1580
- self.vhea_[key] = value
1581
-
1582
- def add_conditionset(self, location, key, value):
1583
- if "fvar" not in self.font:
1584
- raise FeatureLibError(
1585
- "Cannot add feature variations to a font without an 'fvar' table",
1586
- location,
1587
- )
1588
-
1589
- # Normalize
1590
- axisMap = {
1591
- axis.axisTag: (axis.minValue, axis.defaultValue, axis.maxValue)
1592
- for axis in self.axes
1593
- }
1594
-
1595
- value = {
1596
- tag: (
1597
- normalizeValue(bottom, axisMap[tag]),
1598
- normalizeValue(top, axisMap[tag]),
1599
- )
1600
- for tag, (bottom, top) in value.items()
1601
- }
1602
-
1603
- # NOTE: This might result in rounding errors (off-by-ones) compared to
1604
- # rules in Designspace files, since we're working with what's in the
1605
- # `avar` table rather than the original values.
1606
- if "avar" in self.font:
1607
- mapping = self.font["avar"].segments
1608
- value = {
1609
- axis: tuple(
1610
- piecewiseLinearMap(v, mapping[axis]) if axis in mapping else v
1611
- for v in condition_range
1612
- )
1613
- for axis, condition_range in value.items()
1614
- }
1615
-
1616
- self.conditionsets_[key] = value
1617
-
1618
- def makeVariablePos(self, location, varscalar):
1619
- if not self.varstorebuilder:
1620
- raise FeatureLibError(
1621
- "Can't define a variable scalar in a non-variable font", location
1622
- )
1623
-
1624
- varscalar.axes = self.axes
1625
- if not varscalar.does_vary:
1626
- return varscalar.default, None
1627
-
1628
- default, index = varscalar.add_to_variation_store(
1629
- self.varstorebuilder, self.model_cache, self.font.get("avar")
1630
- )
1631
-
1632
- device = None
1633
- if index is not None and index != 0xFFFFFFFF:
1634
- device = buildVarDevTable(index)
1635
-
1636
- return default, device
1637
-
1638
- def makeOpenTypeAnchor(self, location, anchor):
1639
- """ast.Anchor --> otTables.Anchor"""
1640
- if anchor is None:
1641
- return None
1642
- variable = False
1643
- deviceX, deviceY = None, None
1644
- if anchor.xDeviceTable is not None:
1645
- deviceX = otl.buildDevice(dict(anchor.xDeviceTable))
1646
- if anchor.yDeviceTable is not None:
1647
- deviceY = otl.buildDevice(dict(anchor.yDeviceTable))
1648
- for dim in ("x", "y"):
1649
- varscalar = getattr(anchor, dim)
1650
- if not isinstance(varscalar, VariableScalar):
1651
- continue
1652
- if getattr(anchor, dim + "DeviceTable") is not None:
1653
- raise FeatureLibError(
1654
- "Can't define a device coordinate and variable scalar", location
1655
- )
1656
- default, device = self.makeVariablePos(location, varscalar)
1657
- setattr(anchor, dim, default)
1658
- if device is not None:
1659
- if dim == "x":
1660
- deviceX = device
1661
- else:
1662
- deviceY = device
1663
- variable = True
1664
-
1665
- otlanchor = otl.buildAnchor(
1666
- anchor.x, anchor.y, anchor.contourpoint, deviceX, deviceY
1667
- )
1668
- if variable:
1669
- otlanchor.Format = 3
1670
- return otlanchor
1671
-
1672
- _VALUEREC_ATTRS = {
1673
- name[0].lower() + name[1:]: (name, isDevice)
1674
- for _, name, isDevice, _ in otBase.valueRecordFormat
1675
- if not name.startswith("Reserved")
1676
- }
1677
-
1678
- def makeOpenTypeValueRecord(self, location, v, pairPosContext):
1679
- """ast.ValueRecord --> otBase.ValueRecord"""
1680
- if not v:
1681
- return None
1682
-
1683
- vr = {}
1684
- for astName, (otName, isDevice) in self._VALUEREC_ATTRS.items():
1685
- val = getattr(v, astName, None)
1686
- if not val:
1687
- continue
1688
- if isDevice:
1689
- vr[otName] = otl.buildDevice(dict(val))
1690
- elif isinstance(val, VariableScalar):
1691
- otDeviceName = otName[0:4] + "Device"
1692
- feaDeviceName = otDeviceName[0].lower() + otDeviceName[1:]
1693
- if getattr(v, feaDeviceName):
1694
- raise FeatureLibError(
1695
- "Can't define a device coordinate and variable scalar", location
1696
- )
1697
- vr[otName], device = self.makeVariablePos(location, val)
1698
- if device is not None:
1699
- vr[otDeviceName] = device
1700
- else:
1701
- vr[otName] = val
1702
-
1703
- if pairPosContext and not vr:
1704
- vr = {"YAdvance": 0} if v.vertical else {"XAdvance": 0}
1705
- valRec = otl.buildValue(vr)
1706
- return valRec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DaleChen/AutoGPT/autogpt/commands/file_operations.py DELETED
@@ -1,267 +0,0 @@
1
- """File operations for AutoGPT"""
2
- from __future__ import annotations
3
-
4
- import os
5
- import os.path
6
- from typing import Generator
7
-
8
- import requests
9
- from colorama import Back, Fore
10
- from requests.adapters import HTTPAdapter, Retry
11
-
12
- from autogpt.spinner import Spinner
13
- from autogpt.utils import readable_file_size
14
- from autogpt.workspace import WORKSPACE_PATH, path_in_workspace
15
-
16
- LOG_FILE = "file_logger.txt"
17
- LOG_FILE_PATH = WORKSPACE_PATH / LOG_FILE
18
-
19
-
20
- def check_duplicate_operation(operation: str, filename: str) -> bool:
21
- """Check if the operation has already been performed on the given file
22
-
23
- Args:
24
- operation (str): The operation to check for
25
- filename (str): The name of the file to check for
26
-
27
- Returns:
28
- bool: True if the operation has already been performed on the file
29
- """
30
- log_content = read_file(LOG_FILE)
31
- log_entry = f"{operation}: {filename}\n"
32
- return log_entry in log_content
33
-
34
-
35
- def log_operation(operation: str, filename: str) -> None:
36
- """Log the file operation to the file_logger.txt
37
-
38
- Args:
39
- operation (str): The operation to log
40
- filename (str): The name of the file the operation was performed on
41
- """
42
- log_entry = f"{operation}: {filename}\n"
43
-
44
- # Create the log file if it doesn't exist
45
- if not os.path.exists(LOG_FILE_PATH):
46
- with open(LOG_FILE_PATH, "w", encoding="utf-8") as f:
47
- f.write("File Operation Logger ")
48
-
49
- append_to_file(LOG_FILE, log_entry, shouldLog=False)
50
-
51
-
52
- def split_file(
53
- content: str, max_length: int = 4000, overlap: int = 0
54
- ) -> Generator[str, None, None]:
55
- """
56
- Split text into chunks of a specified maximum length with a specified overlap
57
- between chunks.
58
-
59
- :param content: The input text to be split into chunks
60
- :param max_length: The maximum length of each chunk,
61
- default is 4000 (about 1k token)
62
- :param overlap: The number of overlapping characters between chunks,
63
- default is no overlap
64
- :return: A generator yielding chunks of text
65
- """
66
- start = 0
67
- content_length = len(content)
68
-
69
- while start < content_length:
70
- end = start + max_length
71
- if end + overlap < content_length:
72
- chunk = content[start : end + overlap - 1]
73
- else:
74
- chunk = content[start:content_length]
75
-
76
- # Account for the case where the last chunk is shorter than the overlap, so it has already been consumed
77
- if len(chunk) <= overlap:
78
- break
79
-
80
- yield chunk
81
- start += max_length - overlap
82
-
83
-
84
- def read_file(filename: str) -> str:
85
- """Read a file and return the contents
86
-
87
- Args:
88
- filename (str): The name of the file to read
89
-
90
- Returns:
91
- str: The contents of the file
92
- """
93
- try:
94
- filepath = path_in_workspace(filename)
95
- with open(filepath, "r", encoding="utf-8") as f:
96
- content = f.read()
97
- return content
98
- except Exception as e:
99
- return f"Error: {str(e)}"
100
-
101
-
102
- def ingest_file(
103
- filename: str, memory, max_length: int = 4000, overlap: int = 200
104
- ) -> None:
105
- """
106
- Ingest a file by reading its content, splitting it into chunks with a specified
107
- maximum length and overlap, and adding the chunks to the memory storage.
108
-
109
- :param filename: The name of the file to ingest
110
- :param memory: An object with an add() method to store the chunks in memory
111
- :param max_length: The maximum length of each chunk, default is 4000
112
- :param overlap: The number of overlapping characters between chunks, default is 200
113
- """
114
- try:
115
- print(f"Working with file {filename}")
116
- content = read_file(filename)
117
- content_length = len(content)
118
- print(f"File length: {content_length} characters")
119
-
120
- chunks = list(split_file(content, max_length=max_length, overlap=overlap))
121
-
122
- num_chunks = len(chunks)
123
- for i, chunk in enumerate(chunks):
124
- print(f"Ingesting chunk {i + 1} / {num_chunks} into memory")
125
- memory_to_add = (
126
- f"Filename: {filename}\n" f"Content part#{i + 1}/{num_chunks}: {chunk}"
127
- )
128
-
129
- memory.add(memory_to_add)
130
-
131
- print(f"Done ingesting {num_chunks} chunks from {filename}.")
132
- except Exception as e:
133
- print(f"Error while ingesting file '{filename}': {str(e)}")
134
-
135
-
136
- def write_to_file(filename: str, text: str) -> str:
137
- """Write text to a file
138
-
139
- Args:
140
- filename (str): The name of the file to write to
141
- text (str): The text to write to the file
142
-
143
- Returns:
144
- str: A message indicating success or failure
145
- """
146
- if check_duplicate_operation("write", filename):
147
- return "Error: File has already been updated."
148
- try:
149
- filepath = path_in_workspace(filename)
150
- directory = os.path.dirname(filepath)
151
- if not os.path.exists(directory):
152
- os.makedirs(directory)
153
- with open(filepath, "w", encoding="utf-8") as f:
154
- f.write(text)
155
- log_operation("write", filename)
156
- return "File written to successfully."
157
- except Exception as e:
158
- return f"Error: {str(e)}"
159
-
160
-
161
- def append_to_file(filename: str, text: str, shouldLog: bool = True) -> str:
162
- """Append text to a file
163
-
164
- Args:
165
- filename (str): The name of the file to append to
166
- text (str): The text to append to the file
167
-
168
- Returns:
169
- str: A message indicating success or failure
170
- """
171
- try:
172
- filepath = path_in_workspace(filename)
173
- with open(filepath, "a") as f:
174
- f.write(text)
175
-
176
- if shouldLog:
177
- log_operation("append", filename)
178
-
179
- return "Text appended successfully."
180
- except Exception as e:
181
- return f"Error: {str(e)}"
182
-
183
-
184
- def delete_file(filename: str) -> str:
185
- """Delete a file
186
-
187
- Args:
188
- filename (str): The name of the file to delete
189
-
190
- Returns:
191
- str: A message indicating success or failure
192
- """
193
- if check_duplicate_operation("delete", filename):
194
- return "Error: File has already been deleted."
195
- try:
196
- filepath = path_in_workspace(filename)
197
- os.remove(filepath)
198
- log_operation("delete", filename)
199
- return "File deleted successfully."
200
- except Exception as e:
201
- return f"Error: {str(e)}"
202
-
203
-
204
- def search_files(directory: str) -> list[str]:
205
- """Search for files in a directory
206
-
207
- Args:
208
- directory (str): The directory to search in
209
-
210
- Returns:
211
- list[str]: A list of files found in the directory
212
- """
213
- found_files = []
214
-
215
- if directory in {"", "/"}:
216
- search_directory = WORKSPACE_PATH
217
- else:
218
- search_directory = path_in_workspace(directory)
219
-
220
- for root, _, files in os.walk(search_directory):
221
- for file in files:
222
- if file.startswith("."):
223
- continue
224
- relative_path = os.path.relpath(os.path.join(root, file), WORKSPACE_PATH)
225
- found_files.append(relative_path)
226
-
227
- return found_files
228
-
229
-
230
- def download_file(url, filename):
231
- """Downloads a file
232
- Args:
233
- url (str): URL of the file to download
234
- filename (str): Filename to save the file as
235
- """
236
- safe_filename = path_in_workspace(filename)
237
- try:
238
- message = f"{Fore.YELLOW}Downloading file from {Back.LIGHTBLUE_EX}{url}{Back.RESET}{Fore.RESET}"
239
- with Spinner(message) as spinner:
240
- session = requests.Session()
241
- retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
242
- adapter = HTTPAdapter(max_retries=retry)
243
- session.mount("http://", adapter)
244
- session.mount("https://", adapter)
245
-
246
- total_size = 0
247
- downloaded_size = 0
248
-
249
- with session.get(url, allow_redirects=True, stream=True) as r:
250
- r.raise_for_status()
251
- total_size = int(r.headers.get("Content-Length", 0))
252
- downloaded_size = 0
253
-
254
- with open(safe_filename, "wb") as f:
255
- for chunk in r.iter_content(chunk_size=8192):
256
- f.write(chunk)
257
- downloaded_size += len(chunk)
258
-
259
- # Update the progress message
260
- progress = f"{readable_file_size(downloaded_size)} / {readable_file_size(total_size)}"
261
- spinner.update_message(f"{message} {progress}")
262
-
263
- return f'Successfully downloaded and locally stored file: "{filename}"! (Size: {readable_file_size(total_size)})'
264
- except requests.HTTPError as e:
265
- return f"Got an HTTP Error whilst trying to download file: {e}"
266
- except Exception as e:
267
- return "Error: " + str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Datasculptor/DescriptionGPT/tools/merge_lvis_coco.py DELETED
@@ -1,202 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates.
2
- from collections import defaultdict
3
- import torch
4
- import sys
5
- import json
6
- import numpy as np
7
-
8
- from detectron2.structures import Boxes, pairwise_iou
9
- COCO_PATH = 'datasets/coco/annotations/instances_train2017.json'
10
- IMG_PATH = 'datasets/coco/train2017/'
11
- LVIS_PATH = 'datasets/lvis/lvis_v1_train.json'
12
- NO_SEG = False
13
- if NO_SEG:
14
- SAVE_PATH = 'datasets/lvis/lvis_v1_train+coco_box.json'
15
- else:
16
- SAVE_PATH = 'datasets/lvis/lvis_v1_train+coco_mask.json'
17
- THRESH = 0.7
18
- DEBUG = False
19
-
20
- # This mapping is extracted from the official LVIS mapping:
21
- # https://github.com/lvis-dataset/lvis-api/blob/master/data/coco_to_synset.json
22
- COCO_SYNSET_CATEGORIES = [
23
- {"synset": "person.n.01", "coco_cat_id": 1},
24
- {"synset": "bicycle.n.01", "coco_cat_id": 2},
25
- {"synset": "car.n.01", "coco_cat_id": 3},
26
- {"synset": "motorcycle.n.01", "coco_cat_id": 4},
27
- {"synset": "airplane.n.01", "coco_cat_id": 5},
28
- {"synset": "bus.n.01", "coco_cat_id": 6},
29
- {"synset": "train.n.01", "coco_cat_id": 7},
30
- {"synset": "truck.n.01", "coco_cat_id": 8},
31
- {"synset": "boat.n.01", "coco_cat_id": 9},
32
- {"synset": "traffic_light.n.01", "coco_cat_id": 10},
33
- {"synset": "fireplug.n.01", "coco_cat_id": 11},
34
- {"synset": "stop_sign.n.01", "coco_cat_id": 13},
35
- {"synset": "parking_meter.n.01", "coco_cat_id": 14},
36
- {"synset": "bench.n.01", "coco_cat_id": 15},
37
- {"synset": "bird.n.01", "coco_cat_id": 16},
38
- {"synset": "cat.n.01", "coco_cat_id": 17},
39
- {"synset": "dog.n.01", "coco_cat_id": 18},
40
- {"synset": "horse.n.01", "coco_cat_id": 19},
41
- {"synset": "sheep.n.01", "coco_cat_id": 20},
42
- {"synset": "beef.n.01", "coco_cat_id": 21},
43
- {"synset": "elephant.n.01", "coco_cat_id": 22},
44
- {"synset": "bear.n.01", "coco_cat_id": 23},
45
- {"synset": "zebra.n.01", "coco_cat_id": 24},
46
- {"synset": "giraffe.n.01", "coco_cat_id": 25},
47
- {"synset": "backpack.n.01", "coco_cat_id": 27},
48
- {"synset": "umbrella.n.01", "coco_cat_id": 28},
49
- {"synset": "bag.n.04", "coco_cat_id": 31},
50
- {"synset": "necktie.n.01", "coco_cat_id": 32},
51
- {"synset": "bag.n.06", "coco_cat_id": 33},
52
- {"synset": "frisbee.n.01", "coco_cat_id": 34},
53
- {"synset": "ski.n.01", "coco_cat_id": 35},
54
- {"synset": "snowboard.n.01", "coco_cat_id": 36},
55
- {"synset": "ball.n.06", "coco_cat_id": 37},
56
- {"synset": "kite.n.03", "coco_cat_id": 38},
57
- {"synset": "baseball_bat.n.01", "coco_cat_id": 39},
58
- {"synset": "baseball_glove.n.01", "coco_cat_id": 40},
59
- {"synset": "skateboard.n.01", "coco_cat_id": 41},
60
- {"synset": "surfboard.n.01", "coco_cat_id": 42},
61
- {"synset": "tennis_racket.n.01", "coco_cat_id": 43},
62
- {"synset": "bottle.n.01", "coco_cat_id": 44},
63
- {"synset": "wineglass.n.01", "coco_cat_id": 46},
64
- {"synset": "cup.n.01", "coco_cat_id": 47},
65
- {"synset": "fork.n.01", "coco_cat_id": 48},
66
- {"synset": "knife.n.01", "coco_cat_id": 49},
67
- {"synset": "spoon.n.01", "coco_cat_id": 50},
68
- {"synset": "bowl.n.03", "coco_cat_id": 51},
69
- {"synset": "banana.n.02", "coco_cat_id": 52},
70
- {"synset": "apple.n.01", "coco_cat_id": 53},
71
- {"synset": "sandwich.n.01", "coco_cat_id": 54},
72
- {"synset": "orange.n.01", "coco_cat_id": 55},
73
- {"synset": "broccoli.n.01", "coco_cat_id": 56},
74
- {"synset": "carrot.n.01", "coco_cat_id": 57},
75
- # {"synset": "frank.n.02", "coco_cat_id": 58},
76
- {"synset": "sausage.n.01", "coco_cat_id": 58},
77
- {"synset": "pizza.n.01", "coco_cat_id": 59},
78
- {"synset": "doughnut.n.02", "coco_cat_id": 60},
79
- {"synset": "cake.n.03", "coco_cat_id": 61},
80
- {"synset": "chair.n.01", "coco_cat_id": 62},
81
- {"synset": "sofa.n.01", "coco_cat_id": 63},
82
- {"synset": "pot.n.04", "coco_cat_id": 64},
83
- {"synset": "bed.n.01", "coco_cat_id": 65},
84
- {"synset": "dining_table.n.01", "coco_cat_id": 67},
85
- {"synset": "toilet.n.02", "coco_cat_id": 70},
86
- {"synset": "television_receiver.n.01", "coco_cat_id": 72},
87
- {"synset": "laptop.n.01", "coco_cat_id": 73},
88
- {"synset": "mouse.n.04", "coco_cat_id": 74},
89
- {"synset": "remote_control.n.01", "coco_cat_id": 75},
90
- {"synset": "computer_keyboard.n.01", "coco_cat_id": 76},
91
- {"synset": "cellular_telephone.n.01", "coco_cat_id": 77},
92
- {"synset": "microwave.n.02", "coco_cat_id": 78},
93
- {"synset": "oven.n.01", "coco_cat_id": 79},
94
- {"synset": "toaster.n.02", "coco_cat_id": 80},
95
- {"synset": "sink.n.01", "coco_cat_id": 81},
96
- {"synset": "electric_refrigerator.n.01", "coco_cat_id": 82},
97
- {"synset": "book.n.01", "coco_cat_id": 84},
98
- {"synset": "clock.n.01", "coco_cat_id": 85},
99
- {"synset": "vase.n.01", "coco_cat_id": 86},
100
- {"synset": "scissors.n.01", "coco_cat_id": 87},
101
- {"synset": "teddy.n.01", "coco_cat_id": 88},
102
- {"synset": "hand_blower.n.01", "coco_cat_id": 89},
103
- {"synset": "toothbrush.n.01", "coco_cat_id": 90},
104
- ]
105
-
106
-
107
- def get_bbox(ann):
108
- bbox = ann['bbox']
109
- return [bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3]]
110
-
111
-
112
- if __name__ == '__main__':
113
- file_name_key = 'file_name' if 'v0.5' in LVIS_PATH else 'coco_url'
114
- coco_data = json.load(open(COCO_PATH, 'r'))
115
- lvis_data = json.load(open(LVIS_PATH, 'r'))
116
-
117
- coco_cats = coco_data['categories']
118
- lvis_cats = lvis_data['categories']
119
-
120
- num_find = 0
121
- num_not_find = 0
122
- num_twice = 0
123
- coco2lviscats = {}
124
- synset2lvisid = {x['synset']: x['id'] for x in lvis_cats}
125
- # cocoid2synset = {x['coco_cat_id']: x['synset'] for x in COCO_SYNSET_CATEGORIES}
126
- coco2lviscats = {x['coco_cat_id']: synset2lvisid[x['synset']] \
127
- for x in COCO_SYNSET_CATEGORIES if x['synset'] in synset2lvisid}
128
- print(len(coco2lviscats))
129
-
130
- lvis_file2id = {x[file_name_key][-16:]: x['id'] for x in lvis_data['images']}
131
- lvis_id2img = {x['id']: x for x in lvis_data['images']}
132
- lvis_catid2name = {x['id']: x['name'] for x in lvis_data['categories']}
133
-
134
- coco_file2anns = {}
135
- coco_id2img = {x['id']: x for x in coco_data['images']}
136
- coco_img2anns = defaultdict(list)
137
- for ann in coco_data['annotations']:
138
- coco_img = coco_id2img[ann['image_id']]
139
- file_name = coco_img['file_name'][-16:]
140
- if ann['category_id'] in coco2lviscats and \
141
- file_name in lvis_file2id:
142
- lvis_image_id = lvis_file2id[file_name]
143
- lvis_image = lvis_id2img[lvis_image_id]
144
- lvis_cat_id = coco2lviscats[ann['category_id']]
145
- if lvis_cat_id in lvis_image['neg_category_ids']:
146
- continue
147
- if DEBUG:
148
- import cv2
149
- img_path = IMG_PATH + file_name
150
- img = cv2.imread(img_path)
151
- print(lvis_catid2name[lvis_cat_id])
152
- print('neg', [lvis_catid2name[x] for x in lvis_image['neg_category_ids']])
153
- cv2.imshow('img', img)
154
- cv2.waitKey()
155
- ann['category_id'] = lvis_cat_id
156
- ann['image_id'] = lvis_image_id
157
- coco_img2anns[file_name].append(ann)
158
-
159
- lvis_img2anns = defaultdict(list)
160
- for ann in lvis_data['annotations']:
161
- lvis_img = lvis_id2img[ann['image_id']]
162
- file_name = lvis_img[file_name_key][-16:]
163
- lvis_img2anns[file_name].append(ann)
164
-
165
- ann_id_count = 0
166
- anns = []
167
- for file_name in lvis_img2anns:
168
- coco_anns = coco_img2anns[file_name]
169
- lvis_anns = lvis_img2anns[file_name]
170
- ious = pairwise_iou(
171
- Boxes(torch.tensor([get_bbox(x) for x in coco_anns])),
172
- Boxes(torch.tensor([get_bbox(x) for x in lvis_anns]))
173
- )
174
-
175
- for ann in lvis_anns:
176
- ann_id_count = ann_id_count + 1
177
- ann['id'] = ann_id_count
178
- anns.append(ann)
179
-
180
- for i, ann in enumerate(coco_anns):
181
- if len(ious[i]) == 0 or ious[i].max() < THRESH:
182
- ann_id_count = ann_id_count + 1
183
- ann['id'] = ann_id_count
184
- anns.append(ann)
185
- else:
186
- duplicated = False
187
- for j in range(len(ious[i])):
188
- if ious[i, j] >= THRESH and \
189
- coco_anns[i]['category_id'] == lvis_anns[j]['category_id']:
190
- duplicated = True
191
- if not duplicated:
192
- ann_id_count = ann_id_count + 1
193
- ann['id'] = ann_id_count
194
- anns.append(ann)
195
- if NO_SEG:
196
- for ann in anns:
197
- del ann['segmentation']
198
- lvis_data['annotations'] = anns
199
-
200
- print('# Images', len(lvis_data['images']))
201
- print('# Anns', len(lvis_data['annotations']))
202
- json.dump(lvis_data, open(SAVE_PATH, 'w'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Detomo/ai-comic-generation/src/lib/replaceNonWhiteWithTransparent.ts DELETED
@@ -1,46 +0,0 @@
1
- export function replaceNonWhiteWithTransparent(imageBase64: string): Promise<string> {
2
- return new Promise((resolve, reject) => {
3
- const img = new Image();
4
- img.onload = () => {
5
- const canvas = document.createElement('canvas');
6
- const ctx = canvas.getContext('2d');
7
- if (!ctx) {
8
- reject('Unable to get canvas context');
9
- return;
10
- }
11
-
12
- const ratio = window.devicePixelRatio || 1;
13
- canvas.width = img.width * ratio;
14
- canvas.height = img.height * ratio;
15
- ctx.scale(ratio, ratio);
16
-
17
- ctx.drawImage(img, 0, 0);
18
-
19
- const imageData = ctx.getImageData(0, 0, img.width, img.height);
20
- const data = imageData.data;
21
- console.log("ok")
22
-
23
- for (let i = 0; i < data.length; i += 4) {
24
- if (data[i] === 255 && data[i + 1] === 255 && data[i + 2] === 255) {
25
- // Change white (also shades of grays) pixels to black
26
- data[i] = 0;
27
- data[i + 1] = 0;
28
- data[i + 2] = 0;
29
- } else {
30
- // Change all other pixels to transparent
31
- data[i + 3] = 0;
32
- }
33
- }
34
-
35
- ctx.putImageData(imageData, 0, 0);
36
-
37
- resolve(canvas.toDataURL());
38
- };
39
-
40
- img.onerror = (err) => {
41
- reject(err);
42
- };
43
-
44
- img.src = imageBase64;
45
- });
46
- }