parquet-converter commited on
Commit
f0322ad
·
1 Parent(s): bb6ec4f

Update parquet files (step 19 of 397)

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/Crackle Tv App Download.md +0 -38
  2. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download Free Idm Crack Serial Number LINK.md +0 -23
  3. spaces/1gistliPinn/ChatGPT4/Examples/A Pack Of 306 Keygens Patches 2012.md +0 -10
  4. spaces/1gistliPinn/ChatGPT4/Examples/Adobe Animate CC 2018 V18.0.1.115 Patch April Updated.md +0 -28
  5. spaces/1gistliPinn/ChatGPT4/Examples/Blufftitler Bixpack 10 Free HOT! Download.md +0 -29
  6. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Clash of Clans Son Srm APK ndir - Efsanevi Bir Sava Oyunu Deneyimi.md +0 -169
  7. spaces/1phancelerku/anime-remove-background/CarX Drift Racing APK 1.21.1 - Customize Your Car and Compete with Other Players Online.md +0 -131
  8. spaces/1phancelerku/anime-remove-background/Download NIC VPN Beta 6.0 APK for Android - Free and Unlimited DNS.md +0 -155
  9. spaces/2ndelement/voicevox/voicevox_engine/part_of_speech_data.py +0 -144
  10. spaces/2ndelement/voicevox/voicevox_engine/synthesis_engine/core_wrapper.py +0 -538
  11. spaces/4com/SD-XL-CPU/app.py +0 -172
  12. spaces/AI-Hobbyist/Hoyo-RVC/train/mel_processing.py +0 -130
  13. spaces/AIFILMS/StyleGANEX/utils/wandb_utils.py +0 -47
  14. spaces/AILab-CVC/SEED-LLaMA/gradio_demo/utils.py +0 -82
  15. spaces/AIMLApps/Botrite_wip/app.py +0 -362
  16. spaces/ASJMO/freegpt/client/css/button.css +0 -26
  17. spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/__init__.py +0 -0
  18. spaces/Admin08077/Record/README.md +0 -13
  19. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/holygrail/HolyGrail.js +0 -28
  20. spaces/Aki004/herta-so-vits/vdecoder/hifigan/nvSTFT.py +0 -111
  21. spaces/Akmyradov/TurkmenTTSweSTT/uroman/lib/NLP/Romanizer.pm +0 -2020
  22. spaces/Alfasign/Einfach.Stable_DiffPomrpter/README.md +0 -12
  23. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/kandinsky_v22/test_kandinsky.py +0 -262
  24. spaces/Andy1621/uniformer_image_detection/configs/fp16/faster_rcnn_r50_fpn_fp16_1x_coco.py +0 -3
  25. spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/relative_imports.py +0 -13
  26. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/configs/_base_/datasets/ade20k.py +0 -54
  27. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/parallel/data_container.py +0 -89
  28. spaces/Anonymous-sub/Rerender/ControlNet/docs/annotator.md +0 -49
  29. spaces/ArtGAN/Segment-Anything-Video/README.md +0 -15
  30. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/cli/main.py +0 -79
  31. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/platformdirs/android.py +0 -126
  32. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/_collections.py +0 -337
  33. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_resources/_itertools.py +0 -35
  34. spaces/Banbri/zcvzcv/src/app/interface/ai-clip-factory/index.tsx +0 -15
  35. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/pyparsing/core.py +0 -0
  36. spaces/CVPR/LIVE/thrust/testing/unittest/random.h +0 -134
  37. spaces/CVPR/LIVE/thrust/thrust/type_traits/is_trivially_relocatable.h +0 -251
  38. spaces/CVPR/drawings-to-human/ALT-README.md +0 -2
  39. spaces/Caoyunkang/Segment-Any-Anomaly/GroundingDINO/groundingdino/util/box_ops.py +0 -140
  40. spaces/Caoyunkang/Segment-Any-Anomaly/utils/csv_utils.py +0 -34
  41. spaces/Celestinian/Prompt-Generator/README.md +0 -13
  42. spaces/ChallengeHub/Chinese-LangChain/clc/source_service.py +0 -86
  43. spaces/CikeyQI/meme-api/meme_generator/memes/bubble_tea/__init__.py +0 -61
  44. spaces/Cong723/gpt-academic-public/crazy_functions/test_project/cpp/cppipc/waiter.h +0 -83
  45. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/ShareButton-39feba51.js +0 -2
  46. spaces/Daextream/Whisper-Auto-Subtitled-Video-Generator/README.md +0 -13
  47. spaces/Djacon/emotion_detection/files/js/analytics.js +0 -484
  48. spaces/ECCV2022/PSG/OpenPSG/configs/_base_/datasets/vg_sg.py +0 -57
  49. spaces/EronSamez/RVC_HFmeu/infer_batch_rvc.py +0 -215
  50. spaces/EronSamez/RVC_HFmeu/tools/calc_rvc_model_similarity.py +0 -96
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Crackle Tv App Download.md DELETED
@@ -1,38 +0,0 @@
1
-
2
- <h1>How to Download and Use Crackle TV App on Your Device</h1>
3
- <p>If you are looking for a free and legal way to watch movies and TV shows online, you might want to try Crackle TV app. Crackle TV app is a streaming service that offers a variety of content from Sony Pictures Entertainment, including original series, classic shows, and popular movies. In this article, we will show you how to download and use Crackle TV app on your device.</p>
4
- <h2>crackle tv app download</h2><br /><p><b><b>Download</b> &gt;&gt;&gt;&gt;&gt; <a href="https://byltly.com/2uKw1g">https://byltly.com/2uKw1g</a></b></p><br /><br />
5
- <h2>What is Crackle TV App?</h2>
6
- <p>Crackle TV app is a free streaming service that is owned by Sony Pictures Entertainment. It was launched in 2007 and has since expanded to over 20 countries. Some of the features of Crackle TV app include:</p>
7
- <ul>
8
- <li>It offers a wide range of content, including comedy, drama, action, horror, sci-fi, anime, and more.</li>
9
- <li>It has original series, such as StartUp, Snatch, The Oath, and Seinfeld.</li>
10
- <li>It has classic shows, such as All in the Family, The Jeffersons, Good Times, and Mad About You.</li>
11
- <li>It has popular movies, such as Spider-Man, Men in Black, Ghostbusters, and The Karate Kid.</li>
12
- <li>It updates its content regularly and adds new titles every month.</li>
13
- <li>It supports multiple devices, such as smartphones, tablets, computers, smart TVs, game consoles, and streaming devices.</li>
14
- <li>It does not require any subscription or registration. However, you can create a free account to save your preferences and resume watching across devices.</li>
15
- <li>It is ad-supported. You will see some commercials during the streaming. However, the ads are shorter and fewer than on cable TV.</li>
16
- </ul>
17
- <h2>How to Download Crackle TV App?</h2>
18
- <p>To download Crackle TV app on your device, you need to follow these steps:</p>
19
- <ol>
20
- <li>Go to the official website of Crackle TV app and click on the "Download" button.</li>
21
- <li>Select your device type (Android, iOS, Windows) and click on the corresponding link.</li>
22
- <li>You will be redirected to the app store of your device. Click on the "Install" or "Get" button.</li>
23
- <li>Wait for the download to finish and then open the app.</li>
24
- </ol>
25
- <p>Congratulations! You have successfully downloaded Crackle TV app on your device. Now you can start watching movies and TV shows for free.</p>
26
- <p></p>
27
- <h2>How to Use Crackle TV App?</h2>
28
- <p>To use Crackle TV app on your device, you need to follow these steps:</p>
29
- <ol>
30
- <li>Launch the app and browse through the categories or genres of content.</li>
31
- <li>Select the title that you want to watch and tap on it.</li>
32
- <li>You can either watch it immediately or add it to your watchlist for later viewing.</li>
33
- <li>You can also search for a specific title by using the magnifying glass icon on the top right corner.</li>
34
- <li>You can adjust the video quality, subtitles, audio language, and other settings by using the gear icon on the top right corner.</li>
35
- </ol>
36
- <p>You have successfully used Crackle TV app on your device. Enjoy watching movies and TV shows for free.</p> ddb901b051<br />
37
- <br />
38
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download Free Idm Crack Serial Number LINK.md DELETED
@@ -1,23 +0,0 @@
1
-
2
- <h1>How to Download Free IDM Crack Serial Number</h1>
3
- <p>IDM (Internet Download Manager) is a powerful and popular software that allows you to download files from the internet with high speed and efficiency. It supports various protocols, such as HTTP, FTP, HTTPS, MMS, and more. It also integrates with most web browsers, such as Chrome, Firefox, Opera, and Internet Explorer. With IDM, you can download videos, music, documents, games, and any other file type you want.</p>
4
- <p>However, IDM is not a free software. You need to buy a license key to use it without any limitations. The license key costs $24.95 for one year or $9.95 for one month. If you don't have a license key, you can only use IDM for 30 days as a trial version. After that, you need to either buy a license key or use a crack serial number to activate IDM for free.</p>
5
- <h2>download free idm crack serial number</h2><br /><p><b><b>DOWNLOAD</b> >>> <a href="https://byltly.com/2uKA95">https://byltly.com/2uKA95</a></b></p><br /><br />
6
- <h2>What is a Crack Serial Number?</h2>
7
- <p>A crack serial number is a code that can bypass the registration process of IDM and make it work as if you have a valid license key. A crack serial number can be obtained from various sources on the internet, such as websites, blogs, forums, etc. However, not all crack serial numbers are safe and reliable. Some of them may contain viruses, malware, or spyware that can harm your computer or steal your personal information.</p>
8
- <p>Therefore, you need to be careful when downloading and using crack serial numbers for IDM. You should only download them from trusted and reputable sources. You should also scan them with an antivirus program before using them. You should also backup your important files and data before using crack serial numbers for IDM.</p>
9
- <h2>How to Download Free IDM Crack Serial Number?</h2>
10
- <p>If you want to download free IDM crack serial number, you can follow these steps:</p>
11
- <ol>
12
- <li>Go to a website that provides free IDM crack serial numbers, such as iTechGyan, AZUKI Systems, or Followchain. These websites have a list of free IDM crack serial numbers that you can copy and paste.</li>
13
- <li>Choose a crack serial number that matches your IDM version and copy it.</li>
14
- <li>Open IDM and go to Registration > Registration.</li>
15
- <li>Enter your name, email address, and the crack serial number in the fields.</li>
16
- <li>Click OK and restart IDM.</li>
17
- <li>Enjoy using IDM for free!</li>
18
- </ol>
19
- <h2>Conclusion</h2>
20
- <p>IDM is a great software that can help you download files from the internet faster and easier. However, it is not a free software and you need to buy a license key to use it without any restrictions. If you don't want to spend money on IDM, you can use a crack serial number to activate it for free. However, you need to be careful when downloading and using crack serial numbers for IDM. You should only download them from trusted sources and scan them with an antivirus program before using them. You should also backup your important files and data before using crack serial numbers for IDM.</p>
21
- <p></p> ddb901b051<br />
22
- <br />
23
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/A Pack Of 306 Keygens Patches 2012.md DELETED
@@ -1,10 +0,0 @@
1
- <br />
2
- <p>i would like to use the zip package to install it on my new computer but i'm not sure how to do that. i have done the install from the cd in the past. i can't seem to find a way to do it from the software center. can someone please explain how to do this? i know that its a simple question but i can't seem to find a solution. </p>
3
- <h2>a pack of 306 keygens patches 2012</h2><br /><p><b><b>DOWNLOAD</b> &#10001; &#10001; &#10001; <a href="https://imgfil.com/2uxZ91">https://imgfil.com/2uxZ91</a></b></p><br /><br />
4
- <p>i have an r3000 and i installed the opos (a software package) on it. i installed the package using the install from a package disk. while installing the package i was asked to select an authorization key but i did not know what it was. now i have installed the package and i want to install the o365. i downloaded the o365 from the microsoft site and i tried to install it, but the software center does not recognize the o365 software package, just the opos package. what should i do?</p>
5
- <p>the main idea behind it is to provide a simple and quick way to create and manage your own <code>apks</code>. the package manager is based on the debian package management tool, and is currently used to install and manage the packages. this means that the package manager is still a bit immature, as it is very new and has only been tested with a limited set of applications. </p>
6
- <p>as a bonus, this package manager has it's own repository of packages (see below), so you can easily install (or uninstall) them at will, and without having to rely on the host system package manager or apk cache. more about this below.</p>
7
- <p></p>
8
- <p>the package manager is based on the <code>apt-get</code> utility, which is included by default on all debian based systems (and thus on the host system). in order to install the package manager you need to add it as a package for the host system (or in /etc/apt/sources.list.d/).</p> 899543212b<br />
9
- <br />
10
- <br />
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Adobe Animate CC 2018 V18.0.1.115 Patch April Updated.md DELETED
@@ -1,28 +0,0 @@
1
- <h2>Adobe Animate CC 2018 v18.0.1.115 Patch April Updated</h2><br /><p><b><b>Download File</b> &#9889; <a href="https://imgfil.com/2uxWYg">https://imgfil.com/2uxWYg</a></b></p><br /><br />
2
- <br />
3
- 2018
4
-
5
- animation
6
-
7
- anything to do with animation. not just css or flash. includes graphic and interface design. animators from concept to storyboard, via sketches, video, photoshop or daw.
8
-
9
- animate
10
-
11
- In computing, animate is the process of moving, enlarging, shrinking, or rotating an object on screen using an animation program.
12
-
13
- after effects cc 2018 v15.0.4 release january updated 2018
14
-
15
- After Effects is an Adobe Systems proprietary cross-platform software application for authoring motion graphics and visual effects for the web, video, and film. It is part of the Creative Cloud, a subscription-based service including similar tools such as Adobe Photoshop, Illustrator and Acrobat. After Effects can export video or run as a video plug-in for other applications.
16
-
17
- After Effects is available for Windows, macOS and Linux.
18
-
19
- Adobe After Effects CC 2018 v15.0.4.917 Full Activation Code
20
-
21
- after effects cc 2017 v16.0.3 release january updated 2017
22
-
23
- Adobe After Effects CC 2017 v16.0.3.1235 Full Activation Code
24
-
25
- Adobe After Effects is an Adobe Systems proprietary cross-platform software application for authoring motion graphics and visual effects for the web, video, and film. It is part of the Creative Cloud, a subscription- 4fefd39f24<br />
26
- <br />
27
- <br />
28
- <p></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Blufftitler Bixpack 10 Free HOT! Download.md DELETED
@@ -1,29 +0,0 @@
1
-
2
- <h1>Blufftitler Bixpack 10 Free Download: Create Stunning 3D Video Titles in Minutes</h1>
3
- <p>If you are looking for a way to create eye-catching 3D video titles without spending hours on complex software, then you should check out Blufftitler Bixpack 10. This is a collection of ready-made templates that you can use with Blufftitler, a simple and powerful 3D video titling software. In this article, we will show you how to download Blufftitler Bixpack 10 for free and how to use it to create amazing 3D video titles in minutes.</p>
4
- <h2>Blufftitler Bixpack 10 Free Download</h2><br /><p><b><b>DOWNLOAD</b> &#9734; <a href="https://imgfil.com/2uxYII">https://imgfil.com/2uxYII</a></b></p><br /><br />
5
- <h2>What is Blufftitler Bixpack 10?</h2>
6
- <p>Blufftitler Bixpack 10 is the tenth installment of the popular Bixpack series, which are packs of templates that you can use with Blufftitler. Blufftitler is a software that lets you create 3D video titles and animations with ease. You can use it to add text, images, videos, effects, and more to your videos. You can also export your creations as videos or images that you can use in any video editing software.</p>
7
- <p>Bixpack 10 is focused on splines, which are curved lines that you can use to create smooth and organic shapes. With Bixpack 10, you can create 3D video titles that look like ribbons, wires, pipes, ropes, and more. You can also customize the color, texture, lighting, and animation of your splines to suit your needs. Bixpack 10 comes with 30 templates that cover different themes such as sports, music, nature, and technology.</p>
8
- <h2>How to Download Blufftitler Bixpack 10 for Free?</h2>
9
- <p>If you want to download Blufftitler Bixpack 10 for free, you can follow these simple steps:</p>
10
- <ol>
11
- <li>Go to <a href="https://www.outerspace-software.com/download">https://www.outerspace-software.com/download</a> and download the latest version of Blufftitler.</li>
12
- <li>Install Blufftitler on your computer and launch it.</li>
13
- <li>Go to <a href="https://www.outerspace-software.com/bixpack/10">https://www.outerspace-software.com/bixpack/10</a> and click on the "Download" button.</li>
14
- <li>Save the file "BixPack_10_Splines.zip" on your computer and unzip it.</li>
15
- <li>Copy the folder "BixPack_10_Splines" to the "Shows" folder in your Blufftitler installation directory (usually C:\Program Files\Outerspace Software\BluffTitler\Media\Shows).</li>
16
- <li>Restart Blufftitler and go to File > Open Show... and select one of the templates from the "BixPack_10_Splines" folder.</li>
17
- </ol>
18
- <p>Congratulations! You have successfully downloaded Blufftitler Bixpack 10 for free and you can now use it to create stunning 3D video titles.</p>
19
- <p></p>
20
- <h2>How to Use Blufftitler Bixpack 10?</h2>
21
- <p>Using Blufftitler Bixpack 10 is very easy and fun. Here are some tips on how to use it:</p>
22
- <ul>
23
- <li>To change the text of your title, double-click on the text layer and type your own text.</li>
24
- <li>To change the font, size, color, or style of your text, select the text layer and go to the "Text" tab in the toolbar.</li>
25
- <li>To change the spline shape, select the spline layer and go to the "Spline" tab in the toolbar. You can adjust the control points, tension, resolution, and thickness of your spline.</li>
26
- <li>To change the texture of your spline, select the spline layer and go to the "F9 Textures..." dialog. You can choose from different textures or load your own image or video as a texture.</li>
27
- <li>To change the lighting of your title, select the light layer and go to the "Light" tab in the toolbar.</p> d5da3c52bf<br />
28
- <br />
29
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Clash of Clans Son Srm APK ndir - Efsanevi Bir Sava Oyunu Deneyimi.md DELETED
@@ -1,169 +0,0 @@
1
- <br />
2
- <h1>Son Sürüm Clash of Clans APK İndir: Nasıl Yapılır ve Neden Yapmalısınız?</h1>
3
- <p>Clash of Clans, dünyanın en popüler strateji oyunlarından biridir. Milyonlarca oyuncu, kendi köylerini inşa etmek, klan savaşlarına katılmak ve rakiplerini yenmek için bu oyunu oynamaktadır. Peki, son sürüm clash of clans apk indirerek bu oyunu daha da eğlenceli hale getirebilirsiniz. Bu yazıda, son sürüm clash of clans apk indirmenin nasıl yapıldığını, neden yapmanız gerektiğini ve bunun size ne gibi faydalar sağlayacağını anlatacağız.</p>
4
- <h2>son sürüm clash of clans apk indir</h2><br /><p><b><b>Download Zip</b> > <a href="https://urlin.us/2uSYYJ">https://urlin.us/2uSYYJ</a></b></p><br /><br />
5
- <h2>Clash of Clans Nedir ve Neden Popüler?</h2>
6
- <p>Clash of Clans, Supercell tarafından geliştirilen ve 2012 yılında piyasaya sürülen bir çevrimiçi çok oyunculu savaş oyunudur. Oyunun amacı, köyünüzü inşa etmek, üssünüzü tasarlamak ve savunmak, askerlerinizi eğitmek ve geliştirmek, kaynaklarınızı artırmak ve diğer oyuncuların köylerine saldırarak altın, iksir ve kara iksir elde etmektir. Ayrıca, bir klan kurabilir veya başka bir klana katılarak klan savaşlarına, klan liglerine ve klan oyunlarına katılabilirsiniz. Oyun sürekli olarak güncellenmekte ve yeni özellikler, birimler, binalar, büyüler ve etkinlikler eklenmektedir.</p>
7
- <h3>Clash of Clans Oyununun Özellikleri</h3>
8
- <p>Clash of Clans oyununun bazı özellikleri şunlardır:</p>
9
- <ul>
10
- <li>Köyünüzü istediğiniz gibi inşa edebilir ve düzenleyebilirsiniz.</li>
11
- <li>Birbirinden farklı yeteneklere sahip çok sayıda asker tipi arasından seçim yapabilirsiniz.</li>
12
- <li>Benzersiz güçlere ve stratejilere sahip epik savaşlara katılabilirsiniz.</li>
13
- <h3>Clash of Clans Oyununun Avantajları</h3>
14
- <p>Clash of Clans oyununun birçok avantajı vardır. Bunlardan bazıları şunlardır:</p>
15
- <ul>
16
- <li>Oyun ücretsizdir ve herhangi bir cihazda oynanabilir.</li>
17
- <li>Oyun sürekli olarak güncellenir ve yeni içerikler sunar.</li>
18
- <li>Oyun hem bireysel hem de takım halinde oynanabilir.</li>
19
- <li>Oyun strateji, planlama, yaratıcılık ve eğlenceyi bir arada sunar.</li>
20
- <li>Oyun dünyanın her yerinden milyonlarca oyuncu ile sosyalleşme imkanı sağlar.</li>
21
- </ul>
22
- <h2>Son Sürüm Clash of Clans APK İndirmenin Faydaları</h2>
23
- <p>Clash of Clans oyununu resmi olarak Google Play Store veya App Store üzerinden indirebilirsiniz. Ancak, son sürüm clash of clans apk indirerek oyunu daha da geliştirebilirsiniz. APK, Android uygulama paketi anlamına gelir ve oyunun kurulum dosyasını içerir. Son sürüm clash of clans apk indirmenin faydaları şunlardır:</p>
24
- <ul>
25
- <li>Son sürüm clash of clans apk indirerek oyunun en güncel ve en yeni versiyonuna sahip olabilirsiniz.</li>
26
- <li>Son sürüm clash of clans apk indirerek oyunun resmi olarak sunulmayan bazı özelliklerine ve modlarına erişebilirsiniz.</li>
27
- <li>Son sürüm clash of clans apk indirerek oyunu daha hızlı, daha akıcı ve daha sorunsuz bir şekilde oynayabilirsiniz.</li>
28
- <li>Son sürüm clash of clans apk indirerek oyunu istediğiniz zaman ve istediğiniz yerde oynayabilirsiniz.</li>
29
- </ul>
30
- <h3>Son Sürüm Clash of Clans APK İndirmek İçin Gerekenler</h3>
31
- <p>Son sürüm clash of clans apk indirmek için gerekenler şunlardır:</p>
32
- <ul>
33
- <li>Bir Android cihaz (telefon, tablet, bilgisayar vb.)</li>
34
- <li>Bir internet bağlantısı</li>
35
- <li>Bir güvenilir ve güncel son sürüm clash of clans apk indirme sitesi</li>
36
- <li>Bir dosya yöneticisi uygulaması</li>
37
- </ul>
38
- <h3>Son Sürüm Clash of Clans APK İndirmek İçin Adımlar</h3>
39
- <p>Son sürüm clash of clans apk indirmek için adımlar şunlardır:</p>
40
- <p>Clash of Clans son sürüm apk indir 2023<br />
41
- Clash of Clans güncel apk indir ücretsiz<br />
42
- Clash of Clans mod apk indir hileli<br />
43
- Clash of Clans yeni sürüm apk indir android<br />
44
- Clash of Clans apk indir full sürüm<br />
45
- Clash of Clans son güncelleme apk indir<br />
46
- Clash of Clans hızlı apk indir son sürüm<br />
47
- Clash of Clans online apk indir 2023<br />
48
- Clash of Clans son versiyon apk indir<br />
49
- Clash of Clans en son sürüm apk indir<br />
50
- Clash of Clans apk indir son güncellemeli<br />
51
- Clash of Clans hack apk indir 2023<br />
52
- Clash of Clans son sürüm apk indir tabletadam[^1^]<br />
53
- Clash of Clans bedava apk indir son sürüm<br />
54
- Clash of Clans premium apk indir 2023<br />
55
- Clash of Clans son sürüm apk indir cepde<br />
56
- Clash of Clans hileli mod apk indir 2023<br />
57
- Clash of Clans son sürüm apk indir oyunindir.club<br />
58
- Clash of Clans türkçe apk indir son sürüm<br />
59
- Clash of Clans son sürüm apk indir android oyun club<br />
60
- Clash of Clans unlimited gems apk indir 2023<br />
61
- Clash of Clans son sürüm apk indir tamindir<br />
62
- Clash of Clans mega mod apk indir 2023<br />
63
- Clash of Clans son sürüm apk indir apkpure<br />
64
- Clash of Clans private server apk indir 2023<br />
65
- Clash of Clans son sürüm apk indir uptodown<br />
66
- Clash of Clans nulls clash apk indir 2023<br />
67
- Clash of Clans son sürüm apk indir andropalace<br />
68
- Clash of Clans th14 update apk indir 2023<br />
69
- Clash of Clans son sürüm apk indir rexdl<br />
70
- Clash of Clans magic server apk indir 2023<br />
71
- Clash of Clans son sürüm apk indir mobilism<br />
72
- Clash of Clans plenixclash apk indir 2023<br />
73
- Clash of Clans son sürüm apk indir revdl<br />
74
- Clash of Clans fhx server apk indir 2023<br />
75
- Clash of Clans son sürüm apk indir ihackedit<br />
76
- Clash of Clans lights server apk indir 2023<br />
77
- Clash of Clans son sürüm apk indir an1.com<br />
78
- Clash of Clans town hall 14 apk indir 2023<br />
79
- Clash of Clans son sürüm apk indir apkmody.io</p>
80
- <ol>
81
- <li>Öncelikle, cihazınızın ayarlar menüsünden bilinmeyen kaynaklardan uygulama yükleme seçeneğini etkinleştirin. Bu, cihazınıza resmi olmayan uygulamaları kurmanıza izin verecektir.</li>
82
- <li>Ardından, bir internet tarayıcısı açın ve güvenilir bir son sürüm clash of clans apk indirme sitesine gidin. Bu sitelerden bazıları şunlardır: , , . Bu sitelerden birini seçin ve son sürüm clash of clans apk dosyasını indirmek için talimatları takip edin.</li>
83
- <li>Daha sonra, indirdiğiniz son sürüm clash of clans apk dosyasını bulmak için bir dosya yöneticisi uygulaması açın. Bu uygulamaların bazıları şunlardır: , , . Bu uygulamalardan birini seçin ve son sürüm clash of clans apk dosyasını cihazınızın hafızasında veya harici depolama alanında arayın.</li>
84
- <p>kurulum sırasında size bazı izinler isteyebilir. Bu izinleri verin ve kurulumu tamamlayın. Artık son sürüm clash of clans apk oyununu cihazınızda oynamaya başlayabilirsiniz.</p>
85
- <h2>Son Sürüm Clash of Clans APK İndirdikten Sonra Dikkat Etmeniz Gerekenler</h2>
86
- <p>Son sürüm clash of clans apk indirdikten sonra dikkat etmeniz gerekenler şunlardır:</p>
87
- <h3>Son Sürüm Clash of Clans APK Güvenli mi?</h3>
88
- <p>Son sürüm clash of clans apk güvenli olabilir veya olmayabilir. Bu, indirdiğiniz siteye ve dosyaya bağlıdır. Bazı siteler ve dosyalar virüs, malware, spyware veya diğer zararlı yazılımlar içerebilir. Bu nedenle, son sürüm clash of clans apk indirirken güvenilir ve güncel siteleri tercih etmeniz, indirmeden önce dosyanın boyutunu, yorumlarını ve derecelendirmelerini kontrol etmeniz, cihazınızda bir antivirüs programı bulundurmanız ve indirdiğiniz dosyayı taratmanız önemlidir.</p>
89
- <h3>Son Sürüm Clash of Clans APK Oyunun Kurallarına Aykırı mı?</h3>
90
- <p>Son sürüm clash of clans apk oyunun kurallarına aykırı olabilir veya olmayabilir. Bu, indirdiğiniz dosyanın içeriğine bağlıdır. Bazı dosyalar oyunun orijinal versiyonuna sadık kalırken, bazı dosyalar oyunu değiştirerek hile, mod veya hack içerebilir. Bu durumda, oyunun kurallarına aykırı davranmış olursunuz ve oyunun geliştiricisi Supercell tarafından hesabınızın banlanması veya silinmesi riskiyle karşı karşıya kalabilirsiniz. Bu nedenle, son sürüm clash of clans apk indirirken dikkatli olmanız, oyunun resmi politikalarını ve koşullarını okumanız ve oyunu adil ve eğlenceli bir şekilde oynamanız tavsiye edilir.</p>
91
- <h2>Son Sürüm Clash of Clans APK İle Oyunun Keyfini Çıkarın</h2>
92
- <p>Son sürüm clash of clans apk ile oyunun keyfini çıkarmak için yapabileceğiniz şeyler şunlardır:</p>
93
- <h3>Son Sürüm Clash of Clans APK İle Oyunun Tadını Çıkarmak İçin İpuçları</h3>
94
- <p>Son sürüm clash of clans apk ile oyunun tadını çıkarmak için ipuçları şunlardır:</p>
95
- <ul>
96
- <li>Köyünüzü inşa ederken dengeli bir şekilde hem savunma hem de saldırı odaklanın.</li>
97
- <li>Askerlerinizi akıllıca seçin ve farklı durumlara uygun stratejiler geliştirin.</li>
98
- <li>Klanınıza katılın veya kurun ve diğer oyuncularla işbirliği yapın.</li>
99
- <li>Oyunun sunduğu etkinlikleri, görevleri ve ödülleri kaçırmayın.</li>
100
- <li>Oyunu eğlenmek için oynayın ve rakiplerinize saygılı davranın.</li>
101
- </ul>
102
- <h3>Son Sürüm Clash of Clans APK İle Oyunun Tadını Çıkarmak İçin Tablo</h3>
103
- <p>Son sürüm clash of clans apk ile oyunun tadını çıkarmak için tablo şöyledir:</p>
104
- <table>
105
- <tr>
106
- <th>Asker Tipi</th>
107
- <th>Güçlü Olduğu Durumlar</th>
108
- <th>Zayıf Olduğu Durumlar</th>
109
- </tr>
110
- <tr>
111
- <td>Barbar</td>
112
- ma, duvarlara karşı etkili</td>
113
- <td>Yüksek seviye savunma, havadan saldırı</td>
114
- </tr>
115
- <tr>
116
- <td>Okçu</td>
117
- <td>Uzun menzilli saldırı, hava savunmasına karşı etkili</td>
118
- <td>Mortar, büyü kulesi, dev bomba</td>
119
- </tr>
120
- <tr>
121
- <td>Cüce</td>
122
- <td>Kaynak binalarına karşı etkili, duvarları kolayca yıkabilir</td>
123
- <td>Bomba, yay kulesi, dev salyangoz</td>
124
- </tr>
125
- <tr>
126
- <td>Dev</td>
127
- <td>Savunma binalarına karşı etkili, çok dayanıklı</td>
128
- <td>Hava savunması, yay kulesi, iskelet tuzak</td>
129
- </tr>
130
- <tr>
131
- <td>Şifacı</td>
132
- <td>Diğer askerleri iyileştirebilir, uzun ömürlü</td>
133
- <td>Hava savunması, hava mayını, kartal topu</td>
134
- </tr>
135
- <tr>
136
- <td>Ejderha</td>
137
- <td>Hem kara hem de hava hedeflerine saldırabilir, çok güçlü</td>
138
- <td>Hava savunması, hava süpürgesi, inferno kulesi</td>
139
- </tr>
140
- <tr>
141
- <td>P.E.K.K.A.</td>
142
- <td>Çok yüksek hasar verebilir, çok dayanıklı</td>
143
- <td>Tesla kulesi, iskelet tuzak, zehir büyüsü</td>
144
- </tr>
145
- <tr>
146
- <td>Balo</td>
147
- <td>Savunma binalarına karşı etkili, çok hasar verebilir</td>
148
- <td>Hava savunması, hava mayını, kartal topu</td>
149
- </tr>
150
- <tr>
151
- <td>Büyücü</td ><td>Geniş alana saldırabilir, çok hasar verebilir</td ><td>Bomba, yay kulesi, hava süpürgesi</td ></tr ><tr ><td>Dev iskelet</td ><td>Duvarları kolayca yıkabilir, öldüğünde bomba patlatır</td ><td>Savunma binaları, iskelet tuzak, zehir büyüsü</td ></tr ></table>
152
- <h2>Sonuç</h2>
153
- <p>Son sürüm clash of clans apk indirerek oyunu daha da eğlenceli hale getirebilirsiniz. Bu yazıda, son sürüm clash of clans apk indirmenin nasıl yapıldığını, neden yapmanız gerektiğini ve bunun size ne gibi faydalar sağlayacağını anlattık. Ayrıca, oyunun özelliklerini, avantajlarını ve ipuçlarını da paylaştık. Son sürüm clash of clans apk ile oyunun keyfini çıkarın ve rakiplerinizi alt edin. İyi oyunlar!</p>
154
- <h2>Sık Sorulan Sorular</h2>
155
- <p>Son sürüm clash of clans apk ile ilgili sık sorulan sorular şunlardır:</p>
156
- <ol>
157
- <li>Son sürüm clash of clans apk indirmek ücretli mi?</li>
158
- <p>Cevap: Hayır, son sürüm clash of clans apk indirmek ücretsizdir. Ancak, indirdiğiniz siteye bağlı olarak bazı reklamlar veya anketler görebilirsiniz.</p>
159
- <li>Son sürüm clash of clans apk indirmek cihazımı bozar mı?</li>
160
- <p>Cevap: Hayır, son sürüm clash of clans apk indirmek cihazınıza zarar vermez. Ancak, indirdiğiniz dosyanın güvenli olduğundan emin olmanız ve cihazınızda yeterli depolama alanı olduğundan emin olmanız gerekir.</p>
161
- <li>Son sürüm clash of clans apk indirmek oyunumun verilerini siler mi?</li>
162
- <p>Cevap: Hayır, son sürüm clash of clans apk indirmek oyunun verilerini silmez. Ancak, oyunun resmi versiyonu ile uyumlu olmayabilir. Bu durumda, oyununuzun yedeğini almanız ve oyunun resmi versiyonunu indirmeniz gerekir.</p>
163
- <li>Son sürüm clash of clans apk indirmek bana ban sebebi olur mu?</li>
164
- <p>Cevap: Evet, son sürüm clash of clans apk indirmek bana ban sebebi olabilir. Çünkü, oyunun resmi olmayan bir versiyonunu kullanmak oyunun kurallarına aykırıdır. Bu nedenle, oyunun geliştiricisi Supercell tarafından hesabınızın banlanması veya silinmesi riskiyle karşı karşıya kalabilirsiniz.</p>
165
- <li>Son sürüm clash of clans apk indirmek oyunu daha kolay yapar mı?</li>
166
- <p>Cevap: Hayır, son sürüm clash of clans apk indirmek oyunu daha kolay yapmaz. Çünkü, oyunun zorluğu sizin seviyenize, rakiplerinize ve stratejinize bağlıdır. Son sürüm clash of clans apk indirmek sadece oyunu daha güncel ve daha eğlenceli hale getirir.</p>
167
- </ol></p> 197e85843d<br />
168
- <br />
169
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/CarX Drift Racing APK 1.21.1 - Customize Your Car and Compete with Other Players Online.md DELETED
@@ -1,131 +0,0 @@
1
-
2
- <h1>CarX Drift Racing APK 1.21.1: A Review</h1>
3
- <p>If you are a fan of racing games, especially drifting games, you might want to check out CarX Drift Racing APK 1.21.1, the latest version of one of the most popular and realistic drifting games on Android devices. In this article, we will review CarX Drift Racing APK 1.21.1 and tell you everything you need to know about this game, including its features, gameplay, graphics, pros and cons, and how to download and install it on your device.</p>
4
- <h2>Introduction</h2>
5
- <h3>What is CarX Drift Racing?</h3>
6
- <p>CarX Drift Racing is a 3D driving game developed by CarX Technologies, a company that specializes in creating realistic car physics and simulation games. CarX Drift Racing was first released in 2014 and has since gained millions of fans and downloads worldwide. The game is designed to give you the ultimate drifting experience, with realistic car physics, stunning graphics, and various game modes and tracks to choose from.</p>
7
- <h2>carx drift racing apk 1.21.1</h2><br /><p><b><b>Download File</b> >>> <a href="https://jinyurl.com/2uNOzo">https://jinyurl.com/2uNOzo</a></b></p><br /><br />
8
- <h3>What are the features of CarX Drift Racing APK 1.21.1?</h3>
9
- <p>CarX Drift Racing APK 1.21.1 is the latest version of the game that was released in June 2023. It comes with some new features and improvements that make the game more enjoyable and challenging, such as:</p>
10
- <ul>
11
- <li>A new track called "Tokyo Night" that lets you drift in the neon-lit streets of Japan.</li>
12
- <li>A new car pack that includes four new cars: Nissan Skyline GT-R R34, Toyota Supra MK4, Mazda RX-7 FD, and Subaru Impreza WRX STI.</li>
13
- <li>A new game mode called "Drift Wars" that pits you against other players online in a drift battle.</li>
14
- <li>A new feature called "Car Customization" that allows you to modify your car's appearance, performance, and tuning.</li>
15
- <li>A new feature called "Replay Mode" that lets you watch your best drifts from different angles and share them with your friends.</li>
16
- <li>Improved graphics, sound effects, and user interface.</li>
17
- <li>Bug fixes and stability improvements.</li>
18
- </ul>
19
- <h2>Gameplay and Graphics</h2>
20
- <h3>How to play CarX Drift Racing?</h3>
21
- <p>The gameplay of CarX Drift Racing is simple but addictive. Your main objective is not to cross the finish line before everyone else but to get as many points as you can by drifting like crazy. The more you drift, the more points you earn, but also the more tires you wear out. You can control your car using either tilt or touch controls, depending on your preference. You can also adjust the sensitivity and steering angle of your car to suit your driving style.</p>
22
- <h3>What are the game modes and tracks in CarX Drift Racing?</h3>
23
- <p>CarX Drift Racing offers several game modes and tracks to keep you entertained for hours. The game modes include:</p>
24
- <ul>
25
- <li>"Career Mode" where you can complete various missions and challenges to unlock new cars, tracks, and upgrades.</li>
26
- <li>"Multiplayer Mode" where you can compete with other players online in real-time or join a drift club and challenge other clubs.</li>
27
- <li>"Drift Wars Mode" where you can show off your drifting skills and earn respect from other players in a drift battle.</li>
28
- </ul>
29
- <p>The tracks in CarX Drift Racing are diverse and realistic, ranging from asphalt to snow, from city streets to desert roads, from day to night. Some of the tracks include:</p>
30
- <ul>
31
- <li>"Training Base" where you can learn the basics of drifting and test your car's performance.</li>
32
- <li>"Parking Lot" where you can practice your drifting techniques and tricks in a spacious area.</li>
33
- <li>"San Palezzo" where you can drift along the coast and enjoy the scenic view of the sea.</li>
34
- <li>"Red Rock" where you can drift on a dusty road surrounded by red rocks and cacti.</li>
35
- <li>"Tokyo Night" where you can drift in the neon-lit streets of Japan and feel the atmosphere of the city.</li>
36
- </ul>
37
- <h3>How are the graphics and sound effects in CarX Drift Racing?</h3>
38
- <p>The graphics and sound effects in CarX Drift Racing are impressive and immersive, making you feel like you are really driving a car and drifting on the road. The graphics are detailed and smooth, with realistic shadows, reflections, smoke, and sparks. The cars are modeled after real-life vehicles, with accurate proportions, colors, and designs. The sound effects are also realistic and dynamic, with engine noises, tire screeches, collisions, and crowd cheers. You can also choose from a variety of music tracks to suit your mood and style.</p>
39
- <h2>Pros and Cons</h2>
40
- <h3>What are the advantages of CarX Drift Racing APK 1.21.1?</h3>
41
- <p>CarX Drift Racing APK 1.21.1 has many advantages that make it one of the best drifting games on Android devices, such as:</p>
42
- <ul>
43
- <li>It is free to download and play, with optional in-app purchases for extra features and content.</li>
44
- <li>It has realistic and fun gameplay, with smooth controls, physics-based car behavior, and various game modes and tracks.</li>
45
- <li>It has stunning graphics and sound effects, with high-quality visuals, animations, and sounds.</li>
46
- <li>It has a lot of customization options, with over 40 cars to choose from, hundreds of parts and accessories to modify your car's appearance, performance, and tuning.</li>
47
- <li>It has a social aspect, with online multiplayer mode, drift clubs, leaderboards, chat rooms, and replay mode.</li>
48
- </ul>
49
- <h3>What are the disadvantages of CarX Drift Racing APK 1.21.1?</h3>
50
- <p>CarX Drift Racing APK 1.21.1 also has some disadvantages that might affect your enjoyment of the game, such as:</p>
51
- <p>carx drift racing mod apk 1.21.1 unlimited money<br />
52
- carx drift racing 2 apk 1.21.1 download<br />
53
- carx drift racing apk 1.21.1 obb<br />
54
- carx drift racing hack apk 1.21.1<br />
55
- carx drift racing apk 1.21.1 free download<br />
56
- carx drift racing apk 1.21.1 latest version<br />
57
- carx drift racing apk 1.21.1 android<br />
58
- carx drift racing apk 1.21.1 offline<br />
59
- carx drift racing apk 1.21.1 revdl<br />
60
- carx drift racing apk 1.21.1 rexdl<br />
61
- carx drift racing apk 1.21.1 data<br />
62
- carx drift racing apk 1.21.1 full<br />
63
- carx drift racing apk 1.21.1 mega mod<br />
64
- carx drift racing apk 1.21.1 unlimited gold and coins<br />
65
- carx drift racing apk 1.21.1 no root<br />
66
- carx drift racing apk 1.21.1 update<br />
67
- carx drift racing apk 1.21.1 gameplay<br />
68
- carx drift racing apk 1.21.1 features<br />
69
- carx drift racing apk 1.21.1 review<br />
70
- carx drift racing apk 1.21.1 cheats<br />
71
- carx drift racing apk 1.21.1 tips and tricks<br />
72
- carx drift racing apk 1.21.1 best cars<br />
73
- carx drift racing apk 1.21.1 online multiplayer<br />
74
- carx drift racing apk 1.21.1 customizations<br />
75
- carx drift racing apk 1.21.1 graphics settings<br />
76
- carx drift racing apk 1.21.1 system requirements<br />
77
- carx drift racing apk 1.21.1 installation guide<br />
78
- carx drift racing apk 1.21.1 how to play<br />
79
- carx drift racing apk 1.21.1 tutorial<br />
80
- carx drift racing apk 1.21.1 controller support<br />
81
- carx drift racing apk 1.21.1 soundtracks<br />
82
- carx drift racing apk 1.21.1 wallpapers<br />
83
- carx drift racing apk 1.21.1 screenshots<br />
84
- carx drift racing apk 1.21.1 videos<br />
85
- carx drift racing apk 1.21.1 trailer<br />
86
- carx drift racing apk 1.21.1 news and updates<br />
87
- carx drift racing apk 1.21.1 bugs and fixes<br />
88
- carx drift racing apk 1.21.</p>
89
- <ul>
90
- <li>It requires a lot of storage space on your device, as it is a large file that takes up about 600 MB of memory.</li>
91
- <li>It requires a stable internet connection for some features, such as multiplayer mode, drift wars mode, and online updates.</li>
92
- <li>It can be challenging and frustrating for beginners, as it requires a lot of practice and skill to master drifting and earn points.</li>
93
- <li>It can be repetitive and boring for some players, as it does not have a lot of variety or story in its gameplay.</li>
94
- <li>It can be expensive for some players, as it has a lot of in-app purchases that might tempt you to spend real money on coins, golds, or premium cars.</li>
95
- </ul>
96
- <h2>How to download and install CarX Drift Racing APK 1.21.1?</h2>
97
- <h3>Step-by-step guide for downloading and installing CarX Drift Racing APK 1.21.1</h3>
98
- <p>If you want to download and install CarX Drift Racing APK 1.21.1 on your Android device, you can follow these simple steps:</p>
99
- <ol>
100
- <li>Go to [this link] to download the CarX Drift Racing APK 1.21.1 file on your device.</li>
101
- <li>Once the download is complete, locate the file in your device's file manager or downloads folder.</li>
102
- <li>Tap on the file to start the installation process. You might need to enable "Unknown Sources" in your device's settings to allow the installation of apps from sources other than Google Play Store.</li>
103
- <li>Follow the instructions on the screen to complete the installation process.</li>
104
- <h3>Tips and tricks for playing CarX Drift Racing APK 1.21.1</h3>
105
- <p>If you want to improve your drifting skills and get more points in CarX Drift Racing APK 1.21.1, you can follow these tips and tricks:</p>
106
- <ul>
107
- <li>Choose the right car for your drifting style. Different cars have different characteristics, such as speed, acceleration, handling, and driftability. You can compare the stats of each car and test them on different tracks to find the one that suits you best.</li>
108
- <li>Upgrade and tune your car to optimize its performance. You can use coins and golds to buy new parts and accessories for your car, such as tires, engines, brakes, suspensions, and turbos. You can also adjust the tuning of your car, such as camber, toe, caster, differential, and gearbox, to change its behavior on the road.</li>
109
- <li>Use the handbrake and the throttle wisely. The handbrake is useful for initiating and maintaining drifts, while the throttle is useful for controlling the speed and angle of your drifts. You can also use the clutch kick and the weight shift techniques to enhance your drifts.</li>
110
- <li>Practice on different tracks and game modes. The more you practice, the more you will learn how to drift on different surfaces, curves, and obstacles. You can also try different game modes and challenges to test your skills and earn more rewards.</li>
111
- <li>Watch replays and learn from other players. You can watch your own replays or other players' replays to analyze your mistakes and improve your techniques. You can also join a drift club or a drift war to learn from other players and compete with them.</li>
112
- </ul>
113
- <h2>Conclusion</h2>
114
- <h3>Summary of the main points and recommendations</h3>
115
- <p>CarX Drift Racing APK 1.21.1 is a great drifting game that offers realistic and fun gameplay, stunning graphics and sound effects, a lot of customization options, and a social aspect. It is free to download and play, but it also has some drawbacks, such as requiring a lot of storage space and internet connection, being challenging and frustrating for beginners, being repetitive and boring for some players, and being expensive for some players. If you are looking for a drifting game that will give you the ultimate drifting experience, you should give CarX Drift Racing APK 1.21.1 a try.</p>
116
- <h4>FAQs</h4>
117
- <p>Here are some frequently asked questions about CarX Drift Racing APK 1.21.1:</p>
118
- <ol>
119
- <li>Is CarX Drift Racing APK 1.21.1 safe to download and install?</li>
120
- <p>Yes, CarX Drift Racing APK 1.21.1 is safe to download and install, as long as you download it from a trusted source like [this link]. However, you should always be careful when downloading any APK file from unknown sources, as they might contain viruses or malware that could harm your device.</p>
121
- <li>How can I get more coins and golds in CarX Drift Racing APK 1.21.1?</li>
122
- <p>You can get more coins and golds in CarX Drift Racing APK 1.21.1 by completing missions and challenges in career mode, winning races in multiplayer mode or drift wars mode, watching ads or videos in exchange for rewards, or buying them with real money through in-app purchases.</p>
123
- <li>How can I join a drift club or a drift war in CarX Drift Racing APK 1.21.1?</li>
124
- <p>You can join a drift club or a drift war in CarX Drift Racing APK 1.21.1 by going to the multiplayer mode menu and selecting the drift club or drift war option. You can either join an existing club or war or create your own one.</p>
125
- <li>How can I share my replays with my friends in CarX Drift Racing APK 1.21.1?</li>
126
- <p>You can share your replays with your friends in CarX Drift Racing APK 1.21.1 by going to the replay mode menu and selecting the share option. You can either share your replays via social media platforms like Facebook or Instagram or via messaging apps like WhatsApp or Telegram.</p>
127
- <li>How can I contact the developers of CarX Drift Racing APK 1.21.1?</li>
128
- <p>You can contact the developers of CarX Drift Racing APK 1.21.1 by going to the settings menu and selecting the support option. You can either send them an email or visit their website or social media pages.</p>
129
- </ol></p> 197e85843d<br />
130
- <br />
131
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download NIC VPN Beta 6.0 APK for Android - Free and Unlimited DNS.md DELETED
@@ -1,155 +0,0 @@
1
-
2
- <h1>NIC VPN Beta 6 APK Download: What You Need to Know</h1>
3
- <p>If you are looking for a way to bypass geo-restrictions, access blocked websites, and protect your online privacy, you might have come across NIC VPN Beta 6 APK. This is a VPN app that claims to offer fast and secure connections for Android devices. But is it safe to use? What are the features and benefits of NIC VPN Beta 6 APK? How can you download and install it on your device? And how does it compare to other VPN services in the market? In this article, we will answer these questions and more, so you can make an informed decision about whether to use NIC VPN Beta 6 APK or not.</p>
4
- <h2>nic vpn beta 6 apk download</h2><br /><p><b><b>Download Zip</b> &#128279; <a href="https://jinyurl.com/2uNRrX">https://jinyurl.com/2uNRrX</a></b></p><br /><br />
5
- <h2>What is NIC VPN Beta 6 APK?</h2>
6
- <p>NIC VPN Beta 6 APK is an app that allows you to connect to a virtual private network (VPN) on your Android device. A VPN is a service that encrypts your internet traffic and routes it through a server in another location, hiding your IP address and location from prying eyes. This way, you can access websites and services that are otherwise blocked or restricted in your region, such as Netflix, YouTube, Facebook, etc. You can also protect your online privacy from hackers, ISPs, advertisers, and government agencies that might try to monitor or collect your data.</p>
7
- <h3>Features and benefits of NIC VPN Beta 6 APK</h3>
8
- <p>According to its official website, NIC VPN Beta 6 APK offers the following features and benefits:</p>
9
- <ul>
10
- <li>It is free to download and use, with no registration or subscription required.</li>
11
- <li>It supports multiple protocols, such as OpenVPN, WireGuard, IKEv2, etc.</li>
12
- <li>It has a large network of servers in over 50 countries.</li>
13
- <li>It provides unlimited bandwidth and speed.</li>
14
- <li>It has a simple and user-friendly interface.</li>
15
- <li>It works with all Android devices running Android 4.0 or higher.</li>
16
- </ul>
17
- <h3>How to download and install NIC VPN Beta 6 APK</h3>
18
- <p>To download and install NIC VPN Beta 6 APK on your Android device, you need to follow these steps:</p>
19
- <ol>
20
- <li>Go to the official website of NIC VPN Beta 6 APK and click on the download button.</li>
21
- <li>Once the download is complete, locate the APK file on your device and tap on it.</li>
22
- <li>If you see a warning message that says "Install blocked", go to your device settings and enable "Unknown sources" under security options.</li>
23
- <li>Tap on "Install" and wait for the installation process to finish.</li>
24
- <li>Launch the app and select a server location from the list.</li>
25
- <li>Tap on "Connect" and enjoy using NIC VPN Beta 6 APK.</li>
26
- </ol>
27
- <h2>What are the risks of using NIC VPN Beta 6 APK?</h2>
28
- <p>While NIC VPN Beta 6 APK might seem like a convenient and easy way to access blocked websites and protect your online privacy, there are some risks involved in using it. Here are some of the potential dangers of using NIC VPN Beta 6 APK:</p>
29
- <h3>Malware and phishing attacks</h3>
30
- <p>NIC VPN Beta 6 APK is not available on the official Google Play Store, which means that it has not been verified by Google for its safety and quality. This means that there is a possibility that the app might contain malware or viruses that could harm your device or steal your data. Moreover, since the app does not require any registration or subscription, there is no way to verify the identity or credibility of the app developer. This means that you might be exposed to phishing attacks or scams that could trick you into revealing your personal or financial information.</p>
31
- <p>nic vpn beta 6 apk free download<br />
32
- nic vpn beta 6 apk latest version<br />
33
- nic vpn beta 6 apk for android<br />
34
- nic vpn beta 6 apk mod<br />
35
- nic vpn beta 6 apk cracked<br />
36
- nic vpn beta 6 apk premium<br />
37
- nic vpn beta 6 apk unlimited<br />
38
- nic vpn beta 6 apk pro<br />
39
- nic vpn beta 6 apk full<br />
40
- nic vpn beta 6 apk no ads<br />
41
- nic vpn beta 6 apk fast dns<br />
42
- nic vpn beta 6 apk secure connection<br />
43
- nic vpn beta 6 apk unblock sites<br />
44
- nic vpn beta 6 apk bypass firewall<br />
45
- nic vpn beta 6 apk change ip<br />
46
- nic vpn beta 6 apk hide identity<br />
47
- nic vpn beta 6 apk anonymous browsing<br />
48
- nic vpn beta 6 apk protect privacy<br />
49
- nic vpn beta 6 apk encrypt data<br />
50
- nic vpn beta 6 apk high speed<br />
51
- nic vpn beta 6 apk low latency<br />
52
- nic vpn beta 6 apk stable performance<br />
53
- nic vpn beta 6 apk easy to use<br />
54
- nic vpn beta 6 apk user friendly<br />
55
- nic vpn beta 6 apk simple interface<br />
56
- nic vpn beta 6 apk no registration<br />
57
- nic vpn beta 6 apk no login<br />
58
- nic vpn beta 6 apk no root<br />
59
- nic vpn beta 6 apk no subscription<br />
60
- nic vpn beta 6 apk no bandwidth limit<br />
61
- nic vpn beta 6 apk support multiple servers<br />
62
- nic vpn beta 6 apk support multiple protocols<br />
63
- nic vpn beta 6 apk support multiple devices<br />
64
- nic vpn beta 6 apk support multiple platforms<br />
65
- nic vpn beta 6 apk compatible with android phone and tablet[^1^]<br />
66
- nic vpn beta 6 apk updated for android os[^1^]<br />
67
- nic vpn beta 6 apk download link[^1^]<br />
68
- nic vpn beta 6 apk download from google play store[^1^]<br />
69
- nic vpn beta 6 apk download from official website[^1^]<br />
70
- nic vpn beta 6 apk download from third party sources[^1^]<br />
71
- how to download and install nic vpn beta 6 apk[^1^]<br />
72
- how to use and configure nic vpn beta 6 apk[^1^]<br />
73
- how to troubleshoot and fix nic vpn beta 6 apk issues[^1^]<br />
74
- how to update and upgrade nic vpn beta 6 apk[^1^]<br />
75
- how to uninstall and remove nic vpn beta 6 apk[^1^]<br />
76
- what are the features and benefits of nic vpn beta 6 apk[^1^]<br />
77
- what are the requirements and specifications of nic vpn beta 6 apk[^1^]<br />
78
- what are the reviews and ratings of nic vpn beta 6 apk[^1^]<br />
79
- what are the alternatives and competitors of nic vpn beta 6 apk[^1^]</p>
80
- <h3>Data and bandwidth throttling</h3>
81
- <p>Another risk of using NIC VPN Beta 6 APK is that it might not provide the unlimited bandwidth and speed that it claims. Since the app is free to use, it might rely on ads or third-party sponsors to generate revenue. This means that the app might inject ads or pop-ups into your browsing sessions, which could slow down your connection or interfere with your user experience. Moreover, the app might also throttle your data or bandwidth usage, especially during peak hours or when you access high-demand websites or services. This could affect your streaming quality, gaming performance, or download speed.</p>
82
- <h3>Legal and ethical issues</h3>
83
- <p>Finally, using NIC VPN Beta 6 APK might also involve some legal and ethical issues. Depending on your location and the websites or services that you access, you might be violating some laws or regulations that prohibit the use of VPNs or the access of certain content. For example, some countries like China, Iran, Russia, etc. have strict censorship and surveillance policies that ban or block VPNs and other tools that bypass their firewalls. If you are caught using NIC VPN Beta 6 APK in these countries, you might face legal consequences such as fines, arrests, or imprisonment. Moreover, some websites or services like Netflix, Hulu, BBC iPlayer, etc. have geo-restrictions that limit their content availability based on your location. If you use NIC VPN Beta 6 APK to access these websites or services from a different region, you might be violating their terms of service or licensing agreements, which could result in account suspension or termination.</p>
84
- <h2>How to choose a safe and reliable VPN service?</h2>
85
- <p>Given the risks of using NIC VPN Beta 6 APK, you might be wondering how to choose a safe and reliable VPN service that can meet your needs and expectations. Here are some of the factors that you should consider when choosing a VPN service:</p>
86
- <h3>Encryption and protocols</h3>
87
- <p>A good VPN service should provide strong encryption and protocols that can secure your internet traffic and prevent anyone from intercepting or decrypting it. Encryption is the process of converting your data into unreadable code, while protocols are the rules that govern how your data is transmitted and received. Some of the common encryption standards and protocols used by VPNs are AES-256, OpenVPN, WireGuard, IKEv2, etc. You should look for a VPN service that supports these encryption standards and protocols, as they offer the best balance between security and speed.</p>
88
- <h3>No-logs policy and jurisdiction</h3>
89
- <p>A good VPN service should also have a no-logs policy and jurisdiction that can protect your online privacy and anonymity. A no-logs policy means that the VPN service does not collect, store, or share any information about your online activities, such as your IP address, browsing history, bandwidth usage, etc. A jurisdiction means that the VPN service is based in a country that has favorable privacy laws and does not cooperate with any surveillance alliances or authorities that might request your data. Some of the countries that have good privacy jurisdictions are Switzerland, Panama, Romania, etc. You should look for a VPN service that has a no-logs policy and jurisdiction, as they can ensure that your data is not exposed or compromised.</p>
90
- <h3>Speed and performance</h3>
91
- <p>A good VPN service should also provide fast and consistent speed and performance that can enhance your user experience. Speed and performance depend on various factors such as server location, server load, encryption level, protocol type, etc. A good VPN service should have a large network of servers in various locations around the world, so you can choose the one that is closest to you or the one that offers the best connection for your desired website or service. A good VPN service should also have a low server load and a high encryption level, so you can enjoy a smooth and secure connection without any lag or buffering. A good VPN service should also support various protocol types, so you can choose the one that suits your needs and preferences. For example, OpenVPN is the most secure and versatile protocol, but it might be slower than WireGuard, which is the fastest and most modern protocol, but it might be less compatible with some devices or platforms.</p>
92
- <h3>Customer support and reviews</h3>
93
- <p>A good VPN service should also have a responsive and helpful customer support and positive reviews from users and experts. Customer support is important because you might encounter some issues or questions while using the VPN service, such as installation, configuration, troubleshooting, etc. A good VPN service should have a 24/7 live chat, email, phone, or ticket support system that can assist you with any problems or inquiries. A good VPN service should also have positive reviews from users and experts that can attest to its quality and reliability. You should look for a VPN service that has a high rating and a good reputation on various platforms such as Google Play Store, App Store, Trustpilot, Reddit, etc.</p>
94
- <h2>Comparison table of the top VPN services in 2023</h2>
95
- <p>To help you choose a safe and reliable VPN service, we have created a comparison table of the top VPN services in 2023 based on the factors that we have discussed above. Here is the table:</p>
96
- <table>
97
- <tr>
98
- <th>VPN Service</th>
99
- <th>Encryption and Protocols</th>
100
- <th>No-Logs Policy and Jurisdiction</th>
101
- <th>Speed and Performance</th>
102
- <th>Customer Support and Reviews</th>
103
- </tr>
104
- <tr>
105
- <td>NordVPN</td>
106
- <td>AES-256, OpenVPN, WireGuard, IKEv2</td>
107
- <td>Yes, Panama</td>
108
- <td>5,400+ servers in 59 countries, unlimited bandwidth and speed</td>
109
- <td>24/7 live chat, email, phone, ticket; 4.4/5 on Google Play Store, 4.6/5 on App Store, 4.5/5 on Trustpilot</td>
110
- </tr>
111
- <tr>
112
- <td>ExpressVPN</td>
113
- <td>AES-256, OpenVPN, WireGuard, IKEv2</td>
114
- <td>Yes, British Virgin Islands</td>
115
- <td>3,000+ servers in 94 countries, unlimited bandwidth and speed</td>
116
- <td>24/7 live chat, email; 4.1/5 on Google Play Store, 4.6/5 on App Store, 4.7/5 on Trustpilot</td>
117
- </tr>
118
- <tr>
119
- <td>Surfshark</td>
120
- <td>AES-256, OpenVPN, WireGuard, IKEv2</td>
121
- <td>Yes, British Virgin Islands</td>
122
- <td>3,200+ servers in 65 countries, unlimited bandwidth and speed</td>
123
- <td>24/7 live chat, email; 4.3/5 on Google Play Store, 4.4/5 on App Store, 4.3/5 on Trustpilot</td>
124
- </tr>
125
- <tr>
126
- <td>CyberGhost</td>
127
- <td>AES-256, OpenVPN, WireGuard, IKEv2</td>
128
- <td>Yes, Romania</td>
129
- <td>7,000+ servers in 90 countries, unlimited bandwidth and speed</td>
130
- <td>24/7 live chat, email, phone, ticket; 4.1/5 on Google Play Store, 4.2/5 on App Store, 4.8/5 on Trustpilot</td>
131
- </tr>
132
- <tr>
133
- <td>IPVanish</td>
134
- <td>AES-256, OpenVPN, WireGuard, IKEv2</td>
135
- <td>Yes, USA</td>
136
- <td>1,600+ servers in 75+ countries, unlimited bandwidth and speed</td>
137
- <td>24/7 live chat, email; 4.0/5 on Google Play Store, 4.5/5 on App Store, 4.7/5 on Trustpilot</td>
138
- </tr>
139
- </table>
140
- <h2>Conclusion</h2>
141
- <p>NIC VPN Beta 6 APK is a VPN app that claims to offer fast and secure connections for Android devices. However, it also comes with some risks and drawbacks, such as malware and phishing attacks, data and bandwidth throttling, and legal and ethical issues. Therefore, we do not recommend using NIC VPN Beta 6 APK for your online security and privacy needs. Instead, we suggest choosing a safe and reliable VPN service that can provide strong encryption and protocols, no-logs policy and jurisdiction, speed and performance, and customer support and reviews. Some of the top VPN services in 2023 are NordVPN, ExpressVPN, Surfshark, CyberGhost, and IPVanish. You can compare them using the table above and choose the one that suits your needs and preferences.</p>
142
- <h2>FAQs</h2>
143
- <p>Here are some of the frequently asked questions about NIC VPN Beta 6 APK and VPN services:</p>
144
- <h3>Q: Is NIC VPN Beta 6 APK legal?</h3>
145
- <p>A: The legality of NIC VPN Beta 6 APK depends on your location and the websites or services that you access using it. Some countries have laws or regulations that prohibit or restrict the use of VPNs or the access of certain content. If you use NIC VPN Beta 6 APK in these countries or to access these content, you might be breaking the law and face legal consequences.</p>
146
- <h3>Q: Is NIC VPN Beta 6 APK safe?</h3>
147
- <p>A: The safety of NIC VPN Beta 6 APK is not guaranteed, as it is not available on the official Google Play Store and has not been verified by Google for its safety and quality. There is a possibility that the app might contain malware or viruses that could harm your device or steal your data. Moreover, the app might also expose you to phishing attacks or scams that could trick you into revealing your personal or financial information.</p>
148
- <h3>Q: Is NIC VPN Beta 6 APK free?</h3>
149
- <p>A: Yes, NIC VPN Beta 6 APK is free to download and use, with no registration or subscription required. However, this also means that the app might rely on ads or third-party sponsors to generate revenue, which could affect your user experience and connection quality.</p>
150
- <h3>Q: What are the alternatives to NIC VPN Beta 6 APK?</h3>
151
- <p>A: Some of the alternatives to NIC VPN Beta 6 APK are NordVPN, ExpressVPN, Surfshark, CyberGhost, and IPVanish. These are some of the best VPN services in 2023 that can provide you with a safe and reliable online security and privacy solution.</p>
152
- <h3>Q: How can I download NIC VPN Beta 6 APK?</h3>
153
- <p>A: To download NIC VPN Beta 6 APK, you need to go to its official website and click on the download button. Then, you need to locate the APK file on your device and tap on it. If you see a warning message that says "Install blocked", you need to go to your device settings and enable "Unknown sources" under security options. Then, you need to tap on "Install" and wait for the installation process to finish. After that, you can launch the app and select a server location from the list.</p> 197e85843d<br />
154
- <br />
155
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/2ndelement/voicevox/voicevox_engine/part_of_speech_data.py DELETED
@@ -1,144 +0,0 @@
1
- from typing import Dict
2
-
3
- from .model import (
4
- USER_DICT_MAX_PRIORITY,
5
- USER_DICT_MIN_PRIORITY,
6
- PartOfSpeechDetail,
7
- WordTypes,
8
- )
9
-
10
- MIN_PRIORITY = USER_DICT_MIN_PRIORITY
11
- MAX_PRIORITY = USER_DICT_MAX_PRIORITY
12
-
13
- part_of_speech_data: Dict[WordTypes, PartOfSpeechDetail] = {
14
- WordTypes.PROPER_NOUN: PartOfSpeechDetail(
15
- part_of_speech="名詞",
16
- part_of_speech_detail_1="固有名詞",
17
- part_of_speech_detail_2="一般",
18
- part_of_speech_detail_3="*",
19
- context_id=1348,
20
- cost_candidates=[
21
- -988,
22
- 3488,
23
- 4768,
24
- 6048,
25
- 7328,
26
- 8609,
27
- 8734,
28
- 8859,
29
- 8984,
30
- 9110,
31
- 14176,
32
- ],
33
- accent_associative_rules=[
34
- "*",
35
- "C1",
36
- "C2",
37
- "C3",
38
- "C4",
39
- "C5",
40
- ],
41
- ),
42
- WordTypes.COMMON_NOUN: PartOfSpeechDetail(
43
- part_of_speech="名詞",
44
- part_of_speech_detail_1="一般",
45
- part_of_speech_detail_2="*",
46
- part_of_speech_detail_3="*",
47
- context_id=1345,
48
- cost_candidates=[
49
- -4445,
50
- 49,
51
- 1473,
52
- 2897,
53
- 4321,
54
- 5746,
55
- 6554,
56
- 7362,
57
- 8170,
58
- 8979,
59
- 15001,
60
- ],
61
- accent_associative_rules=[
62
- "*",
63
- "C1",
64
- "C2",
65
- "C3",
66
- "C4",
67
- "C5",
68
- ],
69
- ),
70
- WordTypes.VERB: PartOfSpeechDetail(
71
- part_of_speech="動詞",
72
- part_of_speech_detail_1="自立",
73
- part_of_speech_detail_2="*",
74
- part_of_speech_detail_3="*",
75
- context_id=642,
76
- cost_candidates=[
77
- 3100,
78
- 6160,
79
- 6360,
80
- 6561,
81
- 6761,
82
- 6962,
83
- 7414,
84
- 7866,
85
- 8318,
86
- 8771,
87
- 13433,
88
- ],
89
- accent_associative_rules=[
90
- "*",
91
- ],
92
- ),
93
- WordTypes.ADJECTIVE: PartOfSpeechDetail(
94
- part_of_speech="形容詞",
95
- part_of_speech_detail_1="自立",
96
- part_of_speech_detail_2="*",
97
- part_of_speech_detail_3="*",
98
- context_id=20,
99
- cost_candidates=[
100
- 1527,
101
- 3266,
102
- 3561,
103
- 3857,
104
- 4153,
105
- 4449,
106
- 5149,
107
- 5849,
108
- 6549,
109
- 7250,
110
- 10001,
111
- ],
112
- accent_associative_rules=[
113
- "*",
114
- ],
115
- ),
116
- WordTypes.SUFFIX: PartOfSpeechDetail(
117
- part_of_speech="名詞",
118
- part_of_speech_detail_1="接尾",
119
- part_of_speech_detail_2="一般",
120
- part_of_speech_detail_3="*",
121
- context_id=1358,
122
- cost_candidates=[
123
- 4399,
124
- 5373,
125
- 6041,
126
- 6710,
127
- 7378,
128
- 8047,
129
- 9440,
130
- 10834,
131
- 12228,
132
- 13622,
133
- 15847,
134
- ],
135
- accent_associative_rules=[
136
- "*",
137
- "C1",
138
- "C2",
139
- "C3",
140
- "C4",
141
- "C5",
142
- ],
143
- ),
144
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/2ndelement/voicevox/voicevox_engine/synthesis_engine/core_wrapper.py DELETED
@@ -1,538 +0,0 @@
1
- import os
2
- import platform
3
- from ctypes import CDLL, POINTER, c_bool, c_char_p, c_float, c_int, c_long
4
- from ctypes.util import find_library
5
- from dataclasses import dataclass
6
- from enum import Enum, auto
7
- from pathlib import Path
8
- from typing import List, Optional
9
-
10
- import numpy as np
11
-
12
-
13
- class OldCoreError(Exception):
14
- """古いコアが使用されている場合に発生するエラー"""
15
-
16
-
17
- class CoreError(Exception):
18
- """コア呼び出しで発生したエラー"""
19
-
20
-
21
- def load_runtime_lib(runtime_dirs: List[Path]):
22
- if platform.system() == "Windows":
23
- # DirectML.dllはonnxruntimeと互換性のないWindows標準搭載のものを優先して読み込むことがあるため、明示的に読み込む
24
- # 参考 1. https://github.com/microsoft/onnxruntime/issues/3360
25
- # 参考 2. https://tadaoyamaoka.hatenablog.com/entry/2020/06/07/113616
26
- lib_file_names = [
27
- "torch_cpu.dll",
28
- "torch_cuda.dll",
29
- "DirectML.dll",
30
- "onnxruntime.dll",
31
- ]
32
- lib_names = ["torch_cpu", "torch_cuda", "onnxruntime"]
33
- elif platform.system() == "Linux":
34
- lib_file_names = ["libtorch.so", "libonnxruntime.so"]
35
- lib_names = ["torch", "onnxruntime"]
36
- elif platform.system() == "Darwin":
37
- lib_file_names = ["libonnxruntime.dylib"]
38
- lib_names = ["onnxruntime"]
39
- else:
40
- raise RuntimeError("不明なOSです")
41
- for lib_path in runtime_dirs:
42
- for file_name in lib_file_names:
43
- try:
44
- CDLL(str((lib_path / file_name).resolve(strict=True)))
45
- except OSError:
46
- pass
47
- for lib_name in lib_names:
48
- try:
49
- CDLL(find_library(lib_name))
50
- except (OSError, TypeError):
51
- pass
52
-
53
-
54
- class GPUType(Enum):
55
- # NONEはCPUしか対応していないことを示す
56
- NONE = auto()
57
- CUDA = auto()
58
- DIRECT_ML = auto()
59
-
60
-
61
- @dataclass(frozen=True)
62
- class CoreInfo:
63
- name: str
64
- platform: str
65
- arch: str
66
- core_type: str
67
- gpu_type: GPUType
68
-
69
-
70
- # version 0.12 より前のコアの情報
71
- CORE_INFOS = [
72
- # Windows
73
- CoreInfo(
74
- name="core.dll",
75
- platform="Windows",
76
- arch="x64",
77
- core_type="libtorch",
78
- gpu_type=GPUType.CUDA,
79
- ),
80
- CoreInfo(
81
- name="core_cpu.dll",
82
- platform="Windows",
83
- arch="x64",
84
- core_type="libtorch",
85
- gpu_type=GPUType.NONE,
86
- ),
87
- CoreInfo(
88
- name="core_gpu_x64_nvidia.dll",
89
- platform="Windows",
90
- arch="x64",
91
- core_type="onnxruntime",
92
- gpu_type=GPUType.CUDA,
93
- ),
94
- CoreInfo(
95
- name="core_gpu_x64_directml.dll",
96
- platform="Windows",
97
- arch="x64",
98
- core_type="onnxruntime",
99
- gpu_type=GPUType.DIRECT_ML,
100
- ),
101
- CoreInfo(
102
- name="core_cpu_x64.dll",
103
- platform="Windows",
104
- arch="x64",
105
- core_type="onnxruntime",
106
- gpu_type=GPUType.NONE,
107
- ),
108
- CoreInfo(
109
- name="core_cpu_x86.dll",
110
- platform="Windows",
111
- arch="x86",
112
- core_type="onnxruntime",
113
- gpu_type=GPUType.NONE,
114
- ),
115
- CoreInfo(
116
- name="core_gpu_x86_directml.dll",
117
- platform="Windows",
118
- arch="x86",
119
- core_type="onnxruntime",
120
- gpu_type=GPUType.DIRECT_ML,
121
- ),
122
- CoreInfo(
123
- name="core_cpu_arm.dll",
124
- platform="Windows",
125
- arch="armv7l",
126
- core_type="onnxruntime",
127
- gpu_type=GPUType.NONE,
128
- ),
129
- CoreInfo(
130
- name="core_gpu_arm_directml.dll",
131
- platform="Windows",
132
- arch="armv7l",
133
- core_type="onnxruntime",
134
- gpu_type=GPUType.DIRECT_ML,
135
- ),
136
- CoreInfo(
137
- name="core_cpu_arm64.dll",
138
- platform="Windows",
139
- arch="aarch64",
140
- core_type="onnxruntime",
141
- gpu_type=GPUType.NONE,
142
- ),
143
- CoreInfo(
144
- name="core_gpu_arm64_directml.dll",
145
- platform="Windows",
146
- arch="aarch64",
147
- core_type="onnxruntime",
148
- gpu_type=GPUType.DIRECT_ML,
149
- ),
150
- # Linux
151
- CoreInfo(
152
- name="libcore.so",
153
- platform="Linux",
154
- arch="x64",
155
- core_type="libtorch",
156
- gpu_type=GPUType.CUDA,
157
- ),
158
- CoreInfo(
159
- name="libcore_cpu.so",
160
- platform="Linux",
161
- arch="x64",
162
- core_type="libtorch",
163
- gpu_type=GPUType.NONE,
164
- ),
165
- CoreInfo(
166
- name="libcore_gpu_x64_nvidia.so",
167
- platform="Linux",
168
- arch="x64",
169
- core_type="onnxruntime",
170
- gpu_type=GPUType.CUDA,
171
- ),
172
- CoreInfo(
173
- name="libcore_cpu_x64.so",
174
- platform="Linux",
175
- arch="x64",
176
- core_type="onnxruntime",
177
- gpu_type=GPUType.NONE,
178
- ),
179
- CoreInfo(
180
- name="libcore_cpu_armhf.so",
181
- platform="Linux",
182
- arch="armv7l",
183
- core_type="onnxruntime",
184
- gpu_type=GPUType.NONE,
185
- ),
186
- CoreInfo(
187
- name="libcore_cpu_arm64.so",
188
- platform="Linux",
189
- arch="aarch64",
190
- core_type="onnxruntime",
191
- gpu_type=GPUType.NONE,
192
- ),
193
- # macOS
194
- CoreInfo(
195
- name="libcore_cpu_universal2.dylib",
196
- platform="Darwin",
197
- arch="universal",
198
- core_type="onnxruntime",
199
- gpu_type=GPUType.NONE,
200
- ),
201
- ]
202
-
203
-
204
- # version 0.12 以降のコアの名前の辞書
205
- # - version 0.12, 0.13 のコアの名前: core
206
- # - version 0.14 からのコアの名前: voicevox_core
207
- CORENAME_DICT = {
208
- "Windows": ("voicevox_core.dll", "core.dll"),
209
- "Linux": ("libvoicevox_core.so", "libcore.so"),
210
- "Darwin": ("libvoicevox_core.dylib", "libcore.dylib"),
211
- }
212
-
213
-
214
- def find_version_0_12_core_or_later(core_dir: Path) -> Optional[str]:
215
- """
216
- core_dir で指定したディレクトリにあるコアライブラリが Version 0.12 以降である場合、
217
- 見つかった共有ライブラリの名前を返す。
218
-
219
- Version 0.12 以降と判定する条件は、
220
-
221
- - core_dir に metas.json が存在しない
222
- - コアライブラリの名前が CORENAME_DICT の定義に従っている
223
-
224
- の両方が真のときである。
225
- cf. https://github.com/VOICEVOX/voicevox_engine/issues/385
226
- """
227
- if (core_dir / "metas.json").exists():
228
- return None
229
-
230
- for core_name in CORENAME_DICT[platform.system()]:
231
- if (core_dir / core_name).is_file():
232
- return core_name
233
-
234
- return None
235
-
236
-
237
- def get_arch_name() -> Optional[str]:
238
- """
239
- platform.machine() が特定のアーキテクチャ上で複数パターンの文字列を返し得るので、
240
- 一意な文字列に変換する
241
- サポート外のアーキテクチャである場合、None を返す
242
- """
243
- machine = platform.machine()
244
- if machine == "x86_64" or machine == "x64" or machine == "AMD64":
245
- return "x64"
246
- elif machine == "i386" or machine == "x86":
247
- return "x86"
248
- elif machine == "arm64":
249
- return "aarch64"
250
- elif machine in ["armv7l", "aarch64"]:
251
- return machine
252
- else:
253
- return None
254
-
255
-
256
- def get_core_name(
257
- arch_name: str,
258
- platform_name: str,
259
- model_type: str,
260
- gpu_type: GPUType,
261
- ) -> Optional[str]:
262
- if platform_name == "Darwin":
263
- if gpu_type == GPUType.NONE and (arch_name == "x64" or arch_name == "aarch64"):
264
- arch_name = "universal"
265
- else:
266
- return None
267
- for core_info in CORE_INFOS:
268
- if (
269
- core_info.platform == platform_name
270
- and core_info.arch == arch_name
271
- and core_info.core_type == model_type
272
- and core_info.gpu_type == gpu_type
273
- ):
274
- return core_info.name
275
- return None
276
-
277
-
278
- def get_suitable_core_name(
279
- model_type: str,
280
- gpu_type: GPUType,
281
- ) -> Optional[str]:
282
- arch_name = get_arch_name()
283
- if arch_name is None:
284
- return None
285
- platform_name = platform.system()
286
- return get_core_name(arch_name, platform_name, model_type, gpu_type)
287
-
288
-
289
- def check_core_type(core_dir: Path) -> Optional[str]:
290
- # libtorch版はDirectML未対応なので、ここでは`gpu_type=GPUType.DIRECT_ML`は入れない
291
- libtorch_core_names = [
292
- get_suitable_core_name("libtorch", gpu_type=GPUType.CUDA),
293
- get_suitable_core_name("libtorch", gpu_type=GPUType.NONE),
294
- ]
295
- onnxruntime_core_names = [
296
- get_suitable_core_name("onnxruntime", gpu_type=GPUType.CUDA),
297
- get_suitable_core_name("onnxruntime", gpu_type=GPUType.DIRECT_ML),
298
- get_suitable_core_name("onnxruntime", gpu_type=GPUType.NONE),
299
- ]
300
- if any([(core_dir / name).is_file() for name in libtorch_core_names if name]):
301
- return "libtorch"
302
- elif any([(core_dir / name).is_file() for name in onnxruntime_core_names if name]):
303
- return "onnxruntime"
304
- else:
305
- return None
306
-
307
-
308
- def load_core(core_dir: Path, use_gpu: bool) -> CDLL:
309
- core_name = find_version_0_12_core_or_later(core_dir)
310
- if core_name:
311
- try:
312
- # NOTE: CDLL クラスのコンストラクタの引数 name には文字列を渡す必要がある。
313
- # Windows 環境では PathLike オブジェクトを引数として渡すと初期化に失敗する。
314
- return CDLL(str((core_dir / core_name).resolve(strict=True)))
315
- except OSError as err:
316
- raise RuntimeError(f"コアの読み込みに失敗しました:{err}")
317
-
318
- model_type = check_core_type(core_dir)
319
- if model_type is None:
320
- raise RuntimeError("コアが見つかりません")
321
- if use_gpu or model_type == "onnxruntime":
322
- core_name = get_suitable_core_name(model_type, gpu_type=GPUType.CUDA)
323
- if core_name:
324
- try:
325
- return CDLL(str((core_dir / core_name).resolve(strict=True)))
326
- except OSError:
327
- pass
328
- core_name = get_suitable_core_name(model_type, gpu_type=GPUType.DIRECT_ML)
329
- if core_name:
330
- try:
331
- return CDLL(str((core_dir / core_name).resolve(strict=True)))
332
- except OSError:
333
- pass
334
- core_name = get_suitable_core_name(model_type, gpu_type=GPUType.NONE)
335
- if core_name:
336
- try:
337
- return CDLL(str((core_dir / core_name).resolve(strict=True)))
338
- except OSError as err:
339
- if model_type == "libtorch":
340
- core_name = get_suitable_core_name(model_type, gpu_type=GPUType.CUDA)
341
- if core_name:
342
- try:
343
- return CDLL(str((core_dir / core_name).resolve(strict=True)))
344
- except OSError as err_:
345
- err = err_
346
- raise RuntimeError(f"コアの読み込みに失敗しました:{err}")
347
- else:
348
- raise RuntimeError(f"このコンピュータのアーキテクチャ {platform.machine()} で利用可能なコアがありません")
349
-
350
-
351
- class CoreWrapper:
352
- def __init__(
353
- self,
354
- use_gpu: bool,
355
- core_dir: Path,
356
- cpu_num_threads: int = 0,
357
- load_all_models: bool = False,
358
- ) -> None:
359
-
360
- self.core = load_core(core_dir, use_gpu)
361
-
362
- self.core.initialize.restype = c_bool
363
- self.core.metas.restype = c_char_p
364
- self.core.yukarin_s_forward.restype = c_bool
365
- self.core.yukarin_sa_forward.restype = c_bool
366
- self.core.decode_forward.restype = c_bool
367
- self.core.last_error_message.restype = c_char_p
368
-
369
- self.exist_supported_devices = False
370
- self.exist_finalize = False
371
- exist_cpu_num_threads = False
372
- self.exist_load_model = False
373
- self.exist_is_model_loaded = False
374
-
375
- is_version_0_12_core_or_later = (
376
- find_version_0_12_core_or_later(core_dir) is not None
377
- )
378
- if is_version_0_12_core_or_later:
379
- model_type = "onnxruntime"
380
- self.exist_load_model = True
381
- self.exist_is_model_loaded = True
382
- self.core.load_model.argtypes = (c_long,)
383
- self.core.load_model.restype = c_bool
384
- self.core.is_model_loaded.argtypes = (c_long,)
385
- self.core.is_model_loaded.restype = c_bool
386
- else:
387
- model_type = check_core_type(core_dir)
388
- assert model_type is not None
389
-
390
- if model_type == "onnxruntime":
391
- self.core.supported_devices.restype = c_char_p
392
- self.core.finalize.restype = None
393
- self.exist_supported_devices = True
394
- self.exist_finalize = True
395
- exist_cpu_num_threads = True
396
-
397
- self.core.yukarin_s_forward.argtypes = (
398
- c_int,
399
- POINTER(c_long),
400
- POINTER(c_long),
401
- POINTER(c_float),
402
- )
403
- self.core.yukarin_sa_forward.argtypes = (
404
- c_int,
405
- POINTER(c_long),
406
- POINTER(c_long),
407
- POINTER(c_long),
408
- POINTER(c_long),
409
- POINTER(c_long),
410
- POINTER(c_long),
411
- POINTER(c_long),
412
- POINTER(c_float),
413
- )
414
- self.core.decode_forward.argtypes = (
415
- c_int,
416
- c_int,
417
- POINTER(c_float),
418
- POINTER(c_float),
419
- POINTER(c_long),
420
- POINTER(c_float),
421
- )
422
-
423
- cwd = os.getcwd()
424
- os.chdir(core_dir)
425
- try:
426
- if is_version_0_12_core_or_later:
427
- self.assert_core_success(
428
- self.core.initialize(use_gpu, cpu_num_threads, load_all_models)
429
- )
430
- elif exist_cpu_num_threads:
431
- self.assert_core_success(
432
- self.core.initialize(".", use_gpu, cpu_num_threads)
433
- )
434
- else:
435
- self.assert_core_success(self.core.initialize(".", use_gpu))
436
- finally:
437
- os.chdir(cwd)
438
-
439
- def metas(self) -> str:
440
- return self.core.metas().decode("utf-8")
441
-
442
- def yukarin_s_forward(
443
- self,
444
- length: int,
445
- phoneme_list: np.ndarray,
446
- speaker_id: np.ndarray,
447
- ) -> np.ndarray:
448
- output = np.zeros((length,), dtype=np.float32)
449
- self.assert_core_success(
450
- self.core.yukarin_s_forward(
451
- c_int(length),
452
- phoneme_list.ctypes.data_as(POINTER(c_long)),
453
- speaker_id.ctypes.data_as(POINTER(c_long)),
454
- output.ctypes.data_as(POINTER(c_float)),
455
- )
456
- )
457
- return output
458
-
459
- def yukarin_sa_forward(
460
- self,
461
- length: int,
462
- vowel_phoneme_list: np.ndarray,
463
- consonant_phoneme_list: np.ndarray,
464
- start_accent_list: np.ndarray,
465
- end_accent_list: np.ndarray,
466
- start_accent_phrase_list: np.ndarray,
467
- end_accent_phrase_list: np.ndarray,
468
- speaker_id: np.ndarray,
469
- ) -> np.ndarray:
470
- output = np.empty(
471
- (
472
- len(speaker_id),
473
- length,
474
- ),
475
- dtype=np.float32,
476
- )
477
- self.assert_core_success(
478
- self.core.yukarin_sa_forward(
479
- c_int(length),
480
- vowel_phoneme_list.ctypes.data_as(POINTER(c_long)),
481
- consonant_phoneme_list.ctypes.data_as(POINTER(c_long)),
482
- start_accent_list.ctypes.data_as(POINTER(c_long)),
483
- end_accent_list.ctypes.data_as(POINTER(c_long)),
484
- start_accent_phrase_list.ctypes.data_as(POINTER(c_long)),
485
- end_accent_phrase_list.ctypes.data_as(POINTER(c_long)),
486
- speaker_id.ctypes.data_as(POINTER(c_long)),
487
- output.ctypes.data_as(POINTER(c_float)),
488
- )
489
- )
490
- return output
491
-
492
- def decode_forward(
493
- self,
494
- length: int,
495
- phoneme_size: int,
496
- f0: np.ndarray,
497
- phoneme: np.ndarray,
498
- speaker_id: np.ndarray,
499
- ) -> np.ndarray:
500
- output = np.empty((length * 256,), dtype=np.float32)
501
- self.assert_core_success(
502
- self.core.decode_forward(
503
- c_int(length),
504
- c_int(phoneme_size),
505
- f0.ctypes.data_as(POINTER(c_float)),
506
- phoneme.ctypes.data_as(POINTER(c_float)),
507
- speaker_id.ctypes.data_as(POINTER(c_long)),
508
- output.ctypes.data_as(POINTER(c_float)),
509
- )
510
- )
511
- return output
512
-
513
- def supported_devices(self) -> str:
514
- if self.exist_supported_devices:
515
- return self.core.supported_devices().decode("utf-8")
516
- raise OldCoreError
517
-
518
- def finalize(self) -> None:
519
- if self.exist_finalize:
520
- self.core.finalize()
521
- return
522
- raise OldCoreError
523
-
524
- def load_model(self, speaker_id: int) -> None:
525
- if self.exist_load_model:
526
- self.assert_core_success(self.core.load_model(c_long(speaker_id)))
527
- raise OldCoreError
528
-
529
- def is_model_loaded(self, speaker_id: int) -> bool:
530
- if self.exist_is_model_loaded:
531
- return self.core.is_model_loaded(c_long(speaker_id))
532
- raise OldCoreError
533
-
534
- def assert_core_success(self, result: bool) -> None:
535
- if not result:
536
- raise CoreError(
537
- self.core.last_error_message().decode("utf-8", "backslashreplace")
538
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/4com/SD-XL-CPU/app.py DELETED
@@ -1,172 +0,0 @@
1
- import numpy as np
2
- import gradio as gr
3
- import requests
4
- import time
5
- import json
6
- import base64
7
- import os
8
- from PIL import Image
9
- from io import BytesIO
10
-
11
- class Prodia:
12
- def __init__(self, api_key, base=None):
13
- self.base = base or "https://api.prodia.com/v1"
14
- self.headers = {
15
- "X-Prodia-Key": api_key
16
- }
17
-
18
- def generate(self, params):
19
- response = self._post(f"{self.base}/sdxl/generate", params)
20
- return response.json()
21
-
22
- def get_job(self, job_id):
23
- response = self._get(f"{self.base}/job/{job_id}")
24
- return response.json()
25
-
26
- def wait(self, job):
27
- job_result = job
28
-
29
- while job_result['status'] not in ['succeeded', 'failed']:
30
- time.sleep(0.25)
31
- job_result = self.get_job(job['job'])
32
-
33
- return job_result
34
-
35
- def list_models(self):
36
- response = self._get(f"{self.base}/models/list")
37
- return response.json()
38
-
39
- def _post(self, url, params):
40
- headers = {
41
- **self.headers,
42
- "Content-Type": "application/json"
43
- }
44
- response = requests.post(url, headers=headers, data=json.dumps(params))
45
-
46
- if response.status_code != 200:
47
- raise Exception(f"Bad Prodia Response: {response.status_code}")
48
-
49
- return response
50
-
51
- def _get(self, url):
52
- response = requests.get(url, headers=self.headers)
53
-
54
- if response.status_code != 200:
55
- raise Exception(f"Bad Prodia Response: {response.status_code}")
56
-
57
- return response
58
-
59
-
60
- def image_to_base64(image_path):
61
- # Open the image with PIL
62
- with Image.open(image_path) as image:
63
- # Convert the image to bytes
64
- buffered = BytesIO()
65
- image.save(buffered, format="PNG") # You can change format to PNG if needed
66
-
67
- # Encode the bytes to base64
68
- img_str = base64.b64encode(buffered.getvalue())
69
-
70
- return img_str.decode('utf-8') # Convert bytes to string
71
-
72
-
73
-
74
- prodia_client = Prodia(api_key=os.getenv("PRODIA_API_KEY"))
75
-
76
- def flip_text(prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed):
77
- result = prodia_client.generate({
78
- "prompt": prompt,
79
- "negative_prompt": negative_prompt,
80
- "model": model,
81
- "steps": steps,
82
- "sampler": sampler,
83
- "cfg_scale": cfg_scale,
84
- "width": width,
85
- "height": height,
86
- "seed": seed
87
- })
88
-
89
- job = prodia_client.wait(result)
90
-
91
- return job["imageUrl"]
92
-
93
- css = """
94
- #generate {
95
- height: 100%;
96
- }
97
- """
98
-
99
- with gr.Blocks(css=css, theme="Base") as demo:
100
-
101
-
102
-
103
- with gr.Row():
104
- gr.Markdown("<h1><center>Stable Diffusion XL</center></h1>")
105
- with gr.Tab("Playground"):
106
- with gr.Row():
107
- with gr.Column(scale=6, min_width=600):
108
- prompt = gr.Textbox(label="Prompt", placeholder="beautiful cat, 8k", show_label=True, lines=2)
109
- negative_prompt = gr.Textbox(label="Negative Prompt", value="text, blurry, fuzziness", placeholder="text, blurry, fuzziness", show_label=True, lines=3)
110
- with gr.Column():
111
- text_button = gr.Button("Generate", variant='primary', elem_id="generate")
112
-
113
- with gr.Row():
114
-
115
-
116
-
117
- with gr.Column(scale=2):
118
- image_output = gr.Image()
119
-
120
- with gr.Accordion("Advanced options", open=False):
121
- with gr.Row():
122
- with gr.Column(scale=6):
123
- model = gr.Dropdown(interactive=True,value="sd_xl_base_1.0.safetensors [be9edd61]", show_label=True, label="Stable Diffusion Checkpoint", choices=[
124
- "sd_xl_base_1.0.safetensors [be9edd61]",
125
- "dynavisionXL_0411.safetensors [c39cc051]",
126
- "dreamshaperXL10_alpha2.safetensors [c8afe2ef]",
127
- ])
128
-
129
- with gr.Row():
130
- with gr.Column(scale=1):
131
- sampler = gr.Dropdown(value="DPM++ SDE", show_label=True, label="Sampler", choices=[
132
- "Euler",
133
- "Euler a",
134
- "LMS",
135
- "Heun",
136
- "DPM2",
137
- "DPM2 a",
138
- "DPM++ 2S a",
139
- "DPM++ 2M",
140
- "DPM++ SDE",
141
- "DPM fast",
142
- "DPM adaptive",
143
- "LMS Karras",
144
- "DPM2 Karras",
145
- "DPM2 a Karras",
146
- "DPM++ 2S a Karras",
147
- "DPM++ 2M Karras",
148
- "DPM++ SDE Karras",
149
- "DDIM",
150
- "PLMS",
151
- ])
152
-
153
- with gr.Column(scale=1):
154
- steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=30, step=1)
155
-
156
- with gr.Row():
157
- with gr.Column(scale=1):
158
- width = gr.Slider(label="Width", maximum=1024, value=1024, step=8)
159
- height = gr.Slider(label="Height", maximum=1024, value=1024, step=8)
160
-
161
- with gr.Column(scale=1):
162
- batch_size = gr.Slider(label="Batch Size", maximum=1, value=1)
163
- batch_count = gr.Slider(label="Batch Count", maximum=1, value=1)
164
-
165
- cfg_scale = gr.Slider(label="CFG Scale", minimum=1, maximum=20, value=7, step=1)
166
- seed = gr.Number(label="Seed", value=-1, info="""'-1' is random seed""")
167
-
168
-
169
- text_button.click(flip_text, inputs=[prompt, negative_prompt, model, steps, sampler, cfg_scale, width, height, seed], outputs=image_output)
170
-
171
- demo.queue(concurrency_count=1)
172
- demo.launch(debug=False, share=False, show_error=False, show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AI-Hobbyist/Hoyo-RVC/train/mel_processing.py DELETED
@@ -1,130 +0,0 @@
1
- import torch
2
- import torch.utils.data
3
- from librosa.filters import mel as librosa_mel_fn
4
-
5
-
6
- MAX_WAV_VALUE = 32768.0
7
-
8
-
9
- def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
10
- """
11
- PARAMS
12
- ------
13
- C: compression factor
14
- """
15
- return torch.log(torch.clamp(x, min=clip_val) * C)
16
-
17
-
18
- def dynamic_range_decompression_torch(x, C=1):
19
- """
20
- PARAMS
21
- ------
22
- C: compression factor used to compress
23
- """
24
- return torch.exp(x) / C
25
-
26
-
27
- def spectral_normalize_torch(magnitudes):
28
- return dynamic_range_compression_torch(magnitudes)
29
-
30
-
31
- def spectral_de_normalize_torch(magnitudes):
32
- return dynamic_range_decompression_torch(magnitudes)
33
-
34
-
35
- # Reusable banks
36
- mel_basis = {}
37
- hann_window = {}
38
-
39
-
40
- def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
41
- """Convert waveform into Linear-frequency Linear-amplitude spectrogram.
42
-
43
- Args:
44
- y :: (B, T) - Audio waveforms
45
- n_fft
46
- sampling_rate
47
- hop_size
48
- win_size
49
- center
50
- Returns:
51
- :: (B, Freq, Frame) - Linear-frequency Linear-amplitude spectrogram
52
- """
53
- # Validation
54
- if torch.min(y) < -1.07:
55
- print("min value is ", torch.min(y))
56
- if torch.max(y) > 1.07:
57
- print("max value is ", torch.max(y))
58
-
59
- # Window - Cache if needed
60
- global hann_window
61
- dtype_device = str(y.dtype) + "_" + str(y.device)
62
- wnsize_dtype_device = str(win_size) + "_" + dtype_device
63
- if wnsize_dtype_device not in hann_window:
64
- hann_window[wnsize_dtype_device] = torch.hann_window(win_size).to(
65
- dtype=y.dtype, device=y.device
66
- )
67
-
68
- # Padding
69
- y = torch.nn.functional.pad(
70
- y.unsqueeze(1),
71
- (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
72
- mode="reflect",
73
- )
74
- y = y.squeeze(1)
75
-
76
- # Complex Spectrogram :: (B, T) -> (B, Freq, Frame, RealComplex=2)
77
- spec = torch.stft(
78
- y,
79
- n_fft,
80
- hop_length=hop_size,
81
- win_length=win_size,
82
- window=hann_window[wnsize_dtype_device],
83
- center=center,
84
- pad_mode="reflect",
85
- normalized=False,
86
- onesided=True,
87
- return_complex=False,
88
- )
89
-
90
- # Linear-frequency Linear-amplitude spectrogram :: (B, Freq, Frame, RealComplex=2) -> (B, Freq, Frame)
91
- spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
92
- return spec
93
-
94
-
95
- def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
96
- # MelBasis - Cache if needed
97
- global mel_basis
98
- dtype_device = str(spec.dtype) + "_" + str(spec.device)
99
- fmax_dtype_device = str(fmax) + "_" + dtype_device
100
- if fmax_dtype_device not in mel_basis:
101
- mel = librosa_mel_fn(
102
- sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
103
- )
104
- mel_basis[fmax_dtype_device] = torch.from_numpy(mel).to(
105
- dtype=spec.dtype, device=spec.device
106
- )
107
-
108
- # Mel-frequency Log-amplitude spectrogram :: (B, Freq=num_mels, Frame)
109
- melspec = torch.matmul(mel_basis[fmax_dtype_device], spec)
110
- melspec = spectral_normalize_torch(melspec)
111
- return melspec
112
-
113
-
114
- def mel_spectrogram_torch(
115
- y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False
116
- ):
117
- """Convert waveform into Mel-frequency Log-amplitude spectrogram.
118
-
119
- Args:
120
- y :: (B, T) - Waveforms
121
- Returns:
122
- melspec :: (B, Freq, Frame) - Mel-frequency Log-amplitude spectrogram
123
- """
124
- # Linear-frequency Linear-amplitude spectrogram :: (B, T) -> (B, Freq, Frame)
125
- spec = spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center)
126
-
127
- # Mel-frequency Log-amplitude spectrogram :: (B, Freq, Frame) -> (B, Freq=num_mels, Frame)
128
- melspec = spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax)
129
-
130
- return melspec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/StyleGANEX/utils/wandb_utils.py DELETED
@@ -1,47 +0,0 @@
1
- import datetime
2
- import os
3
- import numpy as np
4
- import wandb
5
-
6
- from utils import common
7
-
8
-
9
- class WBLogger:
10
-
11
- def __init__(self, opts):
12
- wandb_run_name = os.path.basename(opts.exp_dir)
13
- wandb.init(project="pixel2style2pixel", config=vars(opts), name=wandb_run_name)
14
-
15
- @staticmethod
16
- def log_best_model():
17
- wandb.run.summary["best-model-save-time"] = datetime.datetime.now()
18
-
19
- @staticmethod
20
- def log(prefix, metrics_dict, global_step):
21
- log_dict = {f'{prefix}_{key}': value for key, value in metrics_dict.items()}
22
- log_dict["global_step"] = global_step
23
- wandb.log(log_dict)
24
-
25
- @staticmethod
26
- def log_dataset_wandb(dataset, dataset_name, n_images=16):
27
- idxs = np.random.choice(a=range(len(dataset)), size=n_images, replace=False)
28
- data = [wandb.Image(dataset.source_paths[idx]) for idx in idxs]
29
- wandb.log({f"{dataset_name} Data Samples": data})
30
-
31
- @staticmethod
32
- def log_images_to_wandb(x, y, y_hat, id_logs, prefix, step, opts):
33
- im_data = []
34
- column_names = ["Source", "Target", "Output"]
35
- if id_logs is not None:
36
- column_names.append("ID Diff Output to Target")
37
- for i in range(len(x)):
38
- cur_im_data = [
39
- wandb.Image(common.log_input_image(x[i], opts)),
40
- wandb.Image(common.tensor2im(y[i])),
41
- wandb.Image(common.tensor2im(y_hat[i])),
42
- ]
43
- if id_logs is not None:
44
- cur_im_data.append(id_logs[i]["diff_target"])
45
- im_data.append(cur_im_data)
46
- outputs_table = wandb.Table(data=im_data, columns=column_names)
47
- wandb.log({f"{prefix.title()} Step {step} Output Samples": outputs_table})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AILab-CVC/SEED-LLaMA/gradio_demo/utils.py DELETED
@@ -1,82 +0,0 @@
1
- import datetime
2
- import logging
3
- import logging.handlers
4
- import os
5
- import sys
6
-
7
- handler = None
8
-
9
-
10
- def build_logger(logger_name, logger_dir):
11
- global handler
12
-
13
- formatter = logging.Formatter(
14
- fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
15
- datefmt="%Y-%m-%d %H:%M:%S",
16
- )
17
-
18
- # Set the format of root handlers
19
- if not logging.getLogger().handlers:
20
- logging.basicConfig(level=logging.INFO)
21
- logging.getLogger().handlers[0].setFormatter(formatter)
22
-
23
- # Redirect stdout and stderr to loggers
24
- stdout_logger = logging.getLogger("stdout")
25
- stdout_logger.setLevel(logging.INFO)
26
- sl = StreamToLogger(stdout_logger, logging.INFO)
27
- sys.stdout = sl
28
-
29
- stderr_logger = logging.getLogger("stderr")
30
- stderr_logger.setLevel(logging.ERROR)
31
- sl = StreamToLogger(stderr_logger, logging.ERROR)
32
- sys.stderr = sl
33
-
34
- # Get logger
35
- logger = logging.getLogger(logger_name)
36
- logger.setLevel(logging.INFO)
37
-
38
- # Add a file handler for all loggers
39
- if handler is None:
40
- os.makedirs(logger_dir, exist_ok=True)
41
- filename = os.path.join(logger_dir, logger_name + '.log')
42
- handler = logging.handlers.TimedRotatingFileHandler(filename, when='D', utc=True)
43
- handler.setFormatter(formatter)
44
-
45
- for name, item in logging.root.manager.loggerDict.items():
46
- if isinstance(item, logging.Logger):
47
- item.addHandler(handler)
48
-
49
- return logger
50
-
51
-
52
- class StreamToLogger(object):
53
- """
54
- Fake file-like stream object that redirects writes to a logger instance.
55
- """
56
- def __init__(self, logger, log_level=logging.INFO):
57
- self.terminal = sys.stdout
58
- self.logger = logger
59
- self.log_level = log_level
60
- self.linebuf = ''
61
-
62
- def __getattr__(self, attr):
63
- return getattr(self.terminal, attr)
64
-
65
- def write(self, buf):
66
- temp_linebuf = self.linebuf + buf
67
- self.linebuf = ''
68
- for line in temp_linebuf.splitlines(True):
69
- # From the io.TextIOWrapper docs:
70
- # On output, if newline is None, any '\n' characters written
71
- # are translated to the system default line separator.
72
- # By default sys.stdout.write() expects '\n' newlines and then
73
- # translates them so this is still cross platform.
74
- if line[-1] == '\n':
75
- self.logger.log(self.log_level, line.rstrip())
76
- else:
77
- self.linebuf += line
78
-
79
- def flush(self):
80
- if self.linebuf != '':
81
- self.logger.log(self.log_level, self.linebuf.rstrip())
82
- self.linebuf = ''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIMLApps/Botrite_wip/app.py DELETED
@@ -1,362 +0,0 @@
1
- import numpy as np
2
- import gradio as gr
3
- import json
4
- import socket
5
- import os
6
- from datetime import datetime
7
- import pandas as pd
8
- from langchain.chains import RetrievalQA
9
- from langchain.llms import OpenAI
10
- from langchain.document_loaders import TextLoader
11
- from langchain.document_loaders import PyPDFLoader
12
- from langchain.indexes import VectorstoreIndexCreator
13
- from langchain.text_splitter import CharacterTextSplitter
14
- from langchain.embeddings import OpenAIEmbeddings
15
- from langchain.vectorstores import Chroma
16
- from langchain.chains import ConversationalRetrievalChain
17
- import shutil
18
- demo = gr.Blocks()
19
- options_org=[]
20
- options_bot=['','','']
21
-
22
-
23
- isExist = os.path.exists("Organizations")
24
- if(isExist==False):
25
- os.mkdir("Organizations")
26
-
27
- if(os.path.isfile('Organizationdetails.json')):
28
- #Getting organization name
29
- f = open('Organizationdetails.json', encoding='utf-8', errors='ignore')
30
- data = json.load(f,strict=False)
31
- for p_id, p_info in data.items():
32
- options_org.append(p_id)
33
- f.close()
34
-
35
-
36
- if(os.path.isfile('Botdetails.json')):
37
- #Getting organization name
38
- f1 = open('Botdetails.json')
39
- data = json.load(f1)
40
- for p_id, p_info in data.items():
41
- options_bot.append(p_id)
42
- f1.close()
43
-
44
-
45
- def Create_Organization(org_name, org_handle):
46
-
47
- o=org_handle
48
- path = o
49
- isExist = os.path.exists(path)
50
- hostname=socket.gethostname()
51
- now = datetime.now()
52
- tim=now.strftime("%d/%m/%Y %H:%M:%S")
53
- Organizationdetails={}
54
- Organization_required_details = ["Organizationame","OrganizationHandle" "Created_by", "Created_Time"]
55
- Organizationdetails[org_handle] = {}
56
- Organizationdetails[org_handle]['Organizationame']=org_name
57
- Organizationdetails[org_handle]['OrganizationHandle']=org_handle
58
- Organizationdetails[org_handle]['Created_by']=hostname
59
- Organizationdetails[org_handle]['Created_Time']=tim
60
- isfileE = os.path.isfile("Organizationdetails.json")
61
- if isfileE: #If file present "rb" and w
62
- with open('Organizationdetails.json', 'rb') as txtfile:
63
- d=json.load(txtfile)
64
- d.update(Organizationdetails)
65
- for p_id, p_info in d.items():
66
- options_org.append(p_id)
67
- with open('Organizationdetails.json', 'w') as txtfile:
68
- json.dump(d, txtfile)
69
- if not isExist: #create folder for working
70
- os.makedirs(os.path.join('Organizations', org_handle))
71
- else: #if file not present then create with 'w'
72
- with open('Organizationdetails.json', 'w') as txtfile:
73
- json.dump(Organizationdetails, txtfile)
74
- if not isExist: #create folder for working
75
- os.makedirs(os.path.join('Organizations', org_handle))
76
- return "Organization Created : "+ o
77
-
78
- def clear():
79
- return None, None, None
80
-
81
- def Create_Bot(Organizationame,Bot_Name,Bot_Handle_Name,Bot_Image,Tools,OpenAI_API_key,
82
- Initial_Message,Intro_Message,Rules):
83
-
84
- botim =Bot_Image.name
85
- print(Bot_Name)
86
- b=Bot_Handle_Name
87
- bo=Organizationame
88
- hostname=socket.gethostname()
89
- now = datetime.now()
90
- tim=now.strftime("%d/%m/%Y %H:%M:%S")
91
- Botdetails = { }
92
- Bot_required_details = ["Bot_Name", "Organizationame", "Created_by", "Created_Time","Bot_Handle_Name","Bot_Image","Tools","OpenAI_API_key",
93
- "Initial_Message","Intro_Message","Rules"]
94
- Botdetails[Bot_Handle_Name] = {}
95
- Botdetails[Bot_Handle_Name]['Bot_Name']=Bot_Name
96
- Botdetails[Bot_Handle_Name]['Organizationame']=Organizationame
97
- Botdetails[Bot_Handle_Name]['Created_by']=hostname
98
- Botdetails[Bot_Handle_Name]['Created_Time']=tim
99
- Botdetails[Bot_Handle_Name]['Bot_Handle_Name']=Bot_Handle_Name
100
- Botdetails[Bot_Handle_Name]['Bot_Image']=botim
101
- Botdetails[Bot_Handle_Name]['Tools']=Tools
102
- Botdetails[Bot_Handle_Name]['OpenAI_API_key']=OpenAI_API_key
103
- Botdetails[Bot_Handle_Name]['Initial_Message']=Initial_Message
104
- Botdetails[Bot_Handle_Name]['Intro_Message']=Intro_Message
105
- Botdetails[Bot_Handle_Name]['Rules']=Rules
106
- path = os.path.join(os.getcwd()+'\\Organizations\\', Organizationame,Bot_Name)
107
- Inputpath = os.path.join(os.getcwd()+'\\Organizations\\', Organizationame,Bot_Name,'Inputs')
108
- Outputpath = os.path.join(os.getcwd()+'\\Organizations\\', Organizationame,Bot_Name,'Outputs')
109
-
110
- isExist = os.path.exists(path)
111
-
112
- pp=os.path.join('Organizations',Organizationame+'\\Botdetails.json')
113
-
114
- isfileE = os.path.isfile(pp)
115
- if isfileE: #If file present "rb" and 'w'
116
- with open(pp, 'rb') as txtfile:
117
- d=json.load(txtfile)
118
- d.update(Botdetails)
119
- with open(pp, 'w') as txtfile:
120
- json.dump(d, txtfile)
121
- if not isExist:
122
- os.makedirs(path)
123
- os.makedirs(Inputpath)
124
- os.makedirs(Outputpath)
125
- else: #if file not present then create with 'w'
126
- with open(pp, 'w') as txtfile:
127
- json.dump(Botdetails, txtfile)
128
- if not isExist:
129
- os.makedirs(path)
130
- os.makedirs(Inputpath)
131
- os.makedirs(Outputpath)
132
- return "Bot Created : " + b +" in "+bo +" Organization "
133
-
134
-
135
-
136
-
137
- def loadbotdata(SelectOrganizationame):
138
- new=[]
139
- if(os.path.isfile(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')):
140
- fd = open(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')
141
- data = json.load(fd)
142
- for p_id, p_info in data.items():
143
- new.append(p_id)
144
- #return new
145
- return gr.update(choices=new, value=new[0])
146
-
147
-
148
- def loadbotdataasdf(SelectOrganizationame):
149
- df=[]
150
- new=[]
151
- if(os.path.isfile(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')):
152
- fl = open(os.getcwd()+'\\Organizations\\'+SelectOrganizationame+'\\Botdetails.json')
153
- data = json.load(fl)
154
- df = pd.DataFrame.from_dict(data, orient='columns')
155
- print (df)
156
- for p_id, p_info in data.items():
157
- new.append(p_id)
158
- return df,gr.update(choices=new, value=new[0])
159
-
160
- def upload_file(org, bot , files):
161
- file_paths = [file.name for file in files]
162
- allfiles=file_paths
163
- path = os.path.join(os.getcwd()+'\\Organizations\\', org,bot,'Inputs')
164
- os.makedirs(path, exist_ok=True)
165
-
166
- for file_path in file_paths:
167
- destination_path = os.path.join(path, file_path)
168
- if not os.path.exists(destination_path):
169
- shutil.copy(file_path, destination_path)
170
-
171
- return file_paths
172
-
173
- def train(files):
174
- for file in files:
175
- print(file.name)
176
- if file.name.endswith(".pdf"):
177
- loader = PyPDFLoader(file.name)
178
- documents = loader.load()
179
- return "Training Done"
180
- chat_history = []
181
-
182
- def construct_index(directory_path):
183
- file_paths=[]
184
- for root, directories, files in os.walk(directory_path):
185
- for file_name in files:
186
- file_path = os.path.join(root, file_name)
187
- file_paths.append(file_path)
188
-
189
-
190
- for file in file_paths:
191
- if file.endswith(".pdf"):
192
- loader = PyPDFLoader(file)
193
- documents = loader.load()
194
- return documents
195
-
196
- data_file_path = "deployment_archive_data.json"
197
- if not os.path.exists(data_file_path):
198
- with open(data_file_path, "w") as file:
199
- json.dump([], file)
200
-
201
- def deployment_or_archive(action_type):
202
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
203
-
204
- # Load existing data from the JSON file
205
- with open(data_file_path, "r") as file:
206
- data = json.load(file)
207
-
208
- # Add the new action to the data list
209
- data.append({"action": action_type, "timestamp": timestamp})
210
-
211
- # Write back the updated data to the JSON file
212
- with open(data_file_path, "w") as file:
213
- json.dump(data, file)
214
-
215
- def deploy_bot(org_name, bot_name):
216
-
217
- deployment_path = os.path.join(os.getcwd(), "Deployment")
218
- os.makedirs(deployment_path, exist_ok=True)
219
-
220
-
221
- org_details_path = os.path.join(os.getcwd(), "Organizationdetails.json")
222
- org_deploy_path = os.path.join(deployment_path, "Organizationdetails.json")
223
- shutil.copy(org_details_path, org_deploy_path)
224
-
225
-
226
- org_path = os.path.join(os.getcwd(), "Organizations", org_name)
227
- bot_details_path = os.path.join(org_path, "Botdetails.json")
228
- bot_deploy_path = os.path.join(deployment_path, "Botdetails.json")
229
- shutil.copy(bot_details_path, bot_deploy_path)
230
-
231
-
232
- bot_path = os.path.join(org_path, bot_name)
233
- model_files = os.listdir(bot_path)
234
- for file_name in model_files:
235
- file_path = os.path.join(bot_path, file_name)
236
- deploy_file_path = os.path.join(deployment_path, file_name)
237
- shutil.copy(file_path, deploy_file_path)
238
-
239
- return "Bot deployed successfully to the Deployment directory."
240
-
241
-
242
-
243
-
244
- def chatbot(input_text):
245
- global chat_history
246
- query = input_text
247
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
248
- texts = text_splitter.split_documents(documents)
249
- embeddings = OpenAIEmbeddings()
250
- db = Chroma.from_documents(texts, embeddings)
251
- retriever = db.as_retriever(search_type="similarity", search_kwargs={"k":2})
252
- vectordbkwargs = {"search_distance": 0.9}
253
- qa = ConversationalRetrievalChain.from_llm(OpenAI(), retriever,return_source_documents=True)
254
- print(chat_history)
255
- if chat_history==[]:
256
- result = qa({"question": query,"chat_history": chat_history, "vectordbkwargs": {"search_distance": 0.9}})
257
- else:
258
- result = qa({"question": query, "chat_history": chat_history, "vectordbkwargs": {"search_distance": 0.9}})
259
- chat_history = [(query, result["answer"])]
260
- return result["answer"]
261
-
262
-
263
- with demo:
264
- gr.Markdown("BotRite")
265
-
266
- with gr.Tabs() :
267
- with gr.TabItem("ChatBot"):
268
- with gr.Row():
269
- SelectOrg = gr.Dropdown(options_org ,label="Select Organization" )
270
-
271
- with gr.Row():
272
- Selectbot = gr.Dropdown( label="Select Bot" ,choices=options_bot,
273
- value=options_bot[0], interactive=True)
274
- # Selectbot = gr.Radio(options_bot ,label="Select Bot")
275
-
276
- with gr.Column():
277
- query_input = gr.Textbox(lines=7, label="Enter your text")
278
- ask_button = gr.Button("Ask")
279
- with gr.TabItem("Settings"):
280
- with gr.Tabs():
281
-
282
- with gr.TabItem("Create Organization:"):
283
- with gr.Row():
284
- org_name = gr.Textbox(label="Name",info="Your name / Nickname",placeholder="Enter you organization full name")
285
- org_handle = gr.Textbox(label="Handle Name",info="Your unique organization name", placeholder="Enter Organization handle name")
286
- output_org =gr.Textbox(label='Status')
287
- with gr.Row():
288
- Createorg_button = gr.Button("Create Organization")
289
- Clearorg_button = gr.Button("Clear", variant="stop")
290
-
291
- with gr.TabItem("Bot Details"):
292
- SelectOrganizationame = gr.Dropdown(options_org, label="Select Organization")
293
- with gr.Tabs():
294
- with gr.TabItem("Your Bots:"):
295
- with gr.Row():
296
- with gr.Column():
297
- #SelectOrganizationame = gr.components.Dropdown(options_org, label="Select Organization")
298
- botdf=gr.Dataframe(headers=["Bot_Name", "Organizationame", "Created_by", "Created_Time","Bot_Handle_Name","Bot_Image","Tools","OpenAI_API_key",
299
- "Initial_Message","Intro_Message","Rules"], label="Bot Details")
300
-
301
- with gr.TabItem("Create Bot:"):
302
-
303
- Organizationame =SelectOrganizationame
304
- botname = gr.Textbox(label="Bot Name",info="Your bot name / Nickname", placeholder="Enter bot full name")
305
- bothandle = gr.Textbox(label="Bot Handle Name",info="Your unique bot name" ,placeholder="Enter bot handle name")
306
- image_button = gr.File(label="Select bot image")
307
- botllm = gr.components.CheckboxGroup(['OpenAI', 'Dolly', 'Q&A Model'],label="Tools")
308
- # model = gr.components.Dropdown(Options1, label="Model")
309
- openai_key = gr.Textbox(label="You OpenAI API key", type="password" , info="Add your OpenAi Key click the link to create new or copy exsisting key from your openai account https://platform.openai.com/account/api-keys")
310
- initailsmsg = gr.Textbox(label="Initial Message", placeholder="This message will be shared by bot as intro​" , info="This message will be shared by bot as intro​")
311
- intromsg = gr.Textbox(label="Intro Message", placeholder="This message will be sent to bot as prefix to first message​", info="This message will be sent to bot as prefix to first message​")
312
- rules = gr.Textbox(label="Rules", placeholder="These rules will be sent to bot as prefix to first message (after introduction)​", info="These rules will be sent to bot as prefix to first message (after introduction)​")
313
- output_bot =gr.Textbox(label='Status')
314
- Createbot_button = gr.Button("Create Bot")
315
- with gr.TabItem("Bot Configuration"):
316
- Selectbotconfig = gr.Dropdown(label="Select Bot",choices=options_bot,
317
- value=options_bot[0], interactive=True)
318
- with gr.TabItem("Load Data"):
319
- with gr.Row():
320
- with gr.Column():
321
- Train_Fileselect_button = gr.UploadButton("Upload PDF Files", file_types=[".pdf"], file_count="multiple")
322
- file_output = gr.File()
323
- with gr.Column():
324
- Train_button = gr.Button("Train Data")
325
- Train_output =gr.Textbox(label='Status')
326
-
327
- with gr.TabItem("Chat with your bot"):
328
- with gr.Row():
329
- with gr.Column():
330
- query_input = gr.Textbox(lines=7, label="Enter your text")
331
- ask_button = gr.Button("Ask")
332
- with gr.Column():
333
- text_output=gr.Text(label="Your Bot Answer")
334
- with gr.TabItem("Deploy"):
335
- with gr.Row():
336
- archive_button = gr.Button("Archive")
337
- deploy_button = gr.Button("Deploy")
338
- deploy_archive_output = gr.Textbox(label='Status')
339
-
340
- archive_output = gr.Textbox(label='Status')
341
- publish_button = gr.Button("Publish")
342
- with gr.TabItem("Logs"):
343
- with gr.Column():
344
- Selectlog = gr.Dropdown( label="Select Log")
345
- logview = gr.Text(label="Log")
346
- #def Dropdown_Org(x):
347
-
348
- SelectOrg.change(fn=loadbotdata, inputs=SelectOrg,outputs=Selectbot )
349
- SelectOrganizationame.change(fn=loadbotdataasdf, inputs=SelectOrganizationame,outputs=[botdf,Selectbotconfig])
350
- Createorg_button.click(fn=Create_Organization,inputs=[org_name, org_handle], outputs=output_org)
351
-
352
- archive_button.click(fn=deploy_bot, inputs=[SelectOrganizationame, Selectbotconfig], outputs=archive_output)
353
- deploy_button.click(lambda: deployment_or_archive("deploy"), outputs=deploy_archive_output)
354
- archive_button.click(lambda: deployment_or_archive("archive"), outputs=deploy_archive_output)
355
-
356
- Clearorg_button.click(lambda : [None,None,None], inputs=None, outputs=[org_name,org_handle,output_org])
357
- Createbot_button.click(fn=Create_Bot,inputs=[Organizationame, botname, bothandle,image_button,botllm,openai_key,initailsmsg,intromsg,rules], outputs=output_bot)
358
-
359
- Train_Fileselect_button.upload(upload_file,inputs=[SelectOrganizationame, Selectbotconfig,Train_Fileselect_button], outputs=[file_output])
360
- Train_button.click(fn=train,inputs=Train_Fileselect_button, outputs=Train_output)
361
-
362
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ASJMO/freegpt/client/css/button.css DELETED
@@ -1,26 +0,0 @@
1
- .button {
2
- display: flex;
3
- padding: 8px 12px;
4
- align-items: center;
5
- justify-content: center;
6
- border: 1px solid var(--conversations);
7
- border-radius: var(--border-radius-1);
8
- width: 100%;
9
- background: transparent;
10
- cursor: pointer;
11
- }
12
-
13
- .button span {
14
- color: var(--colour-3);
15
- font-size: 0.875rem;
16
- }
17
-
18
- .button i::before {
19
- margin-right: 8px;
20
- }
21
-
22
- @media screen and (max-width: 990px) {
23
- .button span {
24
- font-size: 0.75rem;
25
- }
26
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/_base_/__init__.py DELETED
File without changes
spaces/Admin08077/Record/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: Record
3
- emoji: 🐢
4
- colorFrom: yellow
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 3.46.1
8
- app_file: app.py
9
- pinned: false
10
- license: other
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/holygrail/HolyGrail.js DELETED
@@ -1,28 +0,0 @@
1
- import Sizer from '../sizer/Sizer.js';
2
- import Build from './methods/Build.js'
3
-
4
- class HolyGrail extends Sizer {
5
- constructor(scene, config) {
6
- if (config === undefined) {
7
- config = {};
8
- }
9
-
10
- config.orientation = 1; // top-to-bottom
11
- // Create sizer
12
- super(scene, config);
13
- this.type = 'rexHolyGrail';
14
-
15
- this.build(config);
16
- }
17
- }
18
-
19
- var methods = {
20
- build: Build,
21
- }
22
-
23
- Object.assign(
24
- HolyGrail.prototype,
25
- methods,
26
- )
27
-
28
- export default HolyGrail;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Aki004/herta-so-vits/vdecoder/hifigan/nvSTFT.py DELETED
@@ -1,111 +0,0 @@
1
- import math
2
- import os
3
- os.environ["LRU_CACHE_CAPACITY"] = "3"
4
- import random
5
- import torch
6
- import torch.utils.data
7
- import numpy as np
8
- import librosa
9
- from librosa.util import normalize
10
- from librosa.filters import mel as librosa_mel_fn
11
- from scipy.io.wavfile import read
12
- import soundfile as sf
13
-
14
- def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False):
15
- sampling_rate = None
16
- try:
17
- data, sampling_rate = sf.read(full_path, always_2d=True)# than soundfile.
18
- except Exception as ex:
19
- print(f"'{full_path}' failed to load.\nException:")
20
- print(ex)
21
- if return_empty_on_exception:
22
- return [], sampling_rate or target_sr or 32000
23
- else:
24
- raise Exception(ex)
25
-
26
- if len(data.shape) > 1:
27
- data = data[:, 0]
28
- assert len(data) > 2# check duration of audio file is > 2 samples (because otherwise the slice operation was on the wrong dimension)
29
-
30
- if np.issubdtype(data.dtype, np.integer): # if audio data is type int
31
- max_mag = -np.iinfo(data.dtype).min # maximum magnitude = min possible value of intXX
32
- else: # if audio data is type fp32
33
- max_mag = max(np.amax(data), -np.amin(data))
34
- max_mag = (2**31)+1 if max_mag > (2**15) else ((2**15)+1 if max_mag > 1.01 else 1.0) # data should be either 16-bit INT, 32-bit INT or [-1 to 1] float32
35
-
36
- data = torch.FloatTensor(data.astype(np.float32))/max_mag
37
-
38
- if (torch.isinf(data) | torch.isnan(data)).any() and return_empty_on_exception:# resample will crash with inf/NaN inputs. return_empty_on_exception will return empty arr instead of except
39
- return [], sampling_rate or target_sr or 32000
40
- if target_sr is not None and sampling_rate != target_sr:
41
- data = torch.from_numpy(librosa.core.resample(data.numpy(), orig_sr=sampling_rate, target_sr=target_sr))
42
- sampling_rate = target_sr
43
-
44
- return data, sampling_rate
45
-
46
- def dynamic_range_compression(x, C=1, clip_val=1e-5):
47
- return np.log(np.clip(x, a_min=clip_val, a_max=None) * C)
48
-
49
- def dynamic_range_decompression(x, C=1):
50
- return np.exp(x) / C
51
-
52
- def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
53
- return torch.log(torch.clamp(x, min=clip_val) * C)
54
-
55
- def dynamic_range_decompression_torch(x, C=1):
56
- return torch.exp(x) / C
57
-
58
- class STFT():
59
- def __init__(self, sr=22050, n_mels=80, n_fft=1024, win_size=1024, hop_length=256, fmin=20, fmax=11025, clip_val=1e-5):
60
- self.target_sr = sr
61
-
62
- self.n_mels = n_mels
63
- self.n_fft = n_fft
64
- self.win_size = win_size
65
- self.hop_length = hop_length
66
- self.fmin = fmin
67
- self.fmax = fmax
68
- self.clip_val = clip_val
69
- self.mel_basis = {}
70
- self.hann_window = {}
71
-
72
- def get_mel(self, y, center=False):
73
- sampling_rate = self.target_sr
74
- n_mels = self.n_mels
75
- n_fft = self.n_fft
76
- win_size = self.win_size
77
- hop_length = self.hop_length
78
- fmin = self.fmin
79
- fmax = self.fmax
80
- clip_val = self.clip_val
81
-
82
- if torch.min(y) < -1.:
83
- print('min value is ', torch.min(y))
84
- if torch.max(y) > 1.:
85
- print('max value is ', torch.max(y))
86
-
87
- if fmax not in self.mel_basis:
88
- mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax)
89
- self.mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device)
90
- self.hann_window[str(y.device)] = torch.hann_window(self.win_size).to(y.device)
91
-
92
- y = torch.nn.functional.pad(y.unsqueeze(1), (int((n_fft-hop_length)/2), int((n_fft-hop_length)/2)), mode='reflect')
93
- y = y.squeeze(1)
94
-
95
- spec = torch.stft(y, n_fft, hop_length=hop_length, win_length=win_size, window=self.hann_window[str(y.device)],
96
- center=center, pad_mode='reflect', normalized=False, onesided=True)
97
- # print(111,spec)
98
- spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9))
99
- # print(222,spec)
100
- spec = torch.matmul(self.mel_basis[str(fmax)+'_'+str(y.device)], spec)
101
- # print(333,spec)
102
- spec = dynamic_range_compression_torch(spec, clip_val=clip_val)
103
- # print(444,spec)
104
- return spec
105
-
106
- def __call__(self, audiopath):
107
- audio, sr = load_wav_to_torch(audiopath, target_sr=self.target_sr)
108
- spect = self.get_mel(audio.unsqueeze(0)).squeeze(0)
109
- return spect
110
-
111
- stft = STFT()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Akmyradov/TurkmenTTSweSTT/uroman/lib/NLP/Romanizer.pm DELETED
@@ -1,2020 +0,0 @@
1
- ################################################################
2
- # #
3
- # Romanizer #
4
- # #
5
- ################################################################
6
-
7
- package NLP::Romanizer;
8
-
9
- use NLP::Chinese;
10
- use NLP::UTF8;
11
- use NLP::utilities;
12
- use JSON;
13
- $utf8 = NLP::UTF8;
14
- $util = NLP::utilities;
15
- $chinesePM = NLP::Chinese;
16
-
17
- my $verbosePM = 0;
18
- %empty_ht = ();
19
-
20
- my $braille_capital_letter_indicator = "\xE2\xA0\xA0";
21
- my $braille_number_indicator = "\xE2\xA0\xBC";
22
- my $braille_decimal_point = "\xE2\xA0\xA8";
23
- my $braille_comma = "\xE2\xA0\x82";
24
- my $braille_solidus = "\xE2\xA0\x8C";
25
- my $braille_numeric_space = "\xE2\xA0\x90";
26
- my $braille_letter_indicator = "\xE2\xA0\xB0";
27
- my $braille_period = "\xE2\xA0\xB2";
28
-
29
- sub new {
30
- local($caller) = @_;
31
-
32
- my $object = {};
33
- my $class = ref( $caller ) || $caller;
34
- bless($object, $class);
35
- return $object;
36
- }
37
-
38
- sub load_unicode_data {
39
- local($this, *ht, $filename) = @_;
40
- # ../../data/UnicodeData.txt
41
-
42
- $n = 0;
43
- if (open(IN, $filename)) {
44
- while (<IN>) {
45
- if (($unicode_value, $char_name, $general_category, $canon_comb_classes, $bidir_category, $char_decomp_mapping, $decimal_digit_value, $digit_value, $numeric_value, $mirrored, $unicode_1_0_name, $comment_field, $uc_mapping, $lc_mapping, $title_case_mapping) = split(";", $_)) {
46
- $utf8_code = $utf8->unicode_hex_string2string($unicode_value);
47
- $ht{UTF_TO_CHAR_NAME}->{$utf8_code} = $char_name;
48
- $ht{UTF_NAME_TO_UNICODE}->{$char_name} = $unicode_value;
49
- $ht{UTF_NAME_TO_CODE}->{$char_name} = $utf8_code;
50
- $ht{UTF_TO_CAT}->{$utf8_code} = $general_category;
51
- $ht{UTF_TO_NUMERIC}->{$utf8_code} = $numeric_value unless $numeric_value eq "";
52
- $n++;
53
- }
54
- }
55
- close(IN);
56
- # print STDERR "Loaded $n entries from $filename\n";
57
- } else {
58
- print STDERR "Can't open $filename\n";
59
- }
60
- }
61
-
62
- sub load_unicode_overwrite_romanization {
63
- local($this, *ht, $filename) = @_;
64
- # ../../data/UnicodeDataOverwrite.txt
65
-
66
- $n = 0;
67
- if (open(IN, $filename)) {
68
- while (<IN>) {
69
- next if /^#/;
70
- $unicode_value = $util->slot_value_in_double_colon_del_list($_, "u");
71
- $romanization = $util->slot_value_in_double_colon_del_list($_, "r");
72
- $numeric = $util->slot_value_in_double_colon_del_list($_, "num");
73
- $picture = $util->slot_value_in_double_colon_del_list($_, "pic");
74
- $syllable_info = $util->slot_value_in_double_colon_del_list($_, "syllable-info");
75
- $tone_mark = $util->slot_value_in_double_colon_del_list($_, "tone-mark");
76
- $char_name = $util->slot_value_in_double_colon_del_list($_, "name");
77
- $entry_processed_p = 0;
78
- $utf8_code = $utf8->unicode_hex_string2string($unicode_value);
79
- if ($unicode_value) {
80
- $ht{UTF_TO_CHAR_ROMANIZATION}->{$utf8_code} = $romanization if $romanization;
81
- $ht{UTF_TO_NUMERIC}->{$utf8_code} = $numeric if defined($numeric) && ($numeric ne "");
82
- $ht{UTF_TO_PICTURE_DESCR}->{$utf8_code} = $picture if $picture;
83
- $ht{UTF_TO_SYLLABLE_INFO}->{$utf8_code} = $syllable_info if $syllable_info;
84
- $ht{UTF_TO_TONE_MARK}->{$utf8_code} = $tone_mark if $tone_mark;
85
- $ht{UTF_TO_CHAR_NAME}->{$utf8_code} = $char_name if $char_name;
86
- $entry_processed_p = 1 if $romanization || $numeric || $picture || $syllable_info || $tone_mark;
87
- }
88
- $n++ if $entry_processed_p;
89
- }
90
- close(IN);
91
- } else {
92
- print STDERR "Can't open $filename\n";
93
- }
94
- }
95
-
96
- sub load_script_data {
97
- local($this, *ht, $filename) = @_;
98
- # ../../data/Scripts.txt
99
-
100
- $n = 0;
101
- if (open(IN, $filename)) {
102
- while (<IN>) {
103
- next unless $script_name = $util->slot_value_in_double_colon_del_list($_, "script-name");
104
- $abugida_default_vowel_s = $util->slot_value_in_double_colon_del_list($_, "abugida-default-vowel");
105
- $alt_script_name_s = $util->slot_value_in_double_colon_del_list($_, "alt-script-name");
106
- $language_s = $util->slot_value_in_double_colon_del_list($_, "language");
107
- $direction = $util->slot_value_in_double_colon_del_list($_, "direction"); # right-to-left
108
- $font_family_s = $util->slot_value_in_double_colon_del_list($_, "font-family");
109
- $ht{SCRIPT_P}->{$script_name} = 1;
110
- $ht{SCRIPT_NORM}->{(uc $script_name)} = $script_name;
111
- $ht{DIRECTION}->{$script_name} = $direction if $direction;
112
- foreach $language (split(/,\s*/, $language_s)) {
113
- $ht{SCRIPT_LANGUAGE}->{$script_name}->{$language} = 1;
114
- $ht{LANGUAGE_SCRIPT}->{$language}->{$script_name} = 1;
115
- }
116
- foreach $alt_script_name (split(/,\s*/, $alt_script_name_s)) {
117
- $ht{SCRIPT_NORM}->{$alt_script_name} = $script_name;
118
- $ht{SCRIPT_NORM}->{(uc $alt_script_name)} = $script_name;
119
- }
120
- foreach $abugida_default_vowel (split(/,\s*/, $abugida_default_vowel_s)) {
121
- $ht{SCRIPT_ABUDIGA_DEFAULT_VOWEL}->{$script_name}->{$abugida_default_vowel} = 1 if $abugida_default_vowel;
122
- }
123
- foreach $font_family (split(/,\s*/, $font_family_s)) {
124
- $ht{SCRIPT_FONT}->{$script_name}->{$font_family} = 1 if $font_family;
125
- }
126
- $n++;
127
- }
128
- close(IN);
129
- # print STDERR "Loaded $n entries from $filename\n";
130
- } else {
131
- print STDERR "Can't open $filename\n";
132
- }
133
- }
134
-
135
- sub unicode_hangul_romanization {
136
- local($this, $s, $pass_through_p) = @_;
137
-
138
- $pass_through_p = 0 unless defined($pass_through_p);
139
- @leads = split(/\s+/, "g gg n d dd r m b bb s ss - j jj c k t p h");
140
- # @vowels = split(/\s+/, "a ae ya yai e ei ye yei o oa oai oi yo u ue uei ui yu w wi i");
141
- @vowels = split(/\s+/, "a ae ya yae eo e yeo ye o wa wai oe yo u weo we wi yu eu yi i");
142
- @tails = split(/\s+/, "- g gg gs n nj nh d l lg lm lb ls lt lp lh m b bs s ss ng j c k t p h");
143
- $result = "";
144
- @chars = $utf8->split_into_utf8_characters($s, "return only chars", *empty_ht);
145
- foreach $char (@chars) {
146
- $unicode = $utf8->utf8_to_unicode($char);
147
- if (($unicode >= 0xAC00) && ($unicode <= 0xD7A3)) {
148
- $code = $unicode - 0xAC00;
149
- $lead_index = int($code / (28*21));
150
- $vowel_index = int($code/28) % 21;
151
- $tail_index = $code % 28;
152
- $rom = $leads[$lead_index] . $vowels[$vowel_index] . $tails[$tail_index];
153
- $rom =~ s/-//g;
154
- $result .= $rom;
155
- } elsif ($pass_through_p) {
156
- $result .= $char;
157
- }
158
- }
159
- return $result;
160
- }
161
-
162
- sub listify_comma_sep_string {
163
- local($this, $s) = @_;
164
-
165
- @result_list = ();
166
- return @result_list unless $s =~ /\S/;
167
- $s = $util->trim2($s);
168
- my $elem;
169
-
170
- while (($elem, $rest) = ($s =~ /^("(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^"', ]+),\s*(.*)$/)) {
171
- push(@result_list, $util->dequote_string($elem));
172
- $s = $rest;
173
- }
174
- push(@result_list, $util->dequote_string($s)) if $s =~ /\S/;
175
-
176
- return @result_list;
177
- }
178
-
179
- sub braille_string_p {
180
- local($this, $s) = @_;
181
-
182
- return ($s =~ /^(\xE2[\xA0-\xA3][\x80-\xBF])+$/);
183
- }
184
-
185
- sub register_word_boundary_info {
186
- local($this, *ht, $lang_code, $utf8_source_string, $utf8_target_string, $use_only_for_whole_word_p,
187
- $use_only_at_start_of_word_p, $use_only_at_end_of_word_p,
188
- $dont_use_at_start_of_word_p, $dont_use_at_end_of_word_p) = @_;
189
-
190
- if ($use_only_for_whole_word_p) {
191
- if ($lang_code) {
192
- $ht{USE_ONLY_FOR_WHOLE_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = 1;
193
- } else {
194
- $ht{USE_ONLY_FOR_WHOLE_WORD}->{$utf8_source_string}->{$utf8_target_string} = 1;
195
- }
196
- }
197
- if ($use_only_at_start_of_word_p) {
198
- if ($lang_code) {
199
- $ht{USE_ONLY_AT_START_OF_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = 1;
200
- } else {
201
- $ht{USE_ONLY_AT_START_OF_WORD}->{$utf8_source_string}->{$utf8_target_string} = 1;
202
- }
203
- }
204
- if ($use_only_at_end_of_word_p) {
205
- if ($lang_code) {
206
- $ht{USE_ONLY_AT_END_OF_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = 1;
207
- } else {
208
- $ht{USE_ONLY_AT_END_OF_WORD}->{$utf8_source_string}->{$utf8_target_string} = 1;
209
- }
210
- }
211
- if ($dont_use_at_start_of_word_p) {
212
- if ($lang_code) {
213
- $ht{DONT_USE_AT_START_OF_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = 1;
214
- } else {
215
- $ht{DONT_USE_AT_START_OF_WORD}->{$utf8_source_string}->{$utf8_target_string} = 1;
216
- }
217
- }
218
- if ($dont_use_at_end_of_word_p) {
219
- if ($lang_code) {
220
- $ht{DONT_USE_AT_END_OF_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = 1;
221
- } else {
222
- $ht{DONT_USE_AT_END_OF_WORD}->{$utf8_source_string}->{$utf8_target_string} = 1;
223
- }
224
- }
225
- }
226
-
227
- sub load_romanization_table {
228
- local($this, *ht, $filename) = @_;
229
- # ../../data/romanization-table.txt
230
-
231
- $n = 0;
232
- $line_number = 0;
233
- if (open(IN, $filename)) {
234
- while (<IN>) {
235
- $line_number++;
236
- next if /^#/;
237
- if ($_ =~ /^::preserve\s/) {
238
- $from_unicode = $util->slot_value_in_double_colon_del_list($_, "from");
239
- $to_unicode = $util->slot_value_in_double_colon_del_list($_, "to");
240
- if ($from_unicode =~ /^(?:U\+|\\u)[0-9A-F]{4,}$/i) {
241
- $from_unicode =~ s/^(?:U\+|\\u)//;
242
- $from_code_point = hex($from_unicode);
243
- } else {
244
- $from_code_point = "";
245
- }
246
- if ($to_unicode =~ /^(?:U\+|\\u)[0-9A-F]{4,}$/i) {
247
- $to_unicode =~ s/^(?:U\+|\\u)//;
248
- $to_code_point = hex($to_unicode);
249
- } else {
250
- $to_code_point = $from_code_point;
251
- }
252
- if ($from_code_point ne "") {
253
- # print STDERR "Preserve code-points $from_unicode--$to_unicode = $from_code_point--$to_code_point\n";
254
- foreach $code_point (($from_code_point .. $to_code_point)) {
255
- $utf8_string = $utf8->unicode2string($code_point);
256
- $ht{UTF_CHAR_MAPPING}->{$utf8_string}->{$utf8_string} = 1;
257
- }
258
- $n++;
259
- }
260
- next;
261
- }
262
- $utf8_source_string = $util->slot_value_in_double_colon_del_list($_, "s");
263
- $utf8_target_string = $util->slot_value_in_double_colon_del_list($_, "t");
264
- $utf8_alt_target_string_s = $util->slot_value_in_double_colon_del_list($_, "t-alt");
265
- $use_alt_in_pointed_p = ($_ =~ /::use-alt-in-pointed\b/);
266
- $use_only_for_whole_word_p = ($_ =~ /::use-only-for-whole-word\b/);
267
- $use_only_at_start_of_word_p = ($_ =~ /::use-only-at-start-of-word\b/);
268
- $use_only_at_end_of_word_p = ($_ =~ /::use-only-at-end-of-word\b/);
269
- $dont_use_at_start_of_word_p = ($_ =~ /::dont-use-at-start-of-word\b/);
270
- $dont_use_at_end_of_word_p = ($_ =~ /::dont-use-at-end-of-word\b/);
271
- $use_only_in_lower_case_enviroment_p = ($_ =~ /::use-only-in-lower-case-enviroment\b/);
272
- $word_external_punctuation_p = ($_ =~ /::word-external-punctuation\b/);
273
- $utf8_source_string =~ s/\s*$//;
274
- $utf8_target_string =~ s/\s*$//;
275
- $utf8_alt_target_string_s =~ s/\s*$//;
276
- $utf8_target_string =~ s/^"(.*)"$/$1/;
277
- $utf8_target_string =~ s/^'(.*)'$/$1/;
278
- @utf8_alt_targets = $this->listify_comma_sep_string($utf8_alt_target_string_s);
279
- $numeric = $util->slot_value_in_double_colon_del_list($_, "num");
280
- $numeric =~ s/\s*$//;
281
- $annotation = $util->slot_value_in_double_colon_del_list($_, "annotation");
282
- $annotation =~ s/\s*$//;
283
- $lang_code = $util->slot_value_in_double_colon_del_list($_, "lcode");
284
- $prob = $util->slot_value_in_double_colon_del_list($_, "p") || 1;
285
- unless (($utf8_target_string eq "") && ($numeric =~ /\d/)) {
286
- if ($lang_code) {
287
- $ht{UTF_CHAR_MAPPING_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = $prob;
288
- } else {
289
- $ht{UTF_CHAR_MAPPING}->{$utf8_source_string}->{$utf8_target_string} = $prob;
290
- }
291
- if ($word_external_punctuation_p) {
292
- if ($lang_code) {
293
- $ht{WORD_EXTERNAL_PUNCTUATION_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = $prob;
294
- } else {
295
- $ht{WORD_EXTERNAL_PUNCTUATION}->{$utf8_source_string}->{$utf8_target_string} = $prob;
296
- }
297
- }
298
- if ($this->braille_string_p($utf8_source_string)) {
299
- if (($utf8_target_string =~ /^[a-z]+$/)
300
- && (! ($utf8_source_string =~ /^$braille_capital_letter_indicator/))) {
301
- my $uc_utf8_source_string = "$braille_capital_letter_indicator$utf8_source_string";
302
- my $uc_utf8_target_string = ucfirst $utf8_target_string;
303
- if ($lang_code) {
304
- $ht{UTF_CHAR_MAPPING_LANG_SPEC}->{$lang_code}->{$uc_utf8_source_string}->{$uc_utf8_target_string} = $prob;
305
- } else {
306
- $ht{UTF_CHAR_MAPPING}->{$uc_utf8_source_string}->{$uc_utf8_target_string} = $prob;
307
- }
308
- $this->register_word_boundary_info(*ht, $lang_code, $uc_utf8_source_string, $uc_utf8_target_string,
309
- $use_only_for_whole_word_p, $use_only_at_start_of_word_p, $use_only_at_end_of_word_p,
310
- $dont_use_at_start_of_word_p, $dont_use_at_end_of_word_p);
311
- }
312
- if (($utf8_target_string =~ /^[0-9]$/)
313
- && ($utf8_source_string =~ /^$braille_number_indicator./)) {
314
- my $core_number_char = $utf8_source_string;
315
- $core_number_char =~ s/$braille_number_indicator//;
316
- $ht{BRAILLE_TO_DIGIT}->{$core_number_char} = $utf8_target_string;
317
- }
318
- }
319
- }
320
- if ($use_only_in_lower_case_enviroment_p) {
321
- if ($lang_code) {
322
- $ht{USE_ONLY_IN_LOWER_CASE_ENVIROMENT_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_target_string} = 1;
323
- } else {
324
- $ht{USE_ONLY_IN_LOWER_CASE_ENVIROMENT}->{$utf8_source_string}->{$utf8_target_string} = 1;
325
- }
326
- }
327
- $this->register_word_boundary_info(*ht, $lang_code, $utf8_source_string, $utf8_target_string,
328
- $use_only_for_whole_word_p, $use_only_at_start_of_word_p, $use_only_at_end_of_word_p,
329
- $dont_use_at_start_of_word_p, $dont_use_at_end_of_word_p);
330
- foreach $utf8_alt_target (@utf8_alt_targets) {
331
- if ($lang_code) {
332
- $ht{UTF_CHAR_ALT_MAPPING_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_alt_target} = $prob;
333
- $ht{USE_ALT_IN_POINTED_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_alt_target} = 1 if $use_alt_in_pointed_p;
334
- } else {
335
- $ht{UTF_CHAR_ALT_MAPPING}->{$utf8_source_string}->{$utf8_alt_target} = $prob;
336
- $ht{USE_ALT_IN_POINTED}->{$utf8_source_string}->{$utf8_alt_target} = 1 if $use_alt_in_pointed_p;
337
- }
338
- if ($use_only_for_whole_word_p) {
339
- if ($lang_code) {
340
- $ht{USE_ALT_ONLY_FOR_WHOLE_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_alt_target} = 1;
341
- } else {
342
- $ht{USE_ALT_ONLY_FOR_WHOLE_WORD}->{$utf8_source_string}->{$utf8_alt_target} = 1;
343
- }
344
- }
345
- if ($use_only_at_start_of_word_p) {
346
- if ($lang_code) {
347
- $ht{USE_ALT_ONLY_AT_START_OF_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_alt_target} = 1;
348
- } else {
349
- $ht{USE_ALT_ONLY_AT_START_OF_WORD}->{$utf8_source_string}->{$utf8_alt_target} = 1;
350
- }
351
- }
352
- if ($use_only_at_end_of_word_p) {
353
- if ($lang_code) {
354
- $ht{USE_ALT_ONLY_AT_END_OF_WORD_LANG_SPEC}->{$lang_code}->{$utf8_source_string}->{$utf8_alt_target} = 1;
355
- } else {
356
- $ht{USE_ALT_ONLY_AT_END_OF_WORD}->{$utf8_source_string}->{$utf8_alt_target} = 1;
357
- }
358
- }
359
- }
360
- if ($numeric =~ /\d/) {
361
- $ht{UTF_TO_NUMERIC}->{$utf8_source_string} = $numeric;
362
- }
363
- if ($annotation =~ /\S/) {
364
- $ht{UTF_ANNOTATION}->{$utf8_source_string} = $annotation;
365
- }
366
- $n++;
367
- }
368
- close(IN);
369
- # print STDERR "Loaded $n entries from $filename\n";
370
- } else {
371
- print STDERR "Can't open $filename\n";
372
- }
373
- }
374
-
375
- sub char_name_to_script {
376
- local($this, $char_name, *ht) = @_;
377
-
378
- return $cached_result if $cached_result = $ht{CHAR_NAME_TO_SCRIPT}->{$char_name};
379
- $orig_char_name = $char_name;
380
- $char_name =~ s/\s+(CONSONANT|LETTER|LIGATURE|SIGN|SYLLABLE|SYLLABICS|VOWEL)\b.*$//;
381
- my $script_name;
382
- while ($char_name) {
383
- last if $script_name = $ht{SCRIPT_NORM}->{(uc $char_name)};
384
- $char_name =~ s/\s*\S+\s*$//;
385
- }
386
- $script_name = "" unless defined($script_name);
387
- $ht{CHAR_NAME_TO_SCRIPT}->{$char_name} = $script_name;
388
- return $script_name;
389
- }
390
-
391
- sub letter_plus_char_p {
392
- local($this, $char_name) = @_;
393
-
394
- return $cached_result if $cached_result = $ht{CHAR_NAME_LETTER_PLUS}->{$char_name};
395
- my $letter_plus_p = ($char_name =~ /\b(?:LETTER|VOWEL SIGN|AU LENGTH MARK|CONSONANT SIGN|SIGN VIRAMA|SIGN PAMAAEH|SIGN COENG|SIGN AL-LAKUNA|SIGN ASAT|SIGN ANUSVARA|SIGN ANUSVARAYA|SIGN BINDI|TIPPI|SIGN NIKAHIT|SIGN CANDRABINDU|SIGN VISARGA|SIGN REAHMUK|SIGN NUKTA|SIGN DOT BELOW|HEBREW POINT)\b/) ? 1 : 0;
396
- $ht{CHAR_NAME_LETTER_PLUS}->{$char_name} = $letter_plus_p;
397
- return $letter_plus_p;
398
- }
399
-
400
- sub subjoined_char_p {
401
- local($this, $char_name) = @_;
402
-
403
- return $cached_result if $cached_result = $ht{CHAR_NAME_SUBJOINED}->{$char_name};
404
- my $subjoined_p = (($char_name =~ /\b(?:SUBJOINED LETTER|VOWEL SIGN|AU LENGTH MARK|EMPHASIS MARK|CONSONANT SIGN|SIGN VIRAMA|SIGN PAMAAEH|SIGN COENG|SIGN ASAT|SIGN ANUSVARA|SIGN ANUSVARAYA|SIGN BINDI|TIPPI|SIGN NIKAHIT|SIGN CANDRABINDU|SIGN VISARGA|SIGN REAHMUK|SIGN DOT BELOW|HEBREW (POINT|PUNCTUATION GERESH)|ARABIC (?:DAMMA|DAMMATAN|FATHA|FATHATAN|HAMZA|KASRA|KASRATAN|MADDAH|SHADDA|SUKUN))\b/)) ? 1 : 0;
405
- $ht{CHAR_NAME_SUBJOINED}->{$char_name} = $subjoined_p;
406
- return $subjoined_p;
407
- }
408
-
409
- sub new_node_id {
410
- local($this, *chart_ht) = @_;
411
-
412
- my $n_nodes = $chart_ht{N_NODES};
413
- $n_nodes++;
414
- $chart_ht{N_NODES} = $n_nodes;
415
- return $n_nodes;
416
- }
417
-
418
- sub add_node {
419
- local($this, $s, $start, $end, *chart_ht, $type, $comment) = @_;
420
-
421
- my $node_id = $this->new_node_id(*chart_ht);
422
- # print STDERR "add_node($node_id, $start-$end): $s [$comment]\n" if $comment =~ /number/;
423
- # print STDERR "add_node($node_id, $start-$end): $s [$comment]\n" if ($start >= 0) && ($start < 50);
424
- $chart_ht{NODE_START}->{$node_id} = $start;
425
- $chart_ht{NODE_END}->{$node_id} = $end;
426
- $chart_ht{NODES_STARTING_AT}->{$start}->{$node_id} = 1;
427
- $chart_ht{NODES_ENDING_AT}->{$end}->{$node_id} = 1;
428
- $chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end}->{$node_id} = 1;
429
- $chart_ht{NODE_TYPE}->{$node_id} = $type;
430
- $chart_ht{NODE_COMMENT}->{$node_id} = $comment;
431
- $chart_ht{NODE_ROMAN}->{$node_id} = $s;
432
- return $node_id;
433
- }
434
-
435
- sub get_node_for_span {
436
- local($this, $start, $end, *chart_ht) = @_;
437
-
438
- return "" unless defined($chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end});
439
- my @node_ids = sort { $a <=> $b } keys %{$chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end}};
440
-
441
- return (@node_ids) ? $node_ids[0] : "";
442
- }
443
-
444
- sub get_node_for_span_and_type {
445
- local($this, $start, $end, *chart_ht, $type) = @_;
446
-
447
- return "" unless defined($chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end});
448
- my @node_ids = sort { $a <=> $b } keys %{$chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end}};
449
-
450
- foreach $node_id (@node_ids) {
451
- return $node_id if $chart_ht{NODE_TYPE}->{$node_id} eq $type;
452
- }
453
- return "";
454
- }
455
-
456
- sub get_node_roman {
457
- local($this, $node_id, *chart_id, $default) = @_;
458
-
459
- $default = "" unless defined($default);
460
- my $roman = $chart_ht{NODE_ROMAN}->{$node_id};
461
- return (defined($roman)) ? $roman : $default;
462
- }
463
-
464
- sub set_node_id_slot_value {
465
- local($this, $node_id, $slot, $value, *chart_id) = @_;
466
-
467
- $chart_ht{NODE_SLOT}->{$node_id}->{$slot} = $value;
468
- }
469
-
470
- sub copy_slot_values {
471
- local($this, $old_node_id, $new_node_id, *chart_id, @slots) = @_;
472
-
473
- if (@slots) {
474
- foreach $slot (keys %{$chart_ht{NODE_SLOT}->{$old_node_id}}) {
475
- if (($slots[0] eq "all") || $util->member($slot, @slots)) {
476
- my $value = $chart_ht{NODE_SLOT}->{$old_node_id}->{$slot};
477
- $chart_ht{NODE_SLOT}->{$new_node_id}->{$slot} = $value if defined($value);
478
- }
479
- }
480
- }
481
- }
482
-
483
- sub get_node_id_slot_value {
484
- local($this, $node_id, $slot, *chart_id, $default) = @_;
485
-
486
- $default = "" unless defined($default);
487
- my $value = $chart_ht{NODE_SLOT}->{$node_id}->{$slot};
488
- return (defined($value)) ? $value : $default;
489
- }
490
-
491
- sub get_node_for_span_with_slot_value {
492
- local($this, $start, $end, $slot, *chart_id, $default) = @_;
493
-
494
- $default = "" unless defined($default);
495
- return $default unless defined($chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end});
496
- my @node_ids = sort { $a <=> $b } keys %{$chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end}};
497
- foreach $node_id (@node_ids) {
498
- my $value = $chart_ht{NODE_SLOT}->{$node_id}->{$slot};
499
- return $value if defined($value);
500
- }
501
- return $default;
502
- }
503
-
504
- sub get_node_for_span_with_slot {
505
- local($this, $start, $end, $slot, *chart_id, $default) = @_;
506
-
507
- $default = "" unless defined($default);
508
- return $default unless defined($chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end});
509
- my @node_ids = sort { $a <=> $b } keys %{$chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end}};
510
- foreach $node_id (@node_ids) {
511
- my $value = $chart_ht{NODE_SLOT}->{$node_id}->{$slot};
512
- return $node_id if defined($value);
513
- }
514
- return $default;
515
- }
516
-
517
- sub register_new_complex_number_span_segment {
518
- local($this, $start, $mid, $end, *chart_id, $line_number) = @_;
519
- # e.g. 4 10 (= 40); 20 5 (= 25)
520
- # might become part of larger complex number span, e.g. 4 1000 3 100 20 1
521
-
522
- # print STDERR "register_new_complex_number_span_segment $start-$mid-$end\n" if $line_number == 43;
523
- if (defined($old_start = $chart_ht{COMPLEX_NUMERIC_END_START}->{$mid})) {
524
- undef($chart_ht{COMPLEX_NUMERIC_END_START}->{$mid});
525
- $chart_ht{COMPLEX_NUMERIC_START_END}->{$old_start} = $end;
526
- $chart_ht{COMPLEX_NUMERIC_END_START}->{$end} = $old_start;
527
- } else {
528
- $chart_ht{COMPLEX_NUMERIC_START_END}->{$start} = $end;
529
- $chart_ht{COMPLEX_NUMERIC_END_START}->{$end} = $start;
530
- }
531
- }
532
-
533
- sub romanize_by_token_with_caching {
534
- local($this, $s, $lang_code, $output_style, *ht, *pinyin_ht, $initial_char_offset, $control, $line_number) = @_;
535
-
536
- $control = "" unless defined($control);
537
- my $return_chart_p = ($control =~ /return chart/i);
538
- my $return_offset_mappings_p = ($control =~ /return offset mappings/i);
539
- return $this->romanize($s, $lang_code, $output_style, *ht, *pinyin_ht, $initial_char_offset, $control, $line_number)
540
- if $return_chart_p || $return_offset_mappings_p;
541
- my $result = "";
542
- my @separators = ();
543
- my @tokens = ();
544
- $s =~ s/\n$//; # Added May 2, 2019 as bug-fix (duplicate empty lines)
545
- while (($sep, $token, $rest) = ($s =~ /^(\s*)(\S+)(.*)$/)) {
546
- push(@separators, $sep);
547
- push(@tokens, $token);
548
- $s = $rest;
549
- }
550
- push(@separators, $s);
551
- while (@tokens) {
552
- my $sep = shift @separators;
553
- my $token = shift @tokens;
554
- $result .= $sep;
555
- if ($token =~ /^[\x00-\x7F]*$/) { # all ASCII
556
- $result .= $token;
557
- } else {
558
- my $rom_token = $ht{CACHED_ROMANIZATION}->{$lang_code}->{$token};
559
- unless (defined($rom_token)) {
560
- $rom_token = $this->romanize($token, $lang_code, $output_style, *ht, *pinyin_ht, $initial_char_offset, $control, $line_number);
561
- $ht{CACHED_ROMANIZATION}->{$lang_code}->{$token} = $rom_token if defined($rom_token);
562
- }
563
- $result .= $rom_token;
564
- }
565
- }
566
- my $sep = shift @separators;
567
- $result .= $sep if defined($sep);
568
-
569
- return $result;
570
- }
571
-
572
- sub romanize {
573
- local($this, $s, $lang_code, $output_style, *ht, *pinyin_ht, $initial_char_offset, $control, $line_number, $initial_rom_char_offset) = @_;
574
-
575
- my $orig_lang_code = $lang_code;
576
- # Check whether the text (to be romanized) starts with a language code directive.
577
- if (($line_lang_code) = ($s =~ /^::lcode\s+([a-z][a-z][a-z])\s/)) {
578
- $lang_code = $line_lang_code;
579
- }
580
- $initial_char_offset = 0 unless defined($initial_char_offset);
581
- $initial_rom_char_offset = 0 unless defined($initial_rom_char_offset);
582
- $control = "" unless defined($control);
583
- my $return_chart_p = ($control =~ /return chart/i);
584
- my $return_offset_mappings_p = ($control =~ /return offset mappings/i);
585
- $line_number = "" unless defined($line_number);
586
- my @chars = $utf8->split_into_utf8_characters($s, "return only chars", *empty_ht);
587
- my $n_characters = $#chars + 1;
588
- %chart_ht = ();
589
- $chart_ht{N_CHARS} = $n_characters;
590
- $chart_ht{N_NODES} = 0;
591
- my $char = "";
592
- my $char_name = "";
593
- my $prev_script = "";
594
- my $current_script = "";
595
- my $script_start = 0;
596
- my $script_end = 0;
597
- my $prev_letter_plus_script = "";
598
- my $current_letter_plus_script = "";
599
- my $letter_plus_script_start = 0;
600
- my $letter_plus_script_end = 0;
601
- my $log ="";
602
- my $n_right_to_left_chars = 0;
603
- my $n_left_to_right_chars = 0;
604
- my $hebrew_word_start = ""; # used to identify Hebrew words with points
605
- my $hebrew_word_contains_point = 0;
606
- my $current_word_start = "";
607
- my $current_word_script = "";
608
- my $braille_all_caps_p = 0;
609
-
610
- # prep
611
- foreach $i ((0 .. ($#chars + 1))) {
612
- if ($i <= $#chars) {
613
- $char = $chars[$i];
614
- $chart_ht{ORIG_CHAR}->{$i} = $char;
615
- $char_name = $ht{UTF_TO_CHAR_NAME}->{$char} || "";
616
- $chart_ht{CHAR_NAME}->{$i} = $char_name;
617
- $current_script = $this->char_name_to_script($char_name, *ht);
618
- $current_script_direction = $ht{DIRECTION}->{$current_script} || '';
619
- if ($current_script_direction eq 'right-to-left') {
620
- $n_right_to_left_chars++;
621
- } elsif (($char =~ /^[a-z]$/i) || ! ($char =~ /^[\x00-\x7F]$/)) {
622
- $n_left_to_right_chars++;
623
- }
624
- $chart_ht{CHAR_SCRIPT}->{$i} = $current_script;
625
- $chart_ht{SCRIPT_SEGMENT_START}->{$i} = ""; # default value, to be updated later
626
- $chart_ht{SCRIPT_SEGMENT_END}->{$i} = ""; # default value, to be updated later
627
- $chart_ht{LETTER_TOKEN_SEGMENT_START}->{$i} = ""; # default value, to be updated later
628
- $chart_ht{LETTER_TOKEN_SEGMENT_END}->{$i} = ""; # default value, to be updated later
629
- $subjoined_char_p = $this->subjoined_char_p($char_name);
630
- $chart_ht{CHAR_SUBJOINED}->{$i} = $subjoined_char_p;
631
- $letter_plus_char_p = $this->letter_plus_char_p($char_name);
632
- $chart_ht{CHAR_LETTER_PLUS}->{$i} = $letter_plus_char_p;
633
- $current_letter_plus_script = ($letter_plus_char_p) ? $current_script : "";
634
- $numeric_value = $ht{UTF_TO_NUMERIC}->{$char};
635
- $numeric_value = "" unless defined($numeric_value);
636
- $annotation = $ht{UTF_ANNOTATION}->{$char};
637
- $annotation = "" unless defined($annotation);
638
- $chart_ht{CHAR_NUMERIC_VALUE}->{$i} = $numeric_value;
639
- $chart_ht{CHAR_ANNOTATION}->{$i} = $annotation;
640
- $syllable_info = $ht{UTF_TO_SYLLABLE_INFO}->{$char} || "";
641
- $chart_ht{CHAR_SYLLABLE_INFO}->{$i} = $syllable_info;
642
- $tone_mark = $ht{UTF_TO_TONE_MARK}->{$char} || "";
643
- $chart_ht{CHAR_TONE_MARK}->{$i} = $tone_mark;
644
- } else {
645
- $char = "";
646
- $char_name = "";
647
- $current_script = "";
648
- $current_letter_plus_script = "";
649
- }
650
- if ($char_name =~ /^HEBREW (LETTER|POINT|PUNCTUATION GERESH) /) {
651
- $hebrew_word_start = $i if $hebrew_word_start eq "";
652
- $hebrew_word_contains_point = 1 if $char_name =~ /^HEBREW POINT /;
653
- } elsif ($hebrew_word_start ne "") {
654
- if ($hebrew_word_contains_point) {
655
- foreach $j (($hebrew_word_start .. ($i-1))) {
656
- $chart_ht{CHAR_PART_OF_POINTED_HEBREW_WORD}->{$j} = 1;
657
- }
658
- $chart_ht{CHAR_START_OF_WORD}->{$hebrew_word_start} = 1;
659
- $chart_ht{CHAR_END_OF_WORD}->{($i-1)} = 1;
660
- }
661
- $hebrew_word_start = "";
662
- $hebrew_word_contains_point = 0;
663
- }
664
- my $part_of_word_p = $current_script
665
- && ($this->letter_plus_char_p($char_name)
666
- || $this->subjoined_char_p($char_name)
667
- || ($char_name =~ /\b(LETTER|SYLLABLE|SYLLABICS|LIGATURE)\b/));
668
-
669
- # Braille punctuation
670
- my $end_offset = 0;
671
- if ($char_name =~ /^Braille\b/i) {
672
- if (($char =~ /^\s*$/) || ($char_name =~ /BLANK/)) {
673
- $part_of_word_p = 0;
674
- $braille_all_caps_p = 0;
675
- } elsif ($chart_ht{NOT_PART_OF_WORD_P}->{$i}) {
676
- $part_of_word_p = 0;
677
- $braille_all_caps_p = 0;
678
- } elsif ((keys %{$ht{WORD_EXTERNAL_PUNCTUATION_LANG_SPEC}->{$lang_code}->{$char}})
679
- || (keys %{$ht{WORD_EXTERNAL_PUNCTUATION}->{$char}})) {
680
- $part_of_word_p = 0;
681
- $braille_all_caps_p = 0;
682
- } elsif (($i+1 <= $#chars)
683
- && ($s1 = $char . $chars[$i+1])
684
- && ((keys %{$ht{WORD_EXTERNAL_PUNCTUATION_LANG_SPEC}->{$lang_code}->{$s1}})
685
- || (keys %{$ht{WORD_EXTERNAL_PUNCTUATION}->{$s1}}))) {
686
- $part_of_word_p = 0;
687
- $braille_all_caps_p = 0;
688
- $chart_ht{NOT_PART_OF_WORD_P}->{($i+1)} = 1;
689
- } elsif (($i+2 <= $#chars)
690
- && ($s2 = $char . $chars[$i+1] . $chars[$i+2])
691
- && ((keys %{$ht{WORD_EXTERNAL_PUNCTUATION_LANG_SPEC}->{$lang_code}->{$s2}})
692
- || (keys %{$ht{WORD_EXTERNAL_PUNCTUATION}->{$s2}}))) {
693
- $part_of_word_p = 0;
694
- $braille_all_caps_p = 0;
695
- $chart_ht{NOT_PART_OF_WORD_P}->{($i+1)} = 1;
696
- $chart_ht{NOT_PART_OF_WORD_P}->{($i+2)} = 1;
697
- } elsif (($i+1 <= $#chars)
698
- && ($char eq $braille_capital_letter_indicator)
699
- && ($chars[$i+1] eq $braille_capital_letter_indicator)) {
700
- $braille_all_caps_p = 1;
701
- } else {
702
- $part_of_word_p = 1;
703
- }
704
- # last period in Braille text is also not part_of_word_p
705
- if (($char eq $braille_period)
706
- && (($i == $#chars)
707
- || (($i < $#chars)
708
- && (! $this->braille_string_p($chars[$i+1]))))) {
709
- $part_of_word_p = 0;
710
- }
711
- # period before other word-external punctuation is also not part_of_word_p
712
- if (($i > 0)
713
- && ($chars[$i-1] eq $braille_period)
714
- && (! $part_of_word_p)
715
- && ($current_word_start ne "")) {
716
- $end_offset = -1;
717
- }
718
- } else {
719
- $braille_all_caps_p = 0;
720
- }
721
- $chart_ht{BRAILLE_ALL_CAPS_P}->{$i} = $braille_all_caps_p;
722
-
723
- if (($current_word_start ne "")
724
- && ((! $part_of_word_p)
725
- || ($current_script ne $current_word_script))) {
726
- # END OF WORD
727
- $chart_ht{CHAR_START_OF_WORD}->{$current_word_start} = 1;
728
- $chart_ht{CHAR_END_OF_WORD}->{($i-1+$end_offset)} = 1;
729
- my $word = join("", @chars[$current_word_start .. ($i-1+$end_offset)]);
730
- $chart_ht{WORD_START_END}->{$current_word_start}->{$i} = $word;
731
- $chart_ht{WORD_END_START}->{$i+$end_offset}->{$current_word_start} = $word;
732
- # print STDERR "Word ($current_word_start-$i+$end_offset): $word ($current_word_script)\n";
733
- $current_word_start = "";
734
- $current_word_script = "";
735
- }
736
- if ($part_of_word_p && ($current_word_start eq "")) {
737
- # START OF WORD
738
- $current_word_start = $i;
739
- $current_word_script = $current_script;
740
- }
741
- # print STDERR "$i char: $char ($current_script)\n";
742
- unless ($current_script eq $prev_script) {
743
- if ($prev_script && ($i-1 >= $script_start)) {
744
- my $script_end = $i;
745
- $chart_ht{SCRIPT_SEGMENT_START_TO_END}->{$script_start} = $script_end;
746
- $chart_ht{SCRIPT_SEGMENT_END_TO_START}->{$script_end} = $script_start;
747
- foreach $i (($script_start .. $script_end)) {
748
- $chart_ht{SCRIPT_SEGMENT_START}->{$i} = $script_start;
749
- $chart_ht{SCRIPT_SEGMENT_END}->{$i} = $script_end;
750
- }
751
- # print STDERR "Script segment $script_start-$script_end: $prev_script\n";
752
- }
753
- $script_start = $i;
754
- }
755
- unless ($current_letter_plus_script eq $prev_letter_plus_script) {
756
- if ($prev_letter_plus_script && ($i-1 >= $letter_plus_script_start)) {
757
- my $letter_plus_script_end = $i;
758
- $chart_ht{LETTER_TOKEN_SEGMENT_START_TO_END}->{$letter_plus_script_start} = $letter_plus_script_end;
759
- $chart_ht{LETTER_TOKEN_SEGMENT_END_TO_START}->{$letter_plus_script_end} = $letter_plus_script_start;
760
- foreach $i (($letter_plus_script_start .. $letter_plus_script_end)) {
761
- $chart_ht{LETTER_TOKEN_SEGMENT_START}->{$i} = $letter_plus_script_start;
762
- $chart_ht{LETTER_TOKEN_SEGMENT_END}->{$i} = $letter_plus_script_end;
763
- }
764
- # print STDERR "Script token segment $letter_plus_script_start-$letter_plus_script_end: $prev_letter_plus_script\n";
765
- }
766
- $letter_plus_script_start = $i;
767
- }
768
- $prev_script = $current_script;
769
- $prev_letter_plus_script = $current_letter_plus_script;
770
- }
771
- $ht{STRING_IS_DOMINANTLY_RIGHT_TO_LEFT}->{$s} = 1 if $n_right_to_left_chars > $n_left_to_right_chars;
772
-
773
- # main
774
- my $i = 0;
775
- while ($i <= $#chars) {
776
- my $char = $chart_ht{ORIG_CHAR}->{$i};
777
- my $current_script = $chart_ht{CHAR_SCRIPT}->{$i};
778
- $chart_ht{CHART_CONTAINS_SCRIPT}->{$current_script} = 1;
779
- my $script_segment_start = $chart_ht{SCRIPT_SEGMENT_START}->{$i};
780
- my $script_segment_end = $chart_ht{SCRIPT_SEGMENT_END}->{$i};
781
- my $char_name = $chart_ht{CHAR_NAME}->{$i};
782
- my $subjoined_char_p = $chart_ht{CHAR_SUBJOINED}->{$i};
783
- my $letter_plus_char_p = $chart_ht{CHAR_LETTER_PLUS}->{$i};
784
- my $numeric_value = $chart_ht{CHAR_NUMERIC_VALUE}->{$i};
785
- my $annotation = $chart_ht{CHAR_ANNOTATION}->{$i};
786
- # print STDERR " $char_name annotation: $annotation\n" if $annotation;
787
- my $tone_mark = $chart_ht{CHAR_TONE_MARK}->{$i};
788
- my $found_char_mapping_p = 0;
789
- my $prev_char_name = ($i >= 1) ? $chart_ht{CHAR_NAME}->{($i-1)} : "";
790
- my $prev2_script = ($i >= 2) ? $chart_ht{CHAR_SCRIPT}->{($i-2)} : "";
791
- my $prev_script = ($i >= 1) ? $chart_ht{CHAR_SCRIPT}->{($i-1)} : "";
792
- my $next_script = ($i < $#chars) ? $chart_ht{CHAR_SCRIPT}->{($i+1)} : "";
793
- my $next_char = ($i < $#chars) ? $chart_ht{ORIG_CHAR}->{($i+1)} : "";
794
- my $next_char_name = $ht{UTF_TO_CHAR_NAME}->{$next_char} || "";
795
- my $prev2_letter_plus_char_p = ($i >= 2) ? $chart_ht{CHAR_LETTER_PLUS}->{($i-2)} : 0;
796
- my $prev_letter_plus_char_p = ($i >= 1) ? $chart_ht{CHAR_LETTER_PLUS}->{($i-1)} : 0;
797
- my $next_letter_plus_char_p = ($i < $#chars) ? $chart_ht{CHAR_LETTER_PLUS}->{($i+1)} : 0;
798
- my $next_index = $i + 1;
799
-
800
- # Braille numeric mode
801
- if ($char eq $braille_number_indicator) {
802
- my $offset = 0;
803
- my $numeric_value = "";
804
- my $digit;
805
- while ($i+$offset < $#chars) {
806
- $offset++;
807
- my $offset_char = $chart_ht{ORIG_CHAR}->{$i+$offset};
808
- if (defined($digit = $ht{BRAILLE_TO_DIGIT}->{$offset_char})) {
809
- $numeric_value .= $digit;
810
- } elsif (($offset_char eq $braille_decimal_point)
811
- || ($ht{UTF_CHAR_MAPPING}->{$offset_char}->{"."})) {
812
- $numeric_value .= ".";
813
- } elsif ($offset_char eq $braille_comma) {
814
- $numeric_value .= ",";
815
- } elsif ($offset_char eq $braille_numeric_space) {
816
- $numeric_value .= " ";
817
- } elsif ($offset_char eq $braille_solidus) {
818
- $numeric_value .= "/";
819
- } elsif ($offset_char eq $braille_number_indicator) {
820
- # stay in Braille numeric mode
821
- } elsif ($offset_char eq $braille_letter_indicator) {
822
- # consider as part of number, but without contributing to numeric_value
823
- last;
824
- } else {
825
- $offset--;
826
- last;
827
- }
828
- }
829
- if ($offset) {
830
- $next_index = $i + $offset + 1;
831
- $node_id = $this->add_node($numeric_value, $i, $next_index, *chart_ht, "", "braille number");
832
- $found_char_mapping_p = 1;
833
- }
834
- }
835
-
836
- unless ($found_char_mapping_p) {
837
- foreach $string_length (reverse(1 .. 6)) {
838
- next if ($i + $string_length-1) > $#chars;
839
- my $start_of_word_p = $chart_ht{CHAR_START_OF_WORD}->{$i} || 0;
840
- my $end_of_word_p = $chart_ht{CHAR_END_OF_WORD}->{($i+$string_length-1)} || 0;
841
- my $multi_char_substring = join("", @chars[$i..($i+$string_length-1)]);
842
- my @mappings = keys %{$ht{UTF_CHAR_MAPPING_LANG_SPEC}->{$lang_code}->{$multi_char_substring}};
843
- @mappings = keys %{$ht{UTF_CHAR_MAPPING}->{$multi_char_substring}} unless @mappings;
844
- my @mappings_whole = ();
845
- my @mappings_start_or_end = ();
846
- my @mappings_other = ();
847
- foreach $mapping (@mappings) {
848
- next if $mapping =~ /\(__.*__\)/;
849
- if ($ht{USE_ONLY_FOR_WHOLE_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$mapping}
850
- || $ht{USE_ONLY_FOR_WHOLE_WORD}->{$multi_char_substring}->{$mapping}) {
851
- push(@mappings_whole, $mapping) if $start_of_word_p && $end_of_word_p;
852
- } elsif ($ht{USE_ONLY_AT_START_OF_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$mapping}
853
- || $ht{USE_ONLY_AT_START_OF_WORD}->{$multi_char_substring}->{$mapping}) {
854
- push(@mappings_start_or_end, $mapping) if $start_of_word_p;
855
- } elsif ($ht{USE_ONLY_AT_END_OF_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$mapping}
856
- || $ht{USE_ONLY_AT_END_OF_WORD}->{$multi_char_substring}->{$mapping}) {
857
- push(@mappings_start_or_end, $mapping) if $end_of_word_p;
858
- } else {
859
- push(@mappings_other, $mapping);
860
- }
861
- }
862
- @mappings = @mappings_whole;
863
- @mappings = @mappings_start_or_end unless @mappings;
864
- @mappings = @mappings_other unless @mappings;
865
- foreach $mapping (@mappings) {
866
- next if $mapping =~ /\(__.*__\)/;
867
- if ($ht{DONT_USE_AT_START_OF_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$mapping}
868
- || $ht{DONT_USE_AT_START_OF_WORD}->{$multi_char_substring}->{$mapping}) {
869
- next if $start_of_word_p;
870
- }
871
- if ($ht{DONT_USE_AT_END_OF_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$mapping}
872
- || $ht{DONT_USE_AT_END_OF_WORD}->{$multi_char_substring}->{$mapping}) {
873
- next if $end_of_word_p;
874
- }
875
- my $mapping2 = ($chart_ht{BRAILLE_ALL_CAPS_P}->{$i}) ? (uc $mapping) : $mapping;
876
- $node_id = $this->add_node($mapping2, $i, $i+$string_length, *chart_ht, "", "multi-char-mapping");
877
- $next_index = $i + $string_length;
878
- $found_char_mapping_p = 1;
879
- if ($annotation) {
880
- @annotation_elems = split(/,\s*/, $annotation);
881
- foreach $annotation_elem (@annotation_elems) {
882
- if (($a_slot, $a_value) = ($annotation_elem =~ /^(\S+?):(\S+)\s*$/)) {
883
- $this->set_node_id_slot_value($node_id, $a_slot, $a_value, *chart_ht);
884
- } else {
885
- $this->set_node_id_slot_value($node_id, $annotation_elem, 1, *chart_ht);
886
- }
887
- }
888
- }
889
- }
890
- my @alt_mappings = keys %{$ht{UTF_CHAR_ALT_MAPPING_LANG_SPEC}->{$lang_code}->{$multi_char_substring}};
891
- @alt_mappings = keys %{$ht{UTF_CHAR_ALT_MAPPING}->{$multi_char_substring}} unless @alt_mappings;
892
- @alt_mappings = () if ($#alt_mappings == 0) && ($alt_mappings[0] eq "_NONE_");
893
- foreach $alt_mapping (@alt_mappings) {
894
- if ($chart_ht{CHAR_PART_OF_POINTED_HEBREW_WORD}->{$i}) {
895
- next unless
896
- $ht{USE_ALT_IN_POINTED_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$alt_mapping}
897
- || $ht{USE_ALT_IN_POINTED}->{$multi_char_substring}->{$alt_mapping};
898
- }
899
- if ($ht{USE_ALT_ONLY_FOR_WHOLE_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$alt_mapping}
900
- || $ht{USE_ALT_ONLY_FOR_WHOLE_WORD}->{$multi_char_substring}->{$alt_mapping}) {
901
- next unless $start_of_word_p && $end_of_word_p;
902
- }
903
- if ($ht{USE_ALT_ONLY_AT_START_OF_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$alt_mapping}
904
- || $ht{USE_ALT_ONLY_AT_START_OF_WORD}->{$multi_char_substring}->{$alt_mapping}) {
905
- next unless $start_of_word_p;
906
- }
907
- if ($ht{USE_ALT_ONLY_AT_END_OF_WORD_LANG_SPEC}->{$lang_code}->{$multi_char_substring}->{$alt_mapping}
908
- || $ht{USE_ALT_ONLY_AT_END_OF_WORD}->{$multi_char_substring}->{$alt_mapping}) {
909
- next unless $end_of_word_p;
910
- }
911
- my $alt_mapping2 = ($chart_ht{BRAILLE_ALL_CAPS_P}->{$i}) ? (uc $alt_mapping) : $alt_mapping;
912
- $node_id = $this->add_node($alt_mapping2, $i, $i+$string_length, *chart_ht, "alt", "multi-char-mapping");
913
- if ($annotation) {
914
- @annotation_elems = split(/,\s*/, $annotation);
915
- foreach $annotation_elem (@annotation_elems) {
916
- if (($a_slot, $a_value) = ($annotation_elem =~ /^(\S+?):(\S+)\s*$/)) {
917
- $this->set_node_id_slot_value($node_id, $a_slot, $a_value, *chart_ht);
918
- } else {
919
- $this->set_node_id_slot_value($node_id, $annotation_elem, 1, *chart_ht);
920
- }
921
- }
922
- }
923
- }
924
- }
925
- }
926
- unless ($found_char_mapping_p) {
927
- my $prev_node_id = $this->get_node_for_span($i-4, $i, *chart_ht)
928
- || $this->get_node_for_span($i-3, $i, *chart_ht)
929
- || $this->get_node_for_span($i-2, $i, *chart_ht)
930
- || $this->get_node_for_span($i-1, $i, *chart_ht);
931
- my $prev_char_roman = ($prev_node_id) ? $this->get_node_roman($prev_node_id, *chart_id) : "";
932
- my $prev_node_start = ($prev_node_id) ? $chart_ht{NODE_START}->{$prev_node_id} : "";
933
-
934
- # Number
935
- if (($numeric_value =~ /\d/)
936
- && (! ($char_name =~ /SUPERSCRIPT/))) {
937
- my $prev_numeric_value = $this->get_node_for_span_with_slot_value($i-1, $i, "numeric-value", *chart_id);
938
- my $sep = "";
939
- $sep = " " if ($char_name =~ /^vulgar fraction /i) && ($prev_numeric_value =~ /\d/);
940
- $node_id = $this->add_node("$sep$numeric_value", $i, $i+1, *chart_ht, "", "number");
941
- $this->set_node_id_slot_value($node_id, "numeric-value", $numeric_value, *chart_ht);
942
- if ((($prev_numeric_value =~ /\d/) && ($numeric_value =~ /\d\d/))
943
- || (($prev_numeric_value =~ /\d\d/) && ($numeric_value =~ /\d/))) {
944
- # pull in any other parts of single digits
945
- my $j = 1;
946
- # pull in any single digits adjoining on left
947
- if ($prev_numeric_value =~ /^\d$/) {
948
- while (1) {
949
- if (($i-$j-1 >= 0)
950
- && defined($digit_value = $this->get_node_for_span_with_slot_value($i-$j-1, $i-$j, "numeric-value", *chart_id))
951
- && ($digit_value =~ /^\d$/)) {
952
- $j++;
953
- } elsif (($i-$j-2 >= 0)
954
- && ($chart_ht{ORIG_CHAR}->{($i-$j-1)} =~ /^[.,]$/)
955
- && defined($digit_value = $this->get_node_for_span_with_slot_value($i-$j-2, $i-$j-1, "numeric-value", *chart_id))
956
- && ($digit_value =~ /^\d$/)) {
957
- $j += 2;
958
- } else {
959
- last;
960
- }
961
- }
962
- }
963
- # pull in any single digits adjoining on right
964
- my $k = 0;
965
- if ($numeric_value =~ /^\d$/) {
966
- while (1) {
967
- if (defined($next_numeric_value = $chart_ht{CHAR_NUMERIC_VALUE}->{($i+$k+1)})
968
- && ($next_numeric_value =~ /^\d$/)) {
969
- $k++;
970
- } else {
971
- last;
972
- }
973
- }
974
- }
975
- $this->register_new_complex_number_span_segment($i-$j, $i, $i+$k+1, *chart_ht, $line_number);
976
- }
977
- if ($chinesePM->string_contains_utf8_cjk_unified_ideograph_p($char)
978
- && ($tonal_translit = $chinesePM->tonal_pinyin($char, *pinyin_ht, ""))) {
979
- $de_accented_translit = $util->de_accent_string($tonal_translit);
980
- if ($numeric_value =~ /^(10000|1000000000000|10000000000000000)$/) {
981
- $chart_ht{NODE_TYPE}->{$node_id} = "alt"; # keep, but demote
982
- $alt_node_id = $this->add_node($de_accented_translit, $i, $i+1, *chart_ht, "", "CJK");
983
- } else {
984
- $alt_node_id = $this->add_node($de_accented_translit, $i, $i+1, *chart_ht, "alt", "CJK");
985
- }
986
- }
987
-
988
- # ASCII
989
- } elsif ($char =~ /^[\x00-\x7F]$/) {
990
- $this->add_node($char, $i, $i+1, *chart_ht, "", "ASCII"); # ASCII character, incl. control characters
991
-
992
- # Emoji, dingbats, pictographs
993
- } elsif ($char =~ /^(\xE2[\x98-\x9E]|\xF0\x9F[\x8C-\xA7])/) {
994
- $this->add_node($char, $i, $i+1, *chart_ht, "", "pictograph");
995
-
996
- # Hangul (Korean)
997
- } elsif (($char =~ /^[\xEA-\xED]/)
998
- && ($romanized_char = $this->unicode_hangul_romanization($char))) {
999
- $this->add_node($romanized_char, $i, $i+1, *chart_ht, "", "Hangul");
1000
-
1001
- # CJK (Chinese, Japanese, Korean)
1002
- } elsif ($chinesePM->string_contains_utf8_cjk_unified_ideograph_p($char)
1003
- && ($tonal_translit = $chinesePM->tonal_pinyin($char, *pinyin_ht, ""))) {
1004
- $de_accented_translit = $util->de_accent_string($tonal_translit);
1005
- $this->add_node($de_accented_translit, $i, $i+1, *chart_ht, "", "CJK");
1006
-
1007
- # Virama (cancel preceding vowel in Abudiga scripts)
1008
- } elsif ($char_name =~ /\bSIGN (?:VIRAMA|AL-LAKUNA|ASAT|COENG|PAMAAEH)\b/) {
1009
- # VIRAMA: cancel preceding default vowel (in Abudiga scripts)
1010
- if (($prev_script eq $current_script)
1011
- && (($prev_char_roman_consonant, $prev_char_roman_vowel) = ($prev_char_roman =~ /^(.*[bcdfghjklmnpqrstvwxyz])([aeiou]+)$/i))
1012
- && ($ht{SCRIPT_ABUDIGA_DEFAULT_VOWEL}->{$current_script}->{(lc $prev_char_roman_vowel)})) {
1013
- $this->add_node($prev_char_roman_consonant, $prev_node_start, $i+1, *chart_ht, "", "virama");
1014
- } else {
1015
- $this->add_node("", $i, $i+1, *chart_ht, "", "unexpected-virama");
1016
- }
1017
-
1018
- # Nukta (special (typically foreign) variant)
1019
- } elsif ($char_name =~ /\bSIGN (?:NUKTA)\b/) {
1020
- # NUKTA (dot): indicates special (typically foreign) variant; normally covered by multi-mappings
1021
- if ($prev_script eq $current_script) {
1022
- my $node_id = $this->add_node($prev_char_roman, $prev_node_start, $i+1, *chart_ht, "", "nukta");
1023
- $this->copy_slot_values($prev_node_id, $node_id, *chart_id, "all");
1024
- $this->set_node_id_slot_value($node_id, "nukta", 1, *chart_ht);
1025
- } else {
1026
- $this->add_node("", $i, $i+1, *chart_ht, "", "unexpected-nukta");
1027
- }
1028
-
1029
- # Zero-width character, incl. zero width space/non-joiner/joiner, left-to-right/right-to-left mark
1030
- } elsif ($char =~ /^\xE2\x80[\x8B-\x8F\xAA-\xAE]$/) {
1031
- if ($prev_node_id) {
1032
- my $node_id = $this->add_node($prev_char_roman, $prev_node_start, $i+1, *chart_ht, "", "zero-width-char");
1033
- $this->copy_slot_values($prev_node_id, $node_id, *chart_id, "all");
1034
- } else {
1035
- $this->add_node("", $i, $i+1, *chart_ht, "", "zero-width-char");
1036
- }
1037
- } elsif (($char =~ /^\xEF\xBB\xBF$/) && $prev_node_id) { # OK to leave byte-order-mark at beginning of line
1038
- my $node_id = $this->add_node($prev_char_roman, $prev_node_start, $i+1, *chart_ht, "", "zero-width-char");
1039
- $this->copy_slot_values($prev_node_id, $node_id, *chart_id, "all");
1040
-
1041
- # Tone mark
1042
- } elsif ($tone_mark) {
1043
- if ($prev_script eq $current_script) {
1044
- my $node_id = $this->add_node($prev_char_roman, $prev_node_start, $i+1, *chart_ht, "", "tone-mark");
1045
- $this->copy_slot_values($prev_node_id, $node_id, *chart_id, "all");
1046
- $this->set_node_id_slot_value($node_id, "tone-mark", $tone_mark, *chart_ht);
1047
- } else {
1048
- $this->add_node("", $i, $i+1, *chart_ht, "", "unexpected-tone-mark");
1049
- }
1050
-
1051
- # Diacritic
1052
- } elsif (($char_name =~ /\b(ACCENT|TONE|COMBINING DIAERESIS|COMBINING DIAERESIS BELOW|COMBINING MACRON|COMBINING VERTICAL LINE ABOVE|COMBINING DOT ABOVE RIGHT|COMBINING TILDE|COMBINING CYRILLIC|MUUSIKATOAN|TRIISAP)\b/) && ($ht{UTF_TO_CAT}->{$char} =~ /^Mn/)) {
1053
- if ($prev_script eq $current_script) {
1054
- my $node_id = $this->add_node($prev_char_roman, $prev_node_start, $i+1, *chart_ht, "", "diacritic");
1055
- $this->copy_slot_values($prev_node_id, $node_id, *chart_id, "all");
1056
- $diacritic = lc $char_name;
1057
- $diacritic =~ s/^.*(?:COMBINING CYRILLIC|COMBINING|SIGN)\s+//i;
1058
- $diacritic =~ s/^.*(ACCENT|TONE)/$1/i;
1059
- $diacritic =~ s/^\s*//;
1060
- $this->set_node_id_slot_value($node_id, "diacritic", $diacritic, *chart_ht);
1061
- # print STDERR "diacritic: $diacritic\n";
1062
- } else {
1063
- $this->add_node("", $i, $i+1, *chart_ht, "", "unexpected-diacritic");
1064
- }
1065
-
1066
- # Romanize to find out more
1067
- } elsif ($char_name) {
1068
- if (defined($romanized_char = $this->romanize_char_at_position($i, $lang_code, $output_style, *ht, *chart_ht))) {
1069
- # print STDERR "ROM l.$line_number/$i: $romanized_char\n" if $line_number =~ /^[12]$/;
1070
- print STDOUT "ROM l.$line_number/$i: $romanized_char\n" if $verbosePM;
1071
-
1072
- # Empty string mapping
1073
- if ($romanized_char eq "\"\"") {
1074
- $this->add_node("", $i, $i+1, *chart_ht, "", "empty-string-mapping");
1075
- # consider adding something for implausible romanizations of length 6+
1076
-
1077
- # keep original character (instead of romanized_char lengthener, character-18b00 etc.)
1078
- } elsif (($romanized_char =~ /^(character|lengthener|modifier)/)) {
1079
- $this->add_node($char, $i, $i+1, *chart_ht, "", "nevermind-keep-original");
1080
-
1081
- # Syllabic suffix in Abudiga languages, e.g. -m, -ng
1082
- } elsif (($romanized_char =~ /^\+(H|M|N|NG)$/i)
1083
- && ($prev_script eq $current_script)
1084
- && ($ht{SCRIPT_ABUDIGA_DEFAULT_VOWEL}->{$current_script}->{"a"})) {
1085
- my $core_suffix = $romanized_char;
1086
- $core_suffix =~ s/^\+//;
1087
- if ($prev_char_roman =~ /[aeiou]$/i) {
1088
- $this->add_node($core_suffix, $i, $i+1, *chart_ht, "", "syllable-end-consonant");
1089
- } else {
1090
- $this->add_node(join("", $prev_char_roman, "a", $core_suffix), $prev_node_start, $i+1, *chart_ht, "", "syllable-end-consonant-with-added-a");
1091
- $this->add_node(join("", "a", $core_suffix), $i, $i+1, *chart_ht, "backup", "syllable-end-consonant");
1092
- }
1093
-
1094
- # Japanese special cases
1095
- } elsif ($char_name =~ /(?:HIRAGANA|KATAKANA) LETTER SMALL Y/) {
1096
- if (($prev_script eq $current_script)
1097
- && (($prev_char_roman_consonant) = ($prev_char_roman =~ /^(.*[bcdfghjklmnpqrstvwxyz])i$/i))) {
1098
- unless ($this->get_node_for_span_and_type($prev_node_start, $i+1, *chart_ht, "")) {
1099
- $this->add_node("$prev_char_roman_consonant$romanized_char", $prev_node_start, $i+1, *chart_ht, "", "japanese-contraction");
1100
- }
1101
- } else {
1102
- $this->add_node($romanized_char, $i, $i+1, *chart_ht, "", "unexpected-japanese-contraction-character");
1103
- }
1104
- } elsif (($prev_script =~ /^(HIRAGANA|KATAKANA)$/i)
1105
- && ($char_name eq "KATAKANA-HIRAGANA PROLONGED SOUND MARK") # Choonpu
1106
- && (($prev_char_roman_vowel) = ($prev_char_roman =~ /([aeiou])$/i))) {
1107
- $this->add_node("$prev_char_roman$prev_char_roman_vowel", $prev_node_start, $i+1, *chart_ht, "", "japanese-vowel-lengthening");
1108
- } elsif (($current_script =~ /^(Hiragana|Katakana)$/i)
1109
- && ($char_name =~ /^(HIRAGANA|KATAKANA) LETTER SMALL TU$/i) # Sokuon/Sukun
1110
- && ($next_script eq $current_script)
1111
- && ($romanized_next_char = $this->romanize_char_at_position_incl_multi($i+1, $lang_code, $output_style, *ht, *chart_ht))
1112
- && (($doubled_consonant) = ($romanized_next_char =~ /^(ch|[bcdfghjklmnpqrstwz])/i))) {
1113
- # Note: $romanized_next_char could be part of a multi-character mapping
1114
- # print STDERR "current_script: $current_script char_name: $char_name next_script: $next_script romanized_next_char: $romanized_next_char doubled_consonant: $doubled_consonant\n";
1115
- $doubled_consonant = "t" if $doubled_consonant eq "ch";
1116
- $this->add_node($doubled_consonant, $i, $i+1, *chart_ht, "", "japanese-consonant-doubling");
1117
-
1118
- # Greek small letter mu to micro-sign (instead of to "m") as used in abbreviations for microgram/micrometer/microliter/microsecond/micromolar/microfarad etc.
1119
- } elsif (($char_name eq "GREEK SMALL LETTER MU")
1120
- && (! ($prev_script =~ /^GREEK$/))
1121
- && ($i < $#chars)
1122
- && ($chart_ht{ORIG_CHAR}->{($i+1)} =~ /^[cfgjlmstv]$/i)) {
1123
- $this->add_node("\xC2\xB5", $i, $i+1, *chart_ht, "", "greek-mu-to-micro-sign");
1124
-
1125
- # Gurmukhi addak (doubles following consonant)
1126
- } elsif (($current_script eq "Gurmukhi")
1127
- && ($char_name eq "GURMUKHI ADDAK")) {
1128
- if (($next_script eq $current_script)
1129
- && ($romanized_next_char = $this->romanize_char_at_position_incl_multi($i+1, $lang_code, $output_style, *ht, *chart_ht))
1130
- && (($doubled_consonant) = ($romanized_next_char =~ /^([bcdfghjklmnpqrstvwxz])/i))) {
1131
- $this->add_node($doubled_consonant, $i, $i+1, *chart_ht, "", "gurmukhi-consonant-doubling");
1132
- } else {
1133
- $this->add_node("'", $i, $i+1, *chart_ht, "", "gurmukhi-unexpected-addak");
1134
- }
1135
-
1136
- # Subjoined character
1137
- } elsif ($subjoined_char_p
1138
- && ($prev_script eq $current_script)
1139
- && (($prev_char_roman_consonant, $prev_char_roman_vowel) = ($prev_char_roman =~ /^(.*[bcdfghjklmnpqrstvwxyz])([aeiou]+)$/i))
1140
- && ($ht{SCRIPT_ABUDIGA_DEFAULT_VOWEL}->{$current_script}->{(lc $prev_char_roman_vowel)})) {
1141
- my $new_roman = "$prev_char_roman_consonant$romanized_char";
1142
- $this->add_node($new_roman, $prev_node_start, $i+1, *chart_ht, "", "subjoined-character");
1143
- # print STDERR " Subjoin l.$line_number/$i: $new_roman\n" if $line_number =~ /^[12]$/;
1144
-
1145
- # Thai special case: written-pre-consonant-spoken-post-consonant
1146
- } elsif (($char_name =~ /THAI CHARACTER/)
1147
- && ($prev_script eq $current_script)
1148
- && ($chart_ht{CHAR_SYLLABLE_INFO}->{($i-1)} =~ /written-pre-consonant-spoken-post-consonant/i)
1149
- && ($prev_char_roman =~ /^[aeiou]+$/i)
1150
- && ($romanized_char =~ /^[bcdfghjklmnpqrstvwxyz]/)) {
1151
- $this->add_node("$romanized_char$prev_char_roman", $prev_node_start, $i+1, *chart_ht, "", "thai-vowel-consonant-swap");
1152
-
1153
- # Thai special case: THAI CHARACTER O ANG (U+0E2D "\xE0\xB8\xAD")
1154
- } elsif ($char_name eq "THAI CHARACTER O ANG") {
1155
- if ($prev_script ne $current_script) {
1156
- $this->add_node("", $i, $i+1, *chart_ht, "", "thai-initial-o-ang-drop");
1157
- } elsif ($next_script ne $current_script) {
1158
- $this->add_node("", $i, $i+1, *chart_ht, "", "thai-final-o-ang-drop");
1159
- } else {
1160
- my $romanized_next_char = $this->romanize_char_at_position($i+1, $lang_code, $output_style, *ht, *chart_ht);
1161
- my $romanized_prev2_char = $this->romanize_char_at_position($i-2, $lang_code, $output_style, *ht, *chart_ht);
1162
- if (($prev_char_roman =~ /^[bcdfghjklmnpqrstvwxz]+$/i)
1163
- && ($romanized_next_char =~ /^[bcdfghjklmnpqrstvwxz]+$/i)) {
1164
- $this->add_node("o", $i, $i+1, *chart_ht, "", "thai-middle-o-ang"); # keep between consonants
1165
- } elsif (($prev2_script eq $current_script)
1166
- && 0
1167
- && ($prev_char_name =~ /^THAI CHARACTER MAI [A-Z]+$/) # Thai tone
1168
- && ($romanized_prev2_char =~ /^[bcdfghjklmnpqrstvwxz]+$/i)
1169
- && ($romanized_next_char =~ /^[bcdfghjklmnpqrstvwxz]+$/i)) {
1170
- $this->add_node("o", $i, $i+1, *chart_ht, "", "thai-middle-o-ang"); # keep between consonant+tone-mark and consonant
1171
- } else {
1172
- $this->add_node("", $i, $i+1, *chart_ht, "", "thai-middle-o-ang-drop"); # drop next to vowel
1173
- }
1174
- }
1175
-
1176
- # Romanization with space
1177
- } elsif ($romanized_char =~ /\s/) {
1178
- $this->add_node($char, $i, $i+1, *chart_ht, "", "space");
1179
-
1180
- # Tibetan special cases
1181
- } elsif ($current_script eq "Tibetan") {
1182
-
1183
- if ($subjoined_char_p
1184
- && ($prev_script eq $current_script)
1185
- && $prev_letter_plus_char_p
1186
- && ($prev_char_roman =~ /^[bcdfghjklmnpqrstvwxyz]+$/i)) {
1187
- $this->add_node("$prev_char_roman$romanized_char", $prev_node_start, $i+1, *chart_ht, "", "subjoined-tibetan-character");
1188
- } elsif ($romanized_char =~ /^-A$/i) {
1189
- my $romanized_next_char = $this->romanize_char_at_position($i+1, $lang_code, $output_style, *ht, *chart_ht);
1190
- if (! $prev_letter_plus_char_p) {
1191
- $this->add_node("'", $i, $i+1, *chart_ht, "", "tibetan-frontal-dash-a");
1192
- } elsif (($prev_script eq $current_script)
1193
- && ($next_script eq $current_script)
1194
- && ($prev_char_roman =~ /[bcdfghjklmnpqrstvwxyz]$/)
1195
- && ($romanized_next_char =~ /^[aeiou]/)) {
1196
- $this->add_node("a'", $i, $i+1, *chart_ht, "", "tibetan-medial-dash-a");
1197
- } elsif (($prev_script eq $current_script)
1198
- && ($next_script eq $current_script)
1199
- && ($prev_char_roman =~ /[aeiou]$/)
1200
- && ($romanized_next_char =~ /[aeiou]/)) {
1201
- $this->add_node("'", $i, $i+1, *chart_ht, "", "tibetan-reduced-medial-dash-a");
1202
- } elsif (($prev_script eq $current_script)
1203
- && (! ($prev_char_roman =~ /[aeiou]/))
1204
- && (! $next_letter_plus_char_p)) {
1205
- $this->add_node("a", $i, $i+1, *chart_ht, "", "tibetan-final-dash-a");
1206
- } else {
1207
- $this->add_node("a", $i, $i+1, *chart_ht, "", "unexpected-tibetan-dash-a");
1208
- }
1209
- } elsif (($romanized_char =~ /^[AEIOU]/i)
1210
- && ($prev_script eq $current_script)
1211
- && ($prev_char_roman =~ /^A$/i)
1212
- && (! $prev2_letter_plus_char_p)) {
1213
- $this->add_node($romanized_char, $prev_node_start, $i+1, *chart_ht, "", "tibetan-dropped-word-initial-a");
1214
- } else {
1215
- $this->add_node($romanized_char, $i, $i+1, *chart_ht, "", "standard-unicode-based-romanization");
1216
- }
1217
-
1218
- # Khmer (for MUUSIKATOAN etc. see under "Diacritic" above)
1219
- } elsif (($current_script eq "Khmer")
1220
- && (($char_roman_consonant, $char_roman_vowel) = ($romanized_char =~ /^(.*[bcdfghjklmnpqrstvwxyz])([ao]+)-$/i))) {
1221
- my $romanized_next_char = $this->romanize_char_at_position($i+1, $lang_code, $output_style, *ht, *chart_ht);
1222
- if (($next_script eq $current_script)
1223
- && ($romanized_next_char =~ /^[aeiouy]/i)) {
1224
- $this->add_node($char_roman_consonant, $i, $i+1, *chart_ht, "", "khmer-vowel-drop");
1225
- } else {
1226
- $this->add_node("$char_roman_consonant$char_roman_vowel", $i, $i+1, *chart_ht, "", "khmer-standard-unicode-based-romanization");
1227
- }
1228
-
1229
- # Abudiga add default vowel
1230
- } elsif ((@abudiga_default_vowels = sort keys %{$ht{SCRIPT_ABUDIGA_DEFAULT_VOWEL}->{$current_script}})
1231
- && ($abudiga_default_vowel = $abudiga_default_vowels[0])
1232
- && ($romanized_char =~ /^[bcdfghjklmnpqrstvwxyz]+$/i)) {
1233
- my $new_roman = join("", $romanized_char, $abudiga_default_vowel);
1234
- $this->add_node($new_roman, $i, $i+1, *chart_ht, "", "standard-unicode-based-romanization-plus-abudiga-default-vowel");
1235
- # print STDERR " Abudiga add default vowel l.$line_number/$i: $new_roman\n" if $line_number =~ /^[12]$/;
1236
-
1237
- # Standard romanization
1238
- } else {
1239
- $node_id = $this->add_node($romanized_char, $i, $i+1, *chart_ht, "", "standard-unicode-based-romanization");
1240
- }
1241
- } else {
1242
- $this->add_node($char, $i, $i+1, *chart_ht, "", "unexpected-original");
1243
- }
1244
- } elsif (defined($romanized_char = $this->romanize_char_at_position($i, $lang_code, $output_style, *ht, *chart_ht))
1245
- && ((length($romanized_char) <= 2)
1246
- || ($ht{UTF_TO_CHAR_ROMANIZATION}->{$char}))) { # or from unicode_overwrite_romanization table
1247
- $romanized_char =~ s/^""$//;
1248
- $this->add_node($romanized_char, $i, $i+1, *chart_ht, "", "romanized-without-character-name");
1249
- } else {
1250
- $this->add_node($char, $i, $i+1, *chart_ht, "", "unexpected-original-without-character-name");
1251
- }
1252
- }
1253
- $i = $next_index;
1254
- }
1255
-
1256
- $this->schwa_deletion(0, $n_characters, *chart_ht, $lang_code);
1257
- $this->default_vowelize_tibetan(0, $n_characters, *chart_ht, $lang_code, $line_number) if $chart_ht{CHART_CONTAINS_SCRIPT}->{"Tibetan"};
1258
- $this->assemble_numbers_in_chart(*chart_ht, $line_number);
1259
-
1260
- if ($return_chart_p) {
1261
- } elsif ($return_offset_mappings_p) {
1262
- ($result, $offset_mappings, $new_char_offset, $new_rom_char_offset) = $this->best_romanized_string(0, $n_characters, *chart_ht, $control, $initial_char_offset, $initial_rom_char_offset);
1263
- } else {
1264
- $result = $this->best_romanized_string(0, $n_characters, *chart_ht) unless $return_chart_p;
1265
- }
1266
-
1267
- if ($verbosePM) {
1268
- my $logfile = "/nfs/isd/ulf/cgi-mt/amr-tmp/uroman-log.txt";
1269
- $util->append_to_file($logfile, $log) if $log && (-r $logfile);
1270
- }
1271
-
1272
- return ($result, $offset_mappings) if $return_offset_mappings_p;
1273
- return *chart_ht if $return_chart_p;
1274
- return $result;
1275
- }
1276
-
1277
- sub string_to_json_string {
1278
- local($this, $s) = @_;
1279
-
1280
- utf8::decode($s);
1281
- my $j = JSON->new->utf8->encode([$s]);
1282
- $j =~ s/^\[(.*)\]$/$1/;
1283
- return $j;
1284
- }
1285
-
1286
- sub chart_to_json_romanization_elements {
1287
- local($this, $chart_start, $chart_end, *chart_ht, $line_number) = @_;
1288
-
1289
- my $result = "";
1290
- my $start = $chart_start;
1291
- my $end;
1292
- while ($start < $chart_end) {
1293
- $end = $this->find_end_of_rom_segment($start, $chart_end, *chart_ht);
1294
- my @best_romanizations;
1295
- if (($end && ($start < $end))
1296
- && (@best_romanizations = $this->best_romanizations($start, $end, *chart_ht))) {
1297
- $orig_segment = $this->orig_string_at_span($start, $end, *chart_ht);
1298
- $next_start = $end;
1299
- } else {
1300
- $orig_segment = $chart_ht{ORIG_CHAR}->{$start};
1301
- @best_romanizations = ($orig);
1302
- $next_start = $start + 1;
1303
- }
1304
- $exclusive_end = $end - 1;
1305
- # $guarded_orig = $util->string_guard($orig_segment);
1306
- $guarded_orig = $this->string_to_json_string($orig_segment);
1307
- $result .= " { \"line\": $line_number, \"start\": $start, \"end\": $exclusive_end, \"orig\": $guarded_orig, \"roms\": [";
1308
- foreach $i ((0 .. $#best_romanizations)) {
1309
- my $rom = $best_romanizations[$i];
1310
- # my $guarded_rom = $util->string_guard($rom);
1311
- my $guarded_rom = $this->string_to_json_string($rom);
1312
- $result .= " { \"rom\": $guarded_rom";
1313
- # $result .= ", \"alt\": true" if $i >= 1;
1314
- $result .= " }";
1315
- $result .= "," if $i < $#best_romanizations;
1316
- }
1317
- $result .= " ] },\n";
1318
- $start = $next_start;
1319
- }
1320
- return $result;
1321
- }
1322
-
1323
- sub default_vowelize_tibetan {
1324
- local($this, $chart_start, $chart_end, *chart_ht, $lang_code, $line_number) = @_;
1325
-
1326
- # my $verbose = ($line_number == 103);
1327
- # print STDERR "\nStart default_vowelize_tibetan l.$line_number $chart_start-$chart_end\n" if $verbose;
1328
- my $token_start = $chart_start;
1329
- my $next_token_start = $chart_start;
1330
- while (($token_start = $next_token_start) < $chart_end) {
1331
- $next_token_start = $token_start + 1;
1332
-
1333
- next unless $chart_ht{CHAR_LETTER_PLUS}->{$token_start};
1334
- my $current_script = $chart_ht{CHAR_SCRIPT}->{$token_start};
1335
- next unless ($current_script eq "Tibetan");
1336
- my $token_end = $chart_ht{LETTER_TOKEN_SEGMENT_START_TO_END}->{$token_start};
1337
- next unless $token_end;
1338
- next unless $token_end > $token_start;
1339
- $next_token_start = $token_end;
1340
-
1341
- my $start = $token_start;
1342
- my $end;
1343
- my @node_ids = ();
1344
- while ($start < $token_end) {
1345
- $end = $this->find_end_of_rom_segment($start, $chart_end, *chart_ht);
1346
- last unless $end && ($end > $start);
1347
- my @alt_node_ids = sort { $a <=> $b } keys %{$chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end}};
1348
- last unless @alt_node_ids;
1349
- push(@node_ids, $alt_node_ids[0]);
1350
- $start = $end;
1351
- }
1352
- my $contains_vowel_p = 0;
1353
- my @romanizations = ();
1354
- foreach $node_id (@node_ids) {
1355
- my $roman = $chart_ht{NODE_ROMAN}->{$node_id};
1356
- $roman = "" unless defined($roman);
1357
- push(@romanizations, $roman);
1358
- $contains_vowel_p = 1 if $roman =~ /[aeiou]/i;
1359
- }
1360
- # print STDERR " old: $token_start-$token_end @romanizations\n" if $verbose;
1361
- unless ($contains_vowel_p) {
1362
- my $default_vowel_target_index;
1363
- if ($#node_ids <= 1) {
1364
- $default_vowel_target_index = 0;
1365
- } elsif ($romanizations[$#romanizations] eq "s") {
1366
- if ($romanizations[($#romanizations-1)] eq "y") {
1367
- $default_vowel_target_index = $#romanizations-1;
1368
- } else {
1369
- $default_vowel_target_index = $#romanizations-2;
1370
- }
1371
- } else {
1372
- $default_vowel_target_index = $#romanizations-1;
1373
- }
1374
- $romanizations[$default_vowel_target_index] .= "a";
1375
- my $old_node_id = $node_ids[$default_vowel_target_index];
1376
- my $old_start = $chart_ht{NODE_START}->{$old_node_id};
1377
- my $old_end = $chart_ht{NODE_END}->{$old_node_id};
1378
- my $old_roman = $chart_ht{NODE_ROMAN}->{$old_node_id};
1379
- my $new_roman = $old_roman . "a";
1380
- my $new_node_id = $this->add_node($new_roman, $old_start, $old_end, *chart_ht, "", "tibetan-default-vowel");
1381
- $this->copy_slot_values($old_node_id, $new_node_id, *chart_id, "all");
1382
- $chart_ht{NODE_TYPE}->{$old_node_id} = "backup"; # keep, but demote
1383
- }
1384
- if (($romanizations[0] eq "'")
1385
- && ($#romanizations >= 1)
1386
- && ($romanizations[1] =~ /^[o]$/)) {
1387
- my $old_node_id = $node_ids[0];
1388
- my $old_start = $chart_ht{NODE_START}->{$old_node_id};
1389
- my $old_end = $chart_ht{NODE_END}->{$old_node_id};
1390
- my $new_node_id = $this->add_node("", $old_start, $old_end, *chart_ht, "", "tibetan-delete-apostrophe");
1391
- $this->copy_slot_values($old_node_id, $new_node_id, *chart_id, "all");
1392
- $chart_ht{NODE_TYPE}->{$old_node_id} = "alt"; # keep, but demote
1393
- }
1394
- if (($#node_ids >= 1)
1395
- && ($romanizations[$#romanizations] =~ /^[bcdfghjklmnpqrstvwxz]+y$/)) {
1396
- my $old_node_id = $node_ids[$#romanizations];
1397
- my $old_start = $chart_ht{NODE_START}->{$old_node_id};
1398
- my $old_end = $chart_ht{NODE_END}->{$old_node_id};
1399
- my $old_roman = $chart_ht{NODE_ROMAN}->{$old_node_id};
1400
- my $new_roman = $old_roman . "a";
1401
- my $new_node_id = $this->add_node($new_roman, $old_start, $old_end, *chart_ht, "", "tibetan-syllable-final-vowel");
1402
- $this->copy_slot_values($old_node_id, $new_node_id, *chart_id, "all");
1403
- $chart_ht{NODE_TYPE}->{$old_node_id} = "alt"; # keep, but demote
1404
- }
1405
- foreach $old_node_id (@node_ids) {
1406
- my $old_roman = $chart_ht{NODE_ROMAN}->{$old_node_id};
1407
- next unless $old_roman =~ /-a/;
1408
- my $old_start = $chart_ht{NODE_START}->{$old_node_id};
1409
- my $old_end = $chart_ht{NODE_END}->{$old_node_id};
1410
- my $new_roman = $old_roman;
1411
- $new_roman =~ s/-a/a/;
1412
- my $new_node_id = $this->add_node($new_roman, $old_start, $old_end, *chart_ht, "", "tibetan-syllable-delete-dash");
1413
- $this->copy_slot_values($old_node_id, $new_node_id, *chart_id, "all");
1414
- $chart_ht{NODE_TYPE}->{$old_node_id} = "alt"; # keep, but demote
1415
- }
1416
- }
1417
- }
1418
-
1419
- sub schwa_deletion {
1420
- local($this, $chart_start, $chart_end, *chart_ht, $lang_code) = @_;
1421
- # delete word-final simple "a" in Devanagari (e.g. nepaala -> nepaal)
1422
- # see Wikipedia article "Schwa deletion in Indo-Aryan languages"
1423
-
1424
- if ($chart_ht{CHART_CONTAINS_SCRIPT}->{"Devanagari"}) {
1425
- my $script_start = $chart_start;
1426
- my $next_script_start = $chart_start;
1427
- while (($script_start = $next_script_start) < $chart_end) {
1428
- $next_script_start = $script_start + 1;
1429
-
1430
- my $current_script = $chart_ht{CHAR_SCRIPT}->{$script_start};
1431
- next unless ($current_script eq "Devanagari");
1432
- my $script_end = $chart_ht{SCRIPT_SEGMENT_START_TO_END}->{$script_start};
1433
- next unless $script_end;
1434
- next unless $script_end - $script_start >= 2;
1435
- $next_script_start = $script_end;
1436
- my $end_node_id = $this->get_node_for_span($script_end-1, $script_end, *chart_ht);
1437
- next unless $end_node_id;
1438
- my $end_roman = $chart_ht{NODE_ROMAN}->{$end_node_id};
1439
- next unless ($end_consonant) = ($end_roman =~ /^([bcdfghjklmnpqrstvwxz]+)a$/i);
1440
- my $prev_node_id = $this->get_node_for_span($script_end-4, $script_end-1, *chart_ht)
1441
- || $this->get_node_for_span($script_end-3, $script_end-1, *chart_ht)
1442
- || $this->get_node_for_span($script_end-2, $script_end-1, *chart_ht);
1443
- next unless $prev_node_id;
1444
- my $prev_roman = $chart_ht{NODE_ROMAN}->{$prev_node_id};
1445
- next unless $prev_roman =~ /[aeiou]/i;
1446
- # TO DO: check further back for vowel (e.g. if $prev_roman eq "r" due to vowel cancelation)
1447
-
1448
- $chart_ht{NODE_TYPE}->{$end_node_id} = "alt"; # keep, but demote
1449
- # print STDERR "* Schwa deletion " . ($script_end-1) . "-$script_end $end_roman->$end_consonant\n";
1450
- $this->add_node($end_consonant, $script_end-1, $script_end, *chart_ht, "", "devanagari-with-deleted-final-schwa");
1451
- }
1452
- }
1453
- }
1454
-
1455
- sub best_romanized_string {
1456
- local($this, $chart_start, $chart_end, *chart_ht, $control, $orig_char_offset, $rom_char_offset) = @_;
1457
-
1458
- $control = "" unless defined($control);
1459
- my $current_orig_char_offset = $orig_char_offset || 0;
1460
- my $current_rom_char_offset = $rom_char_offset || 0;
1461
- my $return_offset_mappings_p = ($control =~ /\breturn offset mappings\b/);
1462
- my $result = "";
1463
- my $start = $chart_start;
1464
- my $end;
1465
- my @char_offsets = ("$current_orig_char_offset:$current_rom_char_offset");
1466
- while ($start < $chart_end) {
1467
- $end = $this->find_end_of_rom_segment($start, $chart_end, *chart_ht);
1468
- my $n_orig_chars_in_segment = 0;
1469
- my $n_rom_chars_in_segment = 0;
1470
- if ($end && ($start < $end)) {
1471
- my @best_romanizations = $this->best_romanizations($start, $end, *chart_ht);
1472
- my $best_romanization = (@best_romanizations) ? $best_romanizations[0] : undef;
1473
- if (defined($best_romanization)) {
1474
- $result .= $best_romanization;
1475
- if ($return_offset_mappings_p) {
1476
- $n_orig_chars_in_segment = $end-$start;
1477
- $n_rom_chars_in_segment = $utf8->length_in_utf8_chars($best_romanization);
1478
- }
1479
- $start = $end;
1480
- } else {
1481
- my $best_romanization = $chart_ht{ORIG_CHAR}->{$start};
1482
- $result .= $best_romanization;
1483
- $start++;
1484
- if ($return_offset_mappings_p) {
1485
- $n_orig_chars_in_segment = 1;
1486
- $n_rom_chars_in_segment = $utf8->length_in_utf8_chars($best_romanization);
1487
- }
1488
- }
1489
- } else {
1490
- my $best_romanization = $chart_ht{ORIG_CHAR}->{$start};
1491
- $result .= $best_romanization;
1492
- $start++;
1493
- if ($return_offset_mappings_p) {
1494
- $n_orig_chars_in_segment = 1;
1495
- $n_rom_chars_in_segment = $utf8->length_in_utf8_chars($best_romanization);
1496
- }
1497
- }
1498
- if ($return_offset_mappings_p) {
1499
- my $new_orig_char_offset = $current_orig_char_offset + $n_orig_chars_in_segment;
1500
- my $new_rom_char_offset = $current_rom_char_offset + $n_rom_chars_in_segment;
1501
- my $offset_mapping = "$new_orig_char_offset:$new_rom_char_offset";
1502
- push(@char_offsets, $offset_mapping);
1503
- $current_orig_char_offset = $new_orig_char_offset;
1504
- $current_rom_char_offset = $new_rom_char_offset;
1505
- }
1506
- }
1507
- return ($result, join(",", @char_offsets), $current_orig_char_offset, $current_rom_char_offset) if $return_offset_mappings_p;
1508
- return $result;
1509
- }
1510
-
1511
- sub orig_string_at_span {
1512
- local($this, $start, $end, *chart_ht) = @_;
1513
-
1514
- my $result = "";
1515
- foreach $i (($start .. ($end-1))) {
1516
- $result .= $chart_ht{ORIG_CHAR}->{$i};
1517
- }
1518
- return $result;
1519
- }
1520
-
1521
- sub find_end_of_rom_segment {
1522
- local($this, $start, $chart_end, *chart_ht) = @_;
1523
-
1524
- my @ends = sort { $a <=> $b } keys %{$chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}};
1525
- my $end_index = $#ends;
1526
- while (($end_index >= 0) && ($ends[$end_index] > $chart_end)) {
1527
- $end_index--;
1528
- }
1529
- if (($end_index >= 0)
1530
- && defined($end = $ends[$end_index])
1531
- && ($start < $end)) {
1532
- return $end;
1533
- } else {
1534
- return "";
1535
- }
1536
- }
1537
-
1538
- sub best_romanizations {
1539
- local($this, $start, $end, *chart_ht) = @_;
1540
-
1541
- @regular_romanizations = ();
1542
- @alt_romanizations = ();
1543
- @backup_romanizations = ();
1544
-
1545
- foreach $node_id (sort { $a <=> $b } keys %{$chart_ht{NODES_STARTING_AND_ENDING_AT}->{$start}->{$end}}) {
1546
- my $type = $chart_ht{NODE_TYPE}->{$node_id};
1547
- my $roman = $chart_ht{NODE_ROMAN}->{$node_id};
1548
- if (! defined($roman)) {
1549
- # ignore
1550
- } elsif (($type eq "backup") && ! defined($backup_romanization)) {
1551
- push(@backup_romanizations, $roman) unless $util->member($roman, @backup_romanizations);
1552
- } elsif (($type eq "alt") && ! defined($alt_romanization)) {
1553
- push(@alt_romanizations, $roman) unless $util->member($roman, @alt_romanizations);
1554
- } else {
1555
- push(@regular_romanizations, $roman) unless $util->member($roman, @regular_romanizations);
1556
- }
1557
- }
1558
- @regular_alt_romanizations = sort @regular_romanizations;
1559
- foreach $alt_romanization (sort @alt_romanizations) {
1560
- push(@regular_alt_romanizations, $alt_romanization) unless $util->member($alt_romanization, @regular_alt_romanizations);
1561
- }
1562
- return @regular_alt_romanizations if @regular_alt_romanizations;
1563
- return sort @backup_romanizations;
1564
- }
1565
-
1566
- sub join_alt_romanizations_for_viz {
1567
- local($this, @list) = @_;
1568
-
1569
- my @viz_romanizations = ();
1570
-
1571
- foreach $alt_rom (@list) {
1572
- if ($alt_rom eq "") {
1573
- push(@viz_romanizations, "-");
1574
- } else {
1575
- push(@viz_romanizations, $alt_rom);
1576
- }
1577
- }
1578
- return join(", ", @viz_romanizations);
1579
- }
1580
-
1581
- sub markup_orig_rom_strings {
1582
- local($this, $chart_start, $chart_end, *ht, *chart_ht, *pinyin_ht, $last_group_id_index) = @_;
1583
-
1584
- my $marked_up_rom = "";
1585
- my $marked_up_orig = "";
1586
- my $start = $chart_start;
1587
- my $end;
1588
- while ($start < $chart_end) {
1589
- my $segment_start = $start;
1590
- my $segment_end = $start+1;
1591
- my $end = $this->find_end_of_rom_segment($start, $chart_end, *chart_ht);
1592
- my $rom_segment = "";
1593
- my $orig_segment = "";
1594
- my $rom_title = "";
1595
- my $orig_title = "";
1596
- my $contains_alt_romanizations = 0;
1597
- if ($end) {
1598
- $segment_end = $end;
1599
- my @best_romanizations = $this->best_romanizations($start, $end, *chart_ht);
1600
- my $best_romanization = (@best_romanizations) ? $best_romanizations[0] : undef;
1601
- if (defined($best_romanization)) {
1602
- $rom_segment .= $best_romanization;
1603
- $orig_segment .= $this->orig_string_at_span($start, $end, *chart_ht);
1604
- $segment_end = $end;
1605
- if ($#best_romanizations >= 1) {
1606
- $rom_title .= $util->guard_html("Alternative romanizations: " . $this->join_alt_romanizations_for_viz(@best_romanizations) . "\n");
1607
- $contains_alt_romanizations = 1;
1608
- }
1609
- } else {
1610
- my $segment = $this->orig_string_at_span($start, $start+1, *chart_ht);
1611
- $rom_segment .= $segment;
1612
- $orig_segment .= $segment;
1613
- $segment_end = $start+1;
1614
- }
1615
- $start = $segment_end;
1616
- } else {
1617
- $rom_segment .= $chart_ht{ORIG_CHAR}->{$start};
1618
- $orig_segment .= $this->orig_string_at_span($start, $start+1, *chart_ht);
1619
- $segment_end = $start+1;
1620
- $start = $segment_end;
1621
- }
1622
- my $next_char = $chart_ht{ORIG_CHAR}->{$segment_end};
1623
- my $next_char_is_combining_p = $this->char_is_combining_char($next_char, *ht);
1624
- while ($next_char_is_combining_p
1625
- && ($segment_end < $chart_end)
1626
- && ($end = $this->find_end_of_rom_segment($segment_end, $chart_end, *chart_ht))
1627
- && ($end > $segment_end)
1628
- && (@best_romanizations = $this->best_romanizations($segment_end, $end, *chart_ht))
1629
- && defined($best_romanization = $best_romanizations[0])) {
1630
- $orig_segment .= $this->orig_string_at_span($segment_end, $end, *chart_ht);
1631
- $rom_segment .= $best_romanization;
1632
- if ($#best_romanizations >= 1) {
1633
- $rom_title .= $util->guard_html("Alternative romanizations: " . $this->join_alt_romanizations_for_viz(@best_romanizations) . "\n");
1634
- $contains_alt_romanizations = 1;
1635
- }
1636
- $segment_end = $end;
1637
- $start = $segment_end;
1638
- $next_char = $chart_ht{ORIG_CHAR}->{$segment_end};
1639
- $next_char_is_combining_p = $this->char_is_combining_char($next_char, *ht);
1640
- }
1641
- foreach $i (($segment_start .. ($segment_end-1))) {
1642
- $orig_title .= "+&#x200E; &#x200E;" unless $orig_title eq "";
1643
- my $char = $chart_ht{ORIG_CHAR}->{$i};
1644
- my $numeric = $ht{UTF_TO_NUMERIC}->{$char};
1645
- $numeric = "" unless defined($numeric);
1646
- my $pic_descr = $ht{UTF_TO_PICTURE_DESCR}->{$char};
1647
- $pic_descr = "" unless defined($pic_descr);
1648
- if ($char =~ /^\xE4\xB7[\x80-\xBF]$/) {
1649
- $orig_title .= "$char_name\n";
1650
- } elsif (($char =~ /^[\xE3-\xE9][\x80-\xBF]{2,2}$/) && $chinesePM->string_contains_utf8_cjk_unified_ideograph_p($char)) {
1651
- my $unicode = $utf8->utf8_to_unicode($char);
1652
- $orig_title .= "CJK Unified Ideograph U+" . (uc sprintf("%04x", $unicode)) . "\n";
1653
- $orig_title .= "Chinese: $tonal_translit\n" if $tonal_translit = $chinesePM->tonal_pinyin($char, *pinyin_ht, "");
1654
- $orig_title .= "Number: $numeric\n" if $numeric =~ /\d/;
1655
- } elsif ($char_name = $ht{UTF_TO_CHAR_NAME}->{$char}) {
1656
- $orig_title .= "$char_name\n";
1657
- $orig_title .= "Number: $numeric\n" if $numeric =~ /\d/;
1658
- $orig_title .= "Picture: $pic_descr\n" if $pic_descr =~ /\S/;
1659
- } else {
1660
- my $unicode = $utf8->utf8_to_unicode($char);
1661
- if (($unicode >= 0xAC00) && ($unicode <= 0xD7A3)) {
1662
- $orig_title .= "Hangul syllable U+" . (uc sprintf("%04x", $unicode)) . "\n";
1663
- } else {
1664
- $orig_title .= "Unicode character U+" . (uc sprintf("%04x", $unicode)) . "\n";
1665
- }
1666
- }
1667
- }
1668
- (@non_ascii_roms) = ($rom_segment =~ /([\xC0-\xFF][\x80-\xBF]*)/g);
1669
- foreach $char (@non_ascii_roms) {
1670
- my $char_name = $ht{UTF_TO_CHAR_NAME}->{$char};
1671
- my $unicode = $utf8->utf8_to_unicode($char);
1672
- my $unicode_s = "U+" . (uc sprintf("%04x", $unicode));
1673
- if ($char_name) {
1674
- $rom_title .= "$char_name\n";
1675
- } else {
1676
- $rom_title .= "$unicode_s\n";
1677
- }
1678
- }
1679
- $last_group_id_index++;
1680
- $rom_title =~ s/\s*$//;
1681
- $rom_title =~ s/\n/&#xA;/g;
1682
- $orig_title =~ s/\s*$//;
1683
- $orig_title =~ s/\n/&#xA;&#x200E;/g;
1684
- $orig_title = "&#x202D;" . $orig_title . "&#x202C;";
1685
- my $rom_title_clause = ($rom_title eq "") ? "" : " title=\"$rom_title\"";
1686
- my $orig_title_clause = ($orig_title eq "") ? "" : " title=\"$orig_title\"";
1687
- my $alt_rom_clause = ($contains_alt_romanizations) ? "border-bottom:1px dotted;" : "";
1688
- $marked_up_rom .= "<span id=\"span-$last_group_id_index-1\" onmouseover=\"highlight_elems('span-$last_group_id_index','1');\" onmouseout=\"highlight_elems('span-$last_group_id_index','0');\" style=\"color:#00BB00;$alt_rom_clause\"$rom_title_clause>" . $util->guard_html($rom_segment) . "<\/span>";
1689
- $marked_up_orig .= "<span id=\"span-$last_group_id_index-2\" onmouseover=\"highlight_elems('span-$last_group_id_index','1');\" onmouseout=\"highlight_elems('span-$last_group_id_index','0');\"$orig_title_clause>" . $util->guard_html($orig_segment) . "<\/span>";
1690
- if (($last_char = $chart_ht{ORIG_CHAR}->{($segment_end-1)})
1691
- && ($last_char_name = $ht{UTF_TO_CHAR_NAME}->{$last_char})
1692
- && ($last_char_name =~ /^(FULLWIDTH COLON|FULLWIDTH COMMA|FULLWIDTH RIGHT PARENTHESIS|IDEOGRAPHIC COMMA|IDEOGRAPHIC FULL STOP|RIGHT CORNER BRACKET|BRAILLE PATTERN BLANK|TIBETAN MARK .*)$/)) {
1693
- $marked_up_orig .= "<wbr>";
1694
- $marked_up_rom .= "<wbr>";
1695
- }
1696
- }
1697
- return ($marked_up_rom, $marked_up_orig, $last_group_id_index);
1698
- }
1699
-
1700
- sub romanizations_with_alternatives {
1701
- local($this, *ht, *chart_ht, *pinyin_ht, $chart_start, $chart_end) = @_;
1702
-
1703
- $chart_start = 0 unless defined($chart_start);
1704
- $chart_end = $chart_ht{N_CHARS} unless defined($chart_end);
1705
- my $result = "";
1706
- my $start = $chart_start;
1707
- my $end;
1708
- # print STDOUT "romanizations_with_alternatives $chart_start-$chart_end\n";
1709
- while ($start < $chart_end) {
1710
- my $segment_start = $start;
1711
- my $segment_end = $start+1;
1712
- my $end = $this->find_end_of_rom_segment($start, $chart_end, *chart_ht);
1713
- my $rom_segment = "";
1714
- # print STDOUT " $start-$end\n";
1715
- if ($end) {
1716
- $segment_end = $end;
1717
- my @best_romanizations = $this->best_romanizations($start, $end, *chart_ht);
1718
- # print STDOUT " $start-$end @best_romanizations\n";
1719
- if (@best_romanizations) {
1720
- if ($#best_romanizations == 0) {
1721
- $rom_segment .= $best_romanizations[0];
1722
- } else {
1723
- $rom_segment .= "{" . join("|", @best_romanizations) . "}";
1724
- }
1725
- $segment_end = $end;
1726
- } else {
1727
- my $segment = $this->orig_string_at_span($start, $start+1, *chart_ht);
1728
- $rom_segment .= $segment;
1729
- $segment_end = $start+1;
1730
- }
1731
- $start = $segment_end;
1732
- } else {
1733
- $rom_segment .= $chart_ht{ORIG_CHAR}->{$start};
1734
- $segment_end = $start+1;
1735
- $start = $segment_end;
1736
- }
1737
- # print STDOUT " $start-$end ** $rom_segment\n";
1738
- $result .= $rom_segment;
1739
- }
1740
- return $result;
1741
- }
1742
-
1743
- sub quick_romanize {
1744
- local($this, $s, $lang_code, *ht) = @_;
1745
-
1746
- my $result = "";
1747
- my @chars = $utf8->split_into_utf8_characters($s, "return only chars", *empty_ht);
1748
- while (@chars) {
1749
- my $found_match_in_table_p = 0;
1750
- foreach $string_length (reverse(1..4)) {
1751
- next if ($string_length-1) > $#chars;
1752
- $multi_char_substring = join("", @chars[0..($string_length-1)]);
1753
- my @mappings = keys %{$ht{UTF_CHAR_MAPPING_LANG_SPEC}->{$lang_code}->{$multi_char_substring}};
1754
- @mappings = keys %{$ht{UTF_CHAR_MAPPING}->{$multi_char_substring}} unless @mappings;
1755
- if (@mappings) {
1756
- my $mapping = $mappings[0];
1757
- $result .= $mapping;
1758
- foreach $_ ((1 .. $string_length)) {
1759
- shift @chars;
1760
- }
1761
- $found_match_in_table_p = 1;
1762
- last;
1763
- }
1764
- }
1765
- unless ($found_match_in_table_p) {
1766
- $result .= $chars[0];
1767
- shift @chars;
1768
- }
1769
- }
1770
- return $result;
1771
- }
1772
-
1773
- sub char_is_combining_char {
1774
- local($this, $c, *ht) = @_;
1775
-
1776
- return 0 unless $c;
1777
- my $category = $ht{UTF_TO_CAT}->{$c};
1778
- return 0 unless $category;
1779
- return $category =~ /^M/;
1780
- }
1781
-
1782
- sub mark_up_string_for_mouse_over {
1783
- local($this, $s, *ht, $control, *pinyin_ht) = @_;
1784
-
1785
- $control = "" unless defined($control);
1786
- $no_ascii_p = ($control =~ /NO-ASCII/);
1787
- my $result = "";
1788
- @chars = $utf8->split_into_utf8_characters($s, "return only chars", *empty_ht);
1789
- while (@chars) {
1790
- $char = shift @chars;
1791
- $numeric = $ht{UTF_TO_NUMERIC}->{$char};
1792
- $numeric = "" unless defined($numeric);
1793
- $pic_descr = $ht{UTF_TO_PICTURE_DESCR}->{$char};
1794
- $pic_descr = "" unless defined($pic_descr);
1795
- $next_char = ($#chars >= 0) ? $chars[0] : "";
1796
- $next_char_is_combining_p = $this->char_is_combining_char($next_char, *ht);
1797
- if ($no_ascii_p
1798
- && ($char =~ /^[\x00-\x7F]*$/)
1799
- && ! $next_char_is_combining_p) {
1800
- $result .= $util->guard_html($char);
1801
- } elsif (($char =~ /^[\xE3-\xE9][\x80-\xBF]{2,2}$/) && $chinesePM->string_contains_utf8_cjk_unified_ideograph_p($char)) {
1802
- $unicode = $utf8->utf8_to_unicode($char);
1803
- $title = "CJK Unified Ideograph U+" . (uc sprintf("%04x", $unicode));
1804
- $title .= "&#xA;Chinese: $tonal_translit" if $tonal_translit = $chinesePM->tonal_pinyin($char, *pinyin_ht, "");
1805
- $title .= "&#xA;Number: $numeric" if $numeric =~ /\d/;
1806
- $result .= "<span title=\"$title\">" . $util->guard_html($char) . "<\/span>";
1807
- } elsif ($char_name = $ht{UTF_TO_CHAR_NAME}->{$char}) {
1808
- $title = $char_name;
1809
- $title .= "&#xA;Number: $numeric" if $numeric =~ /\d/;
1810
- $title .= "&#xA;Picture: $pic_descr" if $pic_descr =~ /\S/;
1811
- $char_plus = $char;
1812
- while ($next_char_is_combining_p) {
1813
- # combining marks (Mc:non-spacing, Mc:spacing combining, Me: enclosing)
1814
- $next_char_name = $ht{UTF_TO_CHAR_NAME}->{$next_char};
1815
- $title .= "&#xA;+ $next_char_name";
1816
- $char = shift @chars;
1817
- $char_plus .= $char;
1818
- $next_char = ($#chars >= 0) ? $chars[0] : "";
1819
- $next_char_is_combining_p = $this->char_is_combining_char($next_char, *ht);
1820
- }
1821
- $result .= "<span title=\"$title\">" . $util->guard_html($char_plus) . "<\/span>";
1822
- $result .= "<wbr>" if $char_name =~ /^(FULLWIDTH COLON|FULLWIDTH COMMA|FULLWIDTH RIGHT PARENTHESIS|IDEOGRAPHIC COMMA|IDEOGRAPHIC FULL STOP|RIGHT CORNER BRACKET)$/;
1823
- } elsif (($unicode = $utf8->utf8_to_unicode($char))
1824
- && ($unicode >= 0xAC00) && ($unicode <= 0xD7A3)) {
1825
- $title = "Hangul syllable U+" . (uc sprintf("%04x", $unicode));
1826
- $result .= "<span title=\"$title\">" . $util->guard_html($char) . "<\/span>";
1827
- } else {
1828
- $result .= $util->guard_html($char);
1829
- }
1830
- }
1831
- return $result;
1832
- }
1833
-
1834
- sub romanize_char_at_position_incl_multi {
1835
- local($this, $i, $lang_code, $output_style, *ht, *chart_ht) = @_;
1836
-
1837
- my $char = $chart_ht{ORIG_CHAR}->{$i};
1838
- return "" unless defined($char);
1839
- my @mappings = keys %{$ht{UTF_CHAR_MAPPING_LANG_SPEC}->{$lang_code}->{$char}};
1840
- return $mappings[0] if @mappings;
1841
- @mappings = keys %{$ht{UTF_CHAR_MAPPING}->{$char}};
1842
- return $mappings[0] if @mappings;
1843
- return $this->romanize_char_at_position($i, $lang_code, $output_style, *ht, *chart_ht);
1844
- }
1845
-
1846
- sub romanize_char_at_position {
1847
- local($this, $i, $lang_code, $output_style, *ht, *chart_ht) = @_;
1848
-
1849
- my $char = $chart_ht{ORIG_CHAR}->{$i};
1850
- return "" unless defined($char);
1851
- return $char if $char =~ /^[\x00-\x7F]$/; # ASCII
1852
- my $romanization = $ht{UTF_TO_CHAR_ROMANIZATION}->{$char};
1853
- return $romanization if $romanization;
1854
- my $char_name = $chart_ht{CHAR_NAME}->{$i};
1855
- $romanization = $this->romanize_charname($char_name, $lang_code, $output_style, *ht, $char);
1856
- $ht{SUSPICIOUS_ROMANIZATION}->{$char_name}->{$romanization}
1857
- = ($ht{SUSPICIOUS_ROMANIZATION}->{$char_name}->{$romanization} || 0) + 1
1858
- unless (length($romanization) < 4)
1859
- || ($romanization =~ /\s/)
1860
- || ($romanization =~ /^[bcdfghjklmnpqrstvwxyz]{2,3}[aeiou]-$/) # Khmer ngo-/nyo-/pho- OK
1861
- || ($romanization =~ /^[bcdfghjklmnpqrstvwxyz]{2,2}[aeiougw][aeiou]{1,2}$/) # Canadian, Ethiopic syllable OK
1862
- || ($romanization =~ /^(allah|bbux|nyaa|nnya|quuv|rrep|shch|shur|syrx)$/i) # Arabic; Yi; Ethiopic syllable nyaa; Cyrillic letter shcha
1863
- || (($char_name =~ /^(YI SYLLABLE|VAI SYLLABLE|ETHIOPIC SYLLABLE|CANADIAN SYLLABICS|CANADIAN SYLLABICS CARRIER)\s+(\S+)$/) && (length($romanization) <= 5));
1864
- # print STDERR "romanize_char_at_position $i $char_name :: $romanization\n" if $char_name =~ /middle/i;
1865
- return $romanization;
1866
- }
1867
-
1868
- sub romanize_charname {
1869
- local($this, $char_name, $lang_code, $output_style, *ht, $char) = @_;
1870
-
1871
- my $cached_result = $ht{ROMANIZE_CHARNAME}->{$char_name}->{$lang_code}->{$output_style};
1872
- # print STDERR "(C) romanize_charname($char_name): $cached_result\n" if $cached_result && ($char_name =~ /middle/i);
1873
- return $cached_result if defined($cashed_result);
1874
- $orig_char_name = $char_name;
1875
- $char_name =~ s/^.* LETTER\s+([A-Z]+)-\d+$/$1/; # HENTAIGANA LETTER A-3
1876
- $char_name =~ s/^.* LETTER\s+//;
1877
- $char_name =~ s/^.* SYLLABLE\s+B\d\d\d\s+//; # Linear B syllables
1878
- $char_name =~ s/^.* SYLLABLE\s+//;
1879
- $char_name =~ s/^.* SYLLABICS\s+//;
1880
- $char_name =~ s/^.* LIGATURE\s+//;
1881
- $char_name =~ s/^.* VOWEL SIGN\s+//;
1882
- $char_name =~ s/^.* CONSONANT SIGN\s+//;
1883
- $char_name =~ s/^.* CONSONANT\s+//;
1884
- $char_name =~ s/^.* VOWEL\s+//;
1885
- $char_name =~ s/ WITH .*$//;
1886
- $char_name =~ s/ WITHOUT .*$//;
1887
- $char_name =~ s/\s+(ABOVE|AGUNG|BAR|BARREE|BELOW|CEDILLA|CEREK|DIGRAPH|DOACHASHMEE|FINAL FORM|GHUNNA|GOAL|INITIAL FORM|ISOLATED FORM|KAWI|LELET|LELET RASWADI|LONSUM|MAHAPRANA|MEDIAL FORM|MURDA|MURDA MAHAPRANA|REVERSED|ROTUNDA|SASAK|SUNG|TAM|TEDUNG|TYPE ONE|TYPE TWO|WOLOSO)\s*$//;
1888
- $char_name =~ s/^([A-Z]+)\d+$/$1/; # Linear B syllables etc.
1889
- foreach $_ ((1 .. 3)) {
1890
- $char_name =~ s/^.*\b(?:ABKHASIAN|ACADEMY|AFRICAN|AIVILIK|AITON|AKHMIMIC|ALEUT|ALI GALI|ALPAPRAANA|ALTERNATE|ALTERNATIVE|AMBA|ARABIC|ARCHAIC|ASPIRATED|ATHAPASCAN|BASELINE|BLACKLETTER|BARRED|BASHKIR|BERBER|BHATTIPROLU|BIBLE-CREE|BIG|BINOCULAR|BLACKFOOT|BLENDED|BOTTOM|BROAD|BROKEN|CANDRA|CAPITAL|CARRIER|CHILLU|CLOSE|CLOSED|COPTIC|CROSSED|CRYPTOGRAMMIC|CURLED|CURLY|CYRILLIC|DANTAJA|DENTAL|DIALECT-P|DIAERESIZED|DOTLESS|DOUBLE|DOUBLE-STRUCK|EASTERN PWO KAREN|EGYPTOLOGICAL|FARSI|FINAL|FLATTENED|GLOTTAL|GREAT|GREEK|HALF|HIGH|INITIAL|INSULAR|INVERTED|IOTIFIED|JONA|KANTAJA|KASHMIRI|KHAKASSIAN|KHAMTI|KHANDA|KINNA|KIRGHIZ|KOMI|L-SHAPED|LATINATE|LITTLE|LONG|LONG-LEGGED|LOOPED|LOW|MAHAAPRAANA|MALAYALAM|MANCHU|MANDAILING|MATHEMATICAL|MEDIAL|MIDDLE-WELSH|MON|MONOCULAR|MOOSE-CREE|MULTIOCULAR|MUURDHAJA|N-CREE|NARROW|NASKAPI|NDOLE|NEUTRAL|NIKOLSBURG|NORTHERN|NUBIAN|NUNAVIK|NUNAVUT|OJIBWAY|OLD|OPEN|ORKHON|OVERLONG|PALI|PERSIAN|PHARYNGEAL|PRISHTHAMATRA|R-CREE|REDUPLICATION|REVERSED|ROMANIAN|ROUND|ROUNDED|RUDIMENTA|RUMAI PALAUNG|SANSKRIT|SANYAKA|SARA|SAYISI|SCRIPT|SEBATBEIT|SEMISOFT|SGAW KAREN|SHAN|SHARP|SHWE PALAUNG|SHORT|SIBE|SIDEWAYS|SIMALUNGUN|SMALL|SOGDIAN|SOFT|SOUTH-SLAVEY|SOUTHERN|SPIDERY|STIRRUP|STRAIGHT|STRETCHED|SUBSCRIPT|SWASH|TAI LAING|TAILED|TAILLESS|TAALUJA|TH-CREE|TALL|THREE-LEGGED|TURNED|TODO|TOP|TROKUTASTI|TUAREG|UKRAINIAN|UNBLENDED|VISIGOTHIC|VOCALIC|VOICED|VOICELESS|VOLAPUK|WAVY|WESTERN PWO KAREN|WEST-CREE|WESTERN|WIDE|WOODS-CREE|Y-CREE|YENISEI|YIDDISH)\s+//;
1891
- }
1892
- $char_name =~ s/\s+(ABOVE|AGUNG|BAR|BARREE|BELOW|CEDILLA|CEREK|DIGRAPH|DOACHASHMEE|FINAL FORM|GHUNNA|GOAL|INITIAL FORM|ISOLATED FORM|KAWI|LELET|LELET RASWADI|LONSUM|MAHAPRANA|MEDIAL FORM|MURDA|MURDA MAHAPRANA|REVERSED|ROTUNDA|SASAK|SUNG|TAM|TEDUNG|TYPE ONE|TYPE TWO|WOLOSO)\s*$//;
1893
- if ($char_name =~ /THAI CHARACTER/) {
1894
- $char_name =~ s/^THAI CHARACTER\s+//;
1895
- if ($char =~ /^\xE0\xB8[\x81-\xAE]/) {
1896
- # Thai consonants
1897
- $char_name =~ s/^([^AEIOU]*).*/$1/i;
1898
- } elsif ($char_name =~ /^SARA [AEIOU]/) {
1899
- # Thai vowels
1900
- $char_name =~ s/^SARA\s+//;
1901
- } else {
1902
- $char_name = $char;
1903
- }
1904
- }
1905
- if ($orig_char_name =~ /(HIRAGANA LETTER|KATAKANA LETTER|SYLLABLE|LIGATURE)/) {
1906
- $char_name = lc $char_name;
1907
- } elsif ($char_name =~ /\b(ANUSVARA|ANUSVARAYA|NIKAHIT|SIGN BINDI|TIPPI)\b/) {
1908
- $char_name = "+m";
1909
- } elsif ($char_name =~ /\bSCHWA\b/) {
1910
- $char_name = "e";
1911
- } elsif ($char_name =~ /\bIOTA\b/) {
1912
- $char_name = "i";
1913
- } elsif ($char_name =~ /\s/) {
1914
- } elsif ($orig_char_name =~ /KHMER LETTER/) {
1915
- $char_name .= "-";
1916
- } elsif ($orig_char_name =~ /CHEROKEE LETTER/) {
1917
- # use whole letter as is
1918
- } elsif ($orig_char_name =~ /KHMER INDEPENDENT VOWEL/) {
1919
- $char_name =~ s/q//;
1920
- } elsif ($orig_char_name =~ /LETTER/) {
1921
- $char_name =~ s/^[AEIOU]+([^AEIOU]+)$/$1/i;
1922
- $char_name =~ s/^([^-AEIOUY]+)[AEIOU].*/$1/i;
1923
- $char_name =~ s/^(Y)[AEIOU].*/$1/i if $orig_char_name =~ /\b(?:BENGALI|DEVANAGARI|GURMUKHI|GUJARATI|KANNADA|MALAYALAM|MODI|MYANMAR|ORIYA|TAMIL|TELUGU|TIBETAN)\b.*\bLETTER YA\b/;
1924
- $char_name =~ s/^(Y[AEIOU]+)[^AEIOU].*$/$1/i;
1925
- $char_name =~ s/^([AEIOU]+)[^AEIOU]+[AEIOU].*/$1/i;
1926
- }
1927
-
1928
- my $result = ($orig_char_name =~ /\bCAPITAL\b/) ? (uc $char_name) : (lc $char_name);
1929
- # print STDERR "(R) romanize_charname($orig_char_name): $result\n" if $orig_char_name =~ /middle/i;
1930
- $ht{ROMANIZE_CHARNAME}->{$char_name}->{$lang_code}->{$output_style} = $result;
1931
- return $result;
1932
- }
1933
-
1934
- sub assemble_numbers_in_chart {
1935
- local($this, *chart_ht, $line_number) = @_;
1936
-
1937
- foreach $start (sort { $a <=> $b } keys %{$chart_ht{COMPLEX_NUMERIC_START_END}}) {
1938
- my $end = $chart_ht{COMPLEX_NUMERIC_START_END}->{$start};
1939
- my @numbers = ();
1940
- foreach $i (($start .. ($end-1))) {
1941
- my $orig_char = $chart_ht{ORIG_CHAR}->{$i};
1942
- my $node_id = $this->get_node_for_span_with_slot($i, $i+1, "numeric-value", *chart_id);
1943
- if (defined($node_id)) {
1944
- my $number = $chart_ht{NODE_ROMAN}->{$node_id};
1945
- if (defined($number)) {
1946
- push(@numbers, $number);
1947
- } elsif ($orig_char =~ /^[.,]$/) { # decimal point, comma separator
1948
- push(@numbers, $orig_char);
1949
- } else {
1950
- print STDERR "Found no romanization for node_id $node_id ($i-" . ($i+1) . ") in assemble_numbers_in_chart\n" if $verbosePM;
1951
- }
1952
- } else {
1953
- print STDERR "Found no node_id for span $i-" . ($i+1) . " in assemble_numbers_in_chart\n" if $verbosePM;
1954
- }
1955
- }
1956
- my $complex_number = $this->assemble_number(join("\xC2\xB7", @numbers), $line_number);
1957
- # print STDERR "assemble_numbers_in_chart l.$line_number $start-$end $complex_number (@numbers)\n";
1958
- $this->add_node($complex_number, $start, $end, *chart_ht, "", "complex-number");
1959
- }
1960
- }
1961
-
1962
- sub assemble_number {
1963
- local($this, $s, $line_number) = @_;
1964
- # e.g. 10 9 100 7 10 8 = 1978
1965
-
1966
- my $middot = "\xC2\xB7";
1967
- my @tokens = split(/$middot/, $s); # middle dot U+00B7
1968
- my $i = 0;
1969
- my @orig_tokens = @tokens;
1970
-
1971
- # assemble single digit numbers, e.g. 1 7 5 -> 175
1972
- while ($i < $#tokens) {
1973
- if ($tokens[$i] =~ /^\d$/) {
1974
- my $j = $i+1;
1975
- while (($j <= $#tokens) && ($tokens[$j] =~ /^[0-9.,]$/)) {
1976
- $j++;
1977
- }
1978
- $j--;
1979
- if ($j>$i) {
1980
- my $new_token = join("", @tokens[$i .. $j]);
1981
- $new_token =~ s/,//g;
1982
- splice(@tokens, $i, $j-$i+1, $new_token);
1983
- }
1984
- }
1985
- $i++;
1986
- }
1987
-
1988
- foreach $power ((10, 100, 1000, 10000, 100000, 1000000, 100000000, 1000000000, 1000000000000)) {
1989
- for (my $i=0; $i <= $#tokens; $i++) {
1990
- if ($tokens[$i] == $power) {
1991
- if (($i > 0) && ($tokens[($i-1)] < $power)) {
1992
- splice(@tokens, $i-1, 2, ($tokens[($i-1)] * $tokens[$i]));
1993
- $i--;
1994
- if (($i < $#tokens) && ($tokens[($i+1)] < $power)) {
1995
- splice(@tokens, $i, 2, ($tokens[$i] + $tokens[($i+1)]));
1996
- $i--;
1997
- }
1998
- }
1999
- }
2000
- # 400 30 (e.g. Egyptian)
2001
- my $gen_pattern = $power;
2002
- $gen_pattern =~ s/^1/\[1-9\]/;
2003
- if (($tokens[$i] =~ /^$gen_pattern$/) && ($i < $#tokens) && ($tokens[($i+1)] < $power)) {
2004
- splice(@tokens, $i, 2, ($tokens[$i] + $tokens[($i+1)]));
2005
- $i--;
2006
- }
2007
- }
2008
- last if $#tokens == 0;
2009
- }
2010
- my $result = join($middot, @tokens);
2011
- if ($verbosePM) {
2012
- my $logfile = "/nfs/isd/ulf/cgi-mt/amr-tmp/uroman-number-log.txt";
2013
- $util->append_to_file($logfile, "$s -> $result\n") if -r $logfile;
2014
- # print STDERR " assemble number l.$line_number @orig_tokens -> $result\n" if $line_number == 43;
2015
- }
2016
- return $result;
2017
- }
2018
-
2019
- 1;
2020
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alfasign/Einfach.Stable_DiffPomrpter/README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Einfach.Stable DiffPomrpter
3
- emoji: 🐠
4
- colorFrom: gray
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 3.35.2
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/kandinsky_v22/test_kandinsky.py DELETED
@@ -1,262 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2023 HuggingFace Inc.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- import gc
17
- import random
18
- import unittest
19
-
20
- import numpy as np
21
- import torch
22
-
23
- from diffusers import DDIMScheduler, KandinskyV22Pipeline, KandinskyV22PriorPipeline, UNet2DConditionModel, VQModel
24
- from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
25
- from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
26
-
27
- from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
28
-
29
-
30
- enable_full_determinism()
31
-
32
-
33
- class Dummies:
34
- @property
35
- def text_embedder_hidden_size(self):
36
- return 32
37
-
38
- @property
39
- def time_input_dim(self):
40
- return 32
41
-
42
- @property
43
- def block_out_channels_0(self):
44
- return self.time_input_dim
45
-
46
- @property
47
- def time_embed_dim(self):
48
- return self.time_input_dim * 4
49
-
50
- @property
51
- def cross_attention_dim(self):
52
- return 32
53
-
54
- @property
55
- def dummy_unet(self):
56
- torch.manual_seed(0)
57
-
58
- model_kwargs = {
59
- "in_channels": 4,
60
- # Out channels is double in channels because predicts mean and variance
61
- "out_channels": 8,
62
- "addition_embed_type": "image",
63
- "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
64
- "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
65
- "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
66
- "block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),
67
- "layers_per_block": 1,
68
- "encoder_hid_dim": self.text_embedder_hidden_size,
69
- "encoder_hid_dim_type": "image_proj",
70
- "cross_attention_dim": self.cross_attention_dim,
71
- "attention_head_dim": 4,
72
- "resnet_time_scale_shift": "scale_shift",
73
- "class_embed_type": None,
74
- }
75
-
76
- model = UNet2DConditionModel(**model_kwargs)
77
- return model
78
-
79
- @property
80
- def dummy_movq_kwargs(self):
81
- return {
82
- "block_out_channels": [32, 64],
83
- "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
84
- "in_channels": 3,
85
- "latent_channels": 4,
86
- "layers_per_block": 1,
87
- "norm_num_groups": 8,
88
- "norm_type": "spatial",
89
- "num_vq_embeddings": 12,
90
- "out_channels": 3,
91
- "up_block_types": [
92
- "AttnUpDecoderBlock2D",
93
- "UpDecoderBlock2D",
94
- ],
95
- "vq_embed_dim": 4,
96
- }
97
-
98
- @property
99
- def dummy_movq(self):
100
- torch.manual_seed(0)
101
- model = VQModel(**self.dummy_movq_kwargs)
102
- return model
103
-
104
- def get_dummy_components(self):
105
- unet = self.dummy_unet
106
- movq = self.dummy_movq
107
-
108
- scheduler = DDIMScheduler(
109
- num_train_timesteps=1000,
110
- beta_schedule="linear",
111
- beta_start=0.00085,
112
- beta_end=0.012,
113
- clip_sample=False,
114
- set_alpha_to_one=False,
115
- steps_offset=1,
116
- prediction_type="epsilon",
117
- thresholding=False,
118
- )
119
-
120
- components = {
121
- "unet": unet,
122
- "scheduler": scheduler,
123
- "movq": movq,
124
- }
125
- return components
126
-
127
- def get_dummy_inputs(self, device, seed=0):
128
- image_embeds = floats_tensor((1, self.text_embedder_hidden_size), rng=random.Random(seed)).to(device)
129
- negative_image_embeds = floats_tensor((1, self.text_embedder_hidden_size), rng=random.Random(seed + 1)).to(
130
- device
131
- )
132
- if str(device).startswith("mps"):
133
- generator = torch.manual_seed(seed)
134
- else:
135
- generator = torch.Generator(device=device).manual_seed(seed)
136
- inputs = {
137
- "image_embeds": image_embeds,
138
- "negative_image_embeds": negative_image_embeds,
139
- "generator": generator,
140
- "height": 64,
141
- "width": 64,
142
- "guidance_scale": 4.0,
143
- "num_inference_steps": 2,
144
- "output_type": "np",
145
- }
146
- return inputs
147
-
148
-
149
- class KandinskyV22PipelineFastTests(PipelineTesterMixin, unittest.TestCase):
150
- pipeline_class = KandinskyV22Pipeline
151
- params = [
152
- "image_embeds",
153
- "negative_image_embeds",
154
- ]
155
- batch_params = ["image_embeds", "negative_image_embeds"]
156
- required_optional_params = [
157
- "generator",
158
- "height",
159
- "width",
160
- "latents",
161
- "guidance_scale",
162
- "num_inference_steps",
163
- "return_dict",
164
- "guidance_scale",
165
- "num_images_per_prompt",
166
- "output_type",
167
- "return_dict",
168
- ]
169
- test_xformers_attention = False
170
-
171
- def get_dummy_inputs(self, device, seed=0):
172
- dummies = Dummies()
173
- return dummies.get_dummy_inputs(device=device, seed=seed)
174
-
175
- def get_dummy_components(self):
176
- dummies = Dummies()
177
- return dummies.get_dummy_components()
178
-
179
- def test_kandinsky(self):
180
- device = "cpu"
181
-
182
- components = self.get_dummy_components()
183
-
184
- pipe = self.pipeline_class(**components)
185
- pipe = pipe.to(device)
186
-
187
- pipe.set_progress_bar_config(disable=None)
188
-
189
- output = pipe(**self.get_dummy_inputs(device))
190
- image = output.images
191
-
192
- image_from_tuple = pipe(
193
- **self.get_dummy_inputs(device),
194
- return_dict=False,
195
- )[0]
196
-
197
- image_slice = image[0, -3:, -3:, -1]
198
- image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
199
-
200
- assert image.shape == (1, 64, 64, 3)
201
-
202
- expected_slice = np.array([0.3420, 0.9505, 0.3919, 1.0000, 0.5188, 0.3109, 0.6139, 0.5624, 0.6811])
203
-
204
- assert (
205
- np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
206
- ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
207
-
208
- assert (
209
- np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
210
- ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"
211
-
212
-
213
- @slow
214
- @require_torch_gpu
215
- class KandinskyV22PipelineIntegrationTests(unittest.TestCase):
216
- def tearDown(self):
217
- # clean up the VRAM after each test
218
- super().tearDown()
219
- gc.collect()
220
- torch.cuda.empty_cache()
221
-
222
- def test_kandinsky_text2img(self):
223
- expected_image = load_numpy(
224
- "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
225
- "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy"
226
- )
227
-
228
- pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
229
- "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
230
- )
231
- pipe_prior.to(torch_device)
232
-
233
- pipeline = KandinskyV22Pipeline.from_pretrained(
234
- "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
235
- )
236
- pipeline = pipeline.to(torch_device)
237
- pipeline.set_progress_bar_config(disable=None)
238
-
239
- prompt = "red cat, 4k photo"
240
-
241
- generator = torch.Generator(device="cuda").manual_seed(0)
242
- image_emb, zero_image_emb = pipe_prior(
243
- prompt,
244
- generator=generator,
245
- num_inference_steps=5,
246
- negative_prompt="",
247
- ).to_tuple()
248
-
249
- generator = torch.Generator(device="cuda").manual_seed(0)
250
- output = pipeline(
251
- image_embeds=image_emb,
252
- negative_image_embeds=zero_image_emb,
253
- generator=generator,
254
- num_inference_steps=100,
255
- output_type="np",
256
- )
257
-
258
- image = output.images[0]
259
-
260
- assert image.shape == (512, 512, 3)
261
-
262
- assert_mean_pixel_difference(image, expected_image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_detection/configs/fp16/faster_rcnn_r50_fpn_fp16_1x_coco.py DELETED
@@ -1,3 +0,0 @@
1
- _base_ = '../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'
2
- # fp16 settings
3
- fp16 = dict(loss_scale=512.)
 
 
 
 
spaces/AnishKumbhar/ChatBot/text-generation-webui-main/modules/relative_imports.py DELETED
@@ -1,13 +0,0 @@
1
- import sys
2
- from pathlib import Path
3
-
4
-
5
- class RelativeImport:
6
- def __init__(self, path):
7
- self.import_path = Path(path)
8
-
9
- def __enter__(self):
10
- sys.path.insert(0, str(self.import_path))
11
-
12
- def __exit__(self, exc_type, exc_value, traceback):
13
- sys.path.remove(str(self.import_path))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/configs/_base_/datasets/ade20k.py DELETED
@@ -1,54 +0,0 @@
1
- # dataset settings
2
- dataset_type = 'ADE20KDataset'
3
- data_root = 'data/ade/ADEChallengeData2016'
4
- img_norm_cfg = dict(
5
- mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
6
- crop_size = (512, 512)
7
- train_pipeline = [
8
- dict(type='LoadImageFromFile'),
9
- dict(type='LoadAnnotations', reduce_zero_label=True),
10
- dict(type='Resize', img_scale=(2048, 512), ratio_range=(0.5, 2.0)),
11
- dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75),
12
- dict(type='RandomFlip', prob=0.5),
13
- dict(type='PhotoMetricDistortion'),
14
- dict(type='Normalize', **img_norm_cfg),
15
- dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255),
16
- dict(type='DefaultFormatBundle'),
17
- dict(type='Collect', keys=['img', 'gt_semantic_seg']),
18
- ]
19
- test_pipeline = [
20
- dict(type='LoadImageFromFile'),
21
- dict(
22
- type='MultiScaleFlipAug',
23
- img_scale=(2048, 512),
24
- # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],
25
- flip=False,
26
- transforms=[
27
- dict(type='Resize', keep_ratio=True),
28
- dict(type='RandomFlip'),
29
- dict(type='Normalize', **img_norm_cfg),
30
- dict(type='ImageToTensor', keys=['img']),
31
- dict(type='Collect', keys=['img']),
32
- ])
33
- ]
34
- data = dict(
35
- samples_per_gpu=4,
36
- workers_per_gpu=4,
37
- train=dict(
38
- type=dataset_type,
39
- data_root=data_root,
40
- img_dir='images/training',
41
- ann_dir='annotations/training',
42
- pipeline=train_pipeline),
43
- val=dict(
44
- type=dataset_type,
45
- data_root=data_root,
46
- img_dir='images/validation',
47
- ann_dir='annotations/validation',
48
- pipeline=test_pipeline),
49
- test=dict(
50
- type=dataset_type,
51
- data_root=data_root,
52
- img_dir='images/validation',
53
- ann_dir='annotations/validation',
54
- pipeline=test_pipeline))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/parallel/data_container.py DELETED
@@ -1,89 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
- import functools
3
-
4
- import torch
5
-
6
-
7
- def assert_tensor_type(func):
8
-
9
- @functools.wraps(func)
10
- def wrapper(*args, **kwargs):
11
- if not isinstance(args[0].data, torch.Tensor):
12
- raise AttributeError(
13
- f'{args[0].__class__.__name__} has no attribute '
14
- f'{func.__name__} for type {args[0].datatype}')
15
- return func(*args, **kwargs)
16
-
17
- return wrapper
18
-
19
-
20
- class DataContainer:
21
- """A container for any type of objects.
22
-
23
- Typically tensors will be stacked in the collate function and sliced along
24
- some dimension in the scatter function. This behavior has some limitations.
25
- 1. All tensors have to be the same size.
26
- 2. Types are limited (numpy array or Tensor).
27
-
28
- We design `DataContainer` and `MMDataParallel` to overcome these
29
- limitations. The behavior can be either of the following.
30
-
31
- - copy to GPU, pad all tensors to the same size and stack them
32
- - copy to GPU without stacking
33
- - leave the objects as is and pass it to the model
34
- - pad_dims specifies the number of last few dimensions to do padding
35
- """
36
-
37
- def __init__(self,
38
- data,
39
- stack=False,
40
- padding_value=0,
41
- cpu_only=False,
42
- pad_dims=2):
43
- self._data = data
44
- self._cpu_only = cpu_only
45
- self._stack = stack
46
- self._padding_value = padding_value
47
- assert pad_dims in [None, 1, 2, 3]
48
- self._pad_dims = pad_dims
49
-
50
- def __repr__(self):
51
- return f'{self.__class__.__name__}({repr(self.data)})'
52
-
53
- def __len__(self):
54
- return len(self._data)
55
-
56
- @property
57
- def data(self):
58
- return self._data
59
-
60
- @property
61
- def datatype(self):
62
- if isinstance(self.data, torch.Tensor):
63
- return self.data.type()
64
- else:
65
- return type(self.data)
66
-
67
- @property
68
- def cpu_only(self):
69
- return self._cpu_only
70
-
71
- @property
72
- def stack(self):
73
- return self._stack
74
-
75
- @property
76
- def padding_value(self):
77
- return self._padding_value
78
-
79
- @property
80
- def pad_dims(self):
81
- return self._pad_dims
82
-
83
- @assert_tensor_type
84
- def size(self, *args, **kwargs):
85
- return self.data.size(*args, **kwargs)
86
-
87
- @assert_tensor_type
88
- def dim(self):
89
- return self.data.dim()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/docs/annotator.md DELETED
@@ -1,49 +0,0 @@
1
- # Automatic Annotations
2
-
3
- We provide gradio examples to obtain annotations that are aligned to our pretrained production-ready models.
4
-
5
- Just run
6
-
7
- python gradio_annotator.py
8
-
9
- Since everyone has different habit to organize their datasets, we do not hard code any scripts for batch processing. But "gradio_annotator.py" is written in a super readable way, and modifying it to annotate your images should be easy.
10
-
11
- In the gradio UI of "gradio_annotator.py" we have the following interfaces:
12
-
13
- ### Canny Edge
14
-
15
- Be careful about "black edge and white background" or "white edge and black background".
16
-
17
- ![p](../github_page/a1.png)
18
-
19
- ### HED Edge
20
-
21
- Be careful about "black edge and white background" or "white edge and black background".
22
-
23
- ![p](../github_page/a2.png)
24
-
25
- ### MLSD Edge
26
-
27
- Be careful about "black edge and white background" or "white edge and black background".
28
-
29
- ![p](../github_page/a3.png)
30
-
31
- ### MIDAS Depth and Normal
32
-
33
- Be careful about RGB or BGR in normal maps.
34
-
35
- ![p](../github_page/a4.png)
36
-
37
- ### Openpose
38
-
39
- Be careful about RGB or BGR in pose maps.
40
-
41
- For our production-ready model, the hand pose option is turned off.
42
-
43
- ![p](../github_page/a5.png)
44
-
45
- ### Uniformer Segmentation
46
-
47
- Be careful about RGB or BGR in segmentation maps.
48
-
49
- ![p](../github_page/a6.png)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ArtGAN/Segment-Anything-Video/README.md DELETED
@@ -1,15 +0,0 @@
1
- ---
2
- title: Segment-Anything-Video
3
- emoji: 🐨
4
- colorFrom: blue
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 3.19.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- tags:
12
- - making-demos
13
- ---
14
-
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/cli/main.py DELETED
@@ -1,79 +0,0 @@
1
- """Primary application entrypoint.
2
- """
3
- import locale
4
- import logging
5
- import os
6
- import sys
7
- import warnings
8
- from typing import List, Optional
9
-
10
- from pip._internal.cli.autocompletion import autocomplete
11
- from pip._internal.cli.main_parser import parse_command
12
- from pip._internal.commands import create_command
13
- from pip._internal.exceptions import PipError
14
- from pip._internal.utils import deprecation
15
-
16
- logger = logging.getLogger(__name__)
17
-
18
-
19
- # Do not import and use main() directly! Using it directly is actively
20
- # discouraged by pip's maintainers. The name, location and behavior of
21
- # this function is subject to change, so calling it directly is not
22
- # portable across different pip versions.
23
-
24
- # In addition, running pip in-process is unsupported and unsafe. This is
25
- # elaborated in detail at
26
- # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
27
- # That document also provides suggestions that should work for nearly
28
- # all users that are considering importing and using main() directly.
29
-
30
- # However, we know that certain users will still want to invoke pip
31
- # in-process. If you understand and accept the implications of using pip
32
- # in an unsupported manner, the best approach is to use runpy to avoid
33
- # depending on the exact location of this entry point.
34
-
35
- # The following example shows how to use runpy to invoke pip in that
36
- # case:
37
- #
38
- # sys.argv = ["pip", your, args, here]
39
- # runpy.run_module("pip", run_name="__main__")
40
- #
41
- # Note that this will exit the process after running, unlike a direct
42
- # call to main. As it is not safe to do any processing after calling
43
- # main, this should not be an issue in practice.
44
-
45
-
46
- def main(args: Optional[List[str]] = None) -> int:
47
- if args is None:
48
- args = sys.argv[1:]
49
-
50
- # Suppress the pkg_resources deprecation warning
51
- # Note - we use a module of .*pkg_resources to cover
52
- # the normal case (pip._vendor.pkg_resources) and the
53
- # devendored case (a bare pkg_resources)
54
- warnings.filterwarnings(
55
- action="ignore", category=DeprecationWarning, module=".*pkg_resources"
56
- )
57
-
58
- # Configure our deprecation warnings to be sent through loggers
59
- deprecation.install_warning_logger()
60
-
61
- autocomplete()
62
-
63
- try:
64
- cmd_name, cmd_args = parse_command(args)
65
- except PipError as exc:
66
- sys.stderr.write(f"ERROR: {exc}")
67
- sys.stderr.write(os.linesep)
68
- sys.exit(1)
69
-
70
- # Needed for locale.getpreferredencoding(False) to work
71
- # in pip._internal.utils.encoding.auto_decode
72
- try:
73
- locale.setlocale(locale.LC_ALL, "")
74
- except locale.Error as e:
75
- # setlocale can apparently crash if locale are uninitialized
76
- logger.debug("Ignoring error %s when setting locale", e)
77
- command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
78
-
79
- return command.main(cmd_args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/platformdirs/android.py DELETED
@@ -1,126 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import os
4
- import re
5
- import sys
6
- from functools import lru_cache
7
- from typing import cast
8
-
9
- from .api import PlatformDirsABC
10
-
11
-
12
- class Android(PlatformDirsABC):
13
- """
14
- Follows the guidance `from here <https://android.stackexchange.com/a/216132>`_. Makes use of the
15
- `appname <platformdirs.api.PlatformDirsABC.appname>`,
16
- `version <platformdirs.api.PlatformDirsABC.version>`,
17
- `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`.
18
- """
19
-
20
- @property
21
- def user_data_dir(self) -> str:
22
- """:return: data directory tied to the user, e.g. ``/data/user/<userid>/<packagename>/files/<AppName>``"""
23
- return self._append_app_name_and_version(cast(str, _android_folder()), "files")
24
-
25
- @property
26
- def site_data_dir(self) -> str:
27
- """:return: data directory shared by users, same as `user_data_dir`"""
28
- return self.user_data_dir
29
-
30
- @property
31
- def user_config_dir(self) -> str:
32
- """
33
- :return: config directory tied to the user, e.g. ``/data/user/<userid>/<packagename>/shared_prefs/<AppName>``
34
- """
35
- return self._append_app_name_and_version(cast(str, _android_folder()), "shared_prefs")
36
-
37
- @property
38
- def site_config_dir(self) -> str:
39
- """:return: config directory shared by the users, same as `user_config_dir`"""
40
- return self.user_config_dir
41
-
42
- @property
43
- def user_cache_dir(self) -> str:
44
- """:return: cache directory tied to the user, e.g. e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>``"""
45
- return self._append_app_name_and_version(cast(str, _android_folder()), "cache")
46
-
47
- @property
48
- def site_cache_dir(self) -> str:
49
- """:return: cache directory shared by users, same as `user_cache_dir`"""
50
- return self.user_cache_dir
51
-
52
- @property
53
- def user_state_dir(self) -> str:
54
- """:return: state directory tied to the user, same as `user_data_dir`"""
55
- return self.user_data_dir
56
-
57
- @property
58
- def user_log_dir(self) -> str:
59
- """
60
- :return: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it,
61
- e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>/log``
62
- """
63
- path = self.user_cache_dir
64
- if self.opinion:
65
- path = os.path.join(path, "log")
66
- return path
67
-
68
- @property
69
- def user_documents_dir(self) -> str:
70
- """
71
- :return: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``
72
- """
73
- return _android_documents_folder()
74
-
75
- @property
76
- def user_runtime_dir(self) -> str:
77
- """
78
- :return: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it,
79
- e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>/tmp``
80
- """
81
- path = self.user_cache_dir
82
- if self.opinion:
83
- path = os.path.join(path, "tmp")
84
- return path
85
-
86
-
87
- @lru_cache(maxsize=1)
88
- def _android_folder() -> str | None:
89
- """:return: base folder for the Android OS or None if cannot be found"""
90
- try:
91
- # First try to get path to android app via pyjnius
92
- from jnius import autoclass
93
-
94
- Context = autoclass("android.content.Context") # noqa: N806
95
- result: str | None = Context.getFilesDir().getParentFile().getAbsolutePath()
96
- except Exception:
97
- # if fails find an android folder looking path on the sys.path
98
- pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
99
- for path in sys.path:
100
- if pattern.match(path):
101
- result = path.split("/files")[0]
102
- break
103
- else:
104
- result = None
105
- return result
106
-
107
-
108
- @lru_cache(maxsize=1)
109
- def _android_documents_folder() -> str:
110
- """:return: documents folder for the Android OS"""
111
- # Get directories with pyjnius
112
- try:
113
- from jnius import autoclass
114
-
115
- Context = autoclass("android.content.Context") # noqa: N806
116
- Environment = autoclass("android.os.Environment") # noqa: N806
117
- documents_dir: str = Context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
118
- except Exception:
119
- documents_dir = "/storage/emulated/0/Documents"
120
-
121
- return documents_dir
122
-
123
-
124
- __all__ = [
125
- "Android",
126
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/_collections.py DELETED
@@ -1,337 +0,0 @@
1
- from __future__ import absolute_import
2
-
3
- try:
4
- from collections.abc import Mapping, MutableMapping
5
- except ImportError:
6
- from collections import Mapping, MutableMapping
7
- try:
8
- from threading import RLock
9
- except ImportError: # Platform-specific: No threads available
10
-
11
- class RLock:
12
- def __enter__(self):
13
- pass
14
-
15
- def __exit__(self, exc_type, exc_value, traceback):
16
- pass
17
-
18
-
19
- from collections import OrderedDict
20
-
21
- from .exceptions import InvalidHeader
22
- from .packages import six
23
- from .packages.six import iterkeys, itervalues
24
-
25
- __all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"]
26
-
27
-
28
- _Null = object()
29
-
30
-
31
- class RecentlyUsedContainer(MutableMapping):
32
- """
33
- Provides a thread-safe dict-like container which maintains up to
34
- ``maxsize`` keys while throwing away the least-recently-used keys beyond
35
- ``maxsize``.
36
-
37
- :param maxsize:
38
- Maximum number of recent elements to retain.
39
-
40
- :param dispose_func:
41
- Every time an item is evicted from the container,
42
- ``dispose_func(value)`` is called. Callback which will get called
43
- """
44
-
45
- ContainerCls = OrderedDict
46
-
47
- def __init__(self, maxsize=10, dispose_func=None):
48
- self._maxsize = maxsize
49
- self.dispose_func = dispose_func
50
-
51
- self._container = self.ContainerCls()
52
- self.lock = RLock()
53
-
54
- def __getitem__(self, key):
55
- # Re-insert the item, moving it to the end of the eviction line.
56
- with self.lock:
57
- item = self._container.pop(key)
58
- self._container[key] = item
59
- return item
60
-
61
- def __setitem__(self, key, value):
62
- evicted_value = _Null
63
- with self.lock:
64
- # Possibly evict the existing value of 'key'
65
- evicted_value = self._container.get(key, _Null)
66
- self._container[key] = value
67
-
68
- # If we didn't evict an existing value, we might have to evict the
69
- # least recently used item from the beginning of the container.
70
- if len(self._container) > self._maxsize:
71
- _key, evicted_value = self._container.popitem(last=False)
72
-
73
- if self.dispose_func and evicted_value is not _Null:
74
- self.dispose_func(evicted_value)
75
-
76
- def __delitem__(self, key):
77
- with self.lock:
78
- value = self._container.pop(key)
79
-
80
- if self.dispose_func:
81
- self.dispose_func(value)
82
-
83
- def __len__(self):
84
- with self.lock:
85
- return len(self._container)
86
-
87
- def __iter__(self):
88
- raise NotImplementedError(
89
- "Iteration over this class is unlikely to be threadsafe."
90
- )
91
-
92
- def clear(self):
93
- with self.lock:
94
- # Copy pointers to all values, then wipe the mapping
95
- values = list(itervalues(self._container))
96
- self._container.clear()
97
-
98
- if self.dispose_func:
99
- for value in values:
100
- self.dispose_func(value)
101
-
102
- def keys(self):
103
- with self.lock:
104
- return list(iterkeys(self._container))
105
-
106
-
107
- class HTTPHeaderDict(MutableMapping):
108
- """
109
- :param headers:
110
- An iterable of field-value pairs. Must not contain multiple field names
111
- when compared case-insensitively.
112
-
113
- :param kwargs:
114
- Additional field-value pairs to pass in to ``dict.update``.
115
-
116
- A ``dict`` like container for storing HTTP Headers.
117
-
118
- Field names are stored and compared case-insensitively in compliance with
119
- RFC 7230. Iteration provides the first case-sensitive key seen for each
120
- case-insensitive pair.
121
-
122
- Using ``__setitem__`` syntax overwrites fields that compare equal
123
- case-insensitively in order to maintain ``dict``'s api. For fields that
124
- compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``
125
- in a loop.
126
-
127
- If multiple fields that are equal case-insensitively are passed to the
128
- constructor or ``.update``, the behavior is undefined and some will be
129
- lost.
130
-
131
- >>> headers = HTTPHeaderDict()
132
- >>> headers.add('Set-Cookie', 'foo=bar')
133
- >>> headers.add('set-cookie', 'baz=quxx')
134
- >>> headers['content-length'] = '7'
135
- >>> headers['SET-cookie']
136
- 'foo=bar, baz=quxx'
137
- >>> headers['Content-Length']
138
- '7'
139
- """
140
-
141
- def __init__(self, headers=None, **kwargs):
142
- super(HTTPHeaderDict, self).__init__()
143
- self._container = OrderedDict()
144
- if headers is not None:
145
- if isinstance(headers, HTTPHeaderDict):
146
- self._copy_from(headers)
147
- else:
148
- self.extend(headers)
149
- if kwargs:
150
- self.extend(kwargs)
151
-
152
- def __setitem__(self, key, val):
153
- self._container[key.lower()] = [key, val]
154
- return self._container[key.lower()]
155
-
156
- def __getitem__(self, key):
157
- val = self._container[key.lower()]
158
- return ", ".join(val[1:])
159
-
160
- def __delitem__(self, key):
161
- del self._container[key.lower()]
162
-
163
- def __contains__(self, key):
164
- return key.lower() in self._container
165
-
166
- def __eq__(self, other):
167
- if not isinstance(other, Mapping) and not hasattr(other, "keys"):
168
- return False
169
- if not isinstance(other, type(self)):
170
- other = type(self)(other)
171
- return dict((k.lower(), v) for k, v in self.itermerged()) == dict(
172
- (k.lower(), v) for k, v in other.itermerged()
173
- )
174
-
175
- def __ne__(self, other):
176
- return not self.__eq__(other)
177
-
178
- if six.PY2: # Python 2
179
- iterkeys = MutableMapping.iterkeys
180
- itervalues = MutableMapping.itervalues
181
-
182
- __marker = object()
183
-
184
- def __len__(self):
185
- return len(self._container)
186
-
187
- def __iter__(self):
188
- # Only provide the originally cased names
189
- for vals in self._container.values():
190
- yield vals[0]
191
-
192
- def pop(self, key, default=__marker):
193
- """D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
194
- If key is not found, d is returned if given, otherwise KeyError is raised.
195
- """
196
- # Using the MutableMapping function directly fails due to the private marker.
197
- # Using ordinary dict.pop would expose the internal structures.
198
- # So let's reinvent the wheel.
199
- try:
200
- value = self[key]
201
- except KeyError:
202
- if default is self.__marker:
203
- raise
204
- return default
205
- else:
206
- del self[key]
207
- return value
208
-
209
- def discard(self, key):
210
- try:
211
- del self[key]
212
- except KeyError:
213
- pass
214
-
215
- def add(self, key, val):
216
- """Adds a (name, value) pair, doesn't overwrite the value if it already
217
- exists.
218
-
219
- >>> headers = HTTPHeaderDict(foo='bar')
220
- >>> headers.add('Foo', 'baz')
221
- >>> headers['foo']
222
- 'bar, baz'
223
- """
224
- key_lower = key.lower()
225
- new_vals = [key, val]
226
- # Keep the common case aka no item present as fast as possible
227
- vals = self._container.setdefault(key_lower, new_vals)
228
- if new_vals is not vals:
229
- vals.append(val)
230
-
231
- def extend(self, *args, **kwargs):
232
- """Generic import function for any type of header-like object.
233
- Adapted version of MutableMapping.update in order to insert items
234
- with self.add instead of self.__setitem__
235
- """
236
- if len(args) > 1:
237
- raise TypeError(
238
- "extend() takes at most 1 positional "
239
- "arguments ({0} given)".format(len(args))
240
- )
241
- other = args[0] if len(args) >= 1 else ()
242
-
243
- if isinstance(other, HTTPHeaderDict):
244
- for key, val in other.iteritems():
245
- self.add(key, val)
246
- elif isinstance(other, Mapping):
247
- for key in other:
248
- self.add(key, other[key])
249
- elif hasattr(other, "keys"):
250
- for key in other.keys():
251
- self.add(key, other[key])
252
- else:
253
- for key, value in other:
254
- self.add(key, value)
255
-
256
- for key, value in kwargs.items():
257
- self.add(key, value)
258
-
259
- def getlist(self, key, default=__marker):
260
- """Returns a list of all the values for the named field. Returns an
261
- empty list if the key doesn't exist."""
262
- try:
263
- vals = self._container[key.lower()]
264
- except KeyError:
265
- if default is self.__marker:
266
- return []
267
- return default
268
- else:
269
- return vals[1:]
270
-
271
- # Backwards compatibility for httplib
272
- getheaders = getlist
273
- getallmatchingheaders = getlist
274
- iget = getlist
275
-
276
- # Backwards compatibility for http.cookiejar
277
- get_all = getlist
278
-
279
- def __repr__(self):
280
- return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))
281
-
282
- def _copy_from(self, other):
283
- for key in other:
284
- val = other.getlist(key)
285
- if isinstance(val, list):
286
- # Don't need to convert tuples
287
- val = list(val)
288
- self._container[key.lower()] = [key] + val
289
-
290
- def copy(self):
291
- clone = type(self)()
292
- clone._copy_from(self)
293
- return clone
294
-
295
- def iteritems(self):
296
- """Iterate over all header lines, including duplicate ones."""
297
- for key in self:
298
- vals = self._container[key.lower()]
299
- for val in vals[1:]:
300
- yield vals[0], val
301
-
302
- def itermerged(self):
303
- """Iterate over all headers, merging duplicate ones together."""
304
- for key in self:
305
- val = self._container[key.lower()]
306
- yield val[0], ", ".join(val[1:])
307
-
308
- def items(self):
309
- return list(self.iteritems())
310
-
311
- @classmethod
312
- def from_httplib(cls, message): # Python 2
313
- """Read headers from a Python 2 httplib message object."""
314
- # python2.7 does not expose a proper API for exporting multiheaders
315
- # efficiently. This function re-reads raw lines from the message
316
- # object and extracts the multiheaders properly.
317
- obs_fold_continued_leaders = (" ", "\t")
318
- headers = []
319
-
320
- for line in message.headers:
321
- if line.startswith(obs_fold_continued_leaders):
322
- if not headers:
323
- # We received a header line that starts with OWS as described
324
- # in RFC-7230 S3.2.4. This indicates a multiline header, but
325
- # there exists no previous header to which we can attach it.
326
- raise InvalidHeader(
327
- "Header continuation with no previous header: %s" % line
328
- )
329
- else:
330
- key, value = headers[-1]
331
- headers[-1] = (key, value + " " + line.strip())
332
- continue
333
-
334
- key, value = line.split(":", 1)
335
- headers.append((key, value.strip()))
336
-
337
- return cls(headers)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/importlib_resources/_itertools.py DELETED
@@ -1,35 +0,0 @@
1
- from itertools import filterfalse
2
-
3
- from typing import (
4
- Callable,
5
- Iterable,
6
- Iterator,
7
- Optional,
8
- Set,
9
- TypeVar,
10
- Union,
11
- )
12
-
13
- # Type and type variable definitions
14
- _T = TypeVar('_T')
15
- _U = TypeVar('_U')
16
-
17
-
18
- def unique_everseen(
19
- iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
20
- ) -> Iterator[_T]:
21
- "List unique elements, preserving order. Remember all elements ever seen."
22
- # unique_everseen('AAAABBBCCDAABBB') --> A B C D
23
- # unique_everseen('ABBCcAD', str.lower) --> A B C D
24
- seen: Set[Union[_T, _U]] = set()
25
- seen_add = seen.add
26
- if key is None:
27
- for element in filterfalse(seen.__contains__, iterable):
28
- seen_add(element)
29
- yield element
30
- else:
31
- for element in iterable:
32
- k = key(element)
33
- if k not in seen:
34
- seen_add(k)
35
- yield element
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Banbri/zcvzcv/src/app/interface/ai-clip-factory/index.tsx DELETED
@@ -1,15 +0,0 @@
1
- import { Button } from "@/components/ui/button"
2
-
3
- export function AIClipFactory() {
4
- return (
5
- <Button
6
- variant="outline"
7
- className="bg-yellow-300"
8
- onClick={() => {
9
- window.open("https://huggingface.co/spaces/jbilcke-hf/ai-clip-factory?postId=f63df23d-de2f-4dee-961c-a56f160dd159&prompt=pikachu%2C+working+on+a+computer%2C+office%2C+serious%2C+typing%2C+keyboard&model=TheLastBen%2FPikachu_SDXL", "_blank")
10
- }}>
11
- <span className="hidden md:inline">Try the clip factory!</span>
12
- <span className="inline md:hidden">AI Clips</span>
13
- </Button>
14
- )
15
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_vendor/pyparsing/core.py DELETED
The diff for this file is too large to render. See raw diff
 
spaces/CVPR/LIVE/thrust/testing/unittest/random.h DELETED
@@ -1,134 +0,0 @@
1
- #pragma once
2
-
3
- #include <thrust/host_vector.h>
4
- #include <thrust/random.h>
5
- #include <thrust/detail/type_traits.h>
6
-
7
- #include <limits>
8
-
9
- namespace unittest
10
- {
11
-
12
- inline unsigned int hash(unsigned int a)
13
- {
14
- a = (a+0x7ed55d16) + (a<<12);
15
- a = (a^0xc761c23c) ^ (a>>19);
16
- a = (a+0x165667b1) + (a<<5);
17
- a = (a+0xd3a2646c) ^ (a<<9);
18
- a = (a+0xfd7046c5) + (a<<3);
19
- a = (a^0xb55a4f09) ^ (a>>16);
20
- return a;
21
- }
22
-
23
- template<typename T, typename = void>
24
- struct generate_random_integer;
25
-
26
- template<typename T>
27
- struct generate_random_integer<T,
28
- typename thrust::detail::disable_if<
29
- thrust::detail::is_non_bool_arithmetic<T>::value
30
- >::type
31
- >
32
- {
33
- T operator()(unsigned int i) const
34
- {
35
- thrust::default_random_engine rng(hash(i));
36
-
37
- return static_cast<T>(rng());
38
- }
39
- };
40
-
41
- template<typename T>
42
- struct generate_random_integer<T,
43
- typename thrust::detail::enable_if<
44
- thrust::detail::is_non_bool_integral<T>::value
45
- >::type
46
- >
47
- {
48
- T operator()(unsigned int i) const
49
- {
50
- thrust::default_random_engine rng(hash(i));
51
- thrust::uniform_int_distribution<T> dist;
52
-
53
- return static_cast<T>(dist(rng));
54
- }
55
- };
56
-
57
- template<typename T>
58
- struct generate_random_integer<T,
59
- typename thrust::detail::enable_if<
60
- thrust::detail::is_floating_point<T>::value
61
- >::type
62
- >
63
- {
64
- T operator()(unsigned int i) const
65
- {
66
- T const min = std::numeric_limits<T>::min();
67
- T const max = std::numeric_limits<T>::max();
68
-
69
- thrust::default_random_engine rng(hash(i));
70
- thrust::uniform_real_distribution<T> dist(min, max);
71
-
72
- return static_cast<T>(dist(rng));
73
- }
74
- };
75
-
76
- template<>
77
- struct generate_random_integer<bool>
78
- {
79
- bool operator()(unsigned int i) const
80
- {
81
- thrust::default_random_engine rng(hash(i));
82
- thrust::uniform_int_distribution<unsigned int> dist(0,1);
83
-
84
- return dist(rng) == 1;
85
- }
86
- };
87
-
88
-
89
- template<typename T>
90
- struct generate_random_sample
91
- {
92
- T operator()(unsigned int i) const
93
- {
94
- thrust::default_random_engine rng(hash(i));
95
- thrust::uniform_int_distribution<unsigned int> dist(0,20);
96
-
97
- return static_cast<T>(dist(rng));
98
- }
99
- };
100
-
101
-
102
-
103
- template<typename T>
104
- thrust::host_vector<T> random_integers(const size_t N)
105
- {
106
- thrust::host_vector<T> vec(N);
107
- thrust::transform(thrust::counting_iterator<unsigned int>(static_cast<unsigned int>(0)),
108
- thrust::counting_iterator<unsigned int>(static_cast<unsigned int>(N)),
109
- vec.begin(),
110
- generate_random_integer<T>());
111
-
112
- return vec;
113
- }
114
-
115
- template<typename T>
116
- T random_integer()
117
- {
118
- return generate_random_integer<T>()(0);
119
- }
120
-
121
- template<typename T>
122
- thrust::host_vector<T> random_samples(const size_t N)
123
- {
124
- thrust::host_vector<T> vec(N);
125
- thrust::transform(thrust::counting_iterator<unsigned int>(static_cast<unsigned int>(0)),
126
- thrust::counting_iterator<unsigned int>(static_cast<unsigned int>(N)),
127
- vec.begin(),
128
- generate_random_sample<T>());
129
-
130
- return vec;
131
- }
132
-
133
- }; //end namespace unittest
134
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/type_traits/is_trivially_relocatable.h DELETED
@@ -1,251 +0,0 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (c) 2018 NVIDIA Corporation
3
- //
4
- // Distributed under the Boost Software License, Version 1.0. (See accompanying
5
- // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6
- ///////////////////////////////////////////////////////////////////////////////
7
-
8
- /*! \file is_trivially_relocatable.h
9
- * \brief <a href="https://wg21.link/P1144R0">P1144R0</a>'s
10
- * \c is_trivially_relocatable, an extensible type trait indicating
11
- * whether a type can be bitwise copied (e.g. via \c memcpy).
12
- */
13
-
14
- #pragma once
15
-
16
- #include <thrust/detail/config.h>
17
- #include <thrust/detail/static_assert.h>
18
- #include <thrust/detail/type_traits.h>
19
- #include <thrust/type_traits/is_contiguous_iterator.h>
20
-
21
- #if THRUST_CPP_DIALECT >= 2011
22
- #include <type_traits>
23
- #endif
24
-
25
- namespace thrust
26
- {
27
-
28
- namespace detail
29
- {
30
-
31
- template <typename T>
32
- struct is_trivially_relocatable_impl;
33
-
34
- } // namespace detail
35
-
36
- /// Unary metafunction returns \c true_type if \c T is \a TriviallyRelocatable,
37
- /// e.g. can be bitwise copied (with a facility like \c memcpy), and
38
- /// \c false_type otherwise.
39
- template <typename T>
40
- #if THRUST_CPP_DIALECT >= 2011
41
- using is_trivially_relocatable =
42
- #else
43
- struct is_trivially_relocatable :
44
- #endif
45
- detail::is_trivially_relocatable_impl<T>
46
- #if THRUST_CPP_DIALECT < 2011
47
- {}
48
- #endif
49
- ;
50
-
51
- #if THRUST_CPP_DIALECT >= 2014
52
- /// <code>constexpr bool</code> that is \c true if \c T is
53
- /// \a TriviallyRelocatable e.g. can be copied bitwise (with a facility like
54
- /// \c memcpy), and \c false otherwise.
55
- template <typename T>
56
- constexpr bool is_trivially_relocatable_v = is_trivially_relocatable<T>::value;
57
- #endif
58
-
59
- /// Unary metafunction returns \c true_type if \c From is \a TriviallyRelocatable
60
- /// to \c To, e.g. can be bitwise copied (with a facility like \c memcpy), and
61
- /// \c false_type otherwise.
62
- template <typename From, typename To>
63
- #if THRUST_CPP_DIALECT >= 2011
64
- using is_trivially_relocatable_to =
65
- #else
66
- struct is_trivially_relocatable_to :
67
- #endif
68
- integral_constant<
69
- bool
70
- , detail::is_same<From, To>::value && is_trivially_relocatable<To>::value
71
- >
72
- #if THRUST_CPP_DIALECT < 2011
73
- {}
74
- #endif
75
- ;
76
-
77
- #if THRUST_CPP_DIALECT >= 2014
78
- /// <code>constexpr bool</code> that is \c true if \c From is
79
- /// \a TriviallyRelocatable to \c To, e.g. can be copied bitwise (with a
80
- /// facility like \c memcpy), and \c false otherwise.
81
- template <typename From, typename To>
82
- constexpr bool is_trivially_relocatable_to_v
83
- = is_trivially_relocatable_to<From, To>::value;
84
- #endif
85
-
86
- /// Unary metafunction that returns \c true_type if the element type of
87
- /// \c FromIterator is \a TriviallyRelocatable to the element type of
88
- /// \c ToIterator, and \c false_type otherwise.
89
- template <typename FromIterator, typename ToIterator>
90
- #if THRUST_CPP_DIALECT >= 2011
91
- using is_indirectly_trivially_relocatable_to =
92
- #else
93
- struct is_indirectly_trivially_relocatable_to :
94
- #endif
95
- integral_constant<
96
- bool
97
- , is_contiguous_iterator<FromIterator>::value
98
- && is_contiguous_iterator<ToIterator>::value
99
- && is_trivially_relocatable_to<
100
- typename thrust::iterator_traits<FromIterator>::value_type,
101
- typename thrust::iterator_traits<ToIterator>::value_type
102
- >::value
103
- >
104
- #if THRUST_CPP_DIALECT < 2011
105
- {}
106
- #endif
107
- ;
108
-
109
- #if THRUST_CPP_DIALECT >= 2014
110
- /// <code>constexpr bool</code> that is \c true if the element type of
111
- /// \c FromIterator is \a TriviallyRelocatable to the element type of
112
- /// \c ToIterator, and \c false otherwise.
113
- template <typename FromIterator, typename ToIterator>
114
- constexpr bool is_trivial_relocatable_sequence_copy_v
115
- = is_indirectly_trivially_relocatable_to<FromIterator, ToIterator>::value;
116
- #endif
117
-
118
- /// Customization point that can be customized to indicate that a type \c T is
119
- /// \a TriviallyRelocatable, e.g. can be copied bitwise (with a facility like
120
- /// \c memcpy).
121
- template <typename T>
122
- struct proclaim_trivially_relocatable : false_type {};
123
-
124
- /// Declares that the type \c T is \a TriviallyRelocatable by specializing
125
- /// `thrust::proclaim_trivially_relocatable`.
126
- #define THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(T) \
127
- namespace thrust { \
128
- template <> \
129
- struct proclaim_trivially_relocatable<T> : ::thrust::true_type {}; \
130
- } /* end namespace thrust */ \
131
- /**/
132
-
133
- ///////////////////////////////////////////////////////////////////////////////
134
-
135
- namespace detail
136
- {
137
-
138
- // There is no way to actually detect the libstdc++ version; __GLIBCXX__
139
- // is always set to the date of libstdc++ being packaged, not the release
140
- // day or version. This means that we can't detect the libstdc++ version,
141
- // except when compiling with GCC.
142
- //
143
- // Therefore, for the best approximation of is_trivially_copyable, we need to
144
- // handle three distinct cases:
145
- // 1) GCC above 5, or another C++11 compiler not using libstdc++: use the
146
- // standard trait directly.
147
- // 2) A C++11 compiler using libstdc++ that provides the intrinsic: use the
148
- // intrinsic.
149
- // 3) Any other case (essentially: compiling without C++11): has_trivial_assign.
150
-
151
- #ifndef __has_feature
152
- #define __has_feature(x) 0
153
- #endif
154
-
155
- template <typename T>
156
- struct is_trivially_copyable_impl
157
- : integral_constant<
158
- bool,
159
- #if THRUST_CPP_DIALECT >= 2011
160
- #if defined(__GLIBCXX__) && __has_feature(is_trivially_copyable)
161
- __is_trivially_copyable(T)
162
- #elif THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_GCC && THRUST_GCC_VERSION >= 50000
163
- std::is_trivially_copyable<T>::value
164
- #else
165
- has_trivial_assign<T>::value
166
- #endif
167
- #else
168
- has_trivial_assign<T>::value
169
- #endif
170
- >
171
- {
172
- };
173
-
174
- // https://wg21.link/P1144R0#wording-inheritance
175
- template <typename T>
176
- struct is_trivially_relocatable_impl
177
- : integral_constant<
178
- bool,
179
- is_trivially_copyable_impl<T>::value
180
- || proclaim_trivially_relocatable<T>::value
181
- >
182
- {};
183
-
184
- template <typename T, std::size_t N>
185
- struct is_trivially_relocatable_impl<T[N]> : is_trivially_relocatable_impl<T> {};
186
-
187
- } // namespace detail
188
-
189
- } // end namespace thrust
190
-
191
- #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA
192
-
193
- #include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h>
194
-
195
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(char1)
196
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(char2)
197
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(char3)
198
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(char4)
199
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uchar1)
200
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uchar2)
201
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uchar3)
202
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uchar4)
203
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(short1)
204
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(short2)
205
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(short3)
206
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(short4)
207
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ushort1)
208
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ushort2)
209
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ushort3)
210
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ushort4)
211
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(int1)
212
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(int2)
213
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(int3)
214
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(int4)
215
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uint1)
216
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uint2)
217
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uint3)
218
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(uint4)
219
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(long1)
220
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(long2)
221
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(long3)
222
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(long4)
223
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulong1)
224
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulong2)
225
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulong3)
226
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulong4)
227
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(longlong1)
228
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(longlong2)
229
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(longlong3)
230
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(longlong4)
231
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulonglong1)
232
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulonglong2)
233
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulonglong3)
234
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(ulonglong4)
235
-
236
- struct __half;
237
- struct __half2;
238
-
239
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(__half)
240
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(__half2)
241
-
242
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(float1)
243
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(float2)
244
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(float3)
245
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(float4)
246
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(double1)
247
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(double2)
248
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(double3)
249
- THRUST_PROCLAIM_TRIVIALLY_RELOCATABLE(double4)
250
- #endif
251
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/drawings-to-human/ALT-README.md DELETED
@@ -1,2 +0,0 @@
1
- # Drawings to Human
2
-
 
 
 
spaces/Caoyunkang/Segment-Any-Anomaly/GroundingDINO/groundingdino/util/box_ops.py DELETED
@@ -1,140 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
- """
3
- Utilities for bounding box manipulation and GIoU.
4
- """
5
- import torch
6
- from torchvision.ops.boxes import box_area
7
-
8
-
9
- def box_cxcywh_to_xyxy(x):
10
- x_c, y_c, w, h = x.unbind(-1)
11
- b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
12
- return torch.stack(b, dim=-1)
13
-
14
-
15
- def box_xyxy_to_cxcywh(x):
16
- x0, y0, x1, y1 = x.unbind(-1)
17
- b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
18
- return torch.stack(b, dim=-1)
19
-
20
-
21
- # modified from torchvision to also return the union
22
- def box_iou(boxes1, boxes2):
23
- area1 = box_area(boxes1)
24
- area2 = box_area(boxes2)
25
-
26
- # import ipdb; ipdb.set_trace()
27
- lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
28
- rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
29
-
30
- wh = (rb - lt).clamp(min=0) # [N,M,2]
31
- inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
32
-
33
- union = area1[:, None] + area2 - inter
34
-
35
- iou = inter / (union + 1e-6)
36
- return iou, union
37
-
38
-
39
- def generalized_box_iou(boxes1, boxes2):
40
- """
41
- Generalized IoU from https://giou.stanford.edu/
42
-
43
- The boxes should be in [x0, y0, x1, y1] format
44
-
45
- Returns a [N, M] pairwise matrix, where N = len(boxes1)
46
- and M = len(boxes2)
47
- """
48
- # degenerate boxes gives inf / nan results
49
- # so do an early check
50
- assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
51
- assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
52
- # except:
53
- # import ipdb; ipdb.set_trace()
54
- iou, union = box_iou(boxes1, boxes2)
55
-
56
- lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])
57
- rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
58
-
59
- wh = (rb - lt).clamp(min=0) # [N,M,2]
60
- area = wh[:, :, 0] * wh[:, :, 1]
61
-
62
- return iou - (area - union) / (area + 1e-6)
63
-
64
-
65
- # modified from torchvision to also return the union
66
- def box_iou_pairwise(boxes1, boxes2):
67
- area1 = box_area(boxes1)
68
- area2 = box_area(boxes2)
69
-
70
- lt = torch.max(boxes1[:, :2], boxes2[:, :2]) # [N,2]
71
- rb = torch.min(boxes1[:, 2:], boxes2[:, 2:]) # [N,2]
72
-
73
- wh = (rb - lt).clamp(min=0) # [N,2]
74
- inter = wh[:, 0] * wh[:, 1] # [N]
75
-
76
- union = area1 + area2 - inter
77
-
78
- iou = inter / union
79
- return iou, union
80
-
81
-
82
- def generalized_box_iou_pairwise(boxes1, boxes2):
83
- """
84
- Generalized IoU from https://giou.stanford.edu/
85
-
86
- Input:
87
- - boxes1, boxes2: N,4
88
- Output:
89
- - giou: N, 4
90
- """
91
- # degenerate boxes gives inf / nan results
92
- # so do an early check
93
- assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
94
- assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
95
- assert boxes1.shape == boxes2.shape
96
- iou, union = box_iou_pairwise(boxes1, boxes2) # N, 4
97
-
98
- lt = torch.min(boxes1[:, :2], boxes2[:, :2])
99
- rb = torch.max(boxes1[:, 2:], boxes2[:, 2:])
100
-
101
- wh = (rb - lt).clamp(min=0) # [N,2]
102
- area = wh[:, 0] * wh[:, 1]
103
-
104
- return iou - (area - union) / area
105
-
106
-
107
- def masks_to_boxes(masks):
108
- """Compute the bounding boxes around the provided masks
109
-
110
- The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
111
-
112
- Returns a [N, 4] tensors, with the boxes in xyxy format
113
- """
114
- if masks.numel() == 0:
115
- return torch.zeros((0, 4), device=masks.device)
116
-
117
- h, w = masks.shape[-2:]
118
-
119
- y = torch.arange(0, h, dtype=torch.float)
120
- x = torch.arange(0, w, dtype=torch.float)
121
- y, x = torch.meshgrid(y, x)
122
-
123
- x_mask = masks * x.unsqueeze(0)
124
- x_max = x_mask.flatten(1).max(-1)[0]
125
- x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
126
-
127
- y_mask = masks * y.unsqueeze(0)
128
- y_max = y_mask.flatten(1).max(-1)[0]
129
- y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
130
-
131
- return torch.stack([x_min, y_min, x_max, y_max], 1)
132
-
133
-
134
- if __name__ == "__main__":
135
- x = torch.rand(5, 4)
136
- y = torch.rand(3, 4)
137
- iou, union = box_iou(x, y)
138
- import ipdb
139
-
140
- ipdb.set_trace()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Caoyunkang/Segment-Any-Anomaly/utils/csv_utils.py DELETED
@@ -1,34 +0,0 @@
1
- import pandas as pd
2
- import os
3
-
4
- def write_results(results:dict, cur_class, total_classes, csv_path):
5
- keys = list(results.keys())
6
-
7
- if not os.path.exists(csv_path):
8
- df_all = None
9
- for class_name in total_classes:
10
- r = dict()
11
- for k in keys:
12
- r[k] = 0.00
13
- df_temp = pd.DataFrame(r, index=[class_name])
14
-
15
- if df_all is None:
16
- df_all = df_temp
17
- else:
18
- df_all = pd.concat([df_all, df_temp], axis=0)
19
-
20
- df_all.to_csv(csv_path, header=True, float_format='%.2f')
21
-
22
- df = pd.read_csv(csv_path, index_col=0)
23
-
24
- for k in keys:
25
- df.loc[cur_class, k] = results[k]
26
-
27
- df.to_csv(csv_path, header=True, float_format='%.2f')
28
-
29
- def save_metric(metrics, total_classes, class_name, dataset, csv_path):
30
- if dataset != 'mvtec':
31
- for indx in range(len(total_classes)):
32
- total_classes[indx] = f"{dataset}-{total_classes[indx]}"
33
- class_name = f"{dataset}-{class_name}"
34
- write_results(metrics, class_name, total_classes, csv_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Celestinian/Prompt-Generator/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: Prompt Generator
3
- emoji: ⚡
4
- colorFrom: red
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 3.27.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChallengeHub/Chinese-LangChain/clc/source_service.py DELETED
@@ -1,86 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding:utf-8 _*-
3
- """
4
- @author:quincy qiang
5
- @license: Apache Licence
6
- @file: search.py
7
- @time: 2023/04/17
8
- @contact: [email protected]
9
- @software: PyCharm
10
- @description: coding..
11
- """
12
-
13
- import os
14
-
15
- from duckduckgo_search import ddg
16
- from langchain.document_loaders import UnstructuredFileLoader
17
- from langchain.embeddings.huggingface import HuggingFaceEmbeddings
18
- from langchain.vectorstores import FAISS
19
-
20
-
21
- class SourceService(object):
22
- def __init__(self, config):
23
- self.vector_store = None
24
- self.config = config
25
- self.embeddings = HuggingFaceEmbeddings(model_name=self.config.embedding_model_name)
26
- self.docs_path = self.config.docs_path
27
- self.vector_store_path = self.config.vector_store_path
28
-
29
- def init_source_vector(self):
30
- """
31
- 初始化本地知识库向量
32
- :return:
33
- """
34
- docs = []
35
- for doc in os.listdir(self.docs_path):
36
- if doc.endswith('.txt'):
37
- print(doc)
38
- loader = UnstructuredFileLoader(f'{self.docs_path}/{doc}', mode="elements")
39
- doc = loader.load()
40
- docs.extend(doc)
41
- self.vector_store = FAISS.from_documents(docs, self.embeddings)
42
- self.vector_store.save_local(self.vector_store_path)
43
-
44
- def add_document(self, document_path):
45
- loader = UnstructuredFileLoader(document_path, mode="elements")
46
- doc = loader.load()
47
- self.vector_store.add_documents(doc)
48
- self.vector_store.save_local(self.vector_store_path)
49
-
50
- def load_vector_store(self, path):
51
- if path is None:
52
- self.vector_store = FAISS.load_local(self.vector_store_path, self.embeddings)
53
- else:
54
- self.vector_store = FAISS.load_local(path, self.embeddings)
55
- return self.vector_store
56
-
57
- def search_web(self, query):
58
-
59
- # SESSION.proxies = {
60
- # "http": f"socks5h://localhost:7890",
61
- # "https": f"socks5h://localhost:7890"
62
- # }
63
- try:
64
- results = ddg(query)
65
- web_content = ''
66
- if results:
67
- for result in results:
68
- web_content += result['body']
69
- return web_content
70
- except Exception as e:
71
- print(f"网络检索异常:{query}")
72
- return ''
73
- # if __name__ == '__main__':
74
- # config = LangChainCFG()
75
- # source_service = SourceService(config)
76
- # source_service.init_source_vector()
77
- # search_result = source_service.vector_store.similarity_search_with_score('科比')
78
- # print(search_result)
79
- #
80
- # source_service.add_document('/home/searchgpt/yq/Knowledge-ChatGLM/docs/added/科比.txt')
81
- # search_result = source_service.vector_store.similarity_search_with_score('科比')
82
- # print(search_result)
83
- #
84
- # vector_store=source_service.load_vector_store()
85
- # search_result = source_service.vector_store.similarity_search_with_score('科比')
86
- # print(search_result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CikeyQI/meme-api/meme_generator/memes/bubble_tea/__init__.py DELETED
@@ -1,61 +0,0 @@
1
- from pathlib import Path
2
- from typing import List, Literal
3
-
4
- from PIL.Image import Transpose
5
- from pil_utils import BuildImage
6
- from pydantic import Field
7
-
8
- from meme_generator import MemeArgsModel, MemeArgsParser, MemeArgsType, add_meme
9
-
10
- img_dir = Path(__file__).parent / "images"
11
-
12
-
13
- help = "奶茶的位置"
14
-
15
- parser = MemeArgsParser(prefix_chars="-/")
16
- group = parser.add_mutually_exclusive_group()
17
- group.add_argument(
18
- "-p",
19
- "--position",
20
- dest="position",
21
- type=str,
22
- choices=["right", "left", "both"],
23
- default="right",
24
- help=help,
25
- )
26
- group.add_argument(
27
- "--right", "/右手", action="store_const", const="right", dest="position"
28
- )
29
- group.add_argument("--left", "/左手", action="store_const", const="left", dest="position")
30
- group.add_argument("--both", "/双手", action="store_const", const="both", dest="position")
31
-
32
-
33
- class Model(MemeArgsModel):
34
- position: Literal["right", "left", "both"] = Field("right", description=help)
35
-
36
-
37
- def bubble_tea(images: List[BuildImage], texts, args: Model):
38
- frame = images[0].convert("RGBA").resize((500, 500), keep_ratio=True)
39
- bubble_tea = BuildImage.open(img_dir / "0.png")
40
- position = args.position
41
- left = position in ["left", "both"]
42
- right = position in ["right", "both"]
43
- if right:
44
- frame.paste(bubble_tea, alpha=True)
45
- if left:
46
- frame.paste(bubble_tea.transpose(Transpose.FLIP_LEFT_RIGHT), alpha=True)
47
- return frame.save_jpg()
48
-
49
-
50
- add_meme(
51
- "bubble_tea",
52
- bubble_tea,
53
- min_images=1,
54
- max_images=1,
55
- args_type=MemeArgsType(
56
- parser,
57
- Model,
58
- [Model(position="right"), Model(position="left"), Model(position="both")],
59
- ),
60
- keywords=["奶茶"],
61
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cong723/gpt-academic-public/crazy_functions/test_project/cpp/cppipc/waiter.h DELETED
@@ -1,83 +0,0 @@
1
- #pragma once
2
-
3
- #include <utility>
4
- #include <string>
5
- #include <mutex>
6
- #include <atomic>
7
-
8
- #include "libipc/def.h"
9
- #include "libipc/mutex.h"
10
- #include "libipc/condition.h"
11
- #include "libipc/platform/detail.h"
12
-
13
- namespace ipc {
14
- namespace detail {
15
-
16
- class waiter {
17
- ipc::sync::condition cond_;
18
- ipc::sync::mutex lock_;
19
- std::atomic<bool> quit_ {false};
20
-
21
- public:
22
- static void init();
23
-
24
- waiter() = default;
25
- waiter(char const *name) {
26
- open(name);
27
- }
28
-
29
- ~waiter() {
30
- close();
31
- }
32
-
33
- bool valid() const noexcept {
34
- return cond_.valid() && lock_.valid();
35
- }
36
-
37
- bool open(char const *name) noexcept {
38
- quit_.store(false, std::memory_order_relaxed);
39
- if (!cond_.open((std::string{"_waiter_cond_"} + name).c_str())) {
40
- return false;
41
- }
42
- if (!lock_.open((std::string{"_waiter_lock_"} + name).c_str())) {
43
- cond_.close();
44
- return false;
45
- }
46
- return valid();
47
- }
48
-
49
- void close() noexcept {
50
- cond_.close();
51
- lock_.close();
52
- }
53
-
54
- template <typename F>
55
- bool wait_if(F &&pred, std::uint64_t tm = ipc::invalid_value) noexcept {
56
- IPC_UNUSED_ std::lock_guard<ipc::sync::mutex> guard {lock_};
57
- while ([this, &pred] {
58
- return !quit_.load(std::memory_order_relaxed)
59
- && std::forward<F>(pred)();
60
- }()) {
61
- if (!cond_.wait(lock_, tm)) return false;
62
- }
63
- return true;
64
- }
65
-
66
- bool notify() noexcept {
67
- std::lock_guard<ipc::sync::mutex>{lock_}; // barrier
68
- return cond_.notify(lock_);
69
- }
70
-
71
- bool broadcast() noexcept {
72
- std::lock_guard<ipc::sync::mutex>{lock_}; // barrier
73
- return cond_.broadcast(lock_);
74
- }
75
-
76
- bool quit_waiting() {
77
- quit_.store(true, std::memory_order_release);
78
- return broadcast();
79
- }
80
- };
81
-
82
- } // namespace detail
83
- } // namespace ipc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/gradio/templates/frontend/assets/ShareButton-39feba51.js DELETED
@@ -1,2 +0,0 @@
1
- import{S as h,e as m,s as d,J as f,K as c,p as w,M as _,n as u,A as y,k as b,o as v,z as S,v as x,x as A,B}from"./index-3370be2a.js";import{I as M}from"./IconButton-abe5ede9.js";import"./Button-89624748.js";function C(r){let e,n;return{c(){e=f("svg"),n=f("path"),c(n,"d","M23,20a5,5,0,0,0-3.89,1.89L11.8,17.32a4.46,4.46,0,0,0,0-2.64l7.31-4.57A5,5,0,1,0,18,7a4.79,4.79,0,0,0,.2,1.32l-7.31,4.57a5,5,0,1,0,0,6.22l7.31,4.57A4.79,4.79,0,0,0,18,25a5,5,0,1,0,5-5ZM23,4a3,3,0,1,1-3,3A3,3,0,0,1,23,4ZM7,19a3,3,0,1,1,3-3A3,3,0,0,1,7,19Zm16,9a3,3,0,1,1,3-3A3,3,0,0,1,23,28Z"),c(n,"fill","currentColor"),c(e,"id","icon"),c(e,"xmlns","http://www.w3.org/2000/svg"),c(e,"viewBox","0 0 32 32")},m(t,a){w(t,e,a),_(e,n)},p:u,i:u,o:u,d(t){t&&y(e)}}}class k extends h{constructor(e){super(),m(this,e,null,C,d,{})}}class l extends Error{constructor(e){super(e),this.name="ShareError"}}const I=async(r,e)=>{if(window.__gradio_space__==null)throw new l("Must be on Spaces to share.");let n,t,a;if(e==="url"){const o=await fetch(r);n=await o.blob(),t=o.headers.get("content-type")||"",a=o.headers.get("content-disposition")||""}else n=E(r),t=r.split(";")[0].split(":")[1],a="file"+t.split("/")[1];const s=new File([n],a,{type:t}),i=await fetch("https://huggingface.co/uploads",{method:"POST",body:s,headers:{"Content-Type":s.type,"X-Requested-With":"XMLHttpRequest"}});if(!i.ok){if(i.headers.get("content-type")?.includes("application/json")){const o=await i.json();throw new l(`Upload failed: ${o.error}`)}throw new l("Upload failed.")}return await i.text()};function E(r){for(var e=r.split(","),n=e[0].match(/:(.*?);/)[1],t=atob(e[1]),a=t.length,s=new Uint8Array(a);a--;)s[a]=t.charCodeAt(a);return new Blob([s],{type:n})}function R(r){let e,n;return e=new M({props:{Icon:k,label:"Share",pending:r[2]}}),e.$on("click",r[4]),{c(){b(e.$$.fragment)},m(t,a){v(e,t,a),n=!0},p(t,[a]){const s={};a&4&&(s.pending=t[2]),e.$set(s)},i(t){n||(S(e.$$.fragment,t),n=!0)},o(t){x(e.$$.fragment,t),n=!1},d(t){A(e,t)}}}function T(r,e,n){const t=B();let{formatter:a}=e,{value:s}=e,i=!1;const p=async()=>{try{n(2,i=!0);const o=await a(s);t("share",{description:o})}catch(o){console.error(o);let g=o instanceof l?o.message:"Share failed.";t("error",g)}finally{n(2,i=!1)}};return r.$$set=o=>{"formatter"in o&&n(0,a=o.formatter),"value"in o&&n(1,s=o.value)},[a,s,i,t,p]}class L extends h{constructor(e){super(),m(this,e,T,R,d,{formatter:0,value:1})}}export{L as S,I as u};
2
- //# sourceMappingURL=ShareButton-39feba51.js.map
 
 
 
spaces/Daextream/Whisper-Auto-Subtitled-Video-Generator/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: Whisper-Auto-Subtitled-Video-Generator
3
- emoji: 🎥
4
- colorFrom: blue
5
- colorTo: purple
6
- sdk: streamlit
7
- sdk_version: 1.10.0
8
- app_file: 01_🎥_Input_YouTube_Link.py
9
- pinned: false
10
- duplicated_from: BatuhanYilmaz/Whisper-Auto-Subtitled-Video-Generator
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Djacon/emotion_detection/files/js/analytics.js DELETED
@@ -1,484 +0,0 @@
1
- function prettify(num) {
2
- num = +num;
3
- let mark = '';
4
- if (num >= 10**9) {
5
- num /= 10 ** 9;
6
- mark = 'b';
7
- } else if (num >= 10**6) {
8
- num /= 10 ** 6;
9
- mark = 'm';
10
- } else if (num >= 1000) {
11
- num /= 1000;
12
- mark = 'k';
13
- }
14
- if (num > 100) {
15
- num = Math.ceil(num);
16
- } else if (num > 10) {
17
- num = +num.toFixed(1);
18
- } else {
19
- num = +num.toFixed(2);
20
- }
21
- return num + mark;
22
- }
23
-
24
- function median(arr) {
25
- arr.sort((a, b) => a - b);
26
-
27
- var middle = Math.floor(arr.length / 2);
28
-
29
- if (arr.length % 2 === 1) {
30
- return +arr[middle].toFixed(2);
31
- }
32
- var mid1 = arr[middle - 1];
33
- var mid2 = arr[middle];
34
- return +((mid1 + mid2) / 2).toFixed(2);
35
- }
36
-
37
- function get_info(arr) {
38
- let [min, max] = d3.extent(arr);
39
- let avg = +(arr.reduce((a, b) => a + b) / arr.length).toFixed(2);
40
- let dev = +Math.sqrt(arr.reduce((acc, val) => acc + Math.pow(val - avg, 2), 0) / (arr.length - 1)).toFixed(2);
41
- let q50 = median(arr);
42
- return [min, max, avg, q50, dev];
43
- }
44
-
45
-
46
- function plot_hist(col_name, chart_id) {
47
- let column = cache_df.dataset[chart_id];
48
-
49
- let min = column.metadata.min, max = column.metadata.max;
50
- let nan_count = column.metadata.nan_count;
51
- let valid_count = column.metadata.total_values - nan_count;
52
- let nan_percentage = nan_count / column.metadata.total_values * 100;
53
- let info = [
54
- ['DataType', 'Numerical'],
55
- ['Mean', prettify(column.metadata.mean)],
56
- ['Median', prettify(column.metadata.median)],
57
- ['Std. Deviation', prettify(column.metadata.var)],
58
- ['Missing Values', `${nan_count} (${+(nan_percentage).toFixed(1)}%)`],
59
- ['Valid Values', `${valid_count} (${+(100 - nan_percentage).toFixed(1)}%)`],
60
- ]
61
-
62
- addChart(chart_id, col_name, info);
63
-
64
- var width = document.getElementById(`chart-${chart_id}`).clientWidth;
65
- var height = 300;
66
- var margin = { top: 20, right: 20, bottom: 20, left: 20 };
67
-
68
- var svg = d3.select(`#chart-${chart_id}`)
69
- .append("svg")
70
- .attr("width", width)
71
- .attr("height", height)
72
-
73
- var xScale = d3.scaleLinear()
74
- .domain([min, max])
75
- .range([margin.left, width - margin.right])
76
-
77
- var histogram = d3.histogram()
78
- .domain(xScale.domain())(column.data);
79
-
80
- var yScale = d3.scaleLinear()
81
- .domain([0, d3.max(histogram, d => d.length)])
82
- .range([height - margin.bottom, margin.top]);
83
-
84
- var xAxis = d3.axisBottom(xScale)
85
- .tickValues([min, max])
86
- .tickFormat(function(d) {
87
- if ([min, max].includes(d))
88
- return prettify(d);
89
- else
90
- return "";
91
- })
92
-
93
- svg.append("g")
94
- .attr("class", "x-axis")
95
- .attr("transform", "translate(0," + (height - margin.bottom) + ")")
96
- .style("font", "12px arial")
97
- .call(xAxis)
98
-
99
- const rect = svg.selectAll("rect")
100
- .data(histogram)
101
- .enter()
102
- .append("rect")
103
- .attr("x", d => xScale(d.x0))
104
- .attr("y", d => yScale(d.length))
105
- .attr("width", d => xScale(d.x1) - xScale(d.x0) - 1)
106
- .attr("height", d => height - margin.bottom - yScale(d.length))
107
- .attr("fill", "#ffa116")
108
-
109
- const tooltip = d3.select(`#tooltip-${chart_id}`);
110
-
111
- rect.on("mouseover", (event, d) => {
112
- let left = prettify(d[0]), right = prettify(d[d.length-1])
113
- if (left === right) {
114
- tooltip.html(left);
115
- } else {
116
- tooltip.html(`[${left}; ${right}]`);
117
- }
118
- tooltip.style("display", "block")
119
- .style("left", (event.pageX + 10) + "px")
120
- .style("top", (event.pageY - 10) + "px");
121
- }).on("mouseout", () => {
122
- tooltip.style("display", "none");
123
- });
124
- }
125
-
126
- function mode(data) {
127
- let modeLabel = 'Not Found';
128
- let maxCount = 0;
129
-
130
- for (let item of data) {
131
- if (item[1] > maxCount) {
132
- modeLabel = item[0];
133
- maxCount = item[1];
134
- }
135
- }
136
- return [modeLabel, maxCount];
137
- }
138
-
139
-
140
- function plot_pie(col_name, chart_id) {
141
- let column = cache_df.dataset[chart_id];
142
-
143
- let nan_count = column.metadata.nan_count;
144
- let valid_count = column.metadata.total_values - nan_count;
145
- let nan_percentage = nan_count / column.metadata.total_values * 100;
146
- let info = [
147
- ['DataType', 'Categorical'],
148
- ['Unique', column.metadata.unique],
149
- ['Most Common', column.metadata.mode_info],
150
- ['Missing Values', `${nan_count} (${+(nan_percentage).toFixed(1)}%)`],
151
- ['Valid Values', `${valid_count} (${+(100 - nan_percentage).toFixed(1)}%)`],
152
- ];
153
-
154
- addChart(chart_id, col_name, info);
155
-
156
- var width = document.getElementById(`chart-${chart_id}`).clientWidth;
157
- var height = 300;
158
-
159
- const radius = Math.min(width, height) / 2;
160
-
161
- const svg = d3.select(`#chart-${chart_id}`)
162
- .append("svg")
163
- .attr("width", width)
164
- .attr("height", height)
165
- .append("g")
166
- .attr("transform", `translate(${width / 2}, ${height / 2})`);
167
-
168
- const pie = d3.pie()
169
- .value(d => d[1]);
170
-
171
- const arc = d3.arc()
172
- .innerRadius(radius / 2)
173
- .outerRadius(radius)
174
- .cornerRadius(2)
175
-
176
- const arcs = svg.selectAll("arc")
177
- .data(pie(column.data))
178
- .enter()
179
- .append("g")
180
- .append("path")
181
- .attr("fill", (_, i)=> color(i))
182
- .attr("d", arc)
183
-
184
- // svg.selectAll("label")
185
- // .data(pie(column))
186
- // .enter()
187
- // .append("text")
188
- // .attr("transform", d => `translate(${arc.centroid(d)})`)
189
- // .attr("text-anchor", "middle")
190
- // .text(d => d.data[0]);
191
-
192
- arcs.on("mouseover", (_, d) => {
193
- svg.append("text")
194
- .text(`${d.data[0]}: ${+(d.data[1] / valid_count * 100).toFixed(1)}%`)
195
- .attr("x", 0)
196
- .attr("y", 5)
197
- .attr("text-anchor", "middle")
198
- .attr("class", "no-invert")
199
- }).on("mouseout", () => {
200
- svg.select("text").remove();
201
- });
202
- }
203
-
204
-
205
- const fileInput = document.getElementById("data");
206
- const charts = document.getElementById('my-charts');
207
-
208
- const color = d3.scaleOrdinal().range(d3.schemeSet3);
209
-
210
- const MAX_CATS = 10;
211
- const MAX_CHARTS = 5; // temporary
212
-
213
- const cache_df = {is_empty: true, dataset: []};
214
-
215
- function _is_number(n) {
216
- return n && !isNaN(n - 0)
217
- }
218
-
219
- function _handle_column(data, col) {
220
- let cols = [];
221
- let cats_count = 0, cats = {}, maybe_cats = true;
222
- let type = 'none';
223
-
224
- for (let row of data) {
225
- let value = row[col];
226
- if (value !== '') {
227
- if (type != 'object') {
228
- if (_is_number(value)) {
229
- type = 'num';
230
- } else {
231
- type = 'object';
232
- }
233
- }
234
-
235
- if (maybe_cats) {
236
- if (value in cats) {
237
- cats[value] += 1;
238
- } else {
239
- cats_count += 1;
240
- cats[value] = 1
241
- if (cats_count > MAX_CATS) {
242
- maybe_cats = false;
243
- cats = {};
244
- }
245
- }
246
- }
247
- cols.push(value);
248
- }
249
- }
250
-
251
- type = maybe_cats ? 'cat' : type == 'num' ? type : 'object';
252
- // console.log(col, type);
253
-
254
- let nan_count = data.length - cols.length;
255
- if (type == 'cat') {
256
- cats = Object.entries(cats);
257
- let [mode_col, mode_count] = mode(cats);
258
- let col_data = {type, col, data: cats,
259
- metadata: {nan_count, total_values: data.length,
260
- unique: cats_count, mode_info: `${mode_col} (${+(mode_count / cols.length * 100).toFixed(1)}%)`}}
261
- return [true, col_data];
262
- } else if (type == 'num') {
263
- cols = new Float32Array(cols);
264
- let [min, max, mean_col, median_col, var_col] = get_info(cols);
265
- let col_data = {type, col, data: cols,
266
- metadata: {nan_count, total_values: data.length,
267
- min: min, max: max, mean: mean_col, median: median_col, var: var_col}}
268
- return [true, col_data];
269
- }
270
- return [false, {}];
271
- }
272
-
273
- function _update_cache(data) {
274
- cache_df.is_empty = false;
275
- for (let col of data.columns) {
276
- let [is_valid, col_data] = _handle_column(data, col);
277
- if (is_valid) {
278
- cache_df.dataset.push(col_data);
279
- }
280
- }
281
- _update_options();
282
- }
283
-
284
- function _update_options() {
285
- for (let i = 0; i < cache_df.dataset.length; i++) {
286
- const name = cache_df.dataset[i].col;
287
- const newColumnOption = document.createElement('li');
288
- newColumnOption.innerHTML = `
289
- <div class="pl-5 flex items-center p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-600">
290
- <input id="checkbox-item-${i}" type="checkbox" class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500">
291
- <label for="checkbox-item-${i}" class="w-full pl-3 text-sm font-medium text-gray-900 rounded dark:text-gray-300 capitalized">${name}</label>
292
- <a href="#col-${i}">jump</a>
293
- </div>`;
294
- ulColumns.appendChild(newColumnOption);
295
- }
296
-
297
- const inputs = ulColumns.querySelectorAll('input');
298
- const total = inputs.length - 1;
299
-
300
- inputs[0].addEventListener('click', function(_) {
301
- const count = inputs[0].checked * total;
302
- _update_dropdown_text(count, total);
303
- for (let i = 1; i < inputs.length; i++) {
304
- inputs[i].checked = inputs[0].checked;
305
- }
306
- })
307
-
308
- let count = 0;
309
- for (let i = 1; i < inputs.length; i++) {
310
- inputs[i].addEventListener('click', function(_) {
311
- inputs[0].checked = false;
312
-
313
- let count = 0;
314
- let total = inputs.length - 1;
315
- for (let input of inputs) {
316
- count += input.checked;
317
- }
318
- _update_dropdown_text(count, total);
319
- })
320
- if (i <= MAX_CHARTS) {
321
- inputs[i].checked = true;
322
- count += 1;
323
- }
324
- }
325
-
326
- document.getElementById('dropdown').classList.remove('hidden');
327
- _update_dropdown_text(count, total);
328
- }
329
-
330
- function _update_dropdown_text(count, total) {
331
- showDropdownButton.innerHTML = `Select Columns (${count} of ${total})<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12 15.41l-4.29-4.29a1.01 1.01 0 0 0-1.42 0 1.01 1.01 0 0 0 0 1.42l5 5a1.01 1.01 0 0 0 1.42 0l5-5a1.01 1.01 0 0 0 0-1.42 1.01 1.01 0 0 0-1.42 0L12 15.41z"/></svg>`
332
- }
333
-
334
- function _plot(col_id) {
335
- values = cache_df.dataset[col_id];
336
- if (values.type == 'cat') {
337
- plot_pie(values.col, col_id);
338
- } else if (values.type == 'num') {
339
- plot_hist(values.col, col_id);
340
- }
341
- }
342
-
343
- function _toggle_column(col_id, is_open=true) {
344
- let chart_div = document.getElementById(`col-${col_id}`);
345
- if (!chart_div) {
346
- _plot(col_id);
347
- chart_div = document.getElementById(`col-${col_id}`);
348
- }
349
-
350
- if (is_open) {
351
- chart_div.classList.remove('hidden');
352
- } else {
353
- chart_div.classList.add('hidden');
354
- }
355
- }
356
-
357
- function addChart(chartID, name, info) {
358
- info_div = [];
359
- for (let item of info) {
360
- let v = `<p class="mt-1 text-sm text-gray-500 truncate sm:w-auto"><b>${item[0]}:</b> ${item[1]}</p>`
361
- info_div.push(v);
362
- }
363
-
364
- const newChartDiv = document.createElement('div');
365
- newChartDiv.id = `col-${chartID}`;
366
- newChartDiv.className = 'cols p-4 mt-4 w-full overflow-hidden bg-white rounded-lg';
367
- newChartDiv.innerHTML = `
368
- <div class="w-full p-4 bg-white rounded-lg xl:p-6">
369
- <h1 class="text-lg font-medium text-gray-700 capitalize sm:text-xl md:text-2xl">${name}</h1>
370
- <div class="grid gap-12 mt-8 sm:grid-cols-2">
371
- <div id="tooltip-${chartID}" class="rounded-lg" style="position: absolute; display: none; background-color: black; color: white; border: 1px solid black; padding: 5px; z-index: 1;"></div>
372
- <div id="chart-${chartID}" class="flex items-center capitalize no-invert">
373
- </div>
374
- <div class="flow-root mt-6">
375
- <ul>
376
- <li>
377
- <span class="absolute top-4 left-4 rtl:right-4 rtl:left-auto -ml-px h-full w-0.5 bg-gray-200" aria-hidden="true"></span>
378
- <div class="relative flex">
379
- <span class="flex items-center justify-center w-8 h-8 bg-white rounded-full ring-8 ring-white">
380
- <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-indigo-600 no-invert" viewBox="0 0 20 20" fill="currentColor">
381
- <path d="M10 2a6 6 0 00-6 6v3.586l-.707.707A1 1 0 004 14h12a1 1 0 00.707-1.707L16 11.586V8a6 6 0 00-6-6zM10 18a3 3 0 01-3-3h6a3 3 0 01-3 3z"></path>
382
- </svg>
383
- </span>
384
-
385
- <div class="min-w-0 flex-1 pt-1.5 mx-3">
386
- <p class="text-sm font-medium text-gray-700">General Info:</p>
387
- ${info_div.join('\n')}
388
- </div>
389
- </div>
390
- </li>
391
- </ul>
392
- </div>
393
- </div>
394
- </div>`;
395
- charts.appendChild(newChartDiv);
396
- }
397
-
398
- var lastWidth = window.innerWidth;
399
- document.getElementById("submit").addEventListener("click", render);
400
- window.addEventListener("resize", () => {
401
- if (Math.abs(lastWidth - window.innerWidth) > 25) {
402
- render();
403
- lastWidth = window.innerWidth;
404
- }
405
- });
406
-
407
- fileInput.addEventListener('change', function() {
408
- cache_df.is_empty = true;
409
- cache_df.dataset = [];
410
- });
411
-
412
-
413
- function render() {
414
- if (fileInput.files.length > 0) {
415
- if (!fileInput.files[0].name.endsWith('.csv')) {
416
- console.warn('Invalid Format!');
417
- return;
418
- }
419
-
420
- charts.innerHTML = '';
421
- var selectedFile = fileInput.files[0];
422
- var reader = new FileReader();
423
-
424
- reader.onload = function(event) {
425
- var fileContent = event.target.result;
426
- var data = d3.csvParse(fileContent);
427
-
428
- if (cache_df.is_empty) {
429
- ulColumns.innerHTML = '<li><div class="flex items-center p-2 rounded hover:bg-gray-100 dark:hover:bg-gray-600"><input id="checkbox-item-main" type="checkbox" value="" class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"><label for="checkbox-item-main" class="w-full pl-3 text-sm font-medium text-gray-900 rounded dark:text-gray-300">All Columns</label></div></li>';
430
- _update_cache(data);
431
- } else {
432
- console.log('We already have cache!');
433
- }
434
-
435
- inputs = ulColumns.querySelectorAll('input');
436
- for (let i = 1; i < inputs.length; i++) {
437
- if (!inputs[i].checked) continue;
438
- _plot(i-1);
439
- }
440
- };
441
- reader.readAsText(selectedFile);
442
- } else {
443
- console.warn('There is no file!');
444
- }
445
- }
446
-
447
- function _comeback_options() {
448
- dropdownSearch.style.display = 'none';
449
- let ids = new Set();
450
- for (let chart of charts.getElementsByClassName('cols')) {
451
- ids.add(+chart.id.split('-')[1]);
452
- }
453
-
454
- const inputs = ulColumns.querySelectorAll('input');
455
- inputs[0].checked = false;
456
- for (let i = 1; i < inputs.length; i++) {
457
- inputs[i].checked = ids.has(i-1);
458
- }
459
-
460
- _update_dropdown_text(ids.size, inputs.length-1);
461
- }
462
-
463
- function _apply_options() {
464
- dropdownSearch.style.display = 'none';
465
- const inputs = ulColumns.querySelectorAll('input');
466
- for (let i = 1; i < inputs.length; i++) {
467
- _toggle_column(i-1, inputs[i].checked);
468
- }
469
- }
470
-
471
- const showDropdownButton = document.getElementById('showDropdown');
472
- const dropdownSearch = document.getElementById('dropdownSearch');
473
- const ulColumns = document.getElementById('ul-columns');
474
-
475
- showDropdownButton.addEventListener('click', function() {
476
- if (dropdownSearch.style.display === 'none' || dropdownSearch.style.display === '') {
477
- dropdownSearch.style.display = 'block';
478
- } else {
479
- dropdownSearch.style.display = 'none';
480
- }
481
- });
482
-
483
- document.getElementById('cancel').addEventListener('click', _comeback_options);
484
- document.getElementById('apply').addEventListener('click', _apply_options);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ECCV2022/PSG/OpenPSG/configs/_base_/datasets/vg_sg.py DELETED
@@ -1,57 +0,0 @@
1
- # dataset settings
2
- dataset_type = 'SceneGraphDataset'
3
- ann_file = '/mnt/ssd/gzj/data/VisualGenome/data_openpsg.json'
4
- img_dir = '/mnt/ssd/gzj/data/VisualGenome/VG_100K'
5
-
6
- img_norm_cfg = dict(mean=[123.675, 116.28, 103.53],
7
- std=[58.395, 57.12, 57.375],
8
- to_rgb=True)
9
- train_pipeline = [
10
- dict(type='LoadImageFromFile'),
11
- dict(type='LoadSceneGraphAnnotations', with_bbox=True, with_rel=True),
12
- dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
13
- dict(type='RandomFlip', flip_ratio=0.5),
14
- dict(type='Normalize', **img_norm_cfg),
15
- dict(type='Pad', size_divisor=32),
16
- dict(type='SceneGraphFormatBundle'),
17
- dict(type='Collect',
18
- keys=['img', 'gt_bboxes', 'gt_labels', 'gt_rels', 'gt_relmaps']),
19
- ]
20
- test_pipeline = [
21
- dict(type='LoadImageFromFile'),
22
- # Since the forward process may need gt info, annos must be loaded.
23
- dict(type='LoadSceneGraphAnnotations', with_bbox=True, with_rel=True),
24
- dict(
25
- type='MultiScaleFlipAug',
26
- img_scale=(1333, 800),
27
- flip=False,
28
- transforms=[
29
- dict(type='Resize', keep_ratio=True),
30
- dict(type='RandomFlip'),
31
- dict(type='Normalize', **img_norm_cfg),
32
- dict(type='Pad', size_divisor=32),
33
- # NOTE: Do not change the img to DC.
34
- dict(type='ImageToTensor', keys=['img']),
35
- dict(type='ToTensor', keys=['gt_bboxes', 'gt_labels']),
36
- dict(type='ToDataContainer',
37
- fields=(dict(key='gt_bboxes'), dict(key='gt_labels'))),
38
- dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
39
- ])
40
- ]
41
- data = dict(samples_per_gpu=2,
42
- workers_per_gpu=2,
43
- train=dict(type=dataset_type,
44
- ann_file=ann_file,
45
- img_prefix=img_dir,
46
- pipeline=train_pipeline,
47
- split='train'),
48
- val=dict(type=dataset_type,
49
- ann_file=ann_file,
50
- img_prefix=img_dir,
51
- pipeline=test_pipeline,
52
- split='test'),
53
- test=dict(type=dataset_type,
54
- ann_file=ann_file,
55
- img_prefix=img_dir,
56
- pipeline=test_pipeline,
57
- split='test'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/EronSamez/RVC_HFmeu/infer_batch_rvc.py DELETED
@@ -1,215 +0,0 @@
1
- """
2
- v1
3
- runtime\python.exe myinfer-v2-0528.py 0 "E:\codes\py39\RVC-beta\todo-songs" "E:\codes\py39\logs\mi-test\added_IVF677_Flat_nprobe_7.index" harvest "E:\codes\py39\RVC-beta\output" "E:\codes\py39\test-20230416b\weights\mi-test.pth" 0.66 cuda:0 True 3 0 1 0.33
4
- v2
5
- runtime\python.exe myinfer-v2-0528.py 0 "E:\codes\py39\RVC-beta\todo-songs" "E:\codes\py39\test-20230416b\logs\mi-test-v2\aadded_IVF677_Flat_nprobe_1_v2.index" harvest "E:\codes\py39\RVC-beta\output_v2" "E:\codes\py39\test-20230416b\weights\mi-test-v2.pth" 0.66 cuda:0 True 3 0 1 0.33
6
- """
7
- import os, sys, pdb, torch
8
-
9
- now_dir = os.getcwd()
10
- sys.path.append(now_dir)
11
- import sys
12
- import torch
13
- import tqdm as tq
14
- from multiprocessing import cpu_count
15
-
16
-
17
- class Config:
18
- def __init__(self, device, is_half):
19
- self.device = device
20
- self.is_half = is_half
21
- self.n_cpu = 0
22
- self.gpu_name = None
23
- self.gpu_mem = None
24
- self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config()
25
-
26
- def device_config(self) -> tuple:
27
- if torch.cuda.is_available():
28
- i_device = int(self.device.split(":")[-1])
29
- self.gpu_name = torch.cuda.get_device_name(i_device)
30
- if (
31
- ("16" in self.gpu_name and "V100" not in self.gpu_name.upper())
32
- or "P40" in self.gpu_name.upper()
33
- or "1060" in self.gpu_name
34
- or "1070" in self.gpu_name
35
- or "1080" in self.gpu_name
36
- ):
37
- print("16系/10系显卡和P40强制单精度")
38
- self.is_half = False
39
- for config_file in ["32k.json", "40k.json", "48k.json"]:
40
- with open(f"configs/{config_file}", "r") as f:
41
- strr = f.read().replace("true", "false")
42
- with open(f"configs/{config_file}", "w") as f:
43
- f.write(strr)
44
- with open("infer/modules/train/preprocess.py", "r") as f:
45
- strr = f.read().replace("3.7", "3.0")
46
- with open("infer/modules/train/preprocess.py", "w") as f:
47
- f.write(strr)
48
- else:
49
- self.gpu_name = None
50
- self.gpu_mem = int(
51
- torch.cuda.get_device_properties(i_device).total_memory
52
- / 1024
53
- / 1024
54
- / 1024
55
- + 0.4
56
- )
57
- if self.gpu_mem <= 4:
58
- with open("infer/modules/train/preprocess.py", "r") as f:
59
- strr = f.read().replace("3.7", "3.0")
60
- with open("infer/modules/train/preprocess.py", "w") as f:
61
- f.write(strr)
62
- elif torch.backends.mps.is_available():
63
- print("没有发现支持的N卡, 使用MPS进行推理")
64
- self.device = "mps"
65
- else:
66
- print("没有发现支持的N卡, 使用CPU进行推理")
67
- self.device = "cpu"
68
- self.is_half = True
69
-
70
- if self.n_cpu == 0:
71
- self.n_cpu = cpu_count()
72
-
73
- if self.is_half:
74
- # 6G显存配置
75
- x_pad = 3
76
- x_query = 10
77
- x_center = 60
78
- x_max = 65
79
- else:
80
- # 5G显存配置
81
- x_pad = 1
82
- x_query = 6
83
- x_center = 38
84
- x_max = 41
85
-
86
- if self.gpu_mem != None and self.gpu_mem <= 4:
87
- x_pad = 1
88
- x_query = 5
89
- x_center = 30
90
- x_max = 32
91
-
92
- return x_pad, x_query, x_center, x_max
93
-
94
-
95
- f0up_key = sys.argv[1]
96
- input_path = sys.argv[2]
97
- index_path = sys.argv[3]
98
- f0method = sys.argv[4] # harvest or pm
99
- opt_path = sys.argv[5]
100
- model_path = sys.argv[6]
101
- index_rate = float(sys.argv[7])
102
- device = sys.argv[8]
103
- is_half = sys.argv[9].lower() != "false"
104
- filter_radius = int(sys.argv[10])
105
- resample_sr = int(sys.argv[11])
106
- rms_mix_rate = float(sys.argv[12])
107
- protect = float(sys.argv[13])
108
- print(sys.argv)
109
- config = Config(device, is_half)
110
- now_dir = os.getcwd()
111
- sys.path.append(now_dir)
112
- from infer.modules.vc.modules import VC
113
- from lib.infer_pack.models import (
114
- SynthesizerTrnMs256NSFsid,
115
- SynthesizerTrnMs256NSFsid_nono,
116
- SynthesizerTrnMs768NSFsid,
117
- SynthesizerTrnMs768NSFsid_nono,
118
- )
119
- from infer.lib.audio import load_audio
120
- from fairseq import checkpoint_utils
121
- from scipy.io import wavfile
122
-
123
- hubert_model = None
124
-
125
-
126
- def load_hubert():
127
- global hubert_model
128
- models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
129
- ["hubert_base.pt"],
130
- suffix="",
131
- )
132
- hubert_model = models[0]
133
- hubert_model = hubert_model.to(device)
134
- if is_half:
135
- hubert_model = hubert_model.half()
136
- else:
137
- hubert_model = hubert_model.float()
138
- hubert_model.eval()
139
-
140
-
141
- def vc_single(sid, input_audio, f0_up_key, f0_file, f0_method, file_index, index_rate):
142
- global tgt_sr, net_g, vc, hubert_model, version
143
- if input_audio is None:
144
- return "You need to upload an audio", None
145
- f0_up_key = int(f0_up_key)
146
- audio = load_audio(input_audio, 16000)
147
- times = [0, 0, 0]
148
- if hubert_model == None:
149
- load_hubert()
150
- if_f0 = cpt.get("f0", 1)
151
- # audio_opt=vc.pipeline(hubert_model,net_g,sid,audio,times,f0_up_key,f0_method,file_index,file_big_npy,index_rate,if_f0,f0_file=f0_file)
152
- audio_opt = vc.pipeline(
153
- hubert_model,
154
- net_g,
155
- sid,
156
- audio,
157
- input_audio,
158
- times,
159
- f0_up_key,
160
- f0_method,
161
- file_index,
162
- index_rate,
163
- if_f0,
164
- filter_radius,
165
- tgt_sr,
166
- resample_sr,
167
- rms_mix_rate,
168
- version,
169
- protect,
170
- f0_file=f0_file,
171
- )
172
- print(times)
173
- return audio_opt
174
-
175
-
176
- def get_vc(model_path):
177
- global n_spk, tgt_sr, net_g, vc, cpt, device, is_half, version
178
- print("loading pth %s" % model_path)
179
- cpt = torch.load(model_path, map_location="cpu")
180
- tgt_sr = cpt["config"][-1]
181
- cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk
182
- if_f0 = cpt.get("f0", 1)
183
- version = cpt.get("version", "v1")
184
- if version == "v1":
185
- if if_f0 == 1:
186
- net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=is_half)
187
- else:
188
- net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
189
- elif version == "v2":
190
- if if_f0 == 1: #
191
- net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=is_half)
192
- else:
193
- net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"])
194
- del net_g.enc_q
195
- print(net_g.load_state_dict(cpt["weight"], strict=False)) # 不加这一行清不干净,真奇葩
196
- net_g.eval().to(device)
197
- if is_half:
198
- net_g = net_g.half()
199
- else:
200
- net_g = net_g.float()
201
- vc = VC(tgt_sr, config)
202
- n_spk = cpt["config"][-3]
203
- # return {"visible": True,"maximum": n_spk, "__type__": "update"}
204
-
205
-
206
- get_vc(model_path)
207
- audios = os.listdir(input_path)
208
- for file in tq.tqdm(audios):
209
- if file.endswith(".wav"):
210
- file_path = input_path + "/" + file
211
- wav_opt = vc_single(
212
- 0, file_path, f0up_key, None, f0method, index_path, index_rate
213
- )
214
- out_path = opt_path + "/" + file
215
- wavfile.write(out_path, tgt_sr, wav_opt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/EronSamez/RVC_HFmeu/tools/calc_rvc_model_similarity.py DELETED
@@ -1,96 +0,0 @@
1
- # This code references https://huggingface.co/JosephusCheung/ASimilarityCalculatior/blob/main/qwerty.py
2
- # Fill in the path of the model to be queried and the root directory of the reference models, and this script will return the similarity between the model to be queried and all reference models.
3
- import os
4
- import logging
5
-
6
- logger = logging.getLogger(__name__)
7
-
8
- import torch
9
- import torch.nn as nn
10
- import torch.nn.functional as F
11
-
12
-
13
- def cal_cross_attn(to_q, to_k, to_v, rand_input):
14
- hidden_dim, embed_dim = to_q.shape
15
- attn_to_q = nn.Linear(hidden_dim, embed_dim, bias=False)
16
- attn_to_k = nn.Linear(hidden_dim, embed_dim, bias=False)
17
- attn_to_v = nn.Linear(hidden_dim, embed_dim, bias=False)
18
- attn_to_q.load_state_dict({"weight": to_q})
19
- attn_to_k.load_state_dict({"weight": to_k})
20
- attn_to_v.load_state_dict({"weight": to_v})
21
-
22
- return torch.einsum(
23
- "ik, jk -> ik",
24
- F.softmax(
25
- torch.einsum("ij, kj -> ik", attn_to_q(rand_input), attn_to_k(rand_input)),
26
- dim=-1,
27
- ),
28
- attn_to_v(rand_input),
29
- )
30
-
31
-
32
- def model_hash(filename):
33
- try:
34
- with open(filename, "rb") as file:
35
- import hashlib
36
-
37
- m = hashlib.sha256()
38
-
39
- file.seek(0x100000)
40
- m.update(file.read(0x10000))
41
- return m.hexdigest()[0:8]
42
- except FileNotFoundError:
43
- return "NOFILE"
44
-
45
-
46
- def eval(model, n, input):
47
- qk = f"enc_p.encoder.attn_layers.{n}.conv_q.weight"
48
- uk = f"enc_p.encoder.attn_layers.{n}.conv_k.weight"
49
- vk = f"enc_p.encoder.attn_layers.{n}.conv_v.weight"
50
- atoq, atok, atov = model[qk][:, :, 0], model[uk][:, :, 0], model[vk][:, :, 0]
51
-
52
- attn = cal_cross_attn(atoq, atok, atov, input)
53
- return attn
54
-
55
-
56
- def main(path, root):
57
- torch.manual_seed(114514)
58
- model_a = torch.load(path, map_location="cpu")["weight"]
59
-
60
- logger.info("Query:\t\t%s\t%s" % (path, model_hash(path)))
61
-
62
- map_attn_a = {}
63
- map_rand_input = {}
64
- for n in range(6):
65
- hidden_dim, embed_dim, _ = model_a[
66
- f"enc_p.encoder.attn_layers.{n}.conv_v.weight"
67
- ].shape
68
- rand_input = torch.randn([embed_dim, hidden_dim])
69
-
70
- map_attn_a[n] = eval(model_a, n, rand_input)
71
- map_rand_input[n] = rand_input
72
-
73
- del model_a
74
-
75
- for name in sorted(list(os.listdir(root))):
76
- path = "%s/%s" % (root, name)
77
- model_b = torch.load(path, map_location="cpu")["weight"]
78
-
79
- sims = []
80
- for n in range(6):
81
- attn_a = map_attn_a[n]
82
- attn_b = eval(model_b, n, map_rand_input[n])
83
-
84
- sim = torch.mean(torch.cosine_similarity(attn_a, attn_b))
85
- sims.append(sim)
86
-
87
- logger.info(
88
- "Reference:\t%s\t%s\t%s"
89
- % (path, model_hash(path), f"{torch.mean(torch.stack(sims)) * 1e2:.2f}%")
90
- )
91
-
92
-
93
- if __name__ == "__main__":
94
- query_path = r"assets\weights\mi v3.pth"
95
- reference_root = r"assets\weights"
96
- main(query_path, reference_root)