parquet-converter commited on
Commit
6f8e324
·
1 Parent(s): df56c2c

Update parquet files (step 93 of 249)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. spaces/1-13-am/neural-style-transfer/utils.py +0 -138
  2. spaces/109peko/anime-remove-background/README.md +0 -14
  3. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Avast licence key download How to get the most out of your subscription.md +0 -225
  4. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Baahubali 2 - The Conclusion Full Movie In Tamil Download TOP.md +0 -17
  5. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download STEX collection Vol.4(sim city 4 mods disk 4) and discover new ways to play SimCity 4.md +0 -104
  6. spaces/1gistliPinn/ChatGPT4/Examples/Atpl Radio Navigation Cbt Download !FREE!.md +0 -9
  7. spaces/1gistliPinn/ChatGPT4/Examples/Criminal Download Stream or Download the Popular Podcast Series About True Crime Stories.md +0 -28
  8. spaces/1line/AutoGPT/autogpt/memory/base.py +0 -43
  9. spaces/1phancelerku/anime-remove-background/Download BEYBLADE BURST app for iOS and Android - Latest Version.md +0 -199
  10. spaces/1phancelerku/anime-remove-background/Download Battle Playground Simulator Mod APK and Experience the Ultimate Battle Simulation.md +0 -94
  11. spaces/2023Liu2023/bingo/src/components/ui/dropdown-menu.tsx +0 -128
  12. spaces/AIFILMS/generate_human_motion/README.md +0 -14
  13. spaces/AIFILMS/generate_human_motion/VQ-Trans/models/rotation2xyz.py +0 -92
  14. spaces/Abhay834/SY_Bot/app.py +0 -203
  15. spaces/Adapter/T2I-Adapter/docs/FAQ.md +0 -5
  16. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/ScaleMethods.js +0 -121
  17. spaces/Aki004/herta-so-vits/onnx_export.py +0 -56
  18. spaces/Akmyradov/TurkmenTTSweSTT/uroman/lib/JSON/backportPP.pm +0 -2806
  19. spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/eval/verification.py +0 -407
  20. spaces/Amrrs/DragGan-Inversion/stylegan_human/pti/training/coaches/localitly_regulizer.py +0 -70
  21. spaces/AnTo2209/3D_Zeroshot_Neural_Style_Transfer/src/sampler/simple_sampler.py +0 -39
  22. spaces/Anar0140/4.RealTime-MediaPipe-AI-From-Video-On-Any-Device/README.md +0 -14
  23. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/score_sde_ve.md +0 -35
  24. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +0 -414
  25. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/audioldm/__init__.py +0 -0
  26. spaces/Andy1621/uniformer_image_segmentation/configs/_base_/datasets/pascal_voc12_aug.py +0 -9
  27. spaces/AnnasBlackHat/Image-Downloader/app.py +0 -70
  28. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/ops/assign_score_withk.py +0 -123
  29. spaces/Apex-X/ROOPOK/roop/ui.py +0 -285
  30. spaces/Apex-X/nono/roop/__init__.py +0 -0
  31. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/command/install_headers.py +0 -45
  32. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/msvccompiler.py +0 -695
  33. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/install_scripts.py +0 -70
  34. spaces/Avator/gradio-hugging-face/README.md +0 -12
  35. spaces/Banbri/zcvzcv/src/app/interface/progress/progress-bar.tsx +0 -57
  36. spaces/Benson/text-generation/Examples/Autobs Simulador Indonesia Librea Descargar 4k.md +0 -91
  37. spaces/Benson/text-generation/Examples/Descargar Gratis Templo Ejecutar Juego Para Pc.md +0 -74
  38. spaces/Big-Web/MMSD/env/Lib/site-packages/boto3/ec2/deletetags.py +0 -37
  39. spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/pyparsing/exceptions.py +0 -267
  40. spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_importlib.py +0 -47
  41. spaces/BilalSardar/facrec/app.py +0 -92
  42. spaces/CVPR/LIVE/thrust/thrust/system/detail/adl/copy.h +0 -44
  43. spaces/CVPR/SPOTER_Sign_Language_Recognition/spoter/spoter_model.py +0 -70
  44. spaces/Carterclear/swarm-agents/app.py +0 -161
  45. spaces/Cecil8352/vits-models/monotonic_align/core.py +0 -36
  46. spaces/Cicooo/vits-uma-genshin-honkai/text/__init__.py +0 -57
  47. spaces/CikeyQI/Yunzai/Dockerfile +0 -38
  48. spaces/Clebersla/RVC_V2_Huggingface_Version/lib/infer_pack/transforms.py +0 -209
  49. spaces/Cletrason/Cletrason-toad-in-the-mario-movie/Trainer.py +0 -0
  50. spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/data/datasets/evaluation/word/util/thread_.py +0 -62
spaces/1-13-am/neural-style-transfer/utils.py DELETED
@@ -1,138 +0,0 @@
1
- from skimage.exposure import match_histograms
2
- from skimage import io
3
- import os
4
- from PIL import Image
5
- import torch
6
- import torchvision
7
- import torchvision.transforms as transforms
8
-
9
- def normalize():
10
- MEAN = [0.485, 0.456, 0.406]
11
- STD = [0.229, 0.224, 0.225]
12
- return transforms.Normalize(mean = MEAN, std = STD)
13
-
14
- def denormalize():
15
- # out = (x - mean) / std
16
- MEAN = [0.485, 0.456, 0.406]
17
- STD = [0.229, 0.224, 0.225]
18
- MEAN = [-mean/std for mean, std in zip(MEAN, STD)]
19
- STD = [1/std for std in STD]
20
- return transforms.Normalize(mean=MEAN, std=STD)
21
-
22
- def transformer(imsize = None, cropsize = None):
23
- transformer = []
24
- if imsize:
25
- transformer.append(transforms.Resize(imsize))
26
- if cropsize:
27
- transformer.append(transforms.RandomCrop(cropsize))
28
-
29
- transformer.append(transforms.ToTensor())
30
- transformer.append(normalize())
31
- return transforms.Compose(transformer)
32
-
33
- def load_img(path, imsize = None, cropsize = None):
34
- transform = transformer(imsize = imsize, cropsize = cropsize)
35
- # torchvision.transforms supports PIL Images
36
- return transform(Image.open(path).convert("RGB")).unsqueeze(0)
37
-
38
- def tensor_to_img(tensor):
39
- denormalizer = denormalize()
40
- if tensor.device == "cuda":
41
- tensor = tensor.cpu()
42
- #
43
- tensor = torchvision.utils.make_grid(denormalizer(tensor.squeeze()))
44
- image = transforms.functional.to_pil_image(tensor.clamp_(0., 1.))
45
- return image
46
-
47
- def save_img(tensor, path):
48
- pass
49
-
50
- def histogram_matching(image, reference):
51
- """
52
- img: style image
53
- reference: original img
54
- output: style image that resembles original img's color histogram
55
- """
56
- device = image.device
57
- reference = reference.cpu().permute(1, 2, 0).numpy()
58
- image = image.cpu().permute(1, 2, 0).numpy()
59
- output = match_histograms(image, reference, multichannel = True)
60
- return torch.Tensor(output).permute(2, 0, 1).to(device)
61
-
62
- def batch_histogram_matching(images, reference):
63
- """
64
- images of shape BxCxHxW
65
- reference of shape 1xCxHxW
66
- """
67
- reference = reference.squeeze()
68
- output = torch.zeros_like(images, dtype = images.dtype)
69
- B = images.shape[0]
70
- for i in range(B):
71
- output[i] = histogram_matching(images[i], reference)
72
- return output
73
-
74
- def statistics(f, inverse = False, eps = 1e-10):
75
- c, h, w = f.shape
76
- f_mean = torch.mean(f.view(c, h*w), dim=1, keepdim=True)
77
- f_zeromean = f.view(c, h*w) - f_mean
78
- f_cov = torch.mm(f_zeromean, f_zeromean.t())
79
-
80
- u, s, v = torch.svd(f_cov)
81
-
82
- k = c
83
- for i in range(c):
84
- if s[i] < eps:
85
- k = i
86
- break
87
- if inverse:
88
- p = -0.5
89
- else:
90
- p = 0.5
91
-
92
- f_covsqrt = torch.mm(torch.mm(u[:, 0:k], torch.diag(s[0:k].pow(p))), v[:, 0:k].t())
93
- return f_mean, f_covsqrt
94
-
95
- def whitening(f):
96
- c, h, w = f.shape
97
- f_mean, f_inv_covsqrt = statistics(f, inverse = True)
98
- whitened_f = torch.mm(f_inv_covsqrt, f.view(c, h*w) - f_mean)
99
- return whitened_f.view(c, h, w)
100
-
101
- def batch_whitening(f):
102
- b, c, h, w = f.shape
103
- whitened_f = torch.zeros(size = (b, c, h, w), dtype = f.dtype, device = f.device)
104
- for i in range(b):
105
- whitened_f[i] = whitening(f[i])
106
- return whitened_f
107
-
108
- def coloring(style, content):
109
- s_c, s_h, s_w = style.shape
110
- c_mean, c_covsqrt = statistics(content, inverse = False)
111
- colored_s = torch.mm(c_covsqrt, whitening(style).view(s_c, s_h * s_w)) + c_mean
112
- return colored_s.view(s_c, s_h, s_w)
113
-
114
- def batch_coloring(styles, content):
115
- colored_styles = torch.zeros_like(styles, dtype = styles.dtype, device = styles.device)
116
- for i, style in enumerate(styles):
117
- colored_styles[i] = coloring(style, content[i])
118
-
119
- return colored_styles
120
-
121
- def batch_wct(styles, content):
122
- whitened_styles = batch_whitening(styles)
123
- return batch_coloring(whitened_styles, content)
124
-
125
- class Image_Set(torch.utils.data.Dataset):
126
- def __init__(self, root_path, imsize, cropsize):
127
- super(Image_Set, self).__init__()
128
- self.root_path = root_path
129
- self.files = sorted(os.listdir(self.root_path))
130
- self.transformer = transformer(imsize, cropsize)
131
-
132
- def __len__(self):
133
- return len(self.file_names)
134
-
135
- def __getitem__(self, index):
136
- image = Image.open(os.path.join(self.root_path + self.file_names[index])).convert("RGB")
137
- return self.transformer(image)
138
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/109peko/anime-remove-background/README.md DELETED
@@ -1,14 +0,0 @@
1
- ---
2
- title: Anime Remove Background
3
- emoji: 🪄🖼️
4
- colorFrom: indigo
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 3.1.4
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- duplicated_from: skytnt/anime-remove-background
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Avast licence key download How to get the most out of your subscription.md DELETED
@@ -1,225 +0,0 @@
1
-
2
- <h1>Avast License Key Download: How to Get It for Free</h1>
3
- <p>If you are looking for a reliable antivirus software that can protect your devices from malware, ransomware, phishing, and other online threats, you might have heard of <strong>Avast</strong>. But do you know how to get a <strong>free Avast license key</strong> for 2022? In this article, we will show you how to download full versions of Avast products for free without any cracks or keygens.</p>
4
- <h2>What is Avast and why do you need a license key?</h2>
5
- <h3>Avast is a popular antivirus software that protects your devices from malware, ransomware, phishing, and other online threats.</h3>
6
- <p>Avast is one of the most trusted antivirus software in the world, with over 435 million users worldwide. It offers various products for different needs, such as <strong>Avast Free Antivirus</strong>, <strong>Avast Premium Security</strong>, <strong>Avast Ultimate</strong>, <strong>Avast SecureLine VPN</strong>, and more.</p>
7
- <h2>Avast licence key download</h2><br /><p><b><b>Download</b> &middot;&middot;&middot; <a href="https://byltly.com/2uKzPn">https://byltly.com/2uKzPn</a></b></p><br /><br />
8
- <p>Avast products use advanced technologies such as artificial intelligence, cloud-based scanning, and behavioral analysis to detect and block malicious files, websites, and activities before they harm your devices. They also provide features such as webcam protection, password manager, firewall, and sandbox to enhance your security and privacy.</p>
9
- <h3>A license key is a code that activates the full features of Avast products, such as Avast Premium Security, Avast Ultimate, Avast SecureLine VPN, and more.</h3>
10
- <p>A license key is a unique code that you need to enter in order to use the full features of Avast products. A license key usually consists of 18 characters divided into three sections, such as <code>VWYNY2-FC5YAJ-4B445S</code>.</p>
11
- <p>A license key allows you to enjoy the benefits of Avast products for a certain period of time, usually one year. After that, you need to renew your license key or purchase a new one.</p>
12
- <p>A license key also determines how many devices you can protect with Avast products. For example, a single license key for <strong>Avast Premium Security</strong>
13
- can protect up to 10 devices, while a single license key for <strong>Avast Ultimate</strong>
14
- can protect only one device.</p>
15
- <h2>How to get a free Avast license key for 2022?</h2>
16
- <h3>There are two ways to get a free Avast license key for 2022: through the recommendation program or through the official website.</h3>
17
- <p>If you want to get a free Avast license key for 2022, you have two options: you can either use the recommendation program or download full versions of Avast products from the official website.</p>
18
- <h4>Recommendation program</h4>
19
- <h5>The recommendation program allows you to share your unique codes with your friends and family and get free full versions of Avast products for up to 6 months.</h5>
20
- <p>The recommendation program is a feature that lets you share your unique codes with your friends and family via email or social media. When they install <strong>Avast Free Antivirus</strong>
21
- or <strong>Avast Premium Security</strong>
22
- using your codes, you will get rewards in the form of free full versions of <strong>Avast Premium Security</strong>
23
- or <strong>Avast Ultimate</strong>
24
- for up to 6 months.</p>
25
- <p>The more people you recommend, the more rewards you get. You can check your rewards status in the recommendation program dashboard on your <strong>Avast Free Antivirus</strong>
26
- or <strong>Avast Premium Security</strong>.</p>
27
- <h5>You can access the recommendation program from your <strong>Avast Free Antivirus</strong>
28
- or <strong>Avast Premium Security</strong>
29
- dashboard.</h5>
30
- <p>To access the recommendation program, you need to have either <strong>Avast Free Antivirus</strong>
31
- or <strong>Avast Premium Security</strong>
32
- installed on your device. You can download them for free from the official website.</p>
33
- <p>How to get Avast licence key for free<br />
34
- Avast antivirus licence key generator<br />
35
- Avast premium security licence key 2021<br />
36
- Avast cleanup licence key activation code<br />
37
- Avast driver updater licence key crack<br />
38
- Avast internet security licence key file<br />
39
- Avast secureline VPN licence key torrent<br />
40
- Avast ultimate licence key till 2050<br />
41
- Avast pro antivirus licence key serial number<br />
42
- Avast password manager licence key online<br />
43
- Avast mobile security licence key apk<br />
44
- Avast business antivirus licence key email<br />
45
- Avast endpoint protection licence key download<br />
46
- Avast cloudcare licence key manager<br />
47
- Avast managed workplace licence key backup<br />
48
- Avast antivirus for mac licence key update<br />
49
- Avast antivirus for linux licence key install<br />
50
- Avast antivirus for android licence key purchase<br />
51
- Avast antivirus for windows 10 licence key renewal<br />
52
- Avast antivirus for windows 7 licence key offline<br />
53
- Avast antivirus for windows XP licence key free download<br />
54
- Avast antivirus for chromebook licence key extension<br />
55
- Avast antivirus for iPhone licence key app store<br />
56
- Avast antivirus for iPad licence key iCloud<br />
57
- Avast antivirus for firestick licence key amazon<br />
58
- Avast antivirus for smart TV licence key LG<br />
59
- Avast antivirus for gaming PC licence key steam<br />
60
- Avast antivirus for laptop licence key HP<br />
61
- Avast antivirus for desktop licence key Dell<br />
62
- Avast antivirus for tablet licence key Samsung<br />
63
- Avast antivirus for Kindle fire licence key support<br />
64
- Avast antivirus for router licence key Netgear<br />
65
- Avast antivirus for NAS licence key Synology<br />
66
- Avast antivirus for external hard drive licence key Seagate<br />
67
- Avast antivirus for USB flash drive licence key Sandisk<br />
68
- Avast antivirus for SD card licence key Kingston<br />
69
- Avast antivirus for CD/DVD drive licence key LG<br />
70
- Avast antivirus for printer/scanner licence key Canon<br />
71
- Avast antivirus for webcam/microphone licence key Logitech<br />
72
- Avast antivirus for speakers/headphones licence key Bose<br />
73
- Avast antivirus for keyboard/mouse licence key Microsoft<br />
74
- Avast antivirus for monitor/screen licence key Asus<br />
75
- Avast antivirus for projector/licence key Epson<br />
76
- Avast antivirus for smartwatch/licence key Apple<br />
77
- Avast antivirus for fitness tracker/licence key Fitbit<br />
78
- Avast antivirus for drone/licence key DJI<br />
79
- Avast antivirus for camera/licence key Nikon<br />
80
- Avast antivirus for phone case/licence key Otterbox<br />
81
- Avast antivirus for power bank/licence key Anker</p>
82
- <p>Once you have installed them, you can open the recommendation program by clicking on the star icon in the top-bar menu. You will see your unique codes that you can share with others.</p>
83
- <h5>You can choose from <strong>Avast Premium Security</strong>
84
- or <strong>Avast Ultimate</strong>
85
- as your rewards.</h5>
86
- <p>The recommendation program offers two types of rewards: <strong>Avast Premium Security</strong>
87
- or <strong>Avast Ultimate</strong>. You can choose which one you want when you redeem your rewards.</p>
88
- <p><strong>Avast Premium Security</strong>
89
- is a complete online security solution that blocks malware, ransomware, spoofed websites, and other threats. It also offers advanced features such as webcam protection, password manager, firewall, and sandbox.</p>
90
- <p><strong>Avast Ultimate</strong>
91
- is a comprehensive bundle of security, privacy, and performance apps in one package. It includes <strong>Avast Premium Security</strong>, <strong>Avast SecureLine VPN</strong>, <h4>Official website</h4>
92
- <h5>The official website offers free downloads of full versions of Avast products for Windows, Mac, iOS, and Android.</h5>
93
- <p>If you don't want to use the recommendation program, you can also download full versions of Avast products for free from the official website. You can choose from Avast Ultimate, Avast Premium Security, Avast AntiTrack Premium, Avast Cleanup Premium, Avast Driver Updater, and Avast SecureLine VPN.</p>
94
- <p>These products are available for Windows 10, 11, 8, 7, Mac, iOS, and Android. You can download them by clicking on the links below.</p>
95
- <ul>
96
- <li><a href="https://www.avast.com/free-license#ultimate">Avast Ultimate</a></li>
97
- <li><a href="https://www.avast.com/free-license#premium-security">Avast Premium Security</a></li>
98
- <li><a href="https://www.avast.com/free-license#antitrack-premium">Avast AntiTrack Premium</a></li>
99
- <li><a href="https://www.avast.com/free-license#cleanup-premium">Avast Cleanup Premium</a></li>
100
- <li><a href="https://www.avast.com/free-license#driver-updater">Avast Driver Updater</a></li>
101
- <li><a href="https://www.avast.com/free-license#secureline-vpn">Avast SecureLine VPN</a></li>
102
- </ul>
103
- <h5>You can enjoy the free trial periods of these products without any cracks or keygens.</h5>
104
- <p>When you download these products from the official website, you can enjoy the free trial periods of these products without any cracks or keygens. You don't need to enter any license key or activation code to use them.</p>
105
- <p>The free trial periods vary depending on the product. For example, Avast Ultimate and Avast Premium Security have a 30-day free trial period, while Avast SecureLine VPN has a 7-day free trial period. You can check the details of each product on their respective pages.</p>
106
- <p>After the free trial period expires, you can either purchase a license key to continue using the product or uninstall it from your device. You can also switch to another product or try another free trial period.</p>
107
- <h2>What are the benefits of using Avast products?</h2>
108
- <h3>Avast products provide powerful protection and performance for your devices.</h3>
109
- <p>Avast products are designed to provide you with powerful protection and performance for your devices. They use advanced technologies and features to keep your devices safe, fast, and private. Here are some of the benefits of using Avast products.</p>
110
- <h4>Avast Premium Security</h4>
111
- <h5>Avast Premium Security is a complete online security solution that blocks malware, ransomware, spoofed websites, and other threats.</h5>
112
- <p>Avast Premium Security is a complete online security solution that protects your devices from malware, ransomware, spoofed websites, and other online threats. It uses artificial intelligence, cloud-based scanning, and behavioral analysis to detect and block malicious files, websites, and activities before they harm your devices.</p>
113
- <p>It also protects you from hackers, cybercriminals, and identity thieves who try to steal your personal data, financial information, or online accounts. It alerts you when you visit unsafe websites, download suspicious files, or enter sensitive information on unsecured forms.</p>
114
- <h5>It also offers advanced features such as webcam protection, password manager, firewall, and sandbox.</h5>
115
- <p>Avast Premium Security also offers advanced features that enhance your security and privacy. Some of these features are:</p>
116
- <ul>
117
- <li><strong>Webcam protection</strong>: This feature prevents unauthorized applications from accessing your webcam and spying on you.</li>
118
- <li><strong>Password manager</strong>: This feature securely stores and manages your passwords and autofills them on your online accounts.</li>
119
- <li><strong>Firewall</strong>: This feature monitors and controls the network traffic on your device and blocks unauthorized connections.</li>
120
- <li><strong>Sandbox</strong>: This feature allows you to run suspicious applications in a safe environment without affecting your device.</li>
121
- </ul>
122
- <h4>Avast Ultimate</h4>
123
- <h5>Avast Ultimate is a comprehensive bundle of security, privacy, and performance apps in one package.</h5>
124
- <p>Avast Ultimate is a comprehensive bundle of security, privacy, and performance apps in one package. It includes <strong>Avast Premium Security</strong>, <strong>Avast SecureLine VPN</strong>, <h4>Avast Ultimate</h4>
125
- <h5>Avast Ultimate is a comprehensive bundle of security, privacy, and performance apps in one package.</h5>
126
- <p>Avast Ultimate is a comprehensive bundle of security, privacy, and performance apps in one package. It includes <strong>Avast Premium Security</strong>, <strong>Avast SecureLine VPN</strong>, <strong>Avast Cleanup Premium</strong>, and <strong>Avast AntiTrack Premium</strong>. With Avast Ultimate, you can enjoy the best of Avast products in one subscription.</p>
127
- <h5>It includes <strong>Avast Premium Security</strong>, <strong>Avast SecureLine VPN</strong>, <strong>Avast Cleanup Premium</strong>, and <strong>Avast AntiTrack Premium</strong>.</h5>
128
- <p>Avast Ultimate includes four Avast products that provide you with security, privacy, and performance for your devices. These products are:</p>
129
- <ul>
130
- <li><strong>Avast Premium Security</strong>: A complete online security solution that blocks malware, ransomware, spoofed websites, and other threats.</li>
131
- <li><strong>Avast SecureLine VPN</strong>: A fast and reliable VPN service that encrypts your internet connection and hides your IP address.</li>
132
- <li><strong>Avast Cleanup Premium</strong>: A powerful optimization tool that speeds up your PC and frees up space.</li>
133
- <li><strong>Avast AntiTrack Premium</strong>: A privacy protection app that disguises your online identity and stops data collectors from tracking you.</li>
134
- </ul>
135
- <h4>Avast SecureLine VPN</h4>
136
- <h5>Avast SecureLine VPN is a fast and reliable VPN service that encrypts your internet connection and hides your IP address.</h5>
137
- <p>Avast SecureLine VPN is a fast and reliable VPN service that encrypts your internet connection and hides your IP address. It allows you to access any content from anywhere in the world and protects your privacy online.</p>
138
- <p>With Avast SecureLine VPN, you can bypass geo-restrictions and censorship and enjoy streaming services, social media, and websites that are blocked in your region. You can also avoid bandwidth throttling and speed up your connection.</p>
139
- <p>Moreover, with Avast SecureLine VPN, you can prevent hackers, cybercriminals, and ISPs from spying on your online activities and stealing your personal data, financial information, or browsing history. You can also use public Wi-Fi networks safely and securely.</p>
140
- <h5>It allows you to access any content from anywhere in the world and protects your privacy online.</h5>
141
- <p>Avast SecureLine VPN has servers in 55 locations across 34 countries, which means you can connect to any country of your choice and access any content from anywhere in the world. You can also switch between servers as many times as you want without any limits.</p>
142
- <p>When you connect to Avast SecureLine VPN, your IP address is changed to one of the servers' IP addresses, which means your online identity is hidden and your location is masked. This way, you can protect your privacy online and avoid being tracked by data collectors, advertisers, or third parties.</p>
143
- <h4>Avast Cleanup Premium</h4>
144
- <h5>Avast Cleanup Premium is a powerful optimization tool that speeds up your PC and frees up space.</h5>
145
- <p>Avast Cleanup Premium is a powerful optimization tool that speeds up your PC and frees up space. It cleans out junk files, browser cache, registry errors, and other issues that slow down your system. It also optimizes your system settings and removes unwanted programs and bloatware.</p>
146
- <p>With Avast Cleanup Premium, you can boost your PC's performance and make it run like new. You can also extend your battery life and reduce power consumption. You can also schedule automatic scans and cleanups to keep your PC in top shape.</p>
147
- <h5>It cleans out junk files, browser cache, registry errors, and other issues that slow down your system.</h5>
148
- <p>Avast Cleanup Premium scans your PC for junk files, browser cache, registry errors, and other issues that take up space and affect your system's performance. It then removes them safely and securely with a single click.</p>
149
- <p>Junk files are temporary files that are created by applications or processes that are no longer needed or used. They can accumulate over time and clutter your disk space. Browser cache is a collection of files that are stored by your web browser to speed up loading times of websites. However, they can also become outdated and take up unnecessary space. Registry errors are invalid entries or references in the Windows registry that can cause errors or crashes. They can be caused by uninstalling or installing programs incorrectly or incompletely.</p>
150
- <h4>Avast Driver Updater</h4>
151
- <h5>Avast Driver Updater is a smart driver updater that scans, updates, and fixes your PC's drivers.</h5>
152
- <p>Avast Driver Updater is a smart driver updater that scans, updates, and fixes your PC's drivers. Drivers are software components that enable your hardware devices to communicate with your operating system and applications. They are essential for the proper functioning of your PC.</p>
153
- <p>With Avast Driver Updater, you can keep your drivers up to date and ensure compatibility with the latest hardware and software. You can also prevent crashes, improve performance, and enhance features of your devices. You can also backup and restore your drivers in case of any problems.</p>
154
- <h4>Avast Driver Updater</h4>
155
- <h5>You can keep your drivers up to date and ensure compatibility with the latest hardware and software.</h5>
156
- <p>Avast Driver Updater scans your PC for outdated, missing, or corrupted drivers and updates them automatically with a single click. It uses a database of over 500,000 drivers from over 100 major brands to find the best and most compatible drivers for your devices.</p>
157
- <p>By updating your drivers regularly, you can ensure compatibility with the latest hardware and software. You can also avoid errors, glitches, or conflicts that can affect your PC's performance or stability. You can also enjoy new features or enhancements of your devices.</p>
158
- <h4>Avast AntiTrack Premium</h4>
159
- <h5>Avast AntiTrack Premium is a privacy protection app that disguises your online identity and stops data collectors from tracking you.</h5>
160
- <p>Avast AntiTrack Premium is a privacy protection app that disguises your online identity and stops data collectors from tracking you. It prevents websites, advertisers, and third parties from collecting your personal data, browsing history, or online behavior.</p>
161
- <p>With Avast AntiTrack Premium, you can browse the web anonymously and securely. You can also avoid targeted ads, price discrimination, or identity theft. You can also delete your browsing history, cookies, and other traces with a single click.</p>
162
- <h5>It prevents websites, advertisers, and third parties from collecting your personal data, browsing history, or online behavior.</h5>
163
- <p>Avast AntiTrack Premium prevents websites, advertisers, and third parties from collecting your personal data, browsing history, or online behavior by disguising your online "fingerprint". Your online fingerprint is a unique combination of information that identifies you on the web, such as your browser type, screen resolution, device model, and more.</p>
164
- <p>When you visit a website, it can use various techniques to track your online fingerprint and use it for various purposes, such as showing you targeted ads, offering you different prices, or selling your data to other parties. Avast AntiTrack Premium blocks these tracking techniques and changes your online fingerprint periodically to make you unrecognizable.</p>
165
- <h2>Conclusion</h2>
166
- <p>In conclusion, Avast is a popular antivirus software that provides powerful protection and performance for your devices. It offers various products for different needs, such as Avast Premium Security, Avast Ultimate, Avast SecureLine VPN, and more.</p>
167
- <p>If you want to get a free Avast license key for 2022, you can either use the recommendation program or download full versions of Avast products from the official website. You can enjoy the full features of Avast products for free without any cracks or keygens.</p>
168
- <p>If you want to download Avast products for free, you can click on the links below.</p>
169
- <ul>
170
- <li><a href="https://www.avast.com/free-license#ultimate">Avast Ultimate</a></li>
171
- <li><a href="https://www.avast.com/free-license#premium-security">Avast Premium Security</a></li>
172
- <li><a href="https://www.avast.com/free-license#antitrack-premium">Avast AntiTrack Premium</a></li>
173
- <li><a href="https://www.avast.com/free-license#cleanup-premium">Avast Cleanup Premium</a></li>
174
- <li><a href="https://www.avast.com/free-license#driver-updater">Avast Driver Updater</a></li>
175
- <li><a href="https://www.avast.com/free-license#secureline-vpn">Avast SecureLine VPN</a></li>
176
- </ul>
177
- <h2>FAQs</h2>
178
- <h3>Q: How do I activate my Avast license key?</h3>
179
- <p>A: To activate your Avast license key, follow these steps:</p>
180
- <ol>
181
- <li>Open your Avast product and go to Menu > My Subscriptions.</li>
182
- <li>Click Enter a valid activation code.</li>
183
- <li>Type or paste your activation code into the text box and click Enter.</li>
184
- <li>Check your subscription details and click Continue.</li>
185
- <li>Your Avast product is now activated.</li>
186
- </ol>
187
- <h3>Q: How do I renew my Avast license key?</h3>
188
- <p>A: To renew your Avast license key, follow these steps:</p>
189
- <ol>
190
- <li>Open your Avast product and go to Menu > My Subscriptions.</li>
191
- <li>Click Renew now next to the subscription that you want to renew.</li>
192
- <li>Select the renewal option that suits you and follow the instructions to complete the payment.</li>
193
- <li>Your Avast product is now renewed.</li>
194
- </ol>
195
- <h3>Q: How do I uninstall my Avast product?</h3>
196
- <p>A: To uninstall your Avast product, follow these steps:</p>
197
- <ol>
198
- <li>Go to Control Panel > Programs > Programs and Features.</li>
199
- <li>Select your Avast product and click Uninstall/Change.</li>
200
- <li>Click Yes to confirm the uninstallation.</li>
201
- <li>Select the option to uninstall completely and click Uninstall.</li>
202
- <li>Restart your computer when prompted.</li>
203
- <li>Your Avast product is now uninstalled.</li>
204
- </ol>
205
- <h3>Q: How do I contact Avast support?</h3>
206
- <p>A: To contact Avast support, follow these steps:</p>
207
- <ol>
208
- <li>Go to <a href="https://support.avast.com/en-us/contact/">https://support.avast.com/en-us/contact/</a>.</li>
209
- <li>Select the product and issue that you need help with.</li>
210
- <li>Select the contact option that suits you (phone, chat, email, or forum).</li>
211
- <li>Provide the required information and submit your request.</li>
212
- <li>An Avast support agent will get back to you as soon as possible.</li>
213
- </ol>
214
- <h3>Q: How do I update my Avast product?</h3>
215
- <p>A: To update your Avast product, follow these steps:</p>
216
- <ol>
217
- <li>Open your Avast product and go to Menu > Settings > Update.</li>
218
- <li>Select the update option that suits you (automatic or manual).</li>
219
- <li>If you select automatic update, your Avast product will update itself whenever a new version is available.</li>
220
- <li>If you select manual update, you need to click Check for updates periodically to check for new versions and install them manually.</li>
221
- <li>Your Avast product is now updated.</li>
222
- </ol>
223
- </p> 0a6ba089eb<br />
224
- <br />
225
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Baahubali 2 - The Conclusion Full Movie In Tamil Download TOP.md DELETED
@@ -1,17 +0,0 @@
1
-
2
- <h1>Baahubali 2 - The Conclusion: How to Watch the Epic Tamil Movie Online</h1>
3
- <p>If you are a fan of Indian cinema, you must have heard of <strong>Baahubali 2 - The Conclusion</strong>, the sequel to the blockbuster <strong>Baahubali - The Beginning</strong>. This epic fantasy film, directed by S.S. Rajamouli, is one of the highest-grossing Indian movies of all time, with a worldwide box office of over ₹1,800 crore. The film features an ensemble cast of Prabhas, Rana Daggubati, Anushka Shetty, Tamannaah Bhatia, Ramya Krishnan, Sathyaraj and Nassar in the lead roles.</p>
4
- <p>The film tells the story of Amarendra Baahubali (Prabhas), the son of Mahishmati's king Vikramadeva (Nassar), who falls in love with Devasena (Anushka Shetty), the princess of Kuntala. However, his cousin Bhallaladeva (Rana Daggubati), who covets the throne and Devasena, plots against him with the help of his father Bijjaladeva (Nassar) and his loyal slave Kattappa (Sathyaraj). The film reveals the secrets behind Baahubali's death and his son Mahendra Baahubali's (Prabhas) quest to avenge him and reclaim his rightful kingdom.</p>
5
- <h2>Baahubali 2 - The Conclusion full movie in tamil download</h2><br /><p><b><b>Download File</b> &#128504; <a href="https://byltly.com/2uKvb6">https://byltly.com/2uKvb6</a></b></p><br /><br />
6
- <p>The film is a visual spectacle with stunning cinematography, breathtaking action sequences, lavish sets, costumes and special effects. The film also boasts of a captivating soundtrack composed by M.M. Keeravani, with songs sung by prominent singers like Kailash Kher, Daler Mehndi, Kaala Bhairava and Shweta Mohan.</p>
7
- <p>If you are wondering how to watch <strong>Baahubali 2 - The Conclusion full movie in Tamil</strong>, you have come to the right place. In this article, we will tell you how to stream or download the film legally and safely online.</p>
8
- <h2>How to Stream Baahubali 2 - The Conclusion Full Movie in Tamil Online</h2>
9
- <p>The easiest and most convenient way to watch <strong>Baahubali 2 - The Conclusion full movie in Tamil</strong> online is to stream it on a reputable OTT platform. There are several platforms that offer the film in Tamil language with subtitles. Some of them are:</p>
10
- <ul>
11
- <li><a href="https://www.hotstar.com/in/movies/baahubali-2-the-conclusion/1770015814">Disney+ Hotstar</a>: This is one of the most popular streaming services in India, with a huge collection of movies, shows, sports and news. You can watch Baahubali 2 - The Conclusion in Tamil on Disney+ Hotstar with a premium subscription that costs ₹299 per month or ₹1499 per year. You can also get a free trial for seven days before you decide to subscribe.</li>
12
- <li><a href="https://www.netflix.com/in/title/81030762">Netflix</a>: This is another leading streaming platform that offers a wide range of content across genres and languages. You can watch Baahubali 2 - The Conclusion in Tamil on Netflix with a basic subscription that costs ₹199 per month. You can also get a free trial for one month before you decide to subscribe.</li>
13
- <li><a href="https://www.primevideo.com/detail/Baahubali-2-The-Conclusion/0L3C7PKU8MLFNGY6E8LFN9IMXA">Amazon Prime Video</a>: This is another popular streaming service that offers a variety of movies, shows, originals and live events. You can watch Baahubali 2 - The Conclusion in Tamil on Amazon Prime Video with a prime membership that costs ₹129 per month or ₹999 per year. You can also get a free trial for 30 days before you decide to subscribe.</li>
14
- </ul>
15
- <p>These are some of the best options to stream <strong>Baahubali 2 - The Conclusion full movie in Tamil</strong> online legally and safely. However, you should always use a reliable VPN service to protect your privacy and security while streaming online.</p> cec2833e83<br />
16
- <br />
17
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Download STEX collection Vol.4(sim city 4 mods disk 4) and discover new ways to play SimCity 4.md DELETED
@@ -1,104 +0,0 @@
1
- <br />
2
- <h1>STEX collection Vol.4: A must-have for SimCity 4 fans</h1>
3
- <p>If you love playing SimCity 4, you probably know that there are thousands of mods and addons that can make your game more fun, realistic and beautiful. But finding and downloading them can be a hassle, especially if you don't know where to look or what to choose. That's why you need <strong>STEX collection Vol.4</strong>, a curated selection of the best mods and addons for SimCity 4 that you can get with a simple donation to Simtropolis, the largest and most active SimCity community online.</p>
4
- <h2>What is STEX collection Vol.4?</h2>
5
- <h3>A compilation of the best mods and addons for SimCity 4</h3>
6
- <p>STEX collection Vol.4 is a digital disc that contains over 1000 files submitted by talented creators to the <strong>Simtropolis Exchange (STEX)</strong>, the place where SimCity 4 fans share their creations with each other. These files include new buildings, props, textures, networks, maps, tools and more that can enhance your game in various ways.</p>
7
- <h2>STEX collection Vol.4(sim city 4 mods disk 4) download</h2><br /><p><b><b>Download</b> &#10040;&#10040;&#10040; <a href="https://byltly.com/2uKwtM">https://byltly.com/2uKwtM</a></b></p><br /><br />
8
- <p>The STEX DVD Team have picked out the very best files based on quality and feedback from the community, and organized them into categories for easy browsing and searching. You can find anything from skyscrapers to farms, from bridges to parks, from stadiums to museums, and much more.</p>
9
- <h3>How to get STEX collection Vol.4?</h3>
10
- <h4>Donate to Simtropolis and receive it as a gift</h4>
11
- <p>The easiest way to get STEX collection Vol.4 is to make a donation to Simtropolis, the website that hosts the STEX and many other resources for SimCity 4 players. By donating, you will not only receive the disc as a gift, but also support the website's maintenance and development costs, as well as show your appreciation for the creators who have generously shared their work with you.</p>
12
- <p>You can donate any amount you want, but if you donate at least $20, you will receive STEX collection Vol.4 as a gift. If you donate more, you can also receive other discs with more mods and addons, such as STEX collection Vol.3 or STEX collection Vol.5.</p>
13
- <p>How to download STEX collection Vol.4 for SimCity 4<br />
14
- STEX collection Vol.4 review: best mods for SimCity 4<br />
15
- Where to find STEX collection Vol.4 and other SimCity 4 addons<br />
16
- SimCity 4 tips and tricks: using STEX collection Vol.4 to enhance your city<br />
17
- STEX collection Vol.4: the ultimate SimCity 4 modding guide<br />
18
- What's new in STEX collection Vol.4: new features and improvements for SimCity 4<br />
19
- How to install STEX collection Vol.4 on your PC or Mac<br />
20
- The best SimCity 4 cities built with STEX collection Vol.4<br />
21
- How to get STEX collection Vol.4 for free<br />
22
- Comparing STEX collection Vol.4 with other SimCity 4 modding tools<br />
23
- How to create your own mods with STEX collection Vol.4<br />
24
- The history of STEX collection Vol.4: how it started and evolved<br />
25
- The most popular and useful mods in STEX collection Vol.4<br />
26
- How to troubleshoot common issues with STEX collection Vol.4<br />
27
- How to update your existing mods with STEX collection Vol.4<br />
28
- How to backup and restore your SimCity 4 data with STEX collection Vol.4<br />
29
- How to customize your game settings with STEX collection Vol.4<br />
30
- The best sources and communities for finding more SimCity 4 mods<br />
31
- How to uninstall or remove STEX collection Vol.4 from your computer<br />
32
- How to optimize your game performance with STEX collection Vol.4<br />
33
- How to use the Network Addon Mod (NAM) with STEX collection Vol.4<br />
34
- How to download and play custom scenarios with STEX collection Vol.4<br />
35
- How to make your city more realistic with STEX collection Vol.4<br />
36
- The benefits and drawbacks of using STEX collection Vol.4<br />
37
- How to share your creations with other players using STEX collection Vol.4<br />
38
- How to learn from the experts: tutorials and videos on using STEX collection Vol.4<br />
39
- The future of STEX collection Vol.4: what's next for the project<br />
40
- How to support the developers of STEX collection Vol.4<br />
41
- The best alternatives to STEX collection Vol.4 for different play styles<br />
42
- How to combine different mods from different sources with STEX collection Vol.4<br />
43
- How to use the Coastal Development Kit (CDK) with STEX collection Vol.4<br />
44
- How to download and use custom buildings and landmarks with STEX collection Vol.4<br />
45
- How to use the SimFox CandyGarden mod with STEX collection Vol.4<br />
46
- How to download and use custom transportation networks with STEX collection Vol.4<br />
47
- How to use the OpenBooks Library mod with STEX collection Vol.4<br />
48
- How to download and use custom terrain and water mods with STEX collection Vol.4<br />
49
- How to use the Beijing Olympic Stadium mod with STEX collection Vol.</p>
50
- <h4>Download it as a ZIP file from Simtropolis</h4>
51
- <p>If you prefer, you can also download STEX collection Vol.4 as a ZIP file from Simtropolis, without making a donation. However, this option has some drawbacks:</p>
52
- <ul>
53
- <li>You will need a fast and stable internet connection to download a large file (about 2.5 GB).</li>
54
- <li>You will not support Simtropolis or the creators who have contributed to the disc.</li>
55
- <li>You will miss out on some exclusive items that can only be found on the disc.</li>
56
- </ul>
57
- <h2>What are the benefits of STEX collection Vol.4?</h2>
58
- <h3>Enhance your gameplay with new features and options</h3>
59
- <p>One of the main benefits of STEX collection Vol.4 is that it can add new features and options to your game that can make it more fun and realistic. For example:</p>
60
- <ul>
61
- <li>You can use the <strong>Network Addon Mod (NAM)</strong>, which fixes many bugs and glitches in the original game's transportation networks, and adds new options such as roundabouts, diagonal bridges, elevated railroads, tramways, toll booths and more.</li>
62
- <li>You can use the <strong>SC4Fix</strong>, which fixes a serialization bug that could corrupt your savegame, especially when using mods that modify existing game content.</li>
63
- <li>You can use the <strong>Tunnel and Slope Mod</strong>, which allows you to adjust the slope parameters of surface transportation networks in the game, making them smoother or steeper according to your preference.</li>
64
- <li>You can use various tools such as <strong>SC4DataNode</strong>, which audits your game files for errors and conflicts; <strong>SC4Mapper</strong>, which allows you to create custom maps for your regions; or <strong>SC4Terraformer</strong>, which allows you to edit your terrain in 3D.</li>
65
- </ul>
66
- <h3>Improve your city's appearance with custom buildings and props</h3>
67
- <p>Another benefit of STEX collection Vol.4 is that it can improve your city's appearance with custom buildings and props that can replace or complement the default ones in the game. For example:</p>
68
- <ul>
69
- <li>You can use new residential, commercial or industrial buildings that have different styles, sizes and densities than the original ones.</li>
70
- <li>You can use new civic or landmark buildings that have historical or cultural significance or are based on real-life examples.</li>
71
- <li>You can use new parks, plazas or recreational facilities that have different shapes, functions and amenities than the original ones.</li>
72
- <li>You can use new props such as trees, flowers, fences, signs, vehicles or people that can add more detail and variety to your lots.</li>
73
- </ul>
74
- <h3>Support the SimCity 4 community and Simtropolis</h3>
75
- <p>A final benefit of STEX collection Vol.4 is that it can support the SimCity 4 community and Simtropolis by showing your appreciation for their work and contribution. By using their mods and addons in your game, you are acknowledging their creativity and skill; by donating to Simtropolis, you are helping them keep their website running and growing; by sharing your feedback and screenshots with them, you are encouraging them to continue creating and improving their content.</p>
76
- <h2>What are some of the highlights of STEX collection Vol.4?</h2>
77
- <p>STEX collection Vol.4 contains over 1000 files from various categories, so it is impossible to list them all here. However, here are some of the highlights that you might want to check out:</p>
78
- <table border="1">
79
- <tr><th>Name</th><th>Description</th><th>Screenshot</th></tr>
80
- <tr><td><strong>FrankU's Dutch parks and plazas</strong></td><td>A set of parks and plazas inspired by Dutch urban design, featuring brick paths, fountains, benches, flower beds and more.</td><td><img src="https://community.simtropolis.com/uploads/monthly_2017_08/5996a9f9a8c6f_FrankU_DutchParksAndPlazas.jpg" width="200" height="150"></td></tr>
81
- <tr><td><strong>Mattb's midrise office pack</strong></td><td>A pack of midrise office buildings with different styles and colors, ranging from modern glass towers to classic brick structures.</td><td><img src="https://community.simtropolis.com/uploads/monthly_2017_08/5996aa0f8d9f7_Mattb_MidriseOfficePack.jpg" width="200" height="150"></td></tr>
82
- <tr><td><strong>Jasoncw's American architecture set</strong></td><td>A set of American architecture buildings based on real-life examples, including Art Deco skyscrapers, Beaux-Arts landmarks, and Gothic churches.</td><td><img src="https://community.simtropolis.com/uploads/monthly_2017_08/5996aa1c8e8c5_Jasoncw_AmericanArchitectureSet.jpg" width="200" height="150"></td></tr>
83
- ```html various countries and eras, such as the Eiffel Tower, the Taj Mahal, the Colosseum, and the Statue of Liberty.</td><td><img src="https://community.simtropolis.com/uploads/monthly_2017_08/5996aa2c8f9a0_JBSimio_HistoricalLandmarks.jpg" width="200" height="150"></td></tr>
84
- <tr><td><strong>And many more!</strong></td><td>These are just some examples of the amazing content that you can find on STEX collection Vol.4. There are many more files that you can explore and enjoy, such as farms, factories, airports, seaports, stadiums, museums, schools, hospitals, fire stations, police stations, power plants, water plants, landmarks, parks, plazas, trees, flowers, signs, vehicles, people and more.</td><td><img src="https://community.simtropolis.com/uploads/monthly_2017_08/5996aa3b8f9a1_STEXCollectionVol4.jpg" width="200" height="150"></td></tr>
85
- </table>
86
- <h2>Conclusion</h2>
87
- <p>STEX collection Vol.4 is a must-have for SimCity 4 fans who want to enhance their game with new features and options, improve their city's appearance with custom buildings and props, and support the SimCity 4 community and Simtropolis. It is a curated selection of the best mods and addons for SimCity 4 that you can get with a simple donation to Simtropolis or download as a ZIP file from their website. It contains over 1000 files from various categories that can make your game more fun, realistic and beautiful.</p>
88
- <p>If you love playing SimCity 4 and appreciate the work of the creators who have shared their creations with you, don't miss this opportunity to get STEX collection Vol.4 and enjoy it in your game. You will not regret it!</p>
89
- <h2>FAQs</h2>
90
- <ol>
91
- <li><strong>What are the system requirements for STEX collection Vol.4?</strong></li>
92
- <p>You need to have SimCity 4 Deluxe Edition or SimCity 4 with the Rush Hour expansion pack installed on your computer to use STEX collection Vol.4. You also need to have enough disk space to store the files (about 2.5 GB) and enough memory to run the game smoothly.</p>
93
- <li><strong>How do I install STEX collection Vol.4?</strong></li>
94
- <p>If you receive STEX collection Vol.4 as a gift for donating to Simtropolis, you will get a link to download it as a ZIP file. You need to unzip the file and copy the contents to your Plugins folder in your SimCity 4 directory. If you download STEX collection Vol.4 as a ZIP file from Simtropolis without donating, you need to do the same thing.</p>
95
- <li><strong>How do I use STEX collection Vol.4?</strong></li>
96
- <p>Once you have installed STEX collection Vol.4 in your Plugins folder, you can start your game and enjoy the new content in your regions and cities. You can find new buildings in your menus or grow them on your zones; you can find new props in your lot editor or plopper tools; you can find new networks in your transportation options; you can find new maps in your region creator or terraformer tools; you can find new tools in your game settings or data views.</p>
97
- <li><strong>How do I uninstall STEX collection Vol.4?</strong></li>
98
- <p>If you want to uninstall STEX collection Vol.4 from your game, you need to delete the files from your Plugins folder in your SimCity 4 directory. You can either delete them manually or use a tool such as <a href="https://community.simtropolis.com/files/file/28544-sc-cleanitol/">SC Cleanitol</a> to do it automatically.</p>
99
- <li><strong>Where can I get more information or help about STEX collection Vol.4?</strong></li>
100
- <p>If you have any questions or issues about STEX collection Vol.4, you can visit <a href="https://community.simtropolis.com/">Simtropolis</a> and post on their forums or chat with other members. You can also read their <a href="https://community.simtropolis.com/omnibus/simtropolis-articles/stex-collections/">STEX Collections article</a> for more details about the discs and how to get them.</p>
101
- </ol>
102
- </p> 0a6ba089eb<br />
103
- <br />
104
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Atpl Radio Navigation Cbt Download !FREE!.md DELETED
@@ -1,9 +0,0 @@
1
- <br />
2
- <p>on top of the exam itself you will also be required to sit a written exam for each subject area covered by the atpl exams. this adds another level of difficulty, but you can learn the subject areas from www.kcthepilot.com</p>
3
- <p>this atpl course is completely online and self-paced. all of the requirements are delivered using high definition, interactive whiteboard and multimedia technology. there are no downloads or downloads required and no waiting for the next tutorial to start.</p>
4
- <h2>atpl radio navigation cbt download</h2><br /><p><b><b>Download</b> &ndash;&ndash;&ndash; <a href="https://imgfil.com/2uy0DK">https://imgfil.com/2uy0DK</a></b></p><br /><br />
5
- <p>the course is designed to be followed at your own pace, as quickly or slowly as you can take it. the course is available for unlimited students. all you need is a laptop or computer that has an internet connection.</p>
6
- <p>this course is an atpl prep course with a focus on having the student understand the purpose of an atpl, preparation and passing the atpl theory exam. prepare for your atpl theory exams with the flight director course.it includes assessment which includes quizzes, prepared and timed student flights, automatic calculation of scores, setting your own grades and score history.</p>
7
- <p>atpl theory is not complicated if you break things down and look at individual topics, questions or subject areas. provided you can do essential addition, subtraction, multiplication and division and can read and write at gcse level, that will be enough. <p>what makes atpl theory hard is the sheer volume of information that needs to be committed to memory. the other complication with atpl theory is that just because you know the material inside and out on its own will not guarantee a pass.<p>successfully passing atpl exams relies on knowing the material thoroughly and having practised several thousand atpl questions to get into the groove of how the caa would like you to answer the questions.ez_ad_units.push([[300,250],'kcthepilot_com-narrow-sky-2','ezslot_15',142,'0','0']);__ez_fad_position('div-gpt-ad-kcthepilot_com-narrow-sky-2-0');</p> 899543212b<br />
8
- <br />
9
- <br />
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Criminal Download Stream or Download the Popular Podcast Series About True Crime Stories.md DELETED
@@ -1,28 +0,0 @@
1
-
2
- <p>Calendars are in Adobe pdf format. Download the free Reader® by clicking here. <br /> <br /> <br /> <br /> <br /> <strong>DISCLAIMER</strong><br />Please Note: It is understood that the information contained on this website is subject to constant change and that its accuracy cannot be guaranteed. This website is a public resource of general information. The TROUP COUNTY CLERK OF SUPERIOR AND STATE COURTS makes no warranty, representation or guaranty as to the content, sequence, accuracy, timeliness or completeness of any of the information provided herein.Primary sources from which this information is compiled by the Troup County Office of the Clerk, must be consulted for verification and certification of the information contained on this website. The user knowingly waives any and all claims for damages against any and all of the entities comprising this website that may arise from the information contained therein. Court calendars are subject to change after being posted to the site due to additions and deletions by the parties. Contact the Court Clerk at 706-883-1740 to verify the online accuracy or obtain a final copy.By entering this site to view/download calendars you are accepting this disclaimer.</p>
3
- <p>This 1400-page book with downloadable PDF provides the full text of the Pennsylvania Crimes Code with accompanying commentary by Robert L. Evangelista, former Chief Counsel of both the Crime Victims Compensation Board and the Commission on Crime and Delinquency. Mr. Evangelista offers in-depth commentary for all sections of the Code which have had significant cases construing their provisions by: examining language of the Code, comparing various sections of the Code, discussing the possible problems raised by the Code, including references and quotations from the Model Penal Code, and comparing the previous law and the present Code.</p>
4
- <h2>Criminal download</h2><br /><p><b><b>Download Zip</b> &#128504;&#128504;&#128504; <a href="https://imgfil.com/2uy25W">https://imgfil.com/2uy25W</a></b></p><br /><br />
5
- <p>Citations give full attention to Pennsylvania authorities, as well as U.S. Supreme Court cases, particularly those involving the death penalty. In addition to the Crimes Code, the author has included the full statute and insightful commentary to other areas in which there are a significant number of criminal prosecutions: the Controlled Substances Act, Vehicular Homicide, and Driving Under the Influence. New in this Fourth Edition are chapters on Antihazing and Human Trafficking. <br></p>
6
- <p>The Arizona Criminal Justice Commission (ACJC) along with the Department of Public Safety (DPS) & Administrative Office of the Court (AOC) work together to maintain and deliver the Arizona Revised Statutes (ARS) Citable Criminal Offense Table. The following table can be used to read or download the ARS Citable Criminal Codes. Please review the "File Layout & Documentation" for information on how to use the table.</p>
7
- <p>The Department of Public Safety (DPS) manages the distribution of City & County Criminal, Civil, and Tribal Codes. The following table can be used to read or download Codes. Please review the "File Layout & Documentation" for information on how to use the table.</p>
8
- <p>Getting to the bottom of these mysterious deaths will not be an easy task, so be sure you have every available advantage you can get. Click either of the links on this page to instantly download the free Bluestacks Android Emulator tool. Once the automatic process is completed, you can begin to search the Google Play store for top-downloaded apps and games to play on Mac or PC.</p>
9
- <p>The Division of State Police, Criminal Information Unit (CIU) provides fingerprint-based New Jersey criminal history record checks to any resident of the State of New Jersey requesting a copy of their own criminal history record. A personal record request is typically for the purpose of:</p>
10
- <p><strong>If the background check identifies a criminal history the results will be mailed to the applicant's or employer's address. If the background check does not identify a criminal history the results will be available to the applicant or employer in the form of an official letter from the New Jersey State Police which is available for download via the NJSP website. See below for further instructions.</strong></p>
11
- <p>A NJ resident may obtain a criminal history record information (CHRI) check by submitting fingerprints via electronic live scan at one of the approved fingerprint capturing IdentoGO sites. The New Jersey State Police utilizes the live scan fingerprinting services provided by IDEMIA, a private company under contract with the State of New Jersey. To begin the fingerprint process, you are required to contact IDEMIA to schedule a time and place to have your fingerprints captured at one of the IdentoGO sites, which are conveniently located throughout the State of NJ. The quickest and easiest way to schedule your appointment is via the World Wide Web at <strong> </strong>.</p>
12
- <p></p>
13
- <p>IDEMIA has assigned a Service Code for each unique combination of agency and applicant type. The six-character Service Code is used for uniquely identifying the Agency (ORI), and Reason for Fingerprinting (RFP). The use of the Service Code ensures that applicants are being fingerprinted for the correct purpose and are not being processed for a service they do not need. See below for a list of (4) available criminal history background checks provided by the New Jersey State Police with corresponding service codes listed for each type of request.</p>
14
- <p>Once fingerprinted, Applicants and/or Employers will have the ability, within 24 to 72 hours, to download the Personal Record Request letter by clicking on the link, To download the Personal Record Request letter, Applicants and/or Employers will need the <strong>IdentoGO PCN, Last Name and Date of Birth</strong> as entered on the IdentoGO form to be authenticated. The Applicants and/or Employers will have up to <strong>90 days</strong> from the date fingerprinted to download the Personal Record Request letter. After <strong>90 days</strong>, the Applicant will need to repeat the Personal Record Request process and be fingerprinted again.</p>
15
- <p>Failure to provide complete and accurate information may result in having to be fingerprinted again and incurring additional costs. (There are no refunds once a criminal history background check is completed)</strong>. Questions or revisions to responses must be made within a ninety day <strong>(90)</strong> period or the full process will have to be repeated. If you do not receive your response within ten <strong>(10)</strong> working days please contact the <strong>Criminal Information Unit at 609 882-2000 ext. 2302 or [email protected]</strong>.</p>
16
- <p>(A criminal hit will result in full disclosure of the criminal record and will be mailed to the applicant's address. If there is no criminal history the result will be in the form of a letter which is available for download via the NJSP website: )</p>
17
- <p>(A Criminal Hit will result in the disclosure of convictions and pending data only and will be mailed to the applicant's address. If there is no criminal history the result will be in the form of a letter which is available for download via the NJSP website: )</p>
18
- <p><b>Download your <i>Blackstone's Criminal Practice 2022</i> digital pack here.</b><br/>Instructions on how to download the digital pack can be found here.<br/><br/><br/><br/><strong>Receive Blackstone's Briefing</strong><br/>Sign up to receive the <i>Blackstone's Criminal Practice Briefing</i></p>
19
- <p><strong>Register for the monthly online updates</strong><br/>Receive an email every month with the latest updates to criminal law and procedure. See the latest update here<br/><strong>User Guides</strong></p>
20
- <p>The FBI background check will be increasing effective August 1, 2022. The new fee will be $25.25. All applicants will receive an unofficial copy of their reportvia email (<strong>Pleasenote the link is available only for ONE-TIME accessonly, and once accessed will no longer be valid. You should only access thislink from a device that will allow you to download, print, or save your resultsat that time</strong>). Fee is payable to IDEMIA.</p>
21
- <p>Criminal Stories: CSI Episode makes players have to become talented, intelligent detectives to investigate and find the truth behind mysterious and horror cases. Players need to think and make the right choices to catch the real criminals</p>
22
- <p>Coming to Criminal Stories: CSI Episode, the horror criminal cases happen in a row; there needs to be someone who can investigate the mysteries behind it. Players will be transformed into talented detectives to investigate, find hidden truths, and regain justice for the victims.</p>
23
- <p>The criminals in Criminal Stories: CSI Episode are very sophisticated, so it will be difficult for the player to investigate. These are cases that can cause headaches for our talented detectives. Players will have to interrogate victims, interrogate suspects and use investigative tools such as fingerprint analysis, phone recordings, DNA testing, forensic examination to get the right conclusions.</p>
24
- <p>The talented detectives will come to a conclusion after a tough investigation. You must use your intelligent reasoning skills to be able to catch real criminals, bring them to light, and receive appropriate punishment by the law. After you come to a conclusion, you can compare your results with other players then the game will give the final result, revealing the truth.</p>
25
- <p>Criminal Stories: CSI Episode is a place to find genius detectives, help victims catch criminals, and let them be punished appropriately. With challenging cases, the game needs players to show all their reasoning and investigation skills to come up with the best results, helping to uncover the mysterious truths.</p>
26
- <p><br /><br />While the Iowa Supreme Court cannot give prior approval to the instructions, the court has unanimously approved, in principle, the plain English redraft of the Iowa Civil and Criminal Jury Instructions.<br /><br /><strong>PRICE</strong><br />$75 (+tax & shipping)<br /><br />These instructions are also available as a free download to ISBA members.<br /><br /><strong>Click here to download the instructions for free</strong></p> aaccfb2cb3<br />
27
- <br />
28
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1line/AutoGPT/autogpt/memory/base.py DELETED
@@ -1,43 +0,0 @@
1
- """Base class for memory providers."""
2
- import abc
3
-
4
- import openai
5
-
6
- from autogpt.config import AbstractSingleton, Config
7
-
8
- cfg = Config()
9
-
10
-
11
- def get_ada_embedding(text):
12
- text = text.replace("\n", " ")
13
- if cfg.use_azure:
14
- return openai.Embedding.create(
15
- input=[text],
16
- engine=cfg.get_azure_deployment_id_for_model("text-embedding-ada-002"),
17
- )["data"][0]["embedding"]
18
- else:
19
- return openai.Embedding.create(input=[text], model="text-embedding-ada-002")[
20
- "data"
21
- ][0]["embedding"]
22
-
23
-
24
- class MemoryProviderSingleton(AbstractSingleton):
25
- @abc.abstractmethod
26
- def add(self, data):
27
- pass
28
-
29
- @abc.abstractmethod
30
- def get(self, data):
31
- pass
32
-
33
- @abc.abstractmethod
34
- def clear(self):
35
- pass
36
-
37
- @abc.abstractmethod
38
- def get_relevant(self, data, num_relevant=5):
39
- pass
40
-
41
- @abc.abstractmethod
42
- def get_stats(self):
43
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download BEYBLADE BURST app for iOS and Android - Latest Version.md DELETED
@@ -1,199 +0,0 @@
1
-
2
- <h1>Beyblade Burst App Download: How to Play and Enjoy the Game on Your Device</h1>
3
- <p>If you are a fan of the popular anime and toy series Beyblade, you might want to try out the Beyblade Burst App, a mobile game that lets you create, customize, and battle your own Beyblade Burst tops. The game is based on the third generation of the Beyblade franchise, which features a new system of interchangeable parts that can burst during battles. The game also allows you to challenge your friends and other players from around the world in online matches, join or create your own battle league, scan and control Bluetooth enabled Beyblade Burst tops, and use special moves and power-ups to win. In this article, we will show you how to download and install the Beyblade Burst App on your device, how to play the game, and some tips and tricks to help you become a better Blader.</p>
4
- <h2>What is Beyblade Burst App?</h2>
5
- <p>The Beyblade Burst App is a mobile game developed by Hasbro Inc. that is based on the Beyblade Burst anime and toy series. The game was released in 2016 and has been updated regularly with new features, content, and compatibility. The game is available for free on both Android and iOS devices, but it also offers in-app purchases for some items and features. The game has received positive reviews from users and critics, who praised its graphics, gameplay, customization options, and multiplayer modes. The game has also been nominated for several awards, such as the Kids' Choice Awards, the Webby Awards, and the TIGA Games Industry Awards.</p>
6
- <h2>beyblade burst app download</h2><br /><p><b><b>DOWNLOAD</b> ===> <a href="https://jinyurl.com/2uNQjS">https://jinyurl.com/2uNQjS</a></b></p><br /><br />
7
- <h3>Features of Beyblade Burst App</h3>
8
- <p>The Beyblade Burst App has many features that make it fun and engaging for players of all ages. Some of the main features are:</p>
9
- <ul>
10
- <li>Create, customize, and battle your own Beyblade Burst tops with hundreds of different parts and colors.</li>
11
- <li>Challenge your friends and other players from over 90 countries worldwide to global multiplayer online matches, with leaderboards, personalized profiles, an enhanced digital top selection, and the capability of earning achievements.</li>
12
- <li>Join or create a league of your own, where you can invite your friends, choose a season length, earn points by competing in different types of battles, and host a toy tournament party.</li>
13
- <li>Scan a Beyblade Burst Energy Layer to unlock Bluetooth enabled digital controls within the app, where you can swipe left or right onscreen to change spin direction and speed of your top, charge up power during battle, and unleash mighty Avatar attacks.</li>
14
- <li>Experience the new Beyblade Burst Turbo Slingshock system, which features a rail system that propels digital tops through the Beystadium rails and into the Battle Ring for special power-up bonuses.</li>
15
- </ul>
16
- <h3>How to Download and Install Beyblade Burst App</h3>
17
- <p>The Beyblade Burst App is compatible with select Android and iOS devices. You can check the compatibility list on the official website or on the app store page. To download and install the app on your device, follow these steps:</p>
18
- <h4>For Android Devices</h4>
19
- <ol>
20
- <li>Go to the Google Play Store on your device or click <a href="(^1^)">here</a>.</li>
21
- <li>Search for "Beyblade Burst App" or tap on this <a href="(^1^)">link</a>.</li>
22
- <li>Tap on "Install" and wait for the app to download.</li>
23
- <li>Once the download is complete, tap on "Open" to launch the app.</li>
24
- <li>Follow the on-screen instructions to set up your account and start playing.</li>
25
- </ol>
26
- <h4>For iOS Devices</h4>
27
- <ol>
28
- <li>Go to the App Store on your device or click <a href="">here</a>.</li>
29
- <li>Search for "Beyblade Burst App" or tap on this <a href="">link</a>.</li>
30
- <li>Tap on "Get" and enter your Apple ID password or use Touch ID or Face ID to confirm.</li>
31
- <li>Wait for the app to download and install.</li>
32
- <li>Once the installation is done, tap on the app icon to open it.</li>
33
- <li>Follow the on-screen instructions to set up your account and start playing.</li>
34
- </ol>
35
- <h2>How to Play Beyblade Burst App</h2>
36
- <p>The Beyblade Burst App is easy to play and has a user-friendly interface. Here are some of the basic steps to play the game:</p>
37
- <h3>Create and Customize Your Beyblade Burst Tops</h3>
38
- <p>The first thing you need to do is to create your own Beyblade Burst top. You can choose from hundreds of different parts and colors, and mix and match them to create your unique combination. You can also scan a real-life Beyblade Burst top using your device's camera to unlock it in the game. To create and customize your top, follow these steps:</p>
39
- <ol>
40
- <li>Tap on the "Create" button on the main menu.</li>
41
- <li>Select a Bey type: Attack, Defense, Stamina, or Balance.</li>
42
- <li>Select an Energy Layer, a Forge Disc, and a Performance Tip from the available options. You can also tap on the "Randomize" button to get a random combination.</li>
43
- <li>Tap on the "Customize" button to change the colors of your parts. You can also tap on the "Swap" button to switch parts with another top.</li>
44
- <li>Tap on the "Save" button to save your top. You can also tap on the "Edit" button to rename your top or delete it.</li>
45
- </ol>
46
- <h3>Challenge Your Friends and Other Players Online</h3>
47
- <p>The Beyblade Burst App allows you to challenge your friends and other players from around the world in online battles. You can also chat with them, send them gifts, and view their profiles. To challenge someone online, follow these steps:</p>
48
- <p>beyblade burst app free download for android<br />
49
- beyblade burst app download apk<br />
50
- beyblade burst app download for pc<br />
51
- beyblade burst app download ios<br />
52
- beyblade burst app download for windows 10<br />
53
- beyblade burst app download mod apk<br />
54
- beyblade burst app download latest version<br />
55
- beyblade burst app download play store<br />
56
- beyblade burst app download uptodown<br />
57
- beyblade burst app download hack<br />
58
- beyblade burst app download online<br />
59
- beyblade burst app download for laptop<br />
60
- beyblade burst app download for mac<br />
61
- beyblade burst app download for chromebook<br />
62
- beyblade burst app download new update<br />
63
- beyblade burst app download unlimited money<br />
64
- beyblade burst app download game<br />
65
- beyblade burst app download in jio phone<br />
66
- beyblade burst app download for kindle fire<br />
67
- beyblade burst app download qr codes<br />
68
- beyblade burst app download without wifi<br />
69
- beyblade burst app download for android tv<br />
70
- beyblade burst app download for tablet<br />
71
- beyblade burst app download on computer<br />
72
- beyblade burst app download bluestacks<br />
73
- beyblade burst app download with all parts unlocked<br />
74
- beyblade burst app download from apkpure<br />
75
- beyblade burst app download in hindi<br />
76
- beyblade burst app download for samsung<br />
77
- beyblade burst app download size<br />
78
- beyblade burst app download 2023<br />
79
- beyblade burst app download turbo slingshock<br />
80
- beyblade burst app download how to scan codes<br />
81
- beyblade burst app download nox player<br />
82
- beyblade burst app download on iphone<br />
83
- beyblade burst app download with all beys unlocked<br />
84
- beyblade burst app download from google play store<br />
85
- beyblade burst app download in tamil<br />
86
- beyblade burst app download for nokia<br />
87
- beyblade burst app download requirements<br />
88
- beyblade burst app download 2022 update<br />
89
- beyblade burst app download rise hypersphere stadium set up instructions <br />
90
- beyblade burst app download tips and tricks <br />
91
- beyblade burst app download on ipad <br />
92
- beyblade burst app download with all stadiums unlocked <br />
93
- beyblade burst app download from apple store <br />
94
- beyblade burst app download in telugu <br />
95
- beyblade burst app download for oppo <br />
96
- beyblade burst app download ratings and reviews</p>
97
- <ol>
98
- <li>Tap on the "Battle" button on the main menu.</li>
99
- <li>Select a battle mode: Quick Match, League Match, or Friendly Match.</li>
100
- <li>Select a Bey Stadium: Basic Stadium, Slingshock Stadium, or Digital Stadium.</li>
101
- <li>Select a Beyblade Burst top from your collection or scan a new one.</li>
102
- <li>Wait for an opponent to join or invite someone from your friends list or league.</li>
103
- <li>When the battle starts, swipe up on the screen to launch your top. You can also tilt your device to steer your top.</li>
104
- <li>Tap on the screen to charge up power and unleash special moves and power-ups. You can also tap on the avatar icon of your top to activate its Avatar Attack.</li>
105
- <li>The battle ends when one of the tops bursts, stops spinning, or falls out of the stadium. The winner gets points and rewards based on their performance.</li>
106
- </ol>
107
- <h3>Join or Create a Battle League</h3>
108
- <p>The Beyblade Burst App also lets you join or create a battle league of your own, where you can compete with other players in different types of battles and earn points. You can also host a toy tournament party with your friends using real-life Beyblade Burst tops and scan their results into the app. To join or create a league, follow these steps:</p>
109
- <ol>
110
- <li>Tap on the "League" button on the main menu.</li>
111
- <li>Select an option: Join a League or Create a League.</li>
112
- <li>If you want to join a league, browse through the available leagues and tap on one that interests you. You can also search for a league by name or code. Then, tap on the "Join" button and wait for approval from the league owner.</li>
113
- <li>If you want to create a league, tap on the "Create" button and enter a name, description, code, season length, and battle type for your league. Then, tap on the "Create" button again and invite your friends or other players to join your league.</li>
114
- <li>Once you are in a league, you can view its details, members, standings, schedule, chat room, and rewards. You can also leave or delete a league at any time.</li>
115
- </ol>
116
- <h3>Scan and Control Bluetooth Enabled Beyblade Burst Tops</h3> <p>The Beyblade Burst App also supports Bluetooth enabled Beyblade Burst tops, which are special tops that have a built-in chip that can connect to your device via Bluetooth. You can scan these tops using the app and control them with digital commands. To scan and control Bluetooth enabled tops, follow these steps:</p>
117
- <ol>
118
- <li>Make sure your device has Bluetooth turned on and is compatible with the app.</li>
119
- <li>Tap on the "Scan" button on the main menu and select "Bluetooth Scan".</li>
120
- <li>Hold your device over the Energy Layer of the Bluetooth enabled top and wait for the app to recognize it.</li>
121
- <li>Once the top is scanned, you can view its details, customize its parts and colors, and add it to your collection.</li>
122
- <li>To control the top, tap on the "Battle" button and select "Bluetooth Battle".</li>
123
- <li>Select a Bey Stadium and a Bluetooth enabled top from your collection.</li>
124
- <li>Wait for an opponent to join or invite someone from your friends list or league who also has a Bluetooth enabled top.</li>
125
- <li>When the battle starts, swipe left or right on the screen to change the spin direction and speed of your top. You can also tap on the screen to charge up power and unleash special moves and power-ups. You can also tap on the avatar icon of your top to activate its Avatar Attack.</li>
126
- <li>The battle ends when one of the tops bursts, stops spinning, or falls out of the stadium. The winner gets points and rewards based on their performance.</li>
127
- </ol>
128
- <h3>Use Special Moves and Power-Ups</h3>
129
- <p>The Beyblade Burst App also features special moves and power-ups that you can use during battles to gain an edge over your opponent. These include:</p>
130
- <ul>
131
- <li>Avatar Attack: This is a powerful move that unleashes the avatar of your top, which can deal massive damage to your opponent's top. To use this move, you need to fill up the Avatar Meter by tapping on the screen during battle. Once the meter is full, tap on the avatar icon of your top and watch it unleash its fury.</li>
132
- <li>Burst Finish: This is a move that causes your opponent's top to burst instantly, giving you an automatic win. To use this move, you need to fill up the Burst Meter by dealing damage to your opponent's top during battle. Once the meter is full, tap on it and watch your opponent's top explode.</li>
133
- <li>Slingshock Power-Up: This is a power-up that boosts your top's speed and attack power when it enters the Slingshock Stadium. To use this power-up, you need to launch your top with enough force to make it ride on the rails of the stadium. Once it does, it will gain a blue aura and become more powerful.</li>
134
- </ul>
135
- <h2>Tips and Tricks for Beyblade Burst App</h2>
136
- <p>The Beyblade Burst App is a fun and exciting game, but it can also be challenging at times. Here are some tips and tricks to help you improve your skills and win more battles:</p>
137
- <h3>Know Your Bey Types and Their Advantages</h3>
138
- <p>The Beyblade Burst App features four types of Beyblade Burst tops: Attack, Defense, Stamina, and Balance. Each type has its own strengths and weaknesses, and knowing them can help you choose the best top for each battle. Here is a brief overview of each type:</p>
139
- <table>
140
- <tr><th>Type</th><th>Description</th><th>Advantage</th><th>Disadvantage</th></tr>
141
- <tr><td>Attack</td><td>These are aggressive tops that have high speed and attack power. They are designed to deal heavy damage to their opponents and burst them quickly.</td><td>They can overwhelm their opponents with powerful hits and bursts.</td><td>They have low stamina and defense, which makes them vulnerable to counterattacks and outlasting.</td></tr>
142
- <tr><td>Defense</td><td>These are defensive tops that have high durability and stability. They are designed to withstand attacks from their opponents and survive longer in battles.</td><td>They can resist bursts and knockouts from their opponents.</td><td>They have low speed and attack power, which makes them less effective at dealing damage and bursting their opponents.</td></tr>
143
- <tr><td>Stamina</td><td>These are endurance tops that have high spin time and balance. They are designed to outlast their opponents in long battles by spinning longer than them.</td><td>They can win by spin finish or by draining their opponents' stamina.</td><td>They have low attack power and defense, which makes them susceptible to bursts and knockouts from their opponents.</td></tr>
144
- <tr><td>Balance</td><td>These are versatile tops that have a mix of speed, attack power, durability, and stability. They are designed to adapt to different situations and opponents in battles.</td><td>They can perform well in any battle mode and stadium.</td><td>They have no clear advantage or disadvantage over any other type, which makes them unpredictable and inconsistent.</td></tr>
145
- </table>
146
- <p>Knowing your Bey type and its advantages can help you choose the best top for each battle. You can also use this knowledge to counter your opponent's type and exploit their weakness. For example, if you are facing an Attack type, you can use a Defense type to resist their hits and burst them. If you are facing a Defense type, you can use a Stamina type to outlast them and win by spin finish. If you are facing a Stamina type, you can use an Attack type to deal heavy damage and burst them. If you are facing a Balance type, you can use any type that suits your play style and strategy.</p>
147
- <h3>Master Different Launch Techniques</h3>
148
- <p>The way you launch your top can also affect the outcome of the battle. Different launch techniques can give your top different spin directions, speeds, angles, and trajectories, which can influence its performance and behavior in the stadium. Here are some of the launch techniques you can try:</p>
149
- <ul>
150
- <li>Standard Launch: This is the basic launch technique that gives your top a normal spin direction and speed. To perform this launch, swipe up on the screen with moderate force and aim for the center of the stadium.</li>
151
- <li>Sliding Shoot: This is a launch technique that gives your top a curved trajectory and more speed. To perform this launch, swipe up on the screen with more force and angle your swipe slightly to the left or right, depending on your top's spin direction.</li>
152
- <li>Banking Shoot: This is a launch technique that gives your top a high angle and more attack power. To perform this launch, swipe up on the screen with more force and aim for the edge of the stadium.</li>
153
- <li>Counter Break: This is a launch technique that gives your top a reverse spin direction and more defense power. To perform this launch, swipe down on the screen with moderate force and aim for the center of the stadium.</li>
154
- <li>Slingshock Launch: This is a launch technique that gives your top a boost of speed and power when it enters the Slingshock Stadium. To perform this launch, swipe up on the screen with more force and aim for the rails of the stadium.</li>
155
- </ul>
156
- <p>Mastering different launch techniques can help you gain an edge over your opponent and surprise them with unexpected moves. You can also experiment with different combinations of launch techniques and Bey types to find your best match.</p>
157
- <h3>Upgrade Your Beys and Unlock New Parts</h3>
158
- <p>The Beyblade Burst App also allows you to upgrade your Beys and unlock new parts by playing the game and earning rewards. Upgrading your Beys can improve their stats and abilities, while unlocking new parts can give you more options for customization. Here are some of the ways you can upgrade your Beys and unlock new parts:</p>
159
- <ul>
160
- <li>Level Up: You can level up your Beys by using them in battles and gaining experience points. Leveling up your Beys can increase their attack, defense, stamina, speed, agility, burst resistance, weight, size, and avatar power.</li>
161
- <li>Earn Coins: You can earn coins by winning battles, completing quests, watching ads, or buying them with real money. You can use coins to buy new parts from the shop or upgrade your existing parts.</li>
162
- <li>Earn Gems: You can earn gems by completing achievements, participating in events, or buying them with real money. You can use gems to buy premium parts from the shop or unlock special features in the game.</li>
163
- <li>Earn Beycoins: You can earn beycoins by playing in league matches or tournaments. You can use beycoins to buy exclusive parts from the league shop or enter higher-level tournaments.</li>
164
- <li>Earn Gifts: You can earn gifts by playing daily, inviting friends, or receiving them from other players. Gifts can contain coins, gems, beycoins, parts, or other items.</li>
165
- </ul>
166
- <p>Upgrading your Beys and unlocking new parts can help you enhance your performance and expand your collection. You can also trade parts with other players or sell them for coins if you have duplicates or unwanted ones.</p>
167
- <h3>Earn Rewards and Gifts by Playing Daily</h3>
168
- <p>The Beyblade Burst App also rewards you for playing daily by giving you various rewards and gifts. These include:</p>
169
- <ul>
170
- <li>Daily Login Bonus: You can get a daily login bonus by logging in to the game every day. The bonus can be coins, gems, beycoins, parts, or other items. The bonus increases every day until it resets on the seventh day.</li>
171
- <li>Daily Quest Bonus: You can get a daily quest bonus by completing three quests every day. The quests can be related to battles, leagues, tournaments, or other activities. The bonus can be coins, gems, beycoins, parts, or other items.</li>
172
- <li>Daily Spin: You can get a daily spin bonus by spinning a wheel every day. The wheel can give you coins, gems, beycoins, parts, or other items. You can also get extra spins by watching ads or spending gems.</li>
173
- <li>Daily Gift: You can get a daily gift bonus by opening a gift box every day. The gift box can contain coins, gems, beycoins, parts, or other items. You can also get extra gift boxes by watching ads or spending gems.</li>
174
- </ul>
175
- <p>Earning rewards and gifts by playing daily can help you get more resources and items for your Beys and your game. You can also share your rewards and gifts with your friends or other players to show your generosity and appreciation.</p>
176
- <h2>Conclusion</h2>
177
- <p>The Beyblade Burst App is a great game for fans of the Beyblade franchise and for anyone who enjoys spinning tops and battling games. The game offers a lot of features, content, and customization options that make it fun and engaging for players of all ages. The game also allows you to connect with your friends and other players from around the world in online battles, leagues, and tournaments. The game is easy to play and has a user-friendly interface, but it also requires skill and strategy to master. The game is compatible with select Android and iOS devices and is available for free on the app stores. However, the game also offers in-app purchases for some items and features. If you want to download and install the Beyblade Burst App on your device, follow the steps in this article and start playing today.</p>
178
- <h2>FAQs</h2>
179
- <p>Here are some of the frequently asked questions about the Beyblade Burst App:</p>
180
- <ol>
181
- <li>Q: How do I update the Beyblade Burst App?</li>
182
- <li>A: To update the Beyblade Burst App, go to the app store on your device and check if there is a new version available. If there is, tap on the "Update" button and wait for the app to download and install. You can also enable automatic updates on your device settings to get the latest version of the app automatically.</li>
183
- <li>Q: How do I reset the Beyblade Burst App?</li>
184
- <li>A: To reset the Beyblade Burst App, go to the settings menu on the app and tap on the "Reset" button. This will erase all your data and progress in the game and start from scratch. You can also delete and reinstall the app on your device to reset it.</li>
185
- <li>Q: How do I contact the Beyblade Burst App support team?</li>
186
- <li>A: To contact the Beyblade Burst App support team, go to the settings menu on the app and tap on the "Help" button. This will take you to a page where you can find FAQs, tutorials, feedback forms, and contact information for the support team.</li>
187
- <li>Q: How do I report a bug or a problem in the Beyblade Burst App?</li>
188
- <li>A: To report a bug or a problem in the Beyblade Burst App, go to the settings menu on the app and tap on the "Feedback" button. This will take you to a form where you can describe your issue and attach screenshots if needed. You can also email your report to [email protected].</li>
189
- <li>Q: How do I get more coins, gems, beycoins, parts, or other items in the Beyblade Burst App?</li>
190
- <li>A: To get more coins, gems, beycoins, parts, or other items in the Beyblade Burst App, you can do any of the following:</li>
191
- <ul>
192
- <li>Win battles, complete quests, achieve milestones, participate in events, or watch ads.</li>
193
- <li>Buy them with real money through in-app purchases.</li>
194
- <li>Earn them by playing daily and getting bonuses.</li>
195
- <li>Receive them as gifts from your friends or other players.</li>
196
- </ul>
197
- </ol></p> 197e85843d<br />
198
- <br />
199
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download Battle Playground Simulator Mod APK and Experience the Ultimate Battle Simulation.md DELETED
@@ -1,94 +0,0 @@
1
-
2
- <h1>Battle Playground Simulator Mod APK: A Fun and Creative Way to Experience Epic Battles</h1>
3
- <p>Do you love playing war games and simulating epic battles? Do you want to have full control over the outcome of your fights? Do you want to have unlimited money and resources to create your own scenarios? If you answered yes to any of these questions, then you should try Battle Playground Simulator Mod APK.</p>
4
- <h2>What is Battle Playground Simulator?</h2>
5
- <h3>A 3D battle simulator game for Android devices</h3>
6
- <p>Battle Playground Simulator is a game that lets you experience realistic and thrilling battles in 3D. You can choose from different modes, such as campaign, sandbox, or custom. In each mode, you can select from various weapons, units, and environments. You can also adjust the difficulty level and the number of enemies and allies.</p>
7
- <h2>battle playground simulator mod apk</h2><br /><p><b><b>Download File</b> &bull;&bull;&bull; <a href="https://jinyurl.com/2uNMRY">https://jinyurl.com/2uNMRY</a></b></p><br /><br />
8
- <h3>A sandbox mode where you can create your own scenarios</h3>
9
- <p>One of the most fun features of Battle Playground Simulator is the sandbox mode. In this mode, you can create your own scenarios and test them out. You can place any units and weapons you want on the map, and watch them fight each other. You can also change the weather, time, gravity, and other factors. You can even join the battle yourself and control one of the units.</p>
10
- <h3>A modded version that gives you unlimited money and resources</h3>
11
- <p>Battle Playground Simulator Mod APK is a modified version of the original game that gives you unlimited money and resources. This means that you can buy any weapons and units you want without worrying about the cost. You can also unlock all the maps and modes that are otherwise locked in the original game. With this modded version, you can enjoy the game without any limitations.</p>
12
- <h2>Why should you download Battle Playground Simulator Mod APK?</h2>
13
- <h3>To enjoy the realistic graphics and physics of the game</h3>
14
- <p>Battle Playground Simulator has amazing graphics and physics that make the game more immersive and realistic. You can see the details of each weapon and unit, as well as the effects of each shot and explosion. You can also see how the units react to different situations, such as falling, flying, or dying. The game also has realistic sounds and music that add to the atmosphere.</p>
15
- <h3>To experiment with different weapons, units, and environments</h3>
16
- <p>Battle Playground Simulator has a wide variety of weapons, units, and environments that you can choose from. You can use guns, grenades, rockets, tanks, helicopters, planes, robots, zombies, dinosaurs, and more. You can also mix and match different types of units and weapons to create interesting combinations. You can also explore different maps, such as city, desert, forest, island, moon, and more.</p>
17
- <h3>To unleash your creativity and imagination</h3>
18
- <p>Battle Playground Simulator is a game that lets you unleash your creativity and imagination. You can create your own scenarios and see how they play out. You can also modify existing scenarios and change their outcomes. You can experiment with different settings and factors that affect the battles. You can also share your creations with other players online.</p>
19
- <h2>How to download and install Battle Playground Simulator Mod APK?</h2>
20
- <h3>The steps to download the APK file from a trusted source</h3>
21
- <p>To download Battle Playground Simulator Mod APK, you need to find a trusted source that offers the latest version of the file <h3>The steps to download the APK file from a trusted source</h3>
22
- <p>To download Battle Playground Simulator Mod APK, you need to find a trusted source that offers the latest version of the file. You can use a web tool like APKCombo or APKMirror to generate a download link by pasting the Google Play Store URL of the game. Alternatively, you can use an app like App APK Extractor & Analyzer to extract the APK file from the game you already installed from the Play Store. However, this method may not give you the modded version of the game.</p>
23
- <h3>The steps to enable unknown sources on your device settings</h3>
24
- <p>Before you can install the APK file, you need to enable unknown sources on your device settings. This will allow you to install apps from sources other than the Play Store. To do this, follow these steps:</p>
25
- <p>battle playground simulator 3D apk<br />
26
- battle playground simulator android download<br />
27
- battle playground simulator mod apk unlimited money<br />
28
- battle playground simulator ragdoll physics game<br />
29
- battle playground simulator epic battles apk<br />
30
- battle playground simulator free download for android<br />
31
- battle playground simulator mod apk latest version<br />
32
- battle playground simulator wobbly warriors game<br />
33
- battle playground simulator offline apk<br />
34
- battle playground simulator mod apk no ads<br />
35
- battle playground simulator realistic battles apk<br />
36
- battle playground simulator apk full version<br />
37
- battle playground simulator mod apk unlocked everything<br />
38
- battle playground simulator fun simulation game<br />
39
- battle playground simulator custom battles apk<br />
40
- battle playground simulator apk pure download<br />
41
- battle playground simulator mod apk all weapons<br />
42
- battle playground simulator sandbox mode game<br />
43
- battle playground simulator historical battles apk<br />
44
- battle playground simulator apk mirror download<br />
45
- battle playground simulator mod apk god mode<br />
46
- battle playground simulator physics based game<br />
47
- battle playground simulator fantasy battles apk<br />
48
- battle playground simulator apk obb download<br />
49
- battle playground simulator mod apk one hit kill<br />
50
- battle playground simulator ragdoll sandbox game<br />
51
- battle playground simulator medieval battles apk<br />
52
- battle playground simulator apkpure download<br />
53
- battle playground simulator mod apk unlimited health<br />
54
- battle playground simulator hilarious battles game<br />
55
- battle playground simulator futuristic battles apk<br />
56
- battle playground simulator apkmody download<br />
57
- battle playground simulator mod apk no root<br />
58
- battle playground simulator strategy simulation game<br />
59
- battle playground simulator zombie battles apk<br />
60
- battle playground simulator apknite download<br />
61
- battle playground simulator mod apk revdl<br />
62
- battle playground simulator addictive gameplay game<br />
63
- battle playground simulator pirate battles apk<br />
64
- battle playground simulator apkmirror download</p>
65
- <ul>
66
- <li>Go to Settings > Security > Device Administration.</li>
67
- <li>Toggle on the option for Unknown Sources.</li>
68
- <li>Tap OK to confirm.</li>
69
- </ul>
70
- <p>Note: The exact steps may vary depending on your device model and Android version. You can also check this guide for more details.</p>
71
- <h3>The steps to install the APK file and launch the game</h3>
72
- <p>Once you have downloaded the APK file and enabled unknown sources, you can install the APK file and launch the game. To do this, follow these steps:</p>
73
- <ul>
74
- <li>Locate the APK file in your device's storage using a file manager app.</li>
75
- <li>Tap on the APK file and follow the on-screen instructions to install it.</li>
76
- <li>Wait for the installation to complete.</li>
77
- <li>Tap on the game icon on your home screen or app drawer to launch it.</li>
78
- </ul>
79
- <p>Congratulations! You have successfully installed Battle Playground Simulator Mod APK on your device. Enjoy creating and playing your own epic battles!</p>
80
- <h2>Conclusion</h2>
81
- <p>Battle Playground Simulator is a fun and creative way to experience epic battles in 3D. You can choose from different modes, weapons, units, and environments, and create your own scenarios. You can also download Battle Playground Simulator Mod APK to get unlimited money and resources, and unlock all the features of the game. To download and install Battle Playground Simulator Mod APK, you need to follow some simple steps that we have explained in this article. We hope you found this article helpful and informative. If you have any questions or feedback, please let us know in the comments below. And if you liked this article, please share it with your friends who might be interested in this game. Thank you for reading!</p>
82
- <h2>Frequently Asked Questions</h2>
83
- <h3>What are the benefits of downloading Battle Playground Simulator Mod APK?</h3>
84
- <p>Battle Playground Simulator Mod APK gives you unlimited money and resources, which means you can buy any weapons and units you want without worrying about the cost. You can also unlock all the maps and modes that are otherwise locked in the original game. With this modded version, you can enjoy the game without any limitations.</p>
85
- <h3>Is Battle Playground Simulator Mod APK safe to download and install?</h3>
86
- <p>Battle Playground Simulator Mod APK is safe to download and install as long as you get it from a trusted source that verifies the validity and security of the APK file. You should also scan the APK file with an antivirus app before installing it on your device. However, you should be aware that installing apps from unknown sources may pose some risks to your device and data, so proceed at your own discretion.</p>
87
- <h3>How can I update Battle Playground Simulator Mod APK?</h3>
88
- <p>Battle Playground Simulator Mod APK may not update automatically when a new version of the game is released. To update it, you need to download and install the latest version of the modded APK file from a trusted source. You may also need to uninstall the previous version of the game before installing the new one.</p>
89
- <h3>Can I play Battle Playground Simulator Mod APK online with other players?</h3>
90
- <p>Battle Playground Simulator Mod APK does not support online multiplayer mode at the moment. You can only play it offline with AI-controlled units. However, you can share your creations with other players online by uploading them to social media platforms or websites.</p>
91
- <h3>Can I play Battle Playground Simulator Mod APK on PC?</h3>
92
- <p>Battle Playground Simulator Mod APK is designed for Android devices only. However, you can play it on PC by using an Android emulator software that allows you to run Android apps and games on your computer. Some popular Android emulators are BlueStacks, NoxPlayer, and LDPlayer.</p> 197e85843d<br />
93
- <br />
94
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/2023Liu2023/bingo/src/components/ui/dropdown-menu.tsx DELETED
@@ -1,128 +0,0 @@
1
- 'use client'
2
-
3
- import * as React from 'react'
4
- import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'
5
-
6
- import { cn } from '@/lib/utils'
7
-
8
- const DropdownMenu = DropdownMenuPrimitive.Root
9
-
10
- const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
11
-
12
- const DropdownMenuGroup = DropdownMenuPrimitive.Group
13
-
14
- const DropdownMenuPortal = DropdownMenuPrimitive.Portal
15
-
16
- const DropdownMenuSub = DropdownMenuPrimitive.Sub
17
-
18
- const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
19
-
20
- const DropdownMenuSubContent = React.forwardRef<
21
- React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
22
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
23
- >(({ className, ...props }, ref) => (
24
- <DropdownMenuPrimitive.SubContent
25
- ref={ref}
26
- className={cn(
27
- 'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1',
28
- className
29
- )}
30
- {...props}
31
- />
32
- ))
33
- DropdownMenuSubContent.displayName =
34
- DropdownMenuPrimitive.SubContent.displayName
35
-
36
- const DropdownMenuContent = React.forwardRef<
37
- React.ElementRef<typeof DropdownMenuPrimitive.Content>,
38
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
39
- >(({ className, sideOffset = 4, ...props }, ref) => (
40
- <DropdownMenuPrimitive.Portal>
41
- <DropdownMenuPrimitive.Content
42
- ref={ref}
43
- sideOffset={sideOffset}
44
- className={cn(
45
- 'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow animate-in data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
46
- className
47
- )}
48
- {...props}
49
- />
50
- </DropdownMenuPrimitive.Portal>
51
- ))
52
- DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
53
-
54
- const DropdownMenuItem = React.forwardRef<
55
- React.ElementRef<typeof DropdownMenuPrimitive.Item>,
56
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
57
- inset?: boolean
58
- }
59
- >(({ className, inset, ...props }, ref) => (
60
- <DropdownMenuPrimitive.Item
61
- ref={ref}
62
- className={cn(
63
- 'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
64
- inset && 'pl-8',
65
- className
66
- )}
67
- {...props}
68
- />
69
- ))
70
- DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
71
-
72
- const DropdownMenuLabel = React.forwardRef<
73
- React.ElementRef<typeof DropdownMenuPrimitive.Label>,
74
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
75
- inset?: boolean
76
- }
77
- >(({ className, inset, ...props }, ref) => (
78
- <DropdownMenuPrimitive.Label
79
- ref={ref}
80
- className={cn(
81
- 'px-2 py-1.5 text-sm font-semibold',
82
- inset && 'pl-8',
83
- className
84
- )}
85
- {...props}
86
- />
87
- ))
88
- DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
89
-
90
- const DropdownMenuSeparator = React.forwardRef<
91
- React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
92
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
93
- >(({ className, ...props }, ref) => (
94
- <DropdownMenuPrimitive.Separator
95
- ref={ref}
96
- className={cn('-mx-1 my-1 h-px bg-muted', className)}
97
- {...props}
98
- />
99
- ))
100
- DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
101
-
102
- const DropdownMenuShortcut = ({
103
- className,
104
- ...props
105
- }: React.HTMLAttributes<HTMLSpanElement>) => {
106
- return (
107
- <span
108
- className={cn('ml-auto text-xs tracking-widest opacity-60', className)}
109
- {...props}
110
- />
111
- )
112
- }
113
- DropdownMenuShortcut.displayName = 'DropdownMenuShortcut'
114
-
115
- export {
116
- DropdownMenu,
117
- DropdownMenuTrigger,
118
- DropdownMenuContent,
119
- DropdownMenuItem,
120
- DropdownMenuLabel,
121
- DropdownMenuSeparator,
122
- DropdownMenuShortcut,
123
- DropdownMenuGroup,
124
- DropdownMenuPortal,
125
- DropdownMenuSub,
126
- DropdownMenuSubContent,
127
- DropdownMenuRadioGroup
128
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/generate_human_motion/README.md DELETED
@@ -1,14 +0,0 @@
1
- ---
2
- title: Generate Human Motion
3
- emoji: 🏃
4
- colorFrom: green
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 3.16.2
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- duplicated_from: vumichien/generate_human_motion
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/generate_human_motion/VQ-Trans/models/rotation2xyz.py DELETED
@@ -1,92 +0,0 @@
1
- # This code is based on https://github.com/Mathux/ACTOR.git
2
- import torch
3
- import utils.rotation_conversions as geometry
4
-
5
-
6
- from models.smpl import SMPL, JOINTSTYPE_ROOT
7
- # from .get_model import JOINTSTYPES
8
- JOINTSTYPES = ["a2m", "a2mpl", "smpl", "vibe", "vertices"]
9
-
10
-
11
- class Rotation2xyz:
12
- def __init__(self, device, dataset='amass'):
13
- self.device = device
14
- self.dataset = dataset
15
- self.smpl_model = SMPL().eval().to(device)
16
-
17
- def __call__(self, x, mask, pose_rep, translation, glob,
18
- jointstype, vertstrans, betas=None, beta=0,
19
- glob_rot=None, get_rotations_back=False, **kwargs):
20
- if pose_rep == "xyz":
21
- return x
22
-
23
- if mask is None:
24
- mask = torch.ones((x.shape[0], x.shape[-1]), dtype=bool, device=x.device)
25
-
26
- if not glob and glob_rot is None:
27
- raise TypeError("You must specify global rotation if glob is False")
28
-
29
- if jointstype not in JOINTSTYPES:
30
- raise NotImplementedError("This jointstype is not implemented.")
31
-
32
- if translation:
33
- x_translations = x[:, -1, :3]
34
- x_rotations = x[:, :-1]
35
- else:
36
- x_rotations = x
37
-
38
- x_rotations = x_rotations.permute(0, 3, 1, 2)
39
- nsamples, time, njoints, feats = x_rotations.shape
40
-
41
- # Compute rotations (convert only masked sequences output)
42
- if pose_rep == "rotvec":
43
- rotations = geometry.axis_angle_to_matrix(x_rotations[mask])
44
- elif pose_rep == "rotmat":
45
- rotations = x_rotations[mask].view(-1, njoints, 3, 3)
46
- elif pose_rep == "rotquat":
47
- rotations = geometry.quaternion_to_matrix(x_rotations[mask])
48
- elif pose_rep == "rot6d":
49
- rotations = geometry.rotation_6d_to_matrix(x_rotations[mask])
50
- else:
51
- raise NotImplementedError("No geometry for this one.")
52
-
53
- if not glob:
54
- global_orient = torch.tensor(glob_rot, device=x.device)
55
- global_orient = geometry.axis_angle_to_matrix(global_orient).view(1, 1, 3, 3)
56
- global_orient = global_orient.repeat(len(rotations), 1, 1, 1)
57
- else:
58
- global_orient = rotations[:, 0]
59
- rotations = rotations[:, 1:]
60
-
61
- if betas is None:
62
- betas = torch.zeros([rotations.shape[0], self.smpl_model.num_betas],
63
- dtype=rotations.dtype, device=rotations.device)
64
- betas[:, 1] = beta
65
- # import ipdb; ipdb.set_trace()
66
- out = self.smpl_model(body_pose=rotations, global_orient=global_orient, betas=betas)
67
-
68
- # get the desirable joints
69
- joints = out[jointstype]
70
-
71
- x_xyz = torch.empty(nsamples, time, joints.shape[1], 3, device=x.device, dtype=x.dtype)
72
- x_xyz[~mask] = 0
73
- x_xyz[mask] = joints
74
-
75
- x_xyz = x_xyz.permute(0, 2, 3, 1).contiguous()
76
-
77
- # the first translation root at the origin on the prediction
78
- if jointstype != "vertices":
79
- rootindex = JOINTSTYPE_ROOT[jointstype]
80
- x_xyz = x_xyz - x_xyz[:, [rootindex], :, :]
81
-
82
- if translation and vertstrans:
83
- # the first translation root at the origin
84
- x_translations = x_translations - x_translations[:, :, [0]]
85
-
86
- # add the translation to all the joints
87
- x_xyz = x_xyz + x_translations[:, None, :, :]
88
-
89
- if get_rotations_back:
90
- return x_xyz, rotations, global_orient
91
- else:
92
- return x_xyz
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Abhay834/SY_Bot/app.py DELETED
@@ -1,203 +0,0 @@
1
- import os
2
- import gradio as gr
3
- from langchain.chat_models import ChatOpenAI
4
- from langchain import LLMChain, PromptTemplate
5
- from langchain.memory import ConversationBufferMemory
6
-
7
- OPENAI_API_KEY=os.getenv('OPENAI_API_KEY')
8
-
9
- template = """meet SYIT it can have all data about a SY student and also assist like digital assistance
10
- data of the student is following
11
- 'Roll no 1 Name ABHANG ANIKET RAJENDRA having prn no UIT22M1001'
12
- 'Roll no 2 Name AHER PRASHANT RAYCHAND having prn no UIT22M1002'
13
- 'Roll no 3 Name AHIRE HARSHADA BANICHANDhaving prn no UIT22M1003'
14
- 'Roll no 4 Name AMALE ADITYA MAHADEO having prn no UIT22M1004'
15
- 'Roll no 5 Name AMALE ADITYA MAHADEO having prn no UIT22M1005'
16
- 'Roll no 6 Name ARGADE PANKAJ SOMNATH having prn no UIT22M1006'
17
- 'Roll no 7 Name ARGADE PANKAJ SOMNATH having prn no UIT22M1007'
18
- 'Roll no 8 Name AVHAD PRAVIN SOMNATH having prn no UIT22M1008'
19
- 'Roll no 9 Name BADADHE ABHISHEK VIJAY having prn no UIT22M1009'"
20
- 'Roll no 10 Name BADAKH ANIKET RAMESH having prn no UIT22M1010'
21
- 'Roll no 11 Name BADGUJAR MANISH DIPAK having prn no UIT22M1011'
22
- 'Roll no 12 Name BHAGWAT SHREYASH SHRIDHAhaving prn no UIT22M1012'
23
- R.NO
24
- ROLL
25
- NO
26
- ELIGI.NO PRN CANDIDATE NAME M/F GR.NO
27
- 1
28
- 1 12022186614UIT22M1001ABHANG ANIKET RAJENDRA M 221020589
29
- 2
30
- 2 12022186732UIT22M1002AHER PRASHANT RAYCHAND (T M 221020590
31
- 3
32
- 3 12022186610UIT22M1003AHER YASHRAJ BALASAHEB M 221020591
33
- 4
34
- 4 12022186697UIT22F1004 AHIRE HARSHADA BANICHAND F 221020592
35
- 5
36
- 5 12022186622UIT22M1005AMALE ADITYA MAHADEO M 221020593
37
- 6
38
- 6 12022186644UIT22M1006ARGADE PANKAJ SOMNATH M 221020594
39
- 7
40
- 7 12022186703UIT22F1007 ATHARE SNEHAL GUNWANT F 221020595
41
- 8
42
- 8 12022186637UIT22M1008AVHAD PRAVIN SOMNATH M 221020596
43
- 9
44
- 9 12022186660UIT22M1009BADADHE ABHISHEK VIJAY M 221020597
45
- 10
46
- 10 12022186649UIT22M1010BADAKH ANIKET RAMESH M 221020598
47
- 11
48
- 11 12022186608UIT22M1011BADGUJAR MANISH DIPAK M 221020599
49
- 12
50
- 12 12022186655UIT22M1014BHAGWAT SHREYASH SHRIDHA M 221020600
51
- 13
52
- 13 12022186733UIT22M1015BHAVAR ATHARVA SANJAY (EW M 221020601
53
- 14
54
- 14 12022186669UIT22M1016BHAVARI SANKET DILIP M 221020602
55
- 15
56
- 15 12022186623UIT22M1017BHAVSAR SHANTANU KISHOR M 221020603 #REF!
57
- 16
58
- 16 12022186631UIT22M1018BHAWAR UDAYANRAJE VIJAYKU M 221020604
59
- 17
60
- 17 12022186714UIT22M1019BHOJANE SAGAR RAGHUNATH M 221020605
61
- 18
62
- 18 12022186605UIT22F1020 BHOR NIKITA BHASKAR F 221020606
63
- 19
64
- 19 12022186672UIT22M1021BHUJADE SARVESHWAR
65
- SURESH
66
- M 221020607
67
- 20
68
- 20 12022186704UIT22F1022 BHUSARI SHATAKSHI SATISH F 221020608
69
- 21
70
- 21 12022186643UIT22M1023BORDE ABHAY SANTOSH M 221020609
71
- 22
72
- 22 12022186709UIT22M1024BORKAR SAHIL MANISH M 221020610
73
- 23
74
- 23 12022186650UIT22M1013BAGWAN MAUZZAM SAMEER M 221020611
75
- 24
76
- 24 12022186639UIT22M1025BORSE VEDANT SACHIN M 221020612
77
- 25
78
- 25 12022186645UIT22M1026BULKUNDE PRATIK BHAUSAHEB M 221020613
79
- 26
80
- 26 12022186647UIT22M1027CHAUDHARI MAHESH SANJAY M 221020614
81
- 27
82
- 27 12022186675UIT22F1028 CHAVAN AARYA AVINASH F 221020615
83
- 28
84
- 28 12022186620UIT22M1029CHAVAN NIKHIL NILESH M 221020616
85
- 29
86
- 29 12022186729UIT22M1030DAHE MAHESH DAULAT (TFW M 221020617
87
- 30
88
- 30 12022186633UIT22F1031 DAINE KALYANI YADAV F 221020618
89
- 31
90
- 31 12022186642UIT22M1012BADHE OM SAMBHAJI M 221020619
91
- 32
92
- 32 12022186688UIT22F1033 DESHMUKH SANSKRUTI RAVI F 221020621
93
- 33
94
- 33 12022186701UIT22M1034DESHPANDE ATHARVA
95
- RAJENDRA
96
- M 221020622
97
- 34
98
- 34 12022186604UIT22F1035 DEVARE VAIBHAVI RAJENDRA F 221020623
99
- 35
100
- 35 12022186691UIT22F1036 DHAKNE DISHA BIPIN F 221020624
101
- 36
102
- 36 12022186632UIT22M1037DHAMDHERE TANMAY DATTATRA M 221020625
103
- 37
104
- 37 12022186689UIT22M1038DHOKCHAULE ADITYA
105
- SUDHAKAR
106
- M 221020626
107
- 38
108
- 38 12022186619UIT22M1039DOPHE VINIT BALASAHEB M 221020627
109
- 39
110
- 39 12022186626UIT22M1040GADHE SHIVAM RAMESHWAR M 221020628
111
- 40
112
- 40 12022186719UIT22F1041 GAGARE NIKITA BALASAHEB F 221020629
113
- 41
114
- 41 12022186710UIT22M1042GAGARE PRANAV KISHOR M 221020630
115
- 42
116
- 42 12022186724UIT22M1043GAIKWAD PRASAD SUNIL (EW M 221020631
117
- 43
118
- 43 12022186706UIT22M1044GAIKWAD SACHIN PANDURANG M 221020632
119
- 44
120
- 44 12022186681UIT22M1045GANGURDE SHUBHAM SANTOS M 221020633
121
- 45
122
- 45 12022186613UIT22F1056 JADHAV MAYURI RUSHIRAJ F 221020634
123
- 46
124
- 46 12022186731UIT22M1046GAVHANE ADESH BAJIRAO (EW M 221020635
125
- 47
126
- 47 12022186708UIT22F1047 GAWALI TEJASHREE
127
- TULSHIDAS
128
- F 221020636
129
- 48
130
- 48 12022186624UIT22M1048GHUSALE GAURAV SHAMRAO M 221020637
131
- 49
132
- 49 12022186665UIT22M1049GORDE MUKUND GOPINATH M 221020638
133
- 50
134
- 50 12022186670UIT22M1050GULDAGAD RUSHIKESH
135
- SANJAY
136
- M 221020639
137
- 51
138
- 51 12022186648UIT22M1053HON RITESH JAYANAND M 221020642
139
- 52
140
- 52 12022186616UIT22M1054HON SHANTANU M 221020643
141
- 53
142
- 53 12022186609UIT22F1134 VADANE AMRUTA SAKHARAM F 221020644
143
- 54
144
- 54 12022186654UIT22F1055 IMALE BHAKTI PANDIT F 221020645
145
- 55
146
- 55 12022186668UIT22M1057JADHAV UTKARSH SUNIL M 221020646
147
- 56
148
- 56 12022186734UIT22M1058JAGTAP ADITYA RAMBHAU (EW M 221020647
149
- 57
150
- 57 12022186625UIT22F1059 JAGTAP VAISHNAVI VIJAY F 221020648
151
- 58
152
- 58 12022186611UIT22M1060JARE KAUSHAL SANDIP M 221020649
153
- 59
154
- 59 12022186698UIT22F1061 KADAM DNYANESHWARI BALASA F 221020650
155
- 60
156
- 60 12022186735UIT22M1062KADAM RUTVIK RAVINDRA (EW M 221020651
157
- 61
158
- 61 12022186612UIT22F1063 KADAM SANTOSHI PANDIT F 221020652
159
- 62
160
- 62 12022186696UIT22M1064KAKADE SANJYOT SANDEEP M 221020653
161
- 63
162
- 63 12022186671UIT22F1065 KALE PRAJAKTA GORAKSHANAT F 221020654
163
- 64
164
- 64 12022186657UIT22M1066KANDALKAR ADITYA PRAKASH M 221020655
165
- 65
166
- 65 12022186682UIT22M1067KANGUDE SUYASH
167
- HAUSHABAPU
168
- M 221020656
169
- 66
170
- 66 1202120608UIT21M1038LANDE YOGESH CHANDRAKANT M 211019642
171
- 67
172
- 67 1202120608UIT21M1061SHELKE MAYANK VIJAYKUMAR M 211019665
173
- 68 68 12022186969UEC22F1039MATE SONIYA SATISH F 221020420 200
174
- 69
175
- 69 2022186405UEE22F100BHINGARE SAKSHI DATTATRAY F 2
176
-
177
- {chat_history}
178
-
179
- User: {user_message}
180
- Chatbot:"""
181
-
182
- prompt = PromptTemplate(
183
- input_variables=["chat_history", "user_message"], template=template
184
- )
185
-
186
- memory = ConversationBufferMemory(memory_key="chat_history")
187
-
188
- llm_chain = LLMChain(
189
- llm=ChatOpenAI(temperature='0.5', model_name="gpt-3.5-turbo"),
190
- prompt=prompt,
191
- verbose=True,
192
- memory=memory,
193
- )
194
-
195
- def get_text_response(user_message,history):
196
- response = llm_chain.predict(user_message = user_message)
197
- return response
198
-
199
- demo = gr.ChatInterface(get_text_response)
200
-
201
- if __name__ == "__main__":
202
- demo.launch() #To create a public link, set `share=True` in `launch()`. To enable errors and logs, set `debug=True` in `launch()`.
203
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Adapter/T2I-Adapter/docs/FAQ.md DELETED
@@ -1,5 +0,0 @@
1
- # FAQ
2
-
3
- - **Q: The openpose adapter (t2iadapter_openpose_sd14v1) outputs gray-scale images.**
4
-
5
- **A:** You can add `colorful` in the prompt to avoid this problem.
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/basesizer/ScaleMethods.js DELETED
@@ -1,121 +0,0 @@
1
- import PopUp from '../../../plugins/popup.js';
2
- import ScaleDownDestroy from '../../../plugins/scale-down-destroy.js';
3
- import Yoyo from '../../../plugins/behaviors/scale/Yoyo.js';
4
- import { WaitComplete } from '../utils/WaitEvent.js'
5
- import GetParentSizerMethods from './GetParentSizerMethods.js';
6
-
7
- const IsPlainObject = Phaser.Utils.Objects.IsPlainObject;
8
-
9
- var OnInitScale = function (gameObject, scale) {
10
- // Route 'complete' of scale to gameObject
11
- scale.completeEventName = undefined;
12
- scale.on('complete', function () {
13
- if (scale.completeEventName) {
14
- gameObject.emit(scale.completeEventName, gameObject);
15
- scale.completeEventName = undefined;
16
- }
17
- })
18
-
19
- // Update local state
20
- scale.on('update', function () {
21
- var parent = GetParentSizerMethods.getParentSizer(gameObject)
22
- if (parent) {
23
- parent.resetChildPositionState(gameObject);
24
- }
25
- })
26
- }
27
-
28
- export default {
29
- popUp(duration, orientation, ease) {
30
- if (IsPlainObject(duration)) {
31
- var config = duration;
32
- duration = config.duration;
33
- orientation = config.orientation;
34
- ease = config.ease;
35
- }
36
-
37
- var isInit = (this._scaleBehavior === undefined);
38
-
39
- this._scaleBehavior = PopUp(this, duration, orientation, ease, this._scaleBehavior);
40
-
41
- if (isInit) {
42
- OnInitScale(this, this._scaleBehavior);
43
- }
44
-
45
- this._scaleBehavior.completeEventName = 'popup.complete';
46
-
47
- return this;
48
- },
49
-
50
- popUpPromise(duration, orientation, ease) {
51
- this.popUp(duration, orientation, ease);
52
- return WaitComplete(this._scaleBehavior);
53
- },
54
-
55
- scaleDownDestroy(duration, orientation, ease, destroyMode) {
56
- if (IsPlainObject(duration)) {
57
- var config = duration;
58
- duration = config.duration;
59
- orientation = config.orientation;
60
- ease = config.ease;
61
- destroyMode = config.destroy;
62
- }
63
-
64
- var isInit = (this._scaleBehavior === undefined);
65
-
66
- this._scaleBehavior = ScaleDownDestroy(this, duration, orientation, ease, destroyMode, this._scaleBehavior);
67
-
68
- if (isInit) {
69
- OnInitScale(this, this._scaleBehavior);
70
- }
71
-
72
- this._scaleBehavior.completeEventName = 'scaledown.complete';
73
-
74
- return this;
75
- },
76
-
77
- scaleDownDestroyPromise(duration, orientation, ease, destroyMode) {
78
- this.scaleDownDestroy(duration, orientation, ease, destroyMode);
79
- return WaitComplete(this._scaleBehavior);
80
- },
81
-
82
- scaleDown(duration, orientation, ease) {
83
- this.scaleDownDestroy(duration, orientation, ease, false);
84
- return this;
85
- },
86
-
87
- scaleDownPromise(duration, orientation, ease) {
88
- this.scaleDown(duration, orientation, ease);
89
- return WaitComplete(this._scaleBehavior);
90
- },
91
-
92
- scaleYoyo(duration, peakValue, repeat, orientation, ease) {
93
- if (IsPlainObject(duration)) {
94
- var config = duration;
95
- duration = config.duration;
96
- peakValue = config.peakValue;
97
- repeat = config.repeat;
98
- orientation = config.orientation;
99
- ease = config.ease;
100
- }
101
-
102
- var isInit = (this._scaleBehavior === undefined);
103
-
104
- this._scaleBehavior = Yoyo(this, duration, peakValue, repeat, orientation, ease, this._scaleBehavior);
105
-
106
- if (isInit) {
107
- OnInitScale(this, this._scaleBehavior);
108
- }
109
-
110
- this._scaleBehavior.completeEventName = 'scaleyoyo.complete';
111
-
112
- return this;
113
- },
114
-
115
- scaleYoyoPromise(duration, peakValue, repeat, orientation, ease) {
116
- this.scaleYoyo(duration, peakValue, repeat, orientation, ease);
117
- return WaitComplete(this._scaleBehavior);
118
- },
119
-
120
-
121
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Aki004/herta-so-vits/onnx_export.py DELETED
@@ -1,56 +0,0 @@
1
- import torch
2
- from onnxexport.model_onnx import SynthesizerTrn
3
- import utils
4
-
5
- def main(NetExport):
6
- path = "SoVits4.0"
7
- if NetExport:
8
- device = torch.device("cpu")
9
- hps = utils.get_hparams_from_file(f"checkpoints/{path}/config.json")
10
- SVCVITS = SynthesizerTrn(
11
- hps.data.filter_length // 2 + 1,
12
- hps.train.segment_size // hps.data.hop_length,
13
- **hps.model)
14
- _ = utils.load_checkpoint(f"checkpoints/{path}/model.pth", SVCVITS, None)
15
- _ = SVCVITS.eval().to(device)
16
- for i in SVCVITS.parameters():
17
- i.requires_grad = False
18
-
19
- n_frame = 10
20
- hidden_channels = 256 #(Hubert's shape[2])
21
-
22
- test_hidden_unit = torch.rand(1, n_frame, hidden_channels)
23
- test_pitch = torch.rand(1, n_frame)
24
- test_mel2ph = torch.arange(0, n_frame, dtype=torch.int64)[None] # torch.LongTensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).unsqueeze(0)
25
- test_uv = torch.ones(1, n_frame, dtype=torch.float32)
26
- test_noise = torch.randn(1, 192, n_frame)
27
- test_sid = torch.LongTensor([0])
28
- input_names = ["c", "f0", "mel2ph", "uv", "noise", "sid"]
29
- output_names = ["audio", ]
30
-
31
- torch.onnx.export(SVCVITS,
32
- (
33
- test_hidden_unit.to(device),
34
- test_pitch.to(device),
35
- test_mel2ph.to(device),
36
- test_uv.to(device),
37
- test_noise.to(device),
38
- test_sid.to(device)
39
- ),
40
- f"checkpoints/{path}/model.onnx",
41
- dynamic_axes={
42
- "c": [0, 1],
43
- "f0": [1],
44
- "mel2ph": [1],
45
- "uv": [1],
46
- "noise": [2],
47
- },
48
- do_constant_folding=False,
49
- opset_version=16,
50
- verbose=False,
51
- input_names=input_names,
52
- output_names=output_names)
53
-
54
-
55
- if __name__ == '__main__':
56
- main(True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Akmyradov/TurkmenTTSweSTT/uroman/lib/JSON/backportPP.pm DELETED
@@ -1,2806 +0,0 @@
1
- package # This is JSON::backportPP
2
- JSON::PP;
3
-
4
- # JSON-2.0
5
-
6
- use 5.005;
7
- use strict;
8
- use base qw(Exporter);
9
- use overload ();
10
-
11
- use Carp ();
12
- use B ();
13
- #use Devel::Peek;
14
-
15
- use vars qw($VERSION);
16
- $VERSION = '2.27204';
17
-
18
- @JSON::PP::EXPORT = qw(encode_json decode_json from_json to_json);
19
-
20
- # instead of hash-access, i tried index-access for speed.
21
- # but this method is not faster than what i expected. so it will be changed.
22
-
23
- use constant P_ASCII => 0;
24
- use constant P_LATIN1 => 1;
25
- use constant P_UTF8 => 2;
26
- use constant P_INDENT => 3;
27
- use constant P_CANONICAL => 4;
28
- use constant P_SPACE_BEFORE => 5;
29
- use constant P_SPACE_AFTER => 6;
30
- use constant P_ALLOW_NONREF => 7;
31
- use constant P_SHRINK => 8;
32
- use constant P_ALLOW_BLESSED => 9;
33
- use constant P_CONVERT_BLESSED => 10;
34
- use constant P_RELAXED => 11;
35
-
36
- use constant P_LOOSE => 12;
37
- use constant P_ALLOW_BIGNUM => 13;
38
- use constant P_ALLOW_BAREKEY => 14;
39
- use constant P_ALLOW_SINGLEQUOTE => 15;
40
- use constant P_ESCAPE_SLASH => 16;
41
- use constant P_AS_NONBLESSED => 17;
42
-
43
- use constant P_ALLOW_UNKNOWN => 18;
44
-
45
- use constant OLD_PERL => $] < 5.008 ? 1 : 0;
46
-
47
- BEGIN {
48
- my @xs_compati_bit_properties = qw(
49
- latin1 ascii utf8 indent canonical space_before space_after allow_nonref shrink
50
- allow_blessed convert_blessed relaxed allow_unknown
51
- );
52
- my @pp_bit_properties = qw(
53
- allow_singlequote allow_bignum loose
54
- allow_barekey escape_slash as_nonblessed
55
- );
56
-
57
- # Perl version check, Unicode handling is enable?
58
- # Helper module sets @JSON::PP::_properties.
59
- if ($] < 5.008 ) {
60
- my $helper = $] >= 5.006 ? 'JSON::backportPP::Compat5006' : 'JSON::backportPP::Compat5005';
61
- eval qq| require $helper |;
62
- if ($@) { Carp::croak $@; }
63
- }
64
-
65
- for my $name (@xs_compati_bit_properties, @pp_bit_properties) {
66
- my $flag_name = 'P_' . uc($name);
67
-
68
- eval qq/
69
- sub $name {
70
- my \$enable = defined \$_[1] ? \$_[1] : 1;
71
-
72
- if (\$enable) {
73
- \$_[0]->{PROPS}->[$flag_name] = 1;
74
- }
75
- else {
76
- \$_[0]->{PROPS}->[$flag_name] = 0;
77
- }
78
-
79
- \$_[0];
80
- }
81
-
82
- sub get_$name {
83
- \$_[0]->{PROPS}->[$flag_name] ? 1 : '';
84
- }
85
- /;
86
- }
87
-
88
- }
89
-
90
-
91
-
92
- # Functions
93
-
94
- my %encode_allow_method
95
- = map {($_ => 1)} qw/utf8 pretty allow_nonref latin1 self_encode escape_slash
96
- allow_blessed convert_blessed indent indent_length allow_bignum
97
- as_nonblessed
98
- /;
99
- my %decode_allow_method
100
- = map {($_ => 1)} qw/utf8 allow_nonref loose allow_singlequote allow_bignum
101
- allow_barekey max_size relaxed/;
102
-
103
-
104
- my $JSON; # cache
105
-
106
- sub encode_json ($) { # encode
107
- ($JSON ||= __PACKAGE__->new->utf8)->encode(@_);
108
- }
109
-
110
-
111
- sub decode_json { # decode
112
- ($JSON ||= __PACKAGE__->new->utf8)->decode(@_);
113
- }
114
-
115
- # Obsoleted
116
-
117
- sub to_json($) {
118
- Carp::croak ("JSON::PP::to_json has been renamed to encode_json.");
119
- }
120
-
121
-
122
- sub from_json($) {
123
- Carp::croak ("JSON::PP::from_json has been renamed to decode_json.");
124
- }
125
-
126
-
127
- # Methods
128
-
129
- sub new {
130
- my $class = shift;
131
- my $self = {
132
- max_depth => 512,
133
- max_size => 0,
134
- indent => 0,
135
- FLAGS => 0,
136
- fallback => sub { encode_error('Invalid value. JSON can only reference.') },
137
- indent_length => 3,
138
- };
139
-
140
- bless $self, $class;
141
- }
142
-
143
-
144
- sub encode {
145
- return $_[0]->PP_encode_json($_[1]);
146
- }
147
-
148
-
149
- sub decode {
150
- return $_[0]->PP_decode_json($_[1], 0x00000000);
151
- }
152
-
153
-
154
- sub decode_prefix {
155
- return $_[0]->PP_decode_json($_[1], 0x00000001);
156
- }
157
-
158
-
159
- # accessor
160
-
161
-
162
- # pretty printing
163
-
164
- sub pretty {
165
- my ($self, $v) = @_;
166
- my $enable = defined $v ? $v : 1;
167
-
168
- if ($enable) { # indent_length(3) for JSON::XS compatibility
169
- $self->indent(1)->indent_length(3)->space_before(1)->space_after(1);
170
- }
171
- else {
172
- $self->indent(0)->space_before(0)->space_after(0);
173
- }
174
-
175
- $self;
176
- }
177
-
178
- # etc
179
-
180
- sub max_depth {
181
- my $max = defined $_[1] ? $_[1] : 0x80000000;
182
- $_[0]->{max_depth} = $max;
183
- $_[0];
184
- }
185
-
186
-
187
- sub get_max_depth { $_[0]->{max_depth}; }
188
-
189
-
190
- sub max_size {
191
- my $max = defined $_[1] ? $_[1] : 0;
192
- $_[0]->{max_size} = $max;
193
- $_[0];
194
- }
195
-
196
-
197
- sub get_max_size { $_[0]->{max_size}; }
198
-
199
-
200
- sub filter_json_object {
201
- $_[0]->{cb_object} = defined $_[1] ? $_[1] : 0;
202
- $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
203
- $_[0];
204
- }
205
-
206
- sub filter_json_single_key_object {
207
- if (@_ > 1) {
208
- $_[0]->{cb_sk_object}->{$_[1]} = $_[2];
209
- }
210
- $_[0]->{F_HOOK} = ($_[0]->{cb_object} or $_[0]->{cb_sk_object}) ? 1 : 0;
211
- $_[0];
212
- }
213
-
214
- sub indent_length {
215
- if (!defined $_[1] or $_[1] > 15 or $_[1] < 0) {
216
- Carp::carp "The acceptable range of indent_length() is 0 to 15.";
217
- }
218
- else {
219
- $_[0]->{indent_length} = $_[1];
220
- }
221
- $_[0];
222
- }
223
-
224
- sub get_indent_length {
225
- $_[0]->{indent_length};
226
- }
227
-
228
- sub sort_by {
229
- $_[0]->{sort_by} = defined $_[1] ? $_[1] : 1;
230
- $_[0];
231
- }
232
-
233
- sub allow_bigint {
234
- Carp::carp("allow_bigint() is obsoleted. use allow_bignum() insted.");
235
- }
236
-
237
- ###############################
238
-
239
- ###
240
- ### Perl => JSON
241
- ###
242
-
243
-
244
- { # Convert
245
-
246
- my $max_depth;
247
- my $indent;
248
- my $ascii;
249
- my $latin1;
250
- my $utf8;
251
- my $space_before;
252
- my $space_after;
253
- my $canonical;
254
- my $allow_blessed;
255
- my $convert_blessed;
256
-
257
- my $indent_length;
258
- my $escape_slash;
259
- my $bignum;
260
- my $as_nonblessed;
261
-
262
- my $depth;
263
- my $indent_count;
264
- my $keysort;
265
-
266
-
267
- sub PP_encode_json {
268
- my $self = shift;
269
- my $obj = shift;
270
-
271
- $indent_count = 0;
272
- $depth = 0;
273
-
274
- my $idx = $self->{PROPS};
275
-
276
- ($ascii, $latin1, $utf8, $indent, $canonical, $space_before, $space_after, $allow_blessed,
277
- $convert_blessed, $escape_slash, $bignum, $as_nonblessed)
278
- = @{$idx}[P_ASCII .. P_SPACE_AFTER, P_ALLOW_BLESSED, P_CONVERT_BLESSED,
279
- P_ESCAPE_SLASH, P_ALLOW_BIGNUM, P_AS_NONBLESSED];
280
-
281
- ($max_depth, $indent_length) = @{$self}{qw/max_depth indent_length/};
282
-
283
- $keysort = $canonical ? sub { $a cmp $b } : undef;
284
-
285
- if ($self->{sort_by}) {
286
- $keysort = ref($self->{sort_by}) eq 'CODE' ? $self->{sort_by}
287
- : $self->{sort_by} =~ /\D+/ ? $self->{sort_by}
288
- : sub { $a cmp $b };
289
- }
290
-
291
- encode_error("hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)")
292
- if(!ref $obj and !$idx->[ P_ALLOW_NONREF ]);
293
-
294
- my $str = $self->object_to_json($obj);
295
-
296
- $str .= "\n" if ( $indent ); # JSON::XS 2.26 compatible
297
-
298
- unless ($ascii or $latin1 or $utf8) {
299
- utf8::upgrade($str);
300
- }
301
-
302
- if ($idx->[ P_SHRINK ]) {
303
- utf8::downgrade($str, 1);
304
- }
305
-
306
- return $str;
307
- }
308
-
309
-
310
- sub object_to_json {
311
- my ($self, $obj) = @_;
312
- my $type = ref($obj);
313
-
314
- if($type eq 'HASH'){
315
- return $self->hash_to_json($obj);
316
- }
317
- elsif($type eq 'ARRAY'){
318
- return $self->array_to_json($obj);
319
- }
320
- elsif ($type) { # blessed object?
321
- if (blessed($obj)) {
322
-
323
- return $self->value_to_json($obj) if ( $obj->isa('JSON::PP::Boolean') );
324
-
325
- if ( $convert_blessed and $obj->can('TO_JSON') ) {
326
- my $result = $obj->TO_JSON();
327
- if ( defined $result and ref( $result ) ) {
328
- if ( refaddr( $obj ) eq refaddr( $result ) ) {
329
- encode_error( sprintf(
330
- "%s::TO_JSON method returned same object as was passed instead of a new one",
331
- ref $obj
332
- ) );
333
- }
334
- }
335
-
336
- return $self->object_to_json( $result );
337
- }
338
-
339
- return "$obj" if ( $bignum and _is_bignum($obj) );
340
- return $self->blessed_to_json($obj) if ($allow_blessed and $as_nonblessed); # will be removed.
341
-
342
- encode_error( sprintf("encountered object '%s', but neither allow_blessed "
343
- . "nor convert_blessed settings are enabled", $obj)
344
- ) unless ($allow_blessed);
345
-
346
- return 'null';
347
- }
348
- else {
349
- return $self->value_to_json($obj);
350
- }
351
- }
352
- else{
353
- return $self->value_to_json($obj);
354
- }
355
- }
356
-
357
-
358
- sub hash_to_json {
359
- my ($self, $obj) = @_;
360
- my @res;
361
-
362
- encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
363
- if (++$depth > $max_depth);
364
-
365
- my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
366
- my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : '');
367
-
368
- for my $k ( _sort( $obj ) ) {
369
- if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized
370
- push @res, string_to_json( $self, $k )
371
- . $del
372
- . ( $self->object_to_json( $obj->{$k} ) || $self->value_to_json( $obj->{$k} ) );
373
- }
374
-
375
- --$depth;
376
- $self->_down_indent() if ($indent);
377
-
378
- return '{' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . '}';
379
- }
380
-
381
-
382
- sub array_to_json {
383
- my ($self, $obj) = @_;
384
- my @res;
385
-
386
- encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)")
387
- if (++$depth > $max_depth);
388
-
389
- my ($pre, $post) = $indent ? $self->_up_indent() : ('', '');
390
-
391
- for my $v (@$obj){
392
- push @res, $self->object_to_json($v) || $self->value_to_json($v);
393
- }
394
-
395
- --$depth;
396
- $self->_down_indent() if ($indent);
397
-
398
- return '[' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . ']';
399
- }
400
-
401
-
402
- sub value_to_json {
403
- my ($self, $value) = @_;
404
-
405
- return 'null' if(!defined $value);
406
-
407
- my $b_obj = B::svref_2object(\$value); # for round trip problem
408
- my $flags = $b_obj->FLAGS;
409
-
410
- return $value # as is
411
- if $flags & ( B::SVp_IOK | B::SVp_NOK ) and !( $flags & B::SVp_POK ); # SvTYPE is IV or NV?
412
-
413
- my $type = ref($value);
414
-
415
- if(!$type){
416
- return string_to_json($self, $value);
417
- }
418
- elsif( blessed($value) and $value->isa('JSON::PP::Boolean') ){
419
- return $$value == 1 ? 'true' : 'false';
420
- }
421
- elsif ($type) {
422
- if ((overload::StrVal($value) =~ /=(\w+)/)[0]) {
423
- return $self->value_to_json("$value");
424
- }
425
-
426
- if ($type eq 'SCALAR' and defined $$value) {
427
- return $$value eq '1' ? 'true'
428
- : $$value eq '0' ? 'false'
429
- : $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ? 'null'
430
- : encode_error("cannot encode reference to scalar");
431
- }
432
-
433
- if ( $self->{PROPS}->[ P_ALLOW_UNKNOWN ] ) {
434
- return 'null';
435
- }
436
- else {
437
- if ( $type eq 'SCALAR' or $type eq 'REF' ) {
438
- encode_error("cannot encode reference to scalar");
439
- }
440
- else {
441
- encode_error("encountered $value, but JSON can only represent references to arrays or hashes");
442
- }
443
- }
444
-
445
- }
446
- else {
447
- return $self->{fallback}->($value)
448
- if ($self->{fallback} and ref($self->{fallback}) eq 'CODE');
449
- return 'null';
450
- }
451
-
452
- }
453
-
454
-
455
- my %esc = (
456
- "\n" => '\n',
457
- "\r" => '\r',
458
- "\t" => '\t',
459
- "\f" => '\f',
460
- "\b" => '\b',
461
- "\"" => '\"',
462
- "\\" => '\\\\',
463
- "\'" => '\\\'',
464
- );
465
-
466
-
467
- sub string_to_json {
468
- my ($self, $arg) = @_;
469
-
470
- $arg =~ s/([\x22\x5c\n\r\t\f\b])/$esc{$1}/g;
471
- $arg =~ s/\//\\\//g if ($escape_slash);
472
- $arg =~ s/([\x00-\x08\x0b\x0e-\x1f])/'\\u00' . unpack('H2', $1)/eg;
473
-
474
- if ($ascii) {
475
- $arg = JSON_PP_encode_ascii($arg);
476
- }
477
-
478
- if ($latin1) {
479
- $arg = JSON_PP_encode_latin1($arg);
480
- }
481
-
482
- if ($utf8) {
483
- utf8::encode($arg);
484
- }
485
-
486
- return '"' . $arg . '"';
487
- }
488
-
489
-
490
- sub blessed_to_json {
491
- my $reftype = reftype($_[1]) || '';
492
- if ($reftype eq 'HASH') {
493
- return $_[0]->hash_to_json($_[1]);
494
- }
495
- elsif ($reftype eq 'ARRAY') {
496
- return $_[0]->array_to_json($_[1]);
497
- }
498
- else {
499
- return 'null';
500
- }
501
- }
502
-
503
-
504
- sub encode_error {
505
- my $error = shift;
506
- Carp::croak "$error";
507
- }
508
-
509
-
510
- sub _sort {
511
- defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]};
512
- }
513
-
514
-
515
- sub _up_indent {
516
- my $self = shift;
517
- my $space = ' ' x $indent_length;
518
-
519
- my ($pre,$post) = ('','');
520
-
521
- $post = "\n" . $space x $indent_count;
522
-
523
- $indent_count++;
524
-
525
- $pre = "\n" . $space x $indent_count;
526
-
527
- return ($pre,$post);
528
- }
529
-
530
-
531
- sub _down_indent { $indent_count--; }
532
-
533
-
534
- sub PP_encode_box {
535
- {
536
- depth => $depth,
537
- indent_count => $indent_count,
538
- };
539
- }
540
-
541
- } # Convert
542
-
543
-
544
- sub _encode_ascii {
545
- join('',
546
- map {
547
- $_ <= 127 ?
548
- chr($_) :
549
- $_ <= 65535 ?
550
- sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
551
- } unpack('U*', $_[0])
552
- );
553
- }
554
-
555
-
556
- sub _encode_latin1 {
557
- join('',
558
- map {
559
- $_ <= 255 ?
560
- chr($_) :
561
- $_ <= 65535 ?
562
- sprintf('\u%04x', $_) : sprintf('\u%x\u%x', _encode_surrogates($_));
563
- } unpack('U*', $_[0])
564
- );
565
- }
566
-
567
-
568
- sub _encode_surrogates { # from perlunicode
569
- my $uni = $_[0] - 0x10000;
570
- return ($uni / 0x400 + 0xD800, $uni % 0x400 + 0xDC00);
571
- }
572
-
573
-
574
- sub _is_bignum {
575
- $_[0]->isa('Math::BigInt') or $_[0]->isa('Math::BigFloat');
576
- }
577
-
578
-
579
-
580
- #
581
- # JSON => Perl
582
- #
583
-
584
- my $max_intsize;
585
-
586
- BEGIN {
587
- my $checkint = 1111;
588
- for my $d (5..64) {
589
- $checkint .= 1;
590
- my $int = eval qq| $checkint |;
591
- if ($int =~ /[eE]/) {
592
- $max_intsize = $d - 1;
593
- last;
594
- }
595
- }
596
- }
597
-
598
- { # PARSE
599
-
600
- my %escapes = ( # by Jeremy Muhlich <jmuhlich [at] bitflood.org>
601
- b => "\x8",
602
- t => "\x9",
603
- n => "\xA",
604
- f => "\xC",
605
- r => "\xD",
606
- '\\' => '\\',
607
- '"' => '"',
608
- '/' => '/',
609
- );
610
-
611
- my $text; # json data
612
- my $at; # offset
613
- my $ch; # 1chracter
614
- my $len; # text length (changed according to UTF8 or NON UTF8)
615
- # INTERNAL
616
- my $depth; # nest counter
617
- my $encoding; # json text encoding
618
- my $is_valid_utf8; # temp variable
619
- my $utf8_len; # utf8 byte length
620
- # FLAGS
621
- my $utf8; # must be utf8
622
- my $max_depth; # max nest number of objects and arrays
623
- my $max_size;
624
- my $relaxed;
625
- my $cb_object;
626
- my $cb_sk_object;
627
-
628
- my $F_HOOK;
629
-
630
- my $allow_bigint; # using Math::BigInt
631
- my $singlequote; # loosely quoting
632
- my $loose; #
633
- my $allow_barekey; # bareKey
634
-
635
- # $opt flag
636
- # 0x00000001 .... decode_prefix
637
- # 0x10000000 .... incr_parse
638
-
639
- sub PP_decode_json {
640
- my ($self, $opt); # $opt is an effective flag during this decode_json.
641
-
642
- ($self, $text, $opt) = @_;
643
-
644
- ($at, $ch, $depth) = (0, '', 0);
645
-
646
- if ( !defined $text or ref $text ) {
647
- decode_error("malformed JSON string, neither array, object, number, string or atom");
648
- }
649
-
650
- my $idx = $self->{PROPS};
651
-
652
- ($utf8, $relaxed, $loose, $allow_bigint, $allow_barekey, $singlequote)
653
- = @{$idx}[P_UTF8, P_RELAXED, P_LOOSE .. P_ALLOW_SINGLEQUOTE];
654
-
655
- if ( $utf8 ) {
656
- utf8::downgrade( $text, 1 ) or Carp::croak("Wide character in subroutine entry");
657
- }
658
- else {
659
- utf8::upgrade( $text );
660
- }
661
-
662
- $len = length $text;
663
-
664
- ($max_depth, $max_size, $cb_object, $cb_sk_object, $F_HOOK)
665
- = @{$self}{qw/max_depth max_size cb_object cb_sk_object F_HOOK/};
666
-
667
- if ($max_size > 1) {
668
- use bytes;
669
- my $bytes = length $text;
670
- decode_error(
671
- sprintf("attempted decode of JSON text of %s bytes size, but max_size is set to %s"
672
- , $bytes, $max_size), 1
673
- ) if ($bytes > $max_size);
674
- }
675
-
676
- # Currently no effect
677
- # should use regexp
678
- my @octets = unpack('C4', $text);
679
- $encoding = ( $octets[0] and $octets[1]) ? 'UTF-8'
680
- : (!$octets[0] and $octets[1]) ? 'UTF-16BE'
681
- : (!$octets[0] and !$octets[1]) ? 'UTF-32BE'
682
- : ( $octets[2] ) ? 'UTF-16LE'
683
- : (!$octets[2] ) ? 'UTF-32LE'
684
- : 'unknown';
685
-
686
- white(); # remove head white space
687
-
688
- my $valid_start = defined $ch; # Is there a first character for JSON structure?
689
-
690
- my $result = value();
691
-
692
- return undef if ( !$result && ( $opt & 0x10000000 ) ); # for incr_parse
693
-
694
- decode_error("malformed JSON string, neither array, object, number, string or atom") unless $valid_start;
695
-
696
- if ( !$idx->[ P_ALLOW_NONREF ] and !ref $result ) {
697
- decode_error(
698
- 'JSON text must be an object or array (but found number, string, true, false or null,'
699
- . ' use allow_nonref to allow this)', 1);
700
- }
701
-
702
- Carp::croak('something wrong.') if $len < $at; # we won't arrive here.
703
-
704
- my $consumed = defined $ch ? $at - 1 : $at; # consumed JSON text length
705
-
706
- white(); # remove tail white space
707
-
708
- if ( $ch ) {
709
- return ( $result, $consumed ) if ($opt & 0x00000001); # all right if decode_prefix
710
- decode_error("garbage after JSON object");
711
- }
712
-
713
- ( $opt & 0x00000001 ) ? ( $result, $consumed ) : $result;
714
- }
715
-
716
-
717
- sub next_chr {
718
- return $ch = undef if($at >= $len);
719
- $ch = substr($text, $at++, 1);
720
- }
721
-
722
-
723
- sub value {
724
- white();
725
- return if(!defined $ch);
726
- return object() if($ch eq '{');
727
- return array() if($ch eq '[');
728
- return string() if($ch eq '"' or ($singlequote and $ch eq "'"));
729
- return number() if($ch =~ /[0-9]/ or $ch eq '-');
730
- return word();
731
- }
732
-
733
- sub string {
734
- my ($i, $s, $t, $u);
735
- my $utf16;
736
- my $is_utf8;
737
-
738
- ($is_valid_utf8, $utf8_len) = ('', 0);
739
-
740
- $s = ''; # basically UTF8 flag on
741
-
742
- if($ch eq '"' or ($singlequote and $ch eq "'")){
743
- my $boundChar = $ch;
744
-
745
- OUTER: while( defined(next_chr()) ){
746
-
747
- if($ch eq $boundChar){
748
- next_chr();
749
-
750
- if ($utf16) {
751
- decode_error("missing low surrogate character in surrogate pair");
752
- }
753
-
754
- utf8::decode($s) if($is_utf8);
755
-
756
- return $s;
757
- }
758
- elsif($ch eq '\\'){
759
- next_chr();
760
- if(exists $escapes{$ch}){
761
- $s .= $escapes{$ch};
762
- }
763
- elsif($ch eq 'u'){ # UNICODE handling
764
- my $u = '';
765
-
766
- for(1..4){
767
- $ch = next_chr();
768
- last OUTER if($ch !~ /[0-9a-fA-F]/);
769
- $u .= $ch;
770
- }
771
-
772
- # U+D800 - U+DBFF
773
- if ($u =~ /^[dD][89abAB][0-9a-fA-F]{2}/) { # UTF-16 high surrogate?
774
- $utf16 = $u;
775
- }
776
- # U+DC00 - U+DFFF
777
- elsif ($u =~ /^[dD][c-fC-F][0-9a-fA-F]{2}/) { # UTF-16 low surrogate?
778
- unless (defined $utf16) {
779
- decode_error("missing high surrogate character in surrogate pair");
780
- }
781
- $is_utf8 = 1;
782
- $s .= JSON_PP_decode_surrogates($utf16, $u) || next;
783
- $utf16 = undef;
784
- }
785
- else {
786
- if (defined $utf16) {
787
- decode_error("surrogate pair expected");
788
- }
789
-
790
- if ( ( my $hex = hex( $u ) ) > 127 ) {
791
- $is_utf8 = 1;
792
- $s .= JSON_PP_decode_unicode($u) || next;
793
- }
794
- else {
795
- $s .= chr $hex;
796
- }
797
- }
798
-
799
- }
800
- else{
801
- unless ($loose) {
802
- $at -= 2;
803
- decode_error('illegal backslash escape sequence in string');
804
- }
805
- $s .= $ch;
806
- }
807
- }
808
- else{
809
-
810
- if ( ord $ch > 127 ) {
811
- if ( $utf8 ) {
812
- unless( $ch = is_valid_utf8($ch) ) {
813
- $at -= 1;
814
- decode_error("malformed UTF-8 character in JSON string");
815
- }
816
- else {
817
- $at += $utf8_len - 1;
818
- }
819
- }
820
- else {
821
- utf8::encode( $ch );
822
- }
823
-
824
- $is_utf8 = 1;
825
- }
826
-
827
- if (!$loose) {
828
- if ($ch =~ /[\x00-\x1f\x22\x5c]/) { # '/' ok
829
- $at--;
830
- decode_error('invalid character encountered while parsing JSON string');
831
- }
832
- }
833
-
834
- $s .= $ch;
835
- }
836
- }
837
- }
838
-
839
- decode_error("unexpected end of string while parsing JSON string");
840
- }
841
-
842
-
843
- sub white {
844
- while( defined $ch ){
845
- if($ch le ' '){
846
- next_chr();
847
- }
848
- elsif($ch eq '/'){
849
- next_chr();
850
- if(defined $ch and $ch eq '/'){
851
- 1 while(defined(next_chr()) and $ch ne "\n" and $ch ne "\r");
852
- }
853
- elsif(defined $ch and $ch eq '*'){
854
- next_chr();
855
- while(1){
856
- if(defined $ch){
857
- if($ch eq '*'){
858
- if(defined(next_chr()) and $ch eq '/'){
859
- next_chr();
860
- last;
861
- }
862
- }
863
- else{
864
- next_chr();
865
- }
866
- }
867
- else{
868
- decode_error("Unterminated comment");
869
- }
870
- }
871
- next;
872
- }
873
- else{
874
- $at--;
875
- decode_error("malformed JSON string, neither array, object, number, string or atom");
876
- }
877
- }
878
- else{
879
- if ($relaxed and $ch eq '#') { # correctly?
880
- pos($text) = $at;
881
- $text =~ /\G([^\n]*(?:\r\n|\r|\n|$))/g;
882
- $at = pos($text);
883
- next_chr;
884
- next;
885
- }
886
-
887
- last;
888
- }
889
- }
890
- }
891
-
892
-
893
- sub array {
894
- my $a = $_[0] || []; # you can use this code to use another array ref object.
895
-
896
- decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
897
- if (++$depth > $max_depth);
898
-
899
- next_chr();
900
- white();
901
-
902
- if(defined $ch and $ch eq ']'){
903
- --$depth;
904
- next_chr();
905
- return $a;
906
- }
907
- else {
908
- while(defined($ch)){
909
- push @$a, value();
910
-
911
- white();
912
-
913
- if (!defined $ch) {
914
- last;
915
- }
916
-
917
- if($ch eq ']'){
918
- --$depth;
919
- next_chr();
920
- return $a;
921
- }
922
-
923
- if($ch ne ','){
924
- last;
925
- }
926
-
927
- next_chr();
928
- white();
929
-
930
- if ($relaxed and $ch eq ']') {
931
- --$depth;
932
- next_chr();
933
- return $a;
934
- }
935
-
936
- }
937
- }
938
-
939
- decode_error(", or ] expected while parsing array");
940
- }
941
-
942
-
943
- sub object {
944
- my $o = $_[0] || {}; # you can use this code to use another hash ref object.
945
- my $k;
946
-
947
- decode_error('json text or perl structure exceeds maximum nesting level (max_depth set too low?)')
948
- if (++$depth > $max_depth);
949
- next_chr();
950
- white();
951
-
952
- if(defined $ch and $ch eq '}'){
953
- --$depth;
954
- next_chr();
955
- if ($F_HOOK) {
956
- return _json_object_hook($o);
957
- }
958
- return $o;
959
- }
960
- else {
961
- while (defined $ch) {
962
- $k = ($allow_barekey and $ch ne '"' and $ch ne "'") ? bareKey() : string();
963
- white();
964
-
965
- if(!defined $ch or $ch ne ':'){
966
- $at--;
967
- decode_error("':' expected");
968
- }
969
-
970
- next_chr();
971
- $o->{$k} = value();
972
- white();
973
-
974
- last if (!defined $ch);
975
-
976
- if($ch eq '}'){
977
- --$depth;
978
- next_chr();
979
- if ($F_HOOK) {
980
- return _json_object_hook($o);
981
- }
982
- return $o;
983
- }
984
-
985
- if($ch ne ','){
986
- last;
987
- }
988
-
989
- next_chr();
990
- white();
991
-
992
- if ($relaxed and $ch eq '}') {
993
- --$depth;
994
- next_chr();
995
- if ($F_HOOK) {
996
- return _json_object_hook($o);
997
- }
998
- return $o;
999
- }
1000
-
1001
- }
1002
-
1003
- }
1004
-
1005
- $at--;
1006
- decode_error(", or } expected while parsing object/hash");
1007
- }
1008
-
1009
-
1010
- sub bareKey { # doesn't strictly follow Standard ECMA-262 3rd Edition
1011
- my $key;
1012
- while($ch =~ /[^\x00-\x23\x25-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]/){
1013
- $key .= $ch;
1014
- next_chr();
1015
- }
1016
- return $key;
1017
- }
1018
-
1019
-
1020
- sub word {
1021
- my $word = substr($text,$at-1,4);
1022
-
1023
- if($word eq 'true'){
1024
- $at += 3;
1025
- next_chr;
1026
- return $JSON::PP::true;
1027
- }
1028
- elsif($word eq 'null'){
1029
- $at += 3;
1030
- next_chr;
1031
- return undef;
1032
- }
1033
- elsif($word eq 'fals'){
1034
- $at += 3;
1035
- if(substr($text,$at,1) eq 'e'){
1036
- $at++;
1037
- next_chr;
1038
- return $JSON::PP::false;
1039
- }
1040
- }
1041
-
1042
- $at--; # for decode_error report
1043
-
1044
- decode_error("'null' expected") if ($word =~ /^n/);
1045
- decode_error("'true' expected") if ($word =~ /^t/);
1046
- decode_error("'false' expected") if ($word =~ /^f/);
1047
- decode_error("malformed JSON string, neither array, object, number, string or atom");
1048
- }
1049
-
1050
-
1051
- sub number {
1052
- my $n = '';
1053
- my $v;
1054
-
1055
- # According to RFC4627, hex or oct digits are invalid.
1056
- if($ch eq '0'){
1057
- my $peek = substr($text,$at,1);
1058
- my $hex = $peek =~ /[xX]/; # 0 or 1
1059
-
1060
- if($hex){
1061
- decode_error("malformed number (leading zero must not be followed by another digit)");
1062
- ($n) = ( substr($text, $at+1) =~ /^([0-9a-fA-F]+)/);
1063
- }
1064
- else{ # oct
1065
- ($n) = ( substr($text, $at) =~ /^([0-7]+)/);
1066
- if (defined $n and length $n > 1) {
1067
- decode_error("malformed number (leading zero must not be followed by another digit)");
1068
- }
1069
- }
1070
-
1071
- if(defined $n and length($n)){
1072
- if (!$hex and length($n) == 1) {
1073
- decode_error("malformed number (leading zero must not be followed by another digit)");
1074
- }
1075
- $at += length($n) + $hex;
1076
- next_chr;
1077
- return $hex ? hex($n) : oct($n);
1078
- }
1079
- }
1080
-
1081
- if($ch eq '-'){
1082
- $n = '-';
1083
- next_chr;
1084
- if (!defined $ch or $ch !~ /\d/) {
1085
- decode_error("malformed number (no digits after initial minus)");
1086
- }
1087
- }
1088
-
1089
- while(defined $ch and $ch =~ /\d/){
1090
- $n .= $ch;
1091
- next_chr;
1092
- }
1093
-
1094
- if(defined $ch and $ch eq '.'){
1095
- $n .= '.';
1096
-
1097
- next_chr;
1098
- if (!defined $ch or $ch !~ /\d/) {
1099
- decode_error("malformed number (no digits after decimal point)");
1100
- }
1101
- else {
1102
- $n .= $ch;
1103
- }
1104
-
1105
- while(defined(next_chr) and $ch =~ /\d/){
1106
- $n .= $ch;
1107
- }
1108
- }
1109
-
1110
- if(defined $ch and ($ch eq 'e' or $ch eq 'E')){
1111
- $n .= $ch;
1112
- next_chr;
1113
-
1114
- if(defined($ch) and ($ch eq '+' or $ch eq '-')){
1115
- $n .= $ch;
1116
- next_chr;
1117
- if (!defined $ch or $ch =~ /\D/) {
1118
- decode_error("malformed number (no digits after exp sign)");
1119
- }
1120
- $n .= $ch;
1121
- }
1122
- elsif(defined($ch) and $ch =~ /\d/){
1123
- $n .= $ch;
1124
- }
1125
- else {
1126
- decode_error("malformed number (no digits after exp sign)");
1127
- }
1128
-
1129
- while(defined(next_chr) and $ch =~ /\d/){
1130
- $n .= $ch;
1131
- }
1132
-
1133
- }
1134
-
1135
- $v .= $n;
1136
-
1137
- if ($v !~ /[.eE]/ and length $v > $max_intsize) {
1138
- if ($allow_bigint) { # from Adam Sussman
1139
- require Math::BigInt;
1140
- return Math::BigInt->new($v);
1141
- }
1142
- else {
1143
- return "$v";
1144
- }
1145
- }
1146
- elsif ($allow_bigint) {
1147
- require Math::BigFloat;
1148
- return Math::BigFloat->new($v);
1149
- }
1150
-
1151
- return 0+$v;
1152
- }
1153
-
1154
-
1155
- sub is_valid_utf8 {
1156
-
1157
- $utf8_len = $_[0] =~ /[\x00-\x7F]/ ? 1
1158
- : $_[0] =~ /[\xC2-\xDF]/ ? 2
1159
- : $_[0] =~ /[\xE0-\xEF]/ ? 3
1160
- : $_[0] =~ /[\xF0-\xF4]/ ? 4
1161
- : 0
1162
- ;
1163
-
1164
- return unless $utf8_len;
1165
-
1166
- my $is_valid_utf8 = substr($text, $at - 1, $utf8_len);
1167
-
1168
- return ( $is_valid_utf8 =~ /^(?:
1169
- [\x00-\x7F]
1170
- |[\xC2-\xDF][\x80-\xBF]
1171
- |[\xE0][\xA0-\xBF][\x80-\xBF]
1172
- |[\xE1-\xEC][\x80-\xBF][\x80-\xBF]
1173
- |[\xED][\x80-\x9F][\x80-\xBF]
1174
- |[\xEE-\xEF][\x80-\xBF][\x80-\xBF]
1175
- |[\xF0][\x90-\xBF][\x80-\xBF][\x80-\xBF]
1176
- |[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]
1177
- |[\xF4][\x80-\x8F][\x80-\xBF][\x80-\xBF]
1178
- )$/x ) ? $is_valid_utf8 : '';
1179
- }
1180
-
1181
-
1182
- sub decode_error {
1183
- my $error = shift;
1184
- my $no_rep = shift;
1185
- my $str = defined $text ? substr($text, $at) : '';
1186
- my $mess = '';
1187
- my $type = $] >= 5.008 ? 'U*'
1188
- : $] < 5.006 ? 'C*'
1189
- : utf8::is_utf8( $str ) ? 'U*' # 5.6
1190
- : 'C*'
1191
- ;
1192
-
1193
- for my $c ( unpack( $type, $str ) ) { # emulate pv_uni_display() ?
1194
- $mess .= $c == 0x07 ? '\a'
1195
- : $c == 0x09 ? '\t'
1196
- : $c == 0x0a ? '\n'
1197
- : $c == 0x0d ? '\r'
1198
- : $c == 0x0c ? '\f'
1199
- : $c < 0x20 ? sprintf('\x{%x}', $c)
1200
- : $c == 0x5c ? '\\\\'
1201
- : $c < 0x80 ? chr($c)
1202
- : sprintf('\x{%x}', $c)
1203
- ;
1204
- if ( length $mess >= 20 ) {
1205
- $mess .= '...';
1206
- last;
1207
- }
1208
- }
1209
-
1210
- unless ( length $mess ) {
1211
- $mess = '(end of string)';
1212
- }
1213
-
1214
- Carp::croak (
1215
- $no_rep ? "$error" : "$error, at character offset $at (before \"$mess\")"
1216
- );
1217
-
1218
- }
1219
-
1220
-
1221
- sub _json_object_hook {
1222
- my $o = $_[0];
1223
- my @ks = keys %{$o};
1224
-
1225
- if ( $cb_sk_object and @ks == 1 and exists $cb_sk_object->{ $ks[0] } and ref $cb_sk_object->{ $ks[0] } ) {
1226
- my @val = $cb_sk_object->{ $ks[0] }->( $o->{$ks[0]} );
1227
- if (@val == 1) {
1228
- return $val[0];
1229
- }
1230
- }
1231
-
1232
- my @val = $cb_object->($o) if ($cb_object);
1233
- if (@val == 0 or @val > 1) {
1234
- return $o;
1235
- }
1236
- else {
1237
- return $val[0];
1238
- }
1239
- }
1240
-
1241
-
1242
- sub PP_decode_box {
1243
- {
1244
- text => $text,
1245
- at => $at,
1246
- ch => $ch,
1247
- len => $len,
1248
- depth => $depth,
1249
- encoding => $encoding,
1250
- is_valid_utf8 => $is_valid_utf8,
1251
- };
1252
- }
1253
-
1254
- } # PARSE
1255
-
1256
-
1257
- sub _decode_surrogates { # from perlunicode
1258
- my $uni = 0x10000 + (hex($_[0]) - 0xD800) * 0x400 + (hex($_[1]) - 0xDC00);
1259
- my $un = pack('U*', $uni);
1260
- utf8::encode( $un );
1261
- return $un;
1262
- }
1263
-
1264
-
1265
- sub _decode_unicode {
1266
- my $un = pack('U', hex shift);
1267
- utf8::encode( $un );
1268
- return $un;
1269
- }
1270
-
1271
- #
1272
- # Setup for various Perl versions (the code from JSON::PP58)
1273
- #
1274
-
1275
- BEGIN {
1276
-
1277
- unless ( defined &utf8::is_utf8 ) {
1278
- require Encode;
1279
- *utf8::is_utf8 = *Encode::is_utf8;
1280
- }
1281
-
1282
- if ( $] >= 5.008 ) {
1283
- *JSON::PP::JSON_PP_encode_ascii = \&_encode_ascii;
1284
- *JSON::PP::JSON_PP_encode_latin1 = \&_encode_latin1;
1285
- *JSON::PP::JSON_PP_decode_surrogates = \&_decode_surrogates;
1286
- *JSON::PP::JSON_PP_decode_unicode = \&_decode_unicode;
1287
- }
1288
-
1289
- if ($] >= 5.008 and $] < 5.008003) { # join() in 5.8.0 - 5.8.2 is broken.
1290
- package # hide from PAUSE
1291
- JSON::PP;
1292
- require subs;
1293
- subs->import('join');
1294
- eval q|
1295
- sub join {
1296
- return '' if (@_ < 2);
1297
- my $j = shift;
1298
- my $str = shift;
1299
- for (@_) { $str .= $j . $_; }
1300
- return $str;
1301
- }
1302
- |;
1303
- }
1304
-
1305
-
1306
- sub JSON::PP::incr_parse {
1307
- local $Carp::CarpLevel = 1;
1308
- ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_parse( @_ );
1309
- }
1310
-
1311
-
1312
- sub JSON::PP::incr_skip {
1313
- ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_skip;
1314
- }
1315
-
1316
-
1317
- sub JSON::PP::incr_reset {
1318
- ( $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new )->incr_reset;
1319
- }
1320
-
1321
- eval q{
1322
- sub JSON::PP::incr_text : lvalue {
1323
- $_[0]->{_incr_parser} ||= JSON::PP::IncrParser->new;
1324
-
1325
- if ( $_[0]->{_incr_parser}->{incr_parsing} ) {
1326
- Carp::croak("incr_text can not be called when the incremental parser already started parsing");
1327
- }
1328
- $_[0]->{_incr_parser}->{incr_text};
1329
- }
1330
- } if ( $] >= 5.006 );
1331
-
1332
- } # Setup for various Perl versions (the code from JSON::PP58)
1333
-
1334
-
1335
- ###############################
1336
- # Utilities
1337
- #
1338
-
1339
- BEGIN {
1340
- eval 'require Scalar::Util';
1341
- unless($@){
1342
- *JSON::PP::blessed = \&Scalar::Util::blessed;
1343
- *JSON::PP::reftype = \&Scalar::Util::reftype;
1344
- *JSON::PP::refaddr = \&Scalar::Util::refaddr;
1345
- }
1346
- else{ # This code is from Scalar::Util.
1347
- # warn $@;
1348
- eval 'sub UNIVERSAL::a_sub_not_likely_to_be_here { ref($_[0]) }';
1349
- *JSON::PP::blessed = sub {
1350
- local($@, $SIG{__DIE__}, $SIG{__WARN__});
1351
- ref($_[0]) ? eval { $_[0]->a_sub_not_likely_to_be_here } : undef;
1352
- };
1353
- my %tmap = qw(
1354
- B::NULL SCALAR
1355
- B::HV HASH
1356
- B::AV ARRAY
1357
- B::CV CODE
1358
- B::IO IO
1359
- B::GV GLOB
1360
- B::REGEXP REGEXP
1361
- );
1362
- *JSON::PP::reftype = sub {
1363
- my $r = shift;
1364
-
1365
- return undef unless length(ref($r));
1366
-
1367
- my $t = ref(B::svref_2object($r));
1368
-
1369
- return
1370
- exists $tmap{$t} ? $tmap{$t}
1371
- : length(ref($$r)) ? 'REF'
1372
- : 'SCALAR';
1373
- };
1374
- *JSON::PP::refaddr = sub {
1375
- return undef unless length(ref($_[0]));
1376
-
1377
- my $addr;
1378
- if(defined(my $pkg = blessed($_[0]))) {
1379
- $addr .= bless $_[0], 'Scalar::Util::Fake';
1380
- bless $_[0], $pkg;
1381
- }
1382
- else {
1383
- $addr .= $_[0]
1384
- }
1385
-
1386
- $addr =~ /0x(\w+)/;
1387
- local $^W;
1388
- #no warnings 'portable';
1389
- hex($1);
1390
- }
1391
- }
1392
- }
1393
-
1394
-
1395
- # shamelessly copied and modified from JSON::XS code.
1396
-
1397
- unless ( $INC{'JSON/PP.pm'} ) {
1398
- eval q|
1399
- package
1400
- JSON::PP::Boolean;
1401
-
1402
- use overload (
1403
- "0+" => sub { ${$_[0]} },
1404
- "++" => sub { $_[0] = ${$_[0]} + 1 },
1405
- "--" => sub { $_[0] = ${$_[0]} - 1 },
1406
- fallback => 1,
1407
- );
1408
- |;
1409
- }
1410
-
1411
- $JSON::PP::true = do { bless \(my $dummy = 1), "JSON::PP::Boolean" };
1412
- $JSON::PP::false = do { bless \(my $dummy = 0), "JSON::PP::Boolean" };
1413
-
1414
- sub is_bool { defined $_[0] and UNIVERSAL::isa($_[0], "JSON::PP::Boolean"); }
1415
-
1416
- sub true { $JSON::PP::true }
1417
- sub false { $JSON::PP::false }
1418
- sub null { undef; }
1419
-
1420
- ###############################
1421
-
1422
- ###############################
1423
-
1424
- package # hide from PAUSE
1425
- JSON::PP::IncrParser;
1426
-
1427
- use strict;
1428
-
1429
- use constant INCR_M_WS => 0; # initial whitespace skipping
1430
- use constant INCR_M_STR => 1; # inside string
1431
- use constant INCR_M_BS => 2; # inside backslash
1432
- use constant INCR_M_JSON => 3; # outside anything, count nesting
1433
- use constant INCR_M_C0 => 4;
1434
- use constant INCR_M_C1 => 5;
1435
-
1436
- use vars qw($VERSION);
1437
- $VERSION = '1.01';
1438
-
1439
- my $unpack_format = $] < 5.006 ? 'C*' : 'U*';
1440
-
1441
- sub new {
1442
- my ( $class ) = @_;
1443
-
1444
- bless {
1445
- incr_nest => 0,
1446
- incr_text => undef,
1447
- incr_parsing => 0,
1448
- incr_p => 0,
1449
- }, $class;
1450
- }
1451
-
1452
-
1453
- sub incr_parse {
1454
- my ( $self, $coder, $text ) = @_;
1455
-
1456
- $self->{incr_text} = '' unless ( defined $self->{incr_text} );
1457
-
1458
- if ( defined $text ) {
1459
- if ( utf8::is_utf8( $text ) and !utf8::is_utf8( $self->{incr_text} ) ) {
1460
- utf8::upgrade( $self->{incr_text} ) ;
1461
- utf8::decode( $self->{incr_text} ) ;
1462
- }
1463
- $self->{incr_text} .= $text;
1464
- }
1465
-
1466
-
1467
- my $max_size = $coder->get_max_size;
1468
-
1469
- if ( defined wantarray ) {
1470
-
1471
- $self->{incr_mode} = INCR_M_WS unless defined $self->{incr_mode};
1472
-
1473
- if ( wantarray ) {
1474
- my @ret;
1475
-
1476
- $self->{incr_parsing} = 1;
1477
-
1478
- do {
1479
- push @ret, $self->_incr_parse( $coder, $self->{incr_text} );
1480
-
1481
- unless ( !$self->{incr_nest} and $self->{incr_mode} == INCR_M_JSON ) {
1482
- $self->{incr_mode} = INCR_M_WS if $self->{incr_mode} != INCR_M_STR;
1483
- }
1484
-
1485
- } until ( length $self->{incr_text} >= $self->{incr_p} );
1486
-
1487
- $self->{incr_parsing} = 0;
1488
-
1489
- return @ret;
1490
- }
1491
- else { # in scalar context
1492
- $self->{incr_parsing} = 1;
1493
- my $obj = $self->_incr_parse( $coder, $self->{incr_text} );
1494
- $self->{incr_parsing} = 0 if defined $obj; # pointed by Martin J. Evans
1495
- return $obj ? $obj : undef; # $obj is an empty string, parsing was completed.
1496
- }
1497
-
1498
- }
1499
-
1500
- }
1501
-
1502
-
1503
- sub _incr_parse {
1504
- my ( $self, $coder, $text, $skip ) = @_;
1505
- my $p = $self->{incr_p};
1506
- my $restore = $p;
1507
-
1508
- my @obj;
1509
- my $len = length $text;
1510
-
1511
- if ( $self->{incr_mode} == INCR_M_WS ) {
1512
- while ( $len > $p ) {
1513
- my $s = substr( $text, $p, 1 );
1514
- $p++ and next if ( 0x20 >= unpack($unpack_format, $s) );
1515
- $self->{incr_mode} = INCR_M_JSON;
1516
- last;
1517
- }
1518
- }
1519
-
1520
- while ( $len > $p ) {
1521
- my $s = substr( $text, $p++, 1 );
1522
-
1523
- if ( $s eq '"' ) {
1524
- if (substr( $text, $p - 2, 1 ) eq '\\' ) {
1525
- next;
1526
- }
1527
-
1528
- if ( $self->{incr_mode} != INCR_M_STR ) {
1529
- $self->{incr_mode} = INCR_M_STR;
1530
- }
1531
- else {
1532
- $self->{incr_mode} = INCR_M_JSON;
1533
- unless ( $self->{incr_nest} ) {
1534
- last;
1535
- }
1536
- }
1537
- }
1538
-
1539
- if ( $self->{incr_mode} == INCR_M_JSON ) {
1540
-
1541
- if ( $s eq '[' or $s eq '{' ) {
1542
- if ( ++$self->{incr_nest} > $coder->get_max_depth ) {
1543
- Carp::croak('json text or perl structure exceeds maximum nesting level (max_depth set too low?)');
1544
- }
1545
- }
1546
- elsif ( $s eq ']' or $s eq '}' ) {
1547
- last if ( --$self->{incr_nest} <= 0 );
1548
- }
1549
- elsif ( $s eq '#' ) {
1550
- while ( $len > $p ) {
1551
- last if substr( $text, $p++, 1 ) eq "\n";
1552
- }
1553
- }
1554
-
1555
- }
1556
-
1557
- }
1558
-
1559
- $self->{incr_p} = $p;
1560
-
1561
- return if ( $self->{incr_mode} == INCR_M_STR and not $self->{incr_nest} );
1562
- return if ( $self->{incr_mode} == INCR_M_JSON and $self->{incr_nest} > 0 );
1563
-
1564
- return '' unless ( length substr( $self->{incr_text}, 0, $p ) );
1565
-
1566
- local $Carp::CarpLevel = 2;
1567
-
1568
- $self->{incr_p} = $restore;
1569
- $self->{incr_c} = $p;
1570
-
1571
- my ( $obj, $tail ) = $coder->PP_decode_json( substr( $self->{incr_text}, 0, $p ), 0x10000001 );
1572
-
1573
- $self->{incr_text} = substr( $self->{incr_text}, $p );
1574
- $self->{incr_p} = 0;
1575
-
1576
- return $obj || '';
1577
- }
1578
-
1579
-
1580
- sub incr_text {
1581
- if ( $_[0]->{incr_parsing} ) {
1582
- Carp::croak("incr_text can not be called when the incremental parser already started parsing");
1583
- }
1584
- $_[0]->{incr_text};
1585
- }
1586
-
1587
-
1588
- sub incr_skip {
1589
- my $self = shift;
1590
- $self->{incr_text} = substr( $self->{incr_text}, $self->{incr_c} );
1591
- $self->{incr_p} = 0;
1592
- }
1593
-
1594
-
1595
- sub incr_reset {
1596
- my $self = shift;
1597
- $self->{incr_text} = undef;
1598
- $self->{incr_p} = 0;
1599
- $self->{incr_mode} = 0;
1600
- $self->{incr_nest} = 0;
1601
- $self->{incr_parsing} = 0;
1602
- }
1603
-
1604
- ###############################
1605
-
1606
-
1607
- 1;
1608
- __END__
1609
- =pod
1610
-
1611
- =head1 NAME
1612
-
1613
- JSON::PP - JSON::XS compatible pure-Perl module.
1614
-
1615
- =head1 SYNOPSIS
1616
-
1617
- use JSON::PP;
1618
-
1619
- # exported functions, they croak on error
1620
- # and expect/generate UTF-8
1621
-
1622
- $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
1623
- $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
1624
-
1625
- # OO-interface
1626
-
1627
- $coder = JSON::PP->new->ascii->pretty->allow_nonref;
1628
-
1629
- $json_text = $json->encode( $perl_scalar );
1630
- $perl_scalar = $json->decode( $json_text );
1631
-
1632
- $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
1633
-
1634
- # Note that JSON version 2.0 and above will automatically use
1635
- # JSON::XS or JSON::PP, so you should be able to just:
1636
-
1637
- use JSON;
1638
-
1639
-
1640
- =head1 VERSION
1641
-
1642
- 2.27200
1643
-
1644
- L<JSON::XS> 2.27 (~2.30) compatible.
1645
-
1646
- =head1 DESCRIPTION
1647
-
1648
- This module is L<JSON::XS> compatible pure Perl module.
1649
- (Perl 5.8 or later is recommended)
1650
-
1651
- JSON::XS is the fastest and most proper JSON module on CPAN.
1652
- It is written by Marc Lehmann in C, so must be compiled and
1653
- installed in the used environment.
1654
-
1655
- JSON::PP is a pure-Perl module and has compatibility to JSON::XS.
1656
-
1657
-
1658
- =head2 FEATURES
1659
-
1660
- =over
1661
-
1662
- =item * correct unicode handling
1663
-
1664
- This module knows how to handle Unicode (depending on Perl version).
1665
-
1666
- See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL> and
1667
- L<UNICODE HANDLING ON PERLS>.
1668
-
1669
-
1670
- =item * round-trip integrity
1671
-
1672
- When you serialise a perl data structure using only data types
1673
- supported by JSON and Perl, the deserialised data structure is
1674
- identical on the Perl level. (e.g. the string "2.0" doesn't suddenly
1675
- become "2" just because it looks like a number). There I<are> minor
1676
- exceptions to this, read the MAPPING section below to learn about
1677
- those.
1678
-
1679
-
1680
- =item * strict checking of JSON correctness
1681
-
1682
- There is no guessing, no generating of illegal JSON texts by default,
1683
- and only JSON is accepted as input by default (the latter is a
1684
- security feature). But when some options are set, loose checking
1685
- features are available.
1686
-
1687
- =back
1688
-
1689
- =head1 FUNCTIONAL INTERFACE
1690
-
1691
- Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
1692
-
1693
- =head2 encode_json
1694
-
1695
- $json_text = encode_json $perl_scalar
1696
-
1697
- Converts the given Perl data structure to a UTF-8 encoded, binary string.
1698
-
1699
- This function call is functionally identical to:
1700
-
1701
- $json_text = JSON::PP->new->utf8->encode($perl_scalar)
1702
-
1703
- =head2 decode_json
1704
-
1705
- $perl_scalar = decode_json $json_text
1706
-
1707
- The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
1708
- to parse that as an UTF-8 encoded JSON text, returning the resulting
1709
- reference.
1710
-
1711
- This function call is functionally identical to:
1712
-
1713
- $perl_scalar = JSON::PP->new->utf8->decode($json_text)
1714
-
1715
- =head2 JSON::PP::is_bool
1716
-
1717
- $is_boolean = JSON::PP::is_bool($scalar)
1718
-
1719
- Returns true if the passed scalar represents either JSON::PP::true or
1720
- JSON::PP::false, two constants that act like C<1> and C<0> respectively
1721
- and are also used to represent JSON C<true> and C<false> in Perl strings.
1722
-
1723
- =head2 JSON::PP::true
1724
-
1725
- Returns JSON true value which is blessed object.
1726
- It C<isa> JSON::PP::Boolean object.
1727
-
1728
- =head2 JSON::PP::false
1729
-
1730
- Returns JSON false value which is blessed object.
1731
- It C<isa> JSON::PP::Boolean object.
1732
-
1733
- =head2 JSON::PP::null
1734
-
1735
- Returns C<undef>.
1736
-
1737
- See L<MAPPING>, below, for more information on how JSON values are mapped to
1738
- Perl.
1739
-
1740
-
1741
- =head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
1742
-
1743
- This section supposes that your perl version is 5.8 or later.
1744
-
1745
- If you know a JSON text from an outer world - a network, a file content, and so on,
1746
- is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
1747
- with C<utf8> enable. And the decoded result will contain UNICODE characters.
1748
-
1749
- # from network
1750
- my $json = JSON::PP->new->utf8;
1751
- my $json_text = CGI->new->param( 'json_data' );
1752
- my $perl_scalar = $json->decode( $json_text );
1753
-
1754
- # from file content
1755
- local $/;
1756
- open( my $fh, '<', 'json.data' );
1757
- $json_text = <$fh>;
1758
- $perl_scalar = decode_json( $json_text );
1759
-
1760
- If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
1761
-
1762
- use Encode;
1763
- local $/;
1764
- open( my $fh, '<', 'json.data' );
1765
- my $encoding = 'cp932';
1766
- my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
1767
-
1768
- # or you can write the below code.
1769
- #
1770
- # open( my $fh, "<:encoding($encoding)", 'json.data' );
1771
- # $unicode_json_text = <$fh>;
1772
-
1773
- In this case, C<$unicode_json_text> is of course UNICODE string.
1774
- So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
1775
- Instead of them, you use C<JSON> module object with C<utf8> disable.
1776
-
1777
- $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
1778
-
1779
- Or C<encode 'utf8'> and C<decode_json>:
1780
-
1781
- $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
1782
- # this way is not efficient.
1783
-
1784
- And now, you want to convert your C<$perl_scalar> into JSON data and
1785
- send it to an outer world - a network or a file content, and so on.
1786
-
1787
- Your data usually contains UNICODE strings and you want the converted data to be encoded
1788
- in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
1789
-
1790
- print encode_json( $perl_scalar ); # to a network? file? or display?
1791
- # or
1792
- print $json->utf8->encode( $perl_scalar );
1793
-
1794
- If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
1795
- for some reason, then its characters are regarded as B<latin1> for perl
1796
- (because it does not concern with your $encoding).
1797
- You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
1798
- Instead of them, you use C<JSON> module object with C<utf8> disable.
1799
- Note that the resulted text is a UNICODE string but no problem to print it.
1800
-
1801
- # $perl_scalar contains $encoding encoded string values
1802
- $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
1803
- # $unicode_json_text consists of characters less than 0x100
1804
- print $unicode_json_text;
1805
-
1806
- Or C<decode $encoding> all string values and C<encode_json>:
1807
-
1808
- $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
1809
- # ... do it to each string values, then encode_json
1810
- $json_text = encode_json( $perl_scalar );
1811
-
1812
- This method is a proper way but probably not efficient.
1813
-
1814
- See to L<Encode>, L<perluniintro>.
1815
-
1816
-
1817
- =head1 METHODS
1818
-
1819
- Basically, check to L<JSON> or L<JSON::XS>.
1820
-
1821
- =head2 new
1822
-
1823
- $json = JSON::PP->new
1824
-
1825
- Returns a new JSON::PP object that can be used to de/encode JSON
1826
- strings.
1827
-
1828
- All boolean flags described below are by default I<disabled>.
1829
-
1830
- The mutators for flags all return the JSON object again and thus calls can
1831
- be chained:
1832
-
1833
- my $json = JSON::PP->new->utf8->space_after->encode({a => [1,2]})
1834
- => {"a": [1, 2]}
1835
-
1836
- =head2 ascii
1837
-
1838
- $json = $json->ascii([$enable])
1839
-
1840
- $enabled = $json->get_ascii
1841
-
1842
- If $enable is true (or missing), then the encode method will not generate characters outside
1843
- the code range 0..127. Any Unicode characters outside that range will be escaped using either
1844
- a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
1845
- (See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>).
1846
-
1847
- In Perl 5.005, there is no character having high value (more than 255).
1848
- See to L<UNICODE HANDLING ON PERLS>.
1849
-
1850
- If $enable is false, then the encode method will not escape Unicode characters unless
1851
- required by the JSON syntax or other flags. This results in a faster and more compact format.
1852
-
1853
- JSON::PP->new->ascii(1)->encode([chr 0x10401])
1854
- => ["\ud801\udc01"]
1855
-
1856
- =head2 latin1
1857
-
1858
- $json = $json->latin1([$enable])
1859
-
1860
- $enabled = $json->get_latin1
1861
-
1862
- If $enable is true (or missing), then the encode method will encode the resulting JSON
1863
- text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
1864
-
1865
- If $enable is false, then the encode method will not escape Unicode characters
1866
- unless required by the JSON syntax or other flags.
1867
-
1868
- JSON::XS->new->latin1->encode (["\x{89}\x{abc}"]
1869
- => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
1870
-
1871
- See to L<UNICODE HANDLING ON PERLS>.
1872
-
1873
- =head2 utf8
1874
-
1875
- $json = $json->utf8([$enable])
1876
-
1877
- $enabled = $json->get_utf8
1878
-
1879
- If $enable is true (or missing), then the encode method will encode the JSON result
1880
- into UTF-8, as required by many protocols, while the decode method expects to be handled
1881
- an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
1882
- characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
1883
-
1884
- (In Perl 5.005, any character outside the range 0..255 does not exist.
1885
- See to L<UNICODE HANDLING ON PERLS>.)
1886
-
1887
- In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
1888
- encoding families, as described in RFC4627.
1889
-
1890
- If $enable is false, then the encode method will return the JSON string as a (non-encoded)
1891
- Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
1892
- (e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
1893
-
1894
- Example, output UTF-16BE-encoded JSON:
1895
-
1896
- use Encode;
1897
- $jsontext = encode "UTF-16BE", JSON::PP->new->encode ($object);
1898
-
1899
- Example, decode UTF-32LE-encoded JSON:
1900
-
1901
- use Encode;
1902
- $object = JSON::PP->new->decode (decode "UTF-32LE", $jsontext);
1903
-
1904
-
1905
- =head2 pretty
1906
-
1907
- $json = $json->pretty([$enable])
1908
-
1909
- This enables (or disables) all of the C<indent>, C<space_before> and
1910
- C<space_after> flags in one call to generate the most readable
1911
- (or most compact) form possible.
1912
-
1913
- Equivalent to:
1914
-
1915
- $json->indent->space_before->space_after
1916
-
1917
- =head2 indent
1918
-
1919
- $json = $json->indent([$enable])
1920
-
1921
- $enabled = $json->get_indent
1922
-
1923
- The default indent space length is three.
1924
- You can use C<indent_length> to change the length.
1925
-
1926
- =head2 space_before
1927
-
1928
- $json = $json->space_before([$enable])
1929
-
1930
- $enabled = $json->get_space_before
1931
-
1932
- If C<$enable> is true (or missing), then the C<encode> method will add an extra
1933
- optional space before the C<:> separating keys from values in JSON objects.
1934
-
1935
- If C<$enable> is false, then the C<encode> method will not add any extra
1936
- space at those places.
1937
-
1938
- This setting has no effect when decoding JSON texts.
1939
-
1940
- Example, space_before enabled, space_after and indent disabled:
1941
-
1942
- {"key" :"value"}
1943
-
1944
- =head2 space_after
1945
-
1946
- $json = $json->space_after([$enable])
1947
-
1948
- $enabled = $json->get_space_after
1949
-
1950
- If C<$enable> is true (or missing), then the C<encode> method will add an extra
1951
- optional space after the C<:> separating keys from values in JSON objects
1952
- and extra whitespace after the C<,> separating key-value pairs and array
1953
- members.
1954
-
1955
- If C<$enable> is false, then the C<encode> method will not add any extra
1956
- space at those places.
1957
-
1958
- This setting has no effect when decoding JSON texts.
1959
-
1960
- Example, space_before and indent disabled, space_after enabled:
1961
-
1962
- {"key": "value"}
1963
-
1964
- =head2 relaxed
1965
-
1966
- $json = $json->relaxed([$enable])
1967
-
1968
- $enabled = $json->get_relaxed
1969
-
1970
- If C<$enable> is true (or missing), then C<decode> will accept some
1971
- extensions to normal JSON syntax (see below). C<encode> will not be
1972
- affected in anyway. I<Be aware that this option makes you accept invalid
1973
- JSON texts as if they were valid!>. I suggest only to use this option to
1974
- parse application-specific files written by humans (configuration files,
1975
- resource files etc.)
1976
-
1977
- If C<$enable> is false (the default), then C<decode> will only accept
1978
- valid JSON texts.
1979
-
1980
- Currently accepted extensions are:
1981
-
1982
- =over 4
1983
-
1984
- =item * list items can have an end-comma
1985
-
1986
- JSON I<separates> array elements and key-value pairs with commas. This
1987
- can be annoying if you write JSON texts manually and want to be able to
1988
- quickly append elements, so this extension accepts comma at the end of
1989
- such items not just between them:
1990
-
1991
- [
1992
- 1,
1993
- 2, <- this comma not normally allowed
1994
- ]
1995
- {
1996
- "k1": "v1",
1997
- "k2": "v2", <- this comma not normally allowed
1998
- }
1999
-
2000
- =item * shell-style '#'-comments
2001
-
2002
- Whenever JSON allows whitespace, shell-style comments are additionally
2003
- allowed. They are terminated by the first carriage-return or line-feed
2004
- character, after which more white-space and comments are allowed.
2005
-
2006
- [
2007
- 1, # this comment not allowed in JSON
2008
- # neither this one...
2009
- ]
2010
-
2011
- =back
2012
-
2013
- =head2 canonical
2014
-
2015
- $json = $json->canonical([$enable])
2016
-
2017
- $enabled = $json->get_canonical
2018
-
2019
- If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
2020
- by sorting their keys. This is adding a comparatively high overhead.
2021
-
2022
- If C<$enable> is false, then the C<encode> method will output key-value
2023
- pairs in the order Perl stores them (which will likely change between runs
2024
- of the same script).
2025
-
2026
- This option is useful if you want the same data structure to be encoded as
2027
- the same JSON text (given the same overall settings). If it is disabled,
2028
- the same hash might be encoded differently even if contains the same data,
2029
- as key-value pairs have no inherent ordering in Perl.
2030
-
2031
- This setting has no effect when decoding JSON texts.
2032
-
2033
- If you want your own sorting routine, you can give a code reference
2034
- or a subroutine name to C<sort_by>. See to C<JSON::PP OWN METHODS>.
2035
-
2036
- =head2 allow_nonref
2037
-
2038
- $json = $json->allow_nonref([$enable])
2039
-
2040
- $enabled = $json->get_allow_nonref
2041
-
2042
- If C<$enable> is true (or missing), then the C<encode> method can convert a
2043
- non-reference into its corresponding string, number or null JSON value,
2044
- which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
2045
- values instead of croaking.
2046
-
2047
- If C<$enable> is false, then the C<encode> method will croak if it isn't
2048
- passed an arrayref or hashref, as JSON texts must either be an object
2049
- or array. Likewise, C<decode> will croak if given something that is not a
2050
- JSON object or array.
2051
-
2052
- JSON::PP->new->allow_nonref->encode ("Hello, World!")
2053
- => "Hello, World!"
2054
-
2055
- =head2 allow_unknown
2056
-
2057
- $json = $json->allow_unknown ([$enable])
2058
-
2059
- $enabled = $json->get_allow_unknown
2060
-
2061
- If $enable is true (or missing), then "encode" will *not* throw an
2062
- exception when it encounters values it cannot represent in JSON (for
2063
- example, filehandles) but instead will encode a JSON "null" value.
2064
- Note that blessed objects are not included here and are handled
2065
- separately by c<allow_nonref>.
2066
-
2067
- If $enable is false (the default), then "encode" will throw an
2068
- exception when it encounters anything it cannot encode as JSON.
2069
-
2070
- This option does not affect "decode" in any way, and it is
2071
- recommended to leave it off unless you know your communications
2072
- partner.
2073
-
2074
- =head2 allow_blessed
2075
-
2076
- $json = $json->allow_blessed([$enable])
2077
-
2078
- $enabled = $json->get_allow_blessed
2079
-
2080
- If C<$enable> is true (or missing), then the C<encode> method will not
2081
- barf when it encounters a blessed reference. Instead, the value of the
2082
- B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
2083
- disabled or no C<TO_JSON> method found) or a representation of the
2084
- object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
2085
- encoded. Has no effect on C<decode>.
2086
-
2087
- If C<$enable> is false (the default), then C<encode> will throw an
2088
- exception when it encounters a blessed object.
2089
-
2090
- =head2 convert_blessed
2091
-
2092
- $json = $json->convert_blessed([$enable])
2093
-
2094
- $enabled = $json->get_convert_blessed
2095
-
2096
- If C<$enable> is true (or missing), then C<encode>, upon encountering a
2097
- blessed object, will check for the availability of the C<TO_JSON> method
2098
- on the object's class. If found, it will be called in scalar context
2099
- and the resulting scalar will be encoded instead of the object. If no
2100
- C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
2101
- to do.
2102
-
2103
- The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
2104
- returns other blessed objects, those will be handled in the same
2105
- way. C<TO_JSON> must take care of not causing an endless recursion cycle
2106
- (== crash) in this case. The name of C<TO_JSON> was chosen because other
2107
- methods called by the Perl core (== not by the user of the object) are
2108
- usually in upper case letters and to avoid collisions with the C<to_json>
2109
- function or method.
2110
-
2111
- This setting does not yet influence C<decode> in any way.
2112
-
2113
- If C<$enable> is false, then the C<allow_blessed> setting will decide what
2114
- to do when a blessed object is found.
2115
-
2116
- =head2 filter_json_object
2117
-
2118
- $json = $json->filter_json_object([$coderef])
2119
-
2120
- When C<$coderef> is specified, it will be called from C<decode> each
2121
- time it decodes a JSON object. The only argument passed to the coderef
2122
- is a reference to the newly-created hash. If the code references returns
2123
- a single scalar (which need not be a reference), this value
2124
- (i.e. a copy of that scalar to avoid aliasing) is inserted into the
2125
- deserialised data structure. If it returns an empty list
2126
- (NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
2127
- hash will be inserted. This setting can slow down decoding considerably.
2128
-
2129
- When C<$coderef> is omitted or undefined, any existing callback will
2130
- be removed and C<decode> will not change the deserialised hash in any
2131
- way.
2132
-
2133
- Example, convert all JSON objects into the integer 5:
2134
-
2135
- my $js = JSON::PP->new->filter_json_object (sub { 5 });
2136
- # returns [5]
2137
- $js->decode ('[{}]'); # the given subroutine takes a hash reference.
2138
- # throw an exception because allow_nonref is not enabled
2139
- # so a lone 5 is not allowed.
2140
- $js->decode ('{"a":1, "b":2}');
2141
-
2142
- =head2 filter_json_single_key_object
2143
-
2144
- $json = $json->filter_json_single_key_object($key [=> $coderef])
2145
-
2146
- Works remotely similar to C<filter_json_object>, but is only called for
2147
- JSON objects having a single key named C<$key>.
2148
-
2149
- This C<$coderef> is called before the one specified via
2150
- C<filter_json_object>, if any. It gets passed the single value in the JSON
2151
- object. If it returns a single value, it will be inserted into the data
2152
- structure. If it returns nothing (not even C<undef> but the empty list),
2153
- the callback from C<filter_json_object> will be called next, as if no
2154
- single-key callback were specified.
2155
-
2156
- If C<$coderef> is omitted or undefined, the corresponding callback will be
2157
- disabled. There can only ever be one callback for a given key.
2158
-
2159
- As this callback gets called less often then the C<filter_json_object>
2160
- one, decoding speed will not usually suffer as much. Therefore, single-key
2161
- objects make excellent targets to serialise Perl objects into, especially
2162
- as single-key JSON objects are as close to the type-tagged value concept
2163
- as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
2164
- support this in any way, so you need to make sure your data never looks
2165
- like a serialised Perl hash.
2166
-
2167
- Typical names for the single object key are C<__class_whatever__>, or
2168
- C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
2169
- things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
2170
- with real hashes.
2171
-
2172
- Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
2173
- into the corresponding C<< $WIDGET{<id>} >> object:
2174
-
2175
- # return whatever is in $WIDGET{5}:
2176
- JSON::PP
2177
- ->new
2178
- ->filter_json_single_key_object (__widget__ => sub {
2179
- $WIDGET{ $_[0] }
2180
- })
2181
- ->decode ('{"__widget__": 5')
2182
-
2183
- # this can be used with a TO_JSON method in some "widget" class
2184
- # for serialisation to json:
2185
- sub WidgetBase::TO_JSON {
2186
- my ($self) = @_;
2187
-
2188
- unless ($self->{id}) {
2189
- $self->{id} = ..get..some..id..;
2190
- $WIDGET{$self->{id}} = $self;
2191
- }
2192
-
2193
- { __widget__ => $self->{id} }
2194
- }
2195
-
2196
- =head2 shrink
2197
-
2198
- $json = $json->shrink([$enable])
2199
-
2200
- $enabled = $json->get_shrink
2201
-
2202
- In JSON::XS, this flag resizes strings generated by either
2203
- C<encode> or C<decode> to their minimum size possible.
2204
- It will also try to downgrade any strings to octet-form if possible.
2205
-
2206
- In JSON::PP, it is noop about resizing strings but tries
2207
- C<utf8::downgrade> to the returned string by C<encode>.
2208
- See to L<utf8>.
2209
-
2210
- See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
2211
-
2212
- =head2 max_depth
2213
-
2214
- $json = $json->max_depth([$maximum_nesting_depth])
2215
-
2216
- $max_depth = $json->get_max_depth
2217
-
2218
- Sets the maximum nesting level (default C<512>) accepted while encoding
2219
- or decoding. If a higher nesting level is detected in JSON text or a Perl
2220
- data structure, then the encoder and decoder will stop and croak at that
2221
- point.
2222
-
2223
- Nesting level is defined by number of hash- or arrayrefs that the encoder
2224
- needs to traverse to reach a given point or the number of C<{> or C<[>
2225
- characters without their matching closing parenthesis crossed to reach a
2226
- given character in a string.
2227
-
2228
- If no argument is given, the highest possible setting will be used, which
2229
- is rarely useful.
2230
-
2231
- See L<JSON::XS/SSECURITY CONSIDERATIONS> for more info on why this is useful.
2232
-
2233
- When a large value (100 or more) was set and it de/encodes a deep nested object/text,
2234
- it may raise a warning 'Deep recursion on subroutine' at the perl runtime phase.
2235
-
2236
- =head2 max_size
2237
-
2238
- $json = $json->max_size([$maximum_string_size])
2239
-
2240
- $max_size = $json->get_max_size
2241
-
2242
- Set the maximum length a JSON text may have (in bytes) where decoding is
2243
- being attempted. The default is C<0>, meaning no limit. When C<decode>
2244
- is called on a string that is longer then this many bytes, it will not
2245
- attempt to decode the string but throw an exception. This setting has no
2246
- effect on C<encode> (yet).
2247
-
2248
- If no argument is given, the limit check will be deactivated (same as when
2249
- C<0> is specified).
2250
-
2251
- See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
2252
-
2253
- =head2 encode
2254
-
2255
- $json_text = $json->encode($perl_scalar)
2256
-
2257
- Converts the given Perl data structure (a simple scalar or a reference
2258
- to a hash or array) to its JSON representation. Simple scalars will be
2259
- converted into JSON string or number sequences, while references to arrays
2260
- become JSON arrays and references to hashes become JSON objects. Undefined
2261
- Perl values (e.g. C<undef>) become JSON C<null> values.
2262
- References to the integers C<0> and C<1> are converted into C<true> and C<false>.
2263
-
2264
- =head2 decode
2265
-
2266
- $perl_scalar = $json->decode($json_text)
2267
-
2268
- The opposite of C<encode>: expects a JSON text and tries to parse it,
2269
- returning the resulting simple scalar or reference. Croaks on error.
2270
-
2271
- JSON numbers and strings become simple Perl scalars. JSON arrays become
2272
- Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
2273
- C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
2274
- C<null> becomes C<undef>.
2275
-
2276
- =head2 decode_prefix
2277
-
2278
- ($perl_scalar, $characters) = $json->decode_prefix($json_text)
2279
-
2280
- This works like the C<decode> method, but instead of raising an exception
2281
- when there is trailing garbage after the first JSON object, it will
2282
- silently stop parsing there and return the number of characters consumed
2283
- so far.
2284
-
2285
- JSON->new->decode_prefix ("[1] the tail")
2286
- => ([], 3)
2287
-
2288
- =head1 INCREMENTAL PARSING
2289
-
2290
- Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
2291
-
2292
- In some cases, there is the need for incremental parsing of JSON texts.
2293
- This module does allow you to parse a JSON stream incrementally.
2294
- It does so by accumulating text until it has a full JSON object, which
2295
- it then can decode. This process is similar to using C<decode_prefix>
2296
- to see if a full JSON object is available, but is much more efficient
2297
- (and can be implemented with a minimum of method calls).
2298
-
2299
- This module will only attempt to parse the JSON text once it is sure it
2300
- has enough text to get a decisive result, using a very simple but
2301
- truly incremental parser. This means that it sometimes won't stop as
2302
- early as the full parser, for example, it doesn't detect parenthesis
2303
- mismatches. The only thing it guarantees is that it starts decoding as
2304
- soon as a syntactically valid JSON text has been seen. This means you need
2305
- to set resource limits (e.g. C<max_size>) to ensure the parser will stop
2306
- parsing in the presence if syntax errors.
2307
-
2308
- The following methods implement this incremental parser.
2309
-
2310
- =head2 incr_parse
2311
-
2312
- $json->incr_parse( [$string] ) # void context
2313
-
2314
- $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
2315
-
2316
- @obj_or_empty = $json->incr_parse( [$string] ) # list context
2317
-
2318
- This is the central parsing function. It can both append new text and
2319
- extract objects from the stream accumulated so far (both of these
2320
- functions are optional).
2321
-
2322
- If C<$string> is given, then this string is appended to the already
2323
- existing JSON fragment stored in the C<$json> object.
2324
-
2325
- After that, if the function is called in void context, it will simply
2326
- return without doing anything further. This can be used to add more text
2327
- in as many chunks as you want.
2328
-
2329
- If the method is called in scalar context, then it will try to extract
2330
- exactly I<one> JSON object. If that is successful, it will return this
2331
- object, otherwise it will return C<undef>. If there is a parse error,
2332
- this method will croak just as C<decode> would do (one can then use
2333
- C<incr_skip> to skip the erroneous part). This is the most common way of
2334
- using the method.
2335
-
2336
- And finally, in list context, it will try to extract as many objects
2337
- from the stream as it can find and return them, or the empty list
2338
- otherwise. For this to work, there must be no separators between the JSON
2339
- objects or arrays, instead they must be concatenated back-to-back. If
2340
- an error occurs, an exception will be raised as in the scalar context
2341
- case. Note that in this case, any previously-parsed JSON texts will be
2342
- lost.
2343
-
2344
- Example: Parse some JSON arrays/objects in a given string and return them.
2345
-
2346
- my @objs = JSON->new->incr_parse ("[5][7][1,2]");
2347
-
2348
- =head2 incr_text
2349
-
2350
- $lvalue_string = $json->incr_text
2351
-
2352
- This method returns the currently stored JSON fragment as an lvalue, that
2353
- is, you can manipulate it. This I<only> works when a preceding call to
2354
- C<incr_parse> in I<scalar context> successfully returned an object. Under
2355
- all other circumstances you must not call this function (I mean it.
2356
- although in simple tests it might actually work, it I<will> fail under
2357
- real world conditions). As a special exception, you can also call this
2358
- method before having parsed anything.
2359
-
2360
- This function is useful in two cases: a) finding the trailing text after a
2361
- JSON object or b) parsing multiple JSON objects separated by non-JSON text
2362
- (such as commas).
2363
-
2364
- $json->incr_text =~ s/\s*,\s*//;
2365
-
2366
- In Perl 5.005, C<lvalue> attribute is not available.
2367
- You must write codes like the below:
2368
-
2369
- $string = $json->incr_text;
2370
- $string =~ s/\s*,\s*//;
2371
- $json->incr_text( $string );
2372
-
2373
- =head2 incr_skip
2374
-
2375
- $json->incr_skip
2376
-
2377
- This will reset the state of the incremental parser and will remove the
2378
- parsed text from the input buffer. This is useful after C<incr_parse>
2379
- died, in which case the input buffer and incremental parser state is left
2380
- unchanged, to skip the text parsed so far and to reset the parse state.
2381
-
2382
- =head2 incr_reset
2383
-
2384
- $json->incr_reset
2385
-
2386
- This completely resets the incremental parser, that is, after this call,
2387
- it will be as if the parser had never parsed anything.
2388
-
2389
- This is useful if you want to repeatedly parse JSON objects and want to
2390
- ignore any trailing data, which means you have to reset the parser after
2391
- each successful decode.
2392
-
2393
- See to L<JSON::XS/INCREMENTAL PARSING> for examples.
2394
-
2395
-
2396
- =head1 JSON::PP OWN METHODS
2397
-
2398
- =head2 allow_singlequote
2399
-
2400
- $json = $json->allow_singlequote([$enable])
2401
-
2402
- If C<$enable> is true (or missing), then C<decode> will accept
2403
- JSON strings quoted by single quotations that are invalid JSON
2404
- format.
2405
-
2406
- $json->allow_singlequote->decode({"foo":'bar'});
2407
- $json->allow_singlequote->decode({'foo':"bar"});
2408
- $json->allow_singlequote->decode({'foo':'bar'});
2409
-
2410
- As same as the C<relaxed> option, this option may be used to parse
2411
- application-specific files written by humans.
2412
-
2413
-
2414
- =head2 allow_barekey
2415
-
2416
- $json = $json->allow_barekey([$enable])
2417
-
2418
- If C<$enable> is true (or missing), then C<decode> will accept
2419
- bare keys of JSON object that are invalid JSON format.
2420
-
2421
- As same as the C<relaxed> option, this option may be used to parse
2422
- application-specific files written by humans.
2423
-
2424
- $json->allow_barekey->decode('{foo:"bar"}');
2425
-
2426
- =head2 allow_bignum
2427
-
2428
- $json = $json->allow_bignum([$enable])
2429
-
2430
- If C<$enable> is true (or missing), then C<decode> will convert
2431
- the big integer Perl cannot handle as integer into a L<Math::BigInt>
2432
- object and convert a floating number (any) into a L<Math::BigFloat>.
2433
-
2434
- On the contrary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
2435
- objects into JSON numbers with C<allow_blessed> enable.
2436
-
2437
- $json->allow_nonref->allow_blessed->allow_bignum;
2438
- $bigfloat = $json->decode('2.000000000000000000000000001');
2439
- print $json->encode($bigfloat);
2440
- # => 2.000000000000000000000000001
2441
-
2442
- See to L<JSON::XS/MAPPING> about the normal conversion of JSON number.
2443
-
2444
- =head2 loose
2445
-
2446
- $json = $json->loose([$enable])
2447
-
2448
- The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
2449
- and the module doesn't allow to C<decode> to these (except for \x2f).
2450
- If C<$enable> is true (or missing), then C<decode> will accept these
2451
- unescaped strings.
2452
-
2453
- $json->loose->decode(qq|["abc
2454
- def"]|);
2455
-
2456
- See L<JSON::XS/SSECURITY CONSIDERATIONS>.
2457
-
2458
- =head2 escape_slash
2459
-
2460
- $json = $json->escape_slash([$enable])
2461
-
2462
- According to JSON Grammar, I<slash> (U+002F) is escaped. But default
2463
- JSON::PP (as same as JSON::XS) encodes strings without escaping slash.
2464
-
2465
- If C<$enable> is true (or missing), then C<encode> will escape slashes.
2466
-
2467
- =head2 indent_length
2468
-
2469
- $json = $json->indent_length($length)
2470
-
2471
- JSON::XS indent space length is 3 and cannot be changed.
2472
- JSON::PP set the indent space length with the given $length.
2473
- The default is 3. The acceptable range is 0 to 15.
2474
-
2475
- =head2 sort_by
2476
-
2477
- $json = $json->sort_by($function_name)
2478
- $json = $json->sort_by($subroutine_ref)
2479
-
2480
- If $function_name or $subroutine_ref are set, its sort routine are used
2481
- in encoding JSON objects.
2482
-
2483
- $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
2484
- # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
2485
-
2486
- $js = $pc->sort_by('own_sort')->encode($obj);
2487
- # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
2488
-
2489
- sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
2490
-
2491
- As the sorting routine runs in the JSON::PP scope, the given
2492
- subroutine name and the special variables C<$a>, C<$b> will begin
2493
- 'JSON::PP::'.
2494
-
2495
- If $integer is set, then the effect is same as C<canonical> on.
2496
-
2497
- =head1 INTERNAL
2498
-
2499
- For developers.
2500
-
2501
- =over
2502
-
2503
- =item PP_encode_box
2504
-
2505
- Returns
2506
-
2507
- {
2508
- depth => $depth,
2509
- indent_count => $indent_count,
2510
- }
2511
-
2512
-
2513
- =item PP_decode_box
2514
-
2515
- Returns
2516
-
2517
- {
2518
- text => $text,
2519
- at => $at,
2520
- ch => $ch,
2521
- len => $len,
2522
- depth => $depth,
2523
- encoding => $encoding,
2524
- is_valid_utf8 => $is_valid_utf8,
2525
- };
2526
-
2527
- =back
2528
-
2529
- =head1 MAPPING
2530
-
2531
- This section is copied from JSON::XS and modified to C<JSON::PP>.
2532
- JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
2533
-
2534
- See to L<JSON::XS/MAPPING>.
2535
-
2536
- =head2 JSON -> PERL
2537
-
2538
- =over 4
2539
-
2540
- =item object
2541
-
2542
- A JSON object becomes a reference to a hash in Perl. No ordering of object
2543
- keys is preserved (JSON does not preserver object key ordering itself).
2544
-
2545
- =item array
2546
-
2547
- A JSON array becomes a reference to an array in Perl.
2548
-
2549
- =item string
2550
-
2551
- A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
2552
- are represented by the same codepoints in the Perl string, so no manual
2553
- decoding is necessary.
2554
-
2555
- =item number
2556
-
2557
- A JSON number becomes either an integer, numeric (floating point) or
2558
- string scalar in perl, depending on its range and any fractional parts. On
2559
- the Perl level, there is no difference between those as Perl handles all
2560
- the conversion details, but an integer may take slightly less memory and
2561
- might represent more values exactly than floating point numbers.
2562
-
2563
- If the number consists of digits only, C<JSON> will try to represent
2564
- it as an integer value. If that fails, it will try to represent it as
2565
- a numeric (floating point) value if that is possible without loss of
2566
- precision. Otherwise it will preserve the number as a string value (in
2567
- which case you lose roundtripping ability, as the JSON number will be
2568
- re-encoded to a JSON string).
2569
-
2570
- Numbers containing a fractional or exponential part will always be
2571
- represented as numeric (floating point) values, possibly at a loss of
2572
- precision (in which case you might lose perfect roundtripping ability, but
2573
- the JSON number will still be re-encoded as a JSON number).
2574
-
2575
- Note that precision is not accuracy - binary floating point values cannot
2576
- represent most decimal fractions exactly, and when converting from and to
2577
- floating point, C<JSON> only guarantees precision up to but not including
2578
- the least significant bit.
2579
-
2580
- When C<allow_bignum> is enable, the big integers
2581
- and the numeric can be optionally converted into L<Math::BigInt> and
2582
- L<Math::BigFloat> objects.
2583
-
2584
- =item true, false
2585
-
2586
- These JSON atoms become C<JSON::PP::true> and C<JSON::PP::false>,
2587
- respectively. They are overloaded to act almost exactly like the numbers
2588
- C<1> and C<0>. You can check whether a scalar is a JSON boolean by using
2589
- the C<JSON::is_bool> function.
2590
-
2591
- print JSON::PP::true . "\n";
2592
- => true
2593
- print JSON::PP::true + 1;
2594
- => 1
2595
-
2596
- ok(JSON::true eq '1');
2597
- ok(JSON::true == 1);
2598
-
2599
- C<JSON> will install these missing overloading features to the backend modules.
2600
-
2601
-
2602
- =item null
2603
-
2604
- A JSON null atom becomes C<undef> in Perl.
2605
-
2606
- C<JSON::PP::null> returns C<undef>.
2607
-
2608
- =back
2609
-
2610
-
2611
- =head2 PERL -> JSON
2612
-
2613
- The mapping from Perl to JSON is slightly more difficult, as Perl is a
2614
- truly typeless language, so we can only guess which JSON type is meant by
2615
- a Perl value.
2616
-
2617
- =over 4
2618
-
2619
- =item hash references
2620
-
2621
- Perl hash references become JSON objects. As there is no inherent ordering
2622
- in hash keys (or JSON objects), they will usually be encoded in a
2623
- pseudo-random order that can change between runs of the same program but
2624
- stays generally the same within a single run of a program. C<JSON>
2625
- optionally sort the hash keys (determined by the I<canonical> flag), so
2626
- the same data structure will serialise to the same JSON text (given same
2627
- settings and version of JSON::XS), but this incurs a runtime overhead
2628
- and is only rarely useful, e.g. when you want to compare some JSON text
2629
- against another for equality.
2630
-
2631
-
2632
- =item array references
2633
-
2634
- Perl array references become JSON arrays.
2635
-
2636
- =item other references
2637
-
2638
- Other unblessed references are generally not allowed and will cause an
2639
- exception to be thrown, except for references to the integers C<0> and
2640
- C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
2641
- also use C<JSON::false> and C<JSON::true> to improve readability.
2642
-
2643
- to_json [\0,JSON::PP::true] # yields [false,true]
2644
-
2645
- =item JSON::PP::true, JSON::PP::false, JSON::PP::null
2646
-
2647
- These special values become JSON true and JSON false values,
2648
- respectively. You can also use C<\1> and C<\0> directly if you want.
2649
-
2650
- JSON::PP::null returns C<undef>.
2651
-
2652
- =item blessed objects
2653
-
2654
- Blessed objects are not directly representable in JSON. See the
2655
- C<allow_blessed> and C<convert_blessed> methods on various options on
2656
- how to deal with this: basically, you can choose between throwing an
2657
- exception, encoding the reference as if it weren't blessed, or provide
2658
- your own serialiser method.
2659
-
2660
- See to L<convert_blessed>.
2661
-
2662
- =item simple scalars
2663
-
2664
- Simple Perl scalars (any scalar that is not a reference) are the most
2665
- difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
2666
- JSON C<null> values, scalars that have last been used in a string context
2667
- before encoding as JSON strings, and anything else as number value:
2668
-
2669
- # dump as number
2670
- encode_json [2] # yields [2]
2671
- encode_json [-3.0e17] # yields [-3e+17]
2672
- my $value = 5; encode_json [$value] # yields [5]
2673
-
2674
- # used as string, so dump as string
2675
- print $value;
2676
- encode_json [$value] # yields ["5"]
2677
-
2678
- # undef becomes null
2679
- encode_json [undef] # yields [null]
2680
-
2681
- You can force the type to be a string by stringifying it:
2682
-
2683
- my $x = 3.1; # some variable containing a number
2684
- "$x"; # stringified
2685
- $x .= ""; # another, more awkward way to stringify
2686
- print $x; # perl does it for you, too, quite often
2687
-
2688
- You can force the type to be a number by numifying it:
2689
-
2690
- my $x = "3"; # some variable containing a string
2691
- $x += 0; # numify it, ensuring it will be dumped as a number
2692
- $x *= 1; # same thing, the choice is yours.
2693
-
2694
- You can not currently force the type in other, less obscure, ways.
2695
-
2696
- Note that numerical precision has the same meaning as under Perl (so
2697
- binary to decimal conversion follows the same rules as in Perl, which
2698
- can differ to other languages). Also, your perl interpreter might expose
2699
- extensions to the floating point numbers of your platform, such as
2700
- infinities or NaN's - these cannot be represented in JSON, and it is an
2701
- error to pass those in.
2702
-
2703
- =item Big Number
2704
-
2705
- When C<allow_bignum> is enable,
2706
- C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
2707
- objects into JSON numbers.
2708
-
2709
-
2710
- =back
2711
-
2712
- =head1 UNICODE HANDLING ON PERLS
2713
-
2714
- If you do not know about Unicode on Perl well,
2715
- please check L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
2716
-
2717
- =head2 Perl 5.8 and later
2718
-
2719
- Perl can handle Unicode and the JSON::PP de/encode methods also work properly.
2720
-
2721
- $json->allow_nonref->encode(chr hex 3042);
2722
- $json->allow_nonref->encode(chr hex 12345);
2723
-
2724
- Returns C<"\u3042"> and C<"\ud808\udf45"> respectively.
2725
-
2726
- $json->allow_nonref->decode('"\u3042"');
2727
- $json->allow_nonref->decode('"\ud808\udf45"');
2728
-
2729
- Returns UTF-8 encoded strings with UTF8 flag, regarded as C<U+3042> and C<U+12345>.
2730
-
2731
- Note that the versions from Perl 5.8.0 to 5.8.2, Perl built-in C<join> was broken,
2732
- so JSON::PP wraps the C<join> with a subroutine. Thus JSON::PP works slow in the versions.
2733
-
2734
-
2735
- =head2 Perl 5.6
2736
-
2737
- Perl can handle Unicode and the JSON::PP de/encode methods also work.
2738
-
2739
- =head2 Perl 5.005
2740
-
2741
- Perl 5.005 is a byte semantics world -- all strings are sequences of bytes.
2742
- That means the unicode handling is not available.
2743
-
2744
- In encoding,
2745
-
2746
- $json->allow_nonref->encode(chr hex 3042); # hex 3042 is 12354.
2747
- $json->allow_nonref->encode(chr hex 12345); # hex 12345 is 74565.
2748
-
2749
- Returns C<B> and C<E>, as C<chr> takes a value more than 255, it treats
2750
- as C<$value % 256>, so the above codes are equivalent to :
2751
-
2752
- $json->allow_nonref->encode(chr 66);
2753
- $json->allow_nonref->encode(chr 69);
2754
-
2755
- In decoding,
2756
-
2757
- $json->decode('"\u00e3\u0081\u0082"');
2758
-
2759
- The returned is a byte sequence C<0xE3 0x81 0x82> for UTF-8 encoded
2760
- japanese character (C<HIRAGANA LETTER A>).
2761
- And if it is represented in Unicode code point, C<U+3042>.
2762
-
2763
- Next,
2764
-
2765
- $json->decode('"\u3042"');
2766
-
2767
- We ordinary expect the returned value is a Unicode character C<U+3042>.
2768
- But here is 5.005 world. This is C<0xE3 0x81 0x82>.
2769
-
2770
- $json->decode('"\ud808\udf45"');
2771
-
2772
- This is not a character C<U+12345> but bytes - C<0xf0 0x92 0x8d 0x85>.
2773
-
2774
-
2775
- =head1 TODO
2776
-
2777
- =over
2778
-
2779
- =item speed
2780
-
2781
- =item memory saving
2782
-
2783
- =back
2784
-
2785
-
2786
- =head1 SEE ALSO
2787
-
2788
- Most of the document are copied and modified from JSON::XS doc.
2789
-
2790
- L<JSON::XS>
2791
-
2792
- RFC4627 (L<http://www.ietf.org/rfc/rfc4627.txt>)
2793
-
2794
- =head1 AUTHOR
2795
-
2796
- Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
2797
-
2798
-
2799
- =head1 COPYRIGHT AND LICENSE
2800
-
2801
- Copyright 2007-2012 by Makamaka Hannyaharamitu
2802
-
2803
- This library is free software; you can redistribute it and/or modify
2804
- it under the same terms as Perl itself.
2805
-
2806
- =cut
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alpaca233/SadTalker/src/face3d/models/arcface_torch/eval/verification.py DELETED
@@ -1,407 +0,0 @@
1
- """Helper for evaluation on the Labeled Faces in the Wild dataset
2
- """
3
-
4
- # MIT License
5
- #
6
- # Copyright (c) 2016 David Sandberg
7
- #
8
- # Permission is hereby granted, free of charge, to any person obtaining a copy
9
- # of this software and associated documentation files (the "Software"), to deal
10
- # in the Software without restriction, including without limitation the rights
11
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
- # copies of the Software, and to permit persons to whom the Software is
13
- # furnished to do so, subject to the following conditions:
14
- #
15
- # The above copyright notice and this permission notice shall be included in all
16
- # copies or substantial portions of the Software.
17
- #
18
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
- # SOFTWARE.
25
-
26
-
27
- import datetime
28
- import os
29
- import pickle
30
-
31
- import mxnet as mx
32
- import numpy as np
33
- import sklearn
34
- import torch
35
- from mxnet import ndarray as nd
36
- from scipy import interpolate
37
- from sklearn.decomposition import PCA
38
- from sklearn.model_selection import KFold
39
-
40
-
41
- class LFold:
42
- def __init__(self, n_splits=2, shuffle=False):
43
- self.n_splits = n_splits
44
- if self.n_splits > 1:
45
- self.k_fold = KFold(n_splits=n_splits, shuffle=shuffle)
46
-
47
- def split(self, indices):
48
- if self.n_splits > 1:
49
- return self.k_fold.split(indices)
50
- else:
51
- return [(indices, indices)]
52
-
53
-
54
- def calculate_roc(thresholds,
55
- embeddings1,
56
- embeddings2,
57
- actual_issame,
58
- nrof_folds=10,
59
- pca=0):
60
- assert (embeddings1.shape[0] == embeddings2.shape[0])
61
- assert (embeddings1.shape[1] == embeddings2.shape[1])
62
- nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
63
- nrof_thresholds = len(thresholds)
64
- k_fold = LFold(n_splits=nrof_folds, shuffle=False)
65
-
66
- tprs = np.zeros((nrof_folds, nrof_thresholds))
67
- fprs = np.zeros((nrof_folds, nrof_thresholds))
68
- accuracy = np.zeros((nrof_folds))
69
- indices = np.arange(nrof_pairs)
70
-
71
- if pca == 0:
72
- diff = np.subtract(embeddings1, embeddings2)
73
- dist = np.sum(np.square(diff), 1)
74
-
75
- for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
76
- if pca > 0:
77
- print('doing pca on', fold_idx)
78
- embed1_train = embeddings1[train_set]
79
- embed2_train = embeddings2[train_set]
80
- _embed_train = np.concatenate((embed1_train, embed2_train), axis=0)
81
- pca_model = PCA(n_components=pca)
82
- pca_model.fit(_embed_train)
83
- embed1 = pca_model.transform(embeddings1)
84
- embed2 = pca_model.transform(embeddings2)
85
- embed1 = sklearn.preprocessing.normalize(embed1)
86
- embed2 = sklearn.preprocessing.normalize(embed2)
87
- diff = np.subtract(embed1, embed2)
88
- dist = np.sum(np.square(diff), 1)
89
-
90
- # Find the best threshold for the fold
91
- acc_train = np.zeros((nrof_thresholds))
92
- for threshold_idx, threshold in enumerate(thresholds):
93
- _, _, acc_train[threshold_idx] = calculate_accuracy(
94
- threshold, dist[train_set], actual_issame[train_set])
95
- best_threshold_index = np.argmax(acc_train)
96
- for threshold_idx, threshold in enumerate(thresholds):
97
- tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], _ = calculate_accuracy(
98
- threshold, dist[test_set],
99
- actual_issame[test_set])
100
- _, _, accuracy[fold_idx] = calculate_accuracy(
101
- thresholds[best_threshold_index], dist[test_set],
102
- actual_issame[test_set])
103
-
104
- tpr = np.mean(tprs, 0)
105
- fpr = np.mean(fprs, 0)
106
- return tpr, fpr, accuracy
107
-
108
-
109
- def calculate_accuracy(threshold, dist, actual_issame):
110
- predict_issame = np.less(dist, threshold)
111
- tp = np.sum(np.logical_and(predict_issame, actual_issame))
112
- fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))
113
- tn = np.sum(
114
- np.logical_and(np.logical_not(predict_issame),
115
- np.logical_not(actual_issame)))
116
- fn = np.sum(np.logical_and(np.logical_not(predict_issame), actual_issame))
117
-
118
- tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn)
119
- fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn)
120
- acc = float(tp + tn) / dist.size
121
- return tpr, fpr, acc
122
-
123
-
124
- def calculate_val(thresholds,
125
- embeddings1,
126
- embeddings2,
127
- actual_issame,
128
- far_target,
129
- nrof_folds=10):
130
- assert (embeddings1.shape[0] == embeddings2.shape[0])
131
- assert (embeddings1.shape[1] == embeddings2.shape[1])
132
- nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
133
- nrof_thresholds = len(thresholds)
134
- k_fold = LFold(n_splits=nrof_folds, shuffle=False)
135
-
136
- val = np.zeros(nrof_folds)
137
- far = np.zeros(nrof_folds)
138
-
139
- diff = np.subtract(embeddings1, embeddings2)
140
- dist = np.sum(np.square(diff), 1)
141
- indices = np.arange(nrof_pairs)
142
-
143
- for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
144
-
145
- # Find the threshold that gives FAR = far_target
146
- far_train = np.zeros(nrof_thresholds)
147
- for threshold_idx, threshold in enumerate(thresholds):
148
- _, far_train[threshold_idx] = calculate_val_far(
149
- threshold, dist[train_set], actual_issame[train_set])
150
- if np.max(far_train) >= far_target:
151
- f = interpolate.interp1d(far_train, thresholds, kind='slinear')
152
- threshold = f(far_target)
153
- else:
154
- threshold = 0.0
155
-
156
- val[fold_idx], far[fold_idx] = calculate_val_far(
157
- threshold, dist[test_set], actual_issame[test_set])
158
-
159
- val_mean = np.mean(val)
160
- far_mean = np.mean(far)
161
- val_std = np.std(val)
162
- return val_mean, val_std, far_mean
163
-
164
-
165
- def calculate_val_far(threshold, dist, actual_issame):
166
- predict_issame = np.less(dist, threshold)
167
- true_accept = np.sum(np.logical_and(predict_issame, actual_issame))
168
- false_accept = np.sum(
169
- np.logical_and(predict_issame, np.logical_not(actual_issame)))
170
- n_same = np.sum(actual_issame)
171
- n_diff = np.sum(np.logical_not(actual_issame))
172
- # print(true_accept, false_accept)
173
- # print(n_same, n_diff)
174
- val = float(true_accept) / float(n_same)
175
- far = float(false_accept) / float(n_diff)
176
- return val, far
177
-
178
-
179
- def evaluate(embeddings, actual_issame, nrof_folds=10, pca=0):
180
- # Calculate evaluation metrics
181
- thresholds = np.arange(0, 4, 0.01)
182
- embeddings1 = embeddings[0::2]
183
- embeddings2 = embeddings[1::2]
184
- tpr, fpr, accuracy = calculate_roc(thresholds,
185
- embeddings1,
186
- embeddings2,
187
- np.asarray(actual_issame),
188
- nrof_folds=nrof_folds,
189
- pca=pca)
190
- thresholds = np.arange(0, 4, 0.001)
191
- val, val_std, far = calculate_val(thresholds,
192
- embeddings1,
193
- embeddings2,
194
- np.asarray(actual_issame),
195
- 1e-3,
196
- nrof_folds=nrof_folds)
197
- return tpr, fpr, accuracy, val, val_std, far
198
-
199
- @torch.no_grad()
200
- def load_bin(path, image_size):
201
- try:
202
- with open(path, 'rb') as f:
203
- bins, issame_list = pickle.load(f) # py2
204
- except UnicodeDecodeError as e:
205
- with open(path, 'rb') as f:
206
- bins, issame_list = pickle.load(f, encoding='bytes') # py3
207
- data_list = []
208
- for flip in [0, 1]:
209
- data = torch.empty((len(issame_list) * 2, 3, image_size[0], image_size[1]))
210
- data_list.append(data)
211
- for idx in range(len(issame_list) * 2):
212
- _bin = bins[idx]
213
- img = mx.image.imdecode(_bin)
214
- if img.shape[1] != image_size[0]:
215
- img = mx.image.resize_short(img, image_size[0])
216
- img = nd.transpose(img, axes=(2, 0, 1))
217
- for flip in [0, 1]:
218
- if flip == 1:
219
- img = mx.ndarray.flip(data=img, axis=2)
220
- data_list[flip][idx][:] = torch.from_numpy(img.asnumpy())
221
- if idx % 1000 == 0:
222
- print('loading bin', idx)
223
- print(data_list[0].shape)
224
- return data_list, issame_list
225
-
226
- @torch.no_grad()
227
- def test(data_set, backbone, batch_size, nfolds=10):
228
- print('testing verification..')
229
- data_list = data_set[0]
230
- issame_list = data_set[1]
231
- embeddings_list = []
232
- time_consumed = 0.0
233
- for i in range(len(data_list)):
234
- data = data_list[i]
235
- embeddings = None
236
- ba = 0
237
- while ba < data.shape[0]:
238
- bb = min(ba + batch_size, data.shape[0])
239
- count = bb - ba
240
- _data = data[bb - batch_size: bb]
241
- time0 = datetime.datetime.now()
242
- img = ((_data / 255) - 0.5) / 0.5
243
- net_out: torch.Tensor = backbone(img)
244
- _embeddings = net_out.detach().cpu().numpy()
245
- time_now = datetime.datetime.now()
246
- diff = time_now - time0
247
- time_consumed += diff.total_seconds()
248
- if embeddings is None:
249
- embeddings = np.zeros((data.shape[0], _embeddings.shape[1]))
250
- embeddings[ba:bb, :] = _embeddings[(batch_size - count):, :]
251
- ba = bb
252
- embeddings_list.append(embeddings)
253
-
254
- _xnorm = 0.0
255
- _xnorm_cnt = 0
256
- for embed in embeddings_list:
257
- for i in range(embed.shape[0]):
258
- _em = embed[i]
259
- _norm = np.linalg.norm(_em)
260
- _xnorm += _norm
261
- _xnorm_cnt += 1
262
- _xnorm /= _xnorm_cnt
263
-
264
- acc1 = 0.0
265
- std1 = 0.0
266
- embeddings = embeddings_list[0] + embeddings_list[1]
267
- embeddings = sklearn.preprocessing.normalize(embeddings)
268
- print(embeddings.shape)
269
- print('infer time', time_consumed)
270
- _, _, accuracy, val, val_std, far = evaluate(embeddings, issame_list, nrof_folds=nfolds)
271
- acc2, std2 = np.mean(accuracy), np.std(accuracy)
272
- return acc1, std1, acc2, std2, _xnorm, embeddings_list
273
-
274
-
275
- def dumpR(data_set,
276
- backbone,
277
- batch_size,
278
- name='',
279
- data_extra=None,
280
- label_shape=None):
281
- print('dump verification embedding..')
282
- data_list = data_set[0]
283
- issame_list = data_set[1]
284
- embeddings_list = []
285
- time_consumed = 0.0
286
- for i in range(len(data_list)):
287
- data = data_list[i]
288
- embeddings = None
289
- ba = 0
290
- while ba < data.shape[0]:
291
- bb = min(ba + batch_size, data.shape[0])
292
- count = bb - ba
293
-
294
- _data = nd.slice_axis(data, axis=0, begin=bb - batch_size, end=bb)
295
- time0 = datetime.datetime.now()
296
- if data_extra is None:
297
- db = mx.io.DataBatch(data=(_data,), label=(_label,))
298
- else:
299
- db = mx.io.DataBatch(data=(_data, _data_extra),
300
- label=(_label,))
301
- model.forward(db, is_train=False)
302
- net_out = model.get_outputs()
303
- _embeddings = net_out[0].asnumpy()
304
- time_now = datetime.datetime.now()
305
- diff = time_now - time0
306
- time_consumed += diff.total_seconds()
307
- if embeddings is None:
308
- embeddings = np.zeros((data.shape[0], _embeddings.shape[1]))
309
- embeddings[ba:bb, :] = _embeddings[(batch_size - count):, :]
310
- ba = bb
311
- embeddings_list.append(embeddings)
312
- embeddings = embeddings_list[0] + embeddings_list[1]
313
- embeddings = sklearn.preprocessing.normalize(embeddings)
314
- actual_issame = np.asarray(issame_list)
315
- outname = os.path.join('temp.bin')
316
- with open(outname, 'wb') as f:
317
- pickle.dump((embeddings, issame_list),
318
- f,
319
- protocol=pickle.HIGHEST_PROTOCOL)
320
-
321
-
322
- # if __name__ == '__main__':
323
- #
324
- # parser = argparse.ArgumentParser(description='do verification')
325
- # # general
326
- # parser.add_argument('--data-dir', default='', help='')
327
- # parser.add_argument('--model',
328
- # default='../model/softmax,50',
329
- # help='path to load model.')
330
- # parser.add_argument('--target',
331
- # default='lfw,cfp_ff,cfp_fp,agedb_30',
332
- # help='test targets.')
333
- # parser.add_argument('--gpu', default=0, type=int, help='gpu id')
334
- # parser.add_argument('--batch-size', default=32, type=int, help='')
335
- # parser.add_argument('--max', default='', type=str, help='')
336
- # parser.add_argument('--mode', default=0, type=int, help='')
337
- # parser.add_argument('--nfolds', default=10, type=int, help='')
338
- # args = parser.parse_args()
339
- # image_size = [112, 112]
340
- # print('image_size', image_size)
341
- # ctx = mx.gpu(args.gpu)
342
- # nets = []
343
- # vec = args.model.split(',')
344
- # prefix = args.model.split(',')[0]
345
- # epochs = []
346
- # if len(vec) == 1:
347
- # pdir = os.path.dirname(prefix)
348
- # for fname in os.listdir(pdir):
349
- # if not fname.endswith('.params'):
350
- # continue
351
- # _file = os.path.join(pdir, fname)
352
- # if _file.startswith(prefix):
353
- # epoch = int(fname.split('.')[0].split('-')[1])
354
- # epochs.append(epoch)
355
- # epochs = sorted(epochs, reverse=True)
356
- # if len(args.max) > 0:
357
- # _max = [int(x) for x in args.max.split(',')]
358
- # assert len(_max) == 2
359
- # if len(epochs) > _max[1]:
360
- # epochs = epochs[_max[0]:_max[1]]
361
- #
362
- # else:
363
- # epochs = [int(x) for x in vec[1].split('|')]
364
- # print('model number', len(epochs))
365
- # time0 = datetime.datetime.now()
366
- # for epoch in epochs:
367
- # print('loading', prefix, epoch)
368
- # sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)
369
- # # arg_params, aux_params = ch_dev(arg_params, aux_params, ctx)
370
- # all_layers = sym.get_internals()
371
- # sym = all_layers['fc1_output']
372
- # model = mx.mod.Module(symbol=sym, context=ctx, label_names=None)
373
- # # model.bind(data_shapes=[('data', (args.batch_size, 3, image_size[0], image_size[1]))], label_shapes=[('softmax_label', (args.batch_size,))])
374
- # model.bind(data_shapes=[('data', (args.batch_size, 3, image_size[0],
375
- # image_size[1]))])
376
- # model.set_params(arg_params, aux_params)
377
- # nets.append(model)
378
- # time_now = datetime.datetime.now()
379
- # diff = time_now - time0
380
- # print('model loading time', diff.total_seconds())
381
- #
382
- # ver_list = []
383
- # ver_name_list = []
384
- # for name in args.target.split(','):
385
- # path = os.path.join(args.data_dir, name + ".bin")
386
- # if os.path.exists(path):
387
- # print('loading.. ', name)
388
- # data_set = load_bin(path, image_size)
389
- # ver_list.append(data_set)
390
- # ver_name_list.append(name)
391
- #
392
- # if args.mode == 0:
393
- # for i in range(len(ver_list)):
394
- # results = []
395
- # for model in nets:
396
- # acc1, std1, acc2, std2, xnorm, embeddings_list = test(
397
- # ver_list[i], model, args.batch_size, args.nfolds)
398
- # print('[%s]XNorm: %f' % (ver_name_list[i], xnorm))
399
- # print('[%s]Accuracy: %1.5f+-%1.5f' % (ver_name_list[i], acc1, std1))
400
- # print('[%s]Accuracy-Flip: %1.5f+-%1.5f' % (ver_name_list[i], acc2, std2))
401
- # results.append(acc2)
402
- # print('Max of [%s] is %1.5f' % (ver_name_list[i], np.max(results)))
403
- # elif args.mode == 1:
404
- # raise ValueError
405
- # else:
406
- # model = nets[0]
407
- # dumpR(ver_list[0], model, args.batch_size, args.target)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Amrrs/DragGan-Inversion/stylegan_human/pti/training/coaches/localitly_regulizer.py DELETED
@@ -1,70 +0,0 @@
1
- import torch
2
- import numpy as np
3
- import wandb
4
- from pti.pti_configs import hyperparameters, global_config
5
- l2_criterion = torch.nn.MSELoss(reduction='mean')
6
-
7
-
8
- def l2_loss(real_images, generated_images):
9
- loss = l2_criterion(real_images, generated_images)
10
- return loss
11
-
12
-
13
- class Space_Regulizer:
14
- def __init__(self, original_G, lpips_net):
15
- self.original_G = original_G
16
- self.morphing_regulizer_alpha = hyperparameters.regulizer_alpha
17
- self.lpips_loss = lpips_net
18
-
19
- def get_morphed_w_code(self, new_w_code, fixed_w):
20
- interpolation_direction = new_w_code - fixed_w
21
- interpolation_direction_norm = torch.norm(interpolation_direction, p=2)
22
- direction_to_move = hyperparameters.regulizer_alpha * \
23
- interpolation_direction / interpolation_direction_norm
24
- result_w = fixed_w + direction_to_move
25
- self.morphing_regulizer_alpha * fixed_w + \
26
- (1 - self.morphing_regulizer_alpha) * new_w_code
27
-
28
- return result_w
29
-
30
- def get_image_from_ws(self, w_codes, G):
31
- return torch.cat([G.synthesis(w_code, noise_mode='none', force_fp32=True) for w_code in w_codes])
32
-
33
- def ball_holder_loss_lazy(self, new_G, num_of_sampled_latents, w_batch, use_wandb=False):
34
- loss = 0.0
35
-
36
- z_samples = np.random.randn(
37
- num_of_sampled_latents, self.original_G.z_dim)
38
- w_samples = self.original_G.mapping(torch.from_numpy(z_samples).to(global_config.device), None,
39
- truncation_psi=0.5)
40
- territory_indicator_ws = [self.get_morphed_w_code(
41
- w_code.unsqueeze(0), w_batch) for w_code in w_samples]
42
-
43
- for w_code in territory_indicator_ws:
44
- new_img = new_G.synthesis(
45
- w_code, noise_mode='none', force_fp32=True)
46
- with torch.no_grad():
47
- old_img = self.original_G.synthesis(
48
- w_code, noise_mode='none', force_fp32=True)
49
-
50
- if hyperparameters.regulizer_l2_lambda > 0:
51
- l2_loss_val = l2_loss.l2_loss(old_img, new_img)
52
- if use_wandb:
53
- wandb.log({f'space_regulizer_l2_loss_val': l2_loss_val.detach().cpu()},
54
- step=global_config.training_step)
55
- loss += l2_loss_val * hyperparameters.regulizer_l2_lambda
56
-
57
- if hyperparameters.regulizer_lpips_lambda > 0:
58
- loss_lpips = self.lpips_loss(old_img, new_img)
59
- loss_lpips = torch.mean(torch.squeeze(loss_lpips))
60
- if use_wandb:
61
- wandb.log({f'space_regulizer_lpips_loss_val': loss_lpips.detach().cpu()},
62
- step=global_config.training_step)
63
- loss += loss_lpips * hyperparameters.regulizer_lpips_lambda
64
-
65
- return loss / len(territory_indicator_ws)
66
-
67
- def space_regulizer_loss(self, new_G, w_batch, use_wandb):
68
- ret_val = self.ball_holder_loss_lazy(
69
- new_G, hyperparameters.latent_ball_num_of_samples, w_batch, use_wandb)
70
- return ret_val
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AnTo2209/3D_Zeroshot_Neural_Style_Transfer/src/sampler/simple_sampler.py DELETED
@@ -1,39 +0,0 @@
1
- import numpy as np
2
- import torch
3
-
4
-
5
- class SimpleSampler:
6
- def __init__(self, total, batch):
7
- self.total = total
8
- self.batch = batch
9
- self.curr = total
10
- self.ids = None
11
-
12
- def nextids(self):
13
- self.curr+=self.batch
14
- if self.curr + self.batch > self.total:
15
- self.ids = torch.LongTensor(np.random.permutation(self.total))
16
- self.curr = 0
17
- return self.ids[self.curr:self.curr+self.batch]
18
-
19
- def InfiniteSampler(n):
20
- # i = 0
21
- i = n - 1
22
- order = np.random.permutation(n)
23
- while True:
24
- yield order[i]
25
- i += 1
26
- if i >= n:
27
- np.random.seed()
28
- order = np.random.permutation(n)
29
- i = 0
30
-
31
- class InfiniteSamplerWrapper(torch.utils.data.sampler.Sampler):
32
- def __init__(self, num_samples):
33
- self.num_samples = num_samples
34
-
35
- def __iter__(self):
36
- return iter(InfiniteSampler(self.num_samples))
37
-
38
- def __len__(self):
39
- return 2 ** 31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anar0140/4.RealTime-MediaPipe-AI-From-Video-On-Any-Device/README.md DELETED
@@ -1,14 +0,0 @@
1
- ---
2
- title: 4.RealTime MediaPipe AI From Video On Any Device
3
- emoji: 👁💻👁
4
- colorFrom: blue
5
- colorTo: blue
6
- sdk: streamlit
7
- sdk_version: 1.17.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- duplicated_from: AI-ZTH-03-23/4.RealTime-MediaPipe-AI-From-Video-On-Any-Device
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/api/pipelines/score_sde_ve.md DELETED
@@ -1,35 +0,0 @@
1
- <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
-
3
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
- the License. You may obtain a copy of the License at
5
-
6
- http://www.apache.org/licenses/LICENSE-2.0
7
-
8
- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
- an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
- specific language governing permissions and limitations under the License.
11
- -->
12
-
13
- # Score SDE VE
14
-
15
- [Score-Based Generative Modeling through Stochastic Differential Equations](https://huggingface.co/papers/2011.13456) (Score SDE) is by Yang Song, Jascha Sohl-Dickstein, Diederik P. Kingma, Abhishek Kumar, Stefano Ermon and Ben Poole. This pipeline implements the variance expanding (VE) variant of the stochastic differential equation method.
16
-
17
- The abstract from the paper is:
18
-
19
- *Creating noise from data is easy; creating data from noise is generative modeling. We present a stochastic differential equation (SDE) that smoothly transforms a complex data distribution to a known prior distribution by slowly injecting noise, and a corresponding reverse-time SDE that transforms the prior distribution back into the data distribution by slowly removing the noise. Crucially, the reverse-time SDE depends only on the time-dependent gradient field (\aka, score) of the perturbed data distribution. By leveraging advances in score-based generative modeling, we can accurately estimate these scores with neural networks, and use numerical SDE solvers to generate samples. We show that this framework encapsulates previous approaches in score-based generative modeling and diffusion probabilistic modeling, allowing for new sampling procedures and new modeling capabilities. In particular, we introduce a predictor-corrector framework to correct errors in the evolution of the discretized reverse-time SDE. We also derive an equivalent neural ODE that samples from the same distribution as the SDE, but additionally enables exact likelihood computation, and improved sampling efficiency. In addition, we provide a new way to solve inverse problems with score-based models, as demonstrated with experiments on class-conditional generation, image inpainting, and colorization. Combined with multiple architectural improvements, we achieve record-breaking performance for unconditional image generation on CIFAR-10 with an Inception score of 9.89 and FID of 2.20, a competitive likelihood of 2.99 bits/dim, and demonstrate high fidelity generation of 1024 x 1024 images for the first time from a score-based generative model.*
20
-
21
- The original codebase can be found at [yang-song/score_sde_pytorch](https://github.com/yang-song/score_sde_pytorch).
22
-
23
- <Tip>
24
-
25
- Make sure to check out the Schedulers [guide](/using-diffusers/schedulers) to learn how to explore the tradeoff between scheduler speed and quality, and see the [reuse components across pipelines](/using-diffusers/loading#reuse-components-across-pipelines) section to learn how to efficiently load the same components into multiple pipelines.
26
-
27
- </Tip>
28
-
29
- ## ScoreSdeVePipeline
30
- [[autodoc]] ScoreSdeVePipeline
31
- - all
32
- - __call__
33
-
34
- ## ImagePipelineOutput
35
- [[autodoc]] pipelines.ImagePipelineOutput
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py DELETED
@@ -1,414 +0,0 @@
1
- # Copyright 2023 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import inspect
16
- import warnings
17
- from typing import Callable, List, Optional, Union
18
-
19
- import PIL
20
- import torch
21
- from packaging import version
22
- from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
23
-
24
- from ...configuration_utils import FrozenDict
25
- from ...image_processor import VaeImageProcessor
26
- from ...models import AutoencoderKL, UNet2DConditionModel
27
- from ...schedulers import KarrasDiffusionSchedulers
28
- from ...utils import deprecate, logging, randn_tensor
29
- from ..pipeline_utils import DiffusionPipeline
30
- from . import StableDiffusionPipelineOutput
31
- from .safety_checker import StableDiffusionSafetyChecker
32
-
33
-
34
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
-
36
-
37
- class StableDiffusionImageVariationPipeline(DiffusionPipeline):
38
- r"""
39
- Pipeline to generate image variations from an input image using Stable Diffusion.
40
-
41
- This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
42
- implemented for all pipelines (downloading, saving, running on a particular device, etc.).
43
-
44
- Args:
45
- vae ([`AutoencoderKL`]):
46
- Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
47
- image_encoder ([`~transformers.CLIPVisionModelWithProjection`]):
48
- Frozen CLIP image-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
49
- text_encoder ([`~transformers.CLIPTextModel`]):
50
- Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
51
- tokenizer ([`~transformers.CLIPTokenizer`]):
52
- A `CLIPTokenizer` to tokenize text.
53
- unet ([`UNet2DConditionModel`]):
54
- A `UNet2DConditionModel` to denoise the encoded image latents.
55
- scheduler ([`SchedulerMixin`]):
56
- A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
57
- [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
58
- safety_checker ([`StableDiffusionSafetyChecker`]):
59
- Classification module that estimates whether generated images could be considered offensive or harmful.
60
- Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
61
- about a model's potential harms.
62
- feature_extractor ([`~transformers.CLIPImageProcessor`]):
63
- A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
64
- """
65
- # TODO: feature_extractor is required to encode images (if they are in PIL format),
66
- # we should give a descriptive message if the pipeline doesn't have one.
67
- _optional_components = ["safety_checker"]
68
-
69
- def __init__(
70
- self,
71
- vae: AutoencoderKL,
72
- image_encoder: CLIPVisionModelWithProjection,
73
- unet: UNet2DConditionModel,
74
- scheduler: KarrasDiffusionSchedulers,
75
- safety_checker: StableDiffusionSafetyChecker,
76
- feature_extractor: CLIPImageProcessor,
77
- requires_safety_checker: bool = True,
78
- ):
79
- super().__init__()
80
-
81
- if safety_checker is None and requires_safety_checker:
82
- logger.warn(
83
- f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
84
- " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
85
- " results in services or applications open to the public. Both the diffusers team and Hugging Face"
86
- " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
87
- " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
88
- " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
89
- )
90
-
91
- if safety_checker is not None and feature_extractor is None:
92
- raise ValueError(
93
- "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
94
- " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
95
- )
96
-
97
- is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
98
- version.parse(unet.config._diffusers_version).base_version
99
- ) < version.parse("0.9.0.dev0")
100
- is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
101
- if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
102
- deprecation_message = (
103
- "The configuration file of the unet has set the default `sample_size` to smaller than"
104
- " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the"
105
- " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
106
- " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
107
- " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
108
- " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
109
- " in the config might lead to incorrect results in future versions. If you have downloaded this"
110
- " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
111
- " the `unet/config.json` file"
112
- )
113
- deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
114
- new_config = dict(unet.config)
115
- new_config["sample_size"] = 64
116
- unet._internal_dict = FrozenDict(new_config)
117
-
118
- self.register_modules(
119
- vae=vae,
120
- image_encoder=image_encoder,
121
- unet=unet,
122
- scheduler=scheduler,
123
- safety_checker=safety_checker,
124
- feature_extractor=feature_extractor,
125
- )
126
- self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
127
- self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
128
- self.register_to_config(requires_safety_checker=requires_safety_checker)
129
-
130
- def _encode_image(self, image, device, num_images_per_prompt, do_classifier_free_guidance):
131
- dtype = next(self.image_encoder.parameters()).dtype
132
-
133
- if not isinstance(image, torch.Tensor):
134
- image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
135
-
136
- image = image.to(device=device, dtype=dtype)
137
- image_embeddings = self.image_encoder(image).image_embeds
138
- image_embeddings = image_embeddings.unsqueeze(1)
139
-
140
- # duplicate image embeddings for each generation per prompt, using mps friendly method
141
- bs_embed, seq_len, _ = image_embeddings.shape
142
- image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
143
- image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
144
-
145
- if do_classifier_free_guidance:
146
- negative_prompt_embeds = torch.zeros_like(image_embeddings)
147
-
148
- # For classifier free guidance, we need to do two forward passes.
149
- # Here we concatenate the unconditional and text embeddings into a single batch
150
- # to avoid doing two forward passes
151
- image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
152
-
153
- return image_embeddings
154
-
155
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
156
- def run_safety_checker(self, image, device, dtype):
157
- if self.safety_checker is None:
158
- has_nsfw_concept = None
159
- else:
160
- if torch.is_tensor(image):
161
- feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
162
- else:
163
- feature_extractor_input = self.image_processor.numpy_to_pil(image)
164
- safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
165
- image, has_nsfw_concept = self.safety_checker(
166
- images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
167
- )
168
- return image, has_nsfw_concept
169
-
170
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
171
- def decode_latents(self, latents):
172
- warnings.warn(
173
- "The decode_latents method is deprecated and will be removed in a future version. Please"
174
- " use VaeImageProcessor instead",
175
- FutureWarning,
176
- )
177
- latents = 1 / self.vae.config.scaling_factor * latents
178
- image = self.vae.decode(latents, return_dict=False)[0]
179
- image = (image / 2 + 0.5).clamp(0, 1)
180
- # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
181
- image = image.cpu().permute(0, 2, 3, 1).float().numpy()
182
- return image
183
-
184
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
185
- def prepare_extra_step_kwargs(self, generator, eta):
186
- # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
187
- # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
188
- # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
189
- # and should be between [0, 1]
190
-
191
- accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
192
- extra_step_kwargs = {}
193
- if accepts_eta:
194
- extra_step_kwargs["eta"] = eta
195
-
196
- # check if the scheduler accepts generator
197
- accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
198
- if accepts_generator:
199
- extra_step_kwargs["generator"] = generator
200
- return extra_step_kwargs
201
-
202
- def check_inputs(self, image, height, width, callback_steps):
203
- if (
204
- not isinstance(image, torch.Tensor)
205
- and not isinstance(image, PIL.Image.Image)
206
- and not isinstance(image, list)
207
- ):
208
- raise ValueError(
209
- "`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
210
- f" {type(image)}"
211
- )
212
-
213
- if height % 8 != 0 or width % 8 != 0:
214
- raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
215
-
216
- if (callback_steps is None) or (
217
- callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
218
- ):
219
- raise ValueError(
220
- f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
221
- f" {type(callback_steps)}."
222
- )
223
-
224
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
225
- def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
226
- shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
227
- if isinstance(generator, list) and len(generator) != batch_size:
228
- raise ValueError(
229
- f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
230
- f" size of {batch_size}. Make sure the batch size matches the length of the generators."
231
- )
232
-
233
- if latents is None:
234
- latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
235
- else:
236
- latents = latents.to(device)
237
-
238
- # scale the initial noise by the standard deviation required by the scheduler
239
- latents = latents * self.scheduler.init_noise_sigma
240
- return latents
241
-
242
- @torch.no_grad()
243
- def __call__(
244
- self,
245
- image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
246
- height: Optional[int] = None,
247
- width: Optional[int] = None,
248
- num_inference_steps: int = 50,
249
- guidance_scale: float = 7.5,
250
- num_images_per_prompt: Optional[int] = 1,
251
- eta: float = 0.0,
252
- generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
253
- latents: Optional[torch.FloatTensor] = None,
254
- output_type: Optional[str] = "pil",
255
- return_dict: bool = True,
256
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
257
- callback_steps: int = 1,
258
- ):
259
- r"""
260
- The call function to the pipeline for generation.
261
-
262
- Args:
263
- image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
264
- Image or images to guide image generation. If you provide a tensor, it needs to be compatible with
265
- [`CLIPImageProcessor`](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json).
266
- height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
267
- The height in pixels of the generated image.
268
- width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
269
- The width in pixels of the generated image.
270
- num_inference_steps (`int`, *optional*, defaults to 50):
271
- The number of denoising steps. More denoising steps usually lead to a higher quality image at the
272
- expense of slower inference. This parameter is modulated by `strength`.
273
- guidance_scale (`float`, *optional*, defaults to 7.5):
274
- A higher guidance scale value encourages the model to generate images closely linked to the text
275
- `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
276
- num_images_per_prompt (`int`, *optional*, defaults to 1):
277
- The number of images to generate per prompt.
278
- eta (`float`, *optional*, defaults to 0.0):
279
- Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
280
- to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
281
- generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
282
- A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
283
- generation deterministic.
284
- latents (`torch.FloatTensor`, *optional*):
285
- Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
286
- generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
287
- tensor is generated by sampling using the supplied random `generator`.
288
- output_type (`str`, *optional*, defaults to `"pil"`):
289
- The output format of the generated image. Choose between `PIL.Image` or `np.array`.
290
- return_dict (`bool`, *optional*, defaults to `True`):
291
- Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
292
- plain tuple.
293
- callback (`Callable`, *optional*):
294
- A function that calls every `callback_steps` steps during inference. The function is called with the
295
- following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
296
- callback_steps (`int`, *optional*, defaults to 1):
297
- The frequency at which the `callback` function is called. If not specified, the callback is called at
298
- every step.
299
-
300
- Returns:
301
- [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
302
- If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
303
- otherwise a `tuple` is returned where the first element is a list with the generated images and the
304
- second element is a list of `bool`s indicating whether the corresponding generated image contains
305
- "not-safe-for-work" (nsfw) content.
306
-
307
- Examples:
308
-
309
- ```py
310
- from diffusers import StableDiffusionImageVariationPipeline
311
- from PIL import Image
312
- from io import BytesIO
313
- import requests
314
-
315
- pipe = StableDiffusionImageVariationPipeline.from_pretrained(
316
- "lambdalabs/sd-image-variations-diffusers", revision="v2.0"
317
- )
318
- pipe = pipe.to("cuda")
319
-
320
- url = "https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200"
321
-
322
- response = requests.get(url)
323
- image = Image.open(BytesIO(response.content)).convert("RGB")
324
-
325
- out = pipe(image, num_images_per_prompt=3, guidance_scale=15)
326
- out["images"][0].save("result.jpg")
327
- ```
328
- """
329
- # 0. Default height and width to unet
330
- height = height or self.unet.config.sample_size * self.vae_scale_factor
331
- width = width or self.unet.config.sample_size * self.vae_scale_factor
332
-
333
- # 1. Check inputs. Raise error if not correct
334
- self.check_inputs(image, height, width, callback_steps)
335
-
336
- # 2. Define call parameters
337
- if isinstance(image, PIL.Image.Image):
338
- batch_size = 1
339
- elif isinstance(image, list):
340
- batch_size = len(image)
341
- else:
342
- batch_size = image.shape[0]
343
- device = self._execution_device
344
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
345
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
346
- # corresponds to doing no classifier free guidance.
347
- do_classifier_free_guidance = guidance_scale > 1.0
348
-
349
- # 3. Encode input image
350
- image_embeddings = self._encode_image(image, device, num_images_per_prompt, do_classifier_free_guidance)
351
-
352
- # 4. Prepare timesteps
353
- self.scheduler.set_timesteps(num_inference_steps, device=device)
354
- timesteps = self.scheduler.timesteps
355
-
356
- # 5. Prepare latent variables
357
- num_channels_latents = self.unet.config.in_channels
358
- latents = self.prepare_latents(
359
- batch_size * num_images_per_prompt,
360
- num_channels_latents,
361
- height,
362
- width,
363
- image_embeddings.dtype,
364
- device,
365
- generator,
366
- latents,
367
- )
368
-
369
- # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
370
- extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
371
-
372
- # 7. Denoising loop
373
- num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
374
- with self.progress_bar(total=num_inference_steps) as progress_bar:
375
- for i, t in enumerate(timesteps):
376
- # expand the latents if we are doing classifier free guidance
377
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
378
- latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
379
-
380
- # predict the noise residual
381
- noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=image_embeddings).sample
382
-
383
- # perform guidance
384
- if do_classifier_free_guidance:
385
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
386
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
387
-
388
- # compute the previous noisy sample x_t -> x_t-1
389
- latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
390
-
391
- # call the callback, if provided
392
- if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
393
- progress_bar.update()
394
- if callback is not None and i % callback_steps == 0:
395
- callback(i, t, latents)
396
-
397
- if not output_type == "latent":
398
- image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
399
- image, has_nsfw_concept = self.run_safety_checker(image, device, image_embeddings.dtype)
400
- else:
401
- image = latents
402
- has_nsfw_concept = None
403
-
404
- if has_nsfw_concept is None:
405
- do_denormalize = [True] * image.shape[0]
406
- else:
407
- do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
408
-
409
- image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
410
-
411
- if not return_dict:
412
- return (image, has_nsfw_concept)
413
-
414
- return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/audioldm/__init__.py DELETED
File without changes
spaces/Andy1621/uniformer_image_segmentation/configs/_base_/datasets/pascal_voc12_aug.py DELETED
@@ -1,9 +0,0 @@
1
- _base_ = './pascal_voc12.py'
2
- # dataset settings
3
- data = dict(
4
- train=dict(
5
- ann_dir=['SegmentationClass', 'SegmentationClassAug'],
6
- split=[
7
- 'ImageSets/Segmentation/train.txt',
8
- 'ImageSets/Segmentation/aug.txt'
9
- ]))
 
 
 
 
 
 
 
 
 
 
spaces/AnnasBlackHat/Image-Downloader/app.py DELETED
@@ -1,70 +0,0 @@
1
- from cProfile import label
2
- from distutils.log import debug
3
- from random import choices
4
- import gradio as gr
5
- import re
6
- import requests
7
- import os
8
- import shutil
9
- import gofile
10
- import json
11
- import time
12
-
13
-
14
- try: os.mkdir('images')
15
- except: print('images dir might already exist...')
16
-
17
-
18
- def download_local(url):
19
- resp = requests.get(url, allow_redirects=True)
20
- filename, file_extension = os.path.splitext(url)
21
- filename = os.path.basename(url)
22
- if file_extension == '':
23
- filename = filename+'.jpg'
24
-
25
- filename = 'images/{}_{}'.format(int(time.time()), filename)
26
- with open(filename, 'wb') as handler:
27
- handler.write(resp.content)
28
- return filename
29
-
30
-
31
- def download(text, is_upload):
32
- pattern = '(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-&?=%.]+'
33
- print(text)
34
- print('upload?: ',is_upload)
35
-
36
- urls = re.findall(pattern, text)
37
- print(f'{len(urls)} urls')
38
-
39
- if len(urls) == 0 :
40
- return 'No Url Found'
41
-
42
- err_msgs = []
43
-
44
- #downloading all files
45
- print('downloading...')
46
- for i, url in enumerate(urls):
47
- try:
48
- download_local(url)
49
- if i % int(len(urls) * 0.1) == 0:
50
- print(f'>>> {i} files downloaded')
51
- except Exception as e :
52
- err_msgs.append(f'error downloading: {url} - {str(e)}')
53
-
54
- #zipping
55
- print('zipping images...')
56
- shutil.make_archive('images', 'zip', 'images')
57
-
58
- result = '{} link found, {}'.format(len(urls), " ,\n ".join(err_msgs))
59
-
60
- if is_upload == 'yes':
61
- print('uploading...')
62
- download_links = gofile.Gofile().upload(["images.zip"])
63
- result += f'download link : {" ".join(download_links)}'
64
-
65
- return "images.zip", result
66
-
67
- iface = gr.Interface(fn=download,
68
- inputs=["text",gr.Radio(choices=['yes','no'], label='Upload to Gofile? (slow process)')],
69
- outputs=["file", "text"])
70
- iface.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/ops/assign_score_withk.py DELETED
@@ -1,123 +0,0 @@
1
- from torch.autograd import Function
2
-
3
- from ..utils import ext_loader
4
-
5
- ext_module = ext_loader.load_ext(
6
- '_ext', ['assign_score_withk_forward', 'assign_score_withk_backward'])
7
-
8
-
9
- class AssignScoreWithK(Function):
10
- r"""Perform weighted sum to generate output features according to scores.
11
- Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/
12
- scene_seg/lib/paconv_lib/src/gpu>`_.
13
-
14
- This is a memory-efficient CUDA implementation of assign_scores operation,
15
- which first transform all point features with weight bank, then assemble
16
- neighbor features with ``knn_idx`` and perform weighted sum of ``scores``.
17
-
18
- See the `paper <https://arxiv.org/pdf/2103.14635.pdf>`_ appendix Sec. D for
19
- more detailed descriptions.
20
-
21
- Note:
22
- This implementation assumes using ``neighbor`` kernel input, which is
23
- (point_features - center_features, point_features).
24
- See https://github.com/CVMI-Lab/PAConv/blob/main/scene_seg/model/
25
- pointnet2/paconv.py#L128 for more details.
26
- """
27
-
28
- @staticmethod
29
- def forward(ctx,
30
- scores,
31
- point_features,
32
- center_features,
33
- knn_idx,
34
- aggregate='sum'):
35
- """
36
- Args:
37
- scores (torch.Tensor): (B, npoint, K, M), predicted scores to
38
- aggregate weight matrices in the weight bank.
39
- ``npoint`` is the number of sampled centers.
40
- ``K`` is the number of queried neighbors.
41
- ``M`` is the number of weight matrices in the weight bank.
42
- point_features (torch.Tensor): (B, N, M, out_dim)
43
- Pre-computed point features to be aggregated.
44
- center_features (torch.Tensor): (B, N, M, out_dim)
45
- Pre-computed center features to be aggregated.
46
- knn_idx (torch.Tensor): (B, npoint, K), index of sampled kNN.
47
- We assume the first idx in each row is the idx of the center.
48
- aggregate (str, optional): Aggregation method.
49
- Can be 'sum', 'avg' or 'max'. Defaults: 'sum'.
50
-
51
- Returns:
52
- torch.Tensor: (B, out_dim, npoint, K), the aggregated features.
53
- """
54
- agg = {'sum': 0, 'avg': 1, 'max': 2}
55
-
56
- B, N, M, out_dim = point_features.size()
57
- _, npoint, K, _ = scores.size()
58
-
59
- output = point_features.new_zeros((B, out_dim, npoint, K))
60
- ext_module.assign_score_withk_forward(
61
- point_features.contiguous(),
62
- center_features.contiguous(),
63
- scores.contiguous(),
64
- knn_idx.contiguous(),
65
- output,
66
- B=B,
67
- N0=N,
68
- N1=npoint,
69
- M=M,
70
- K=K,
71
- O=out_dim,
72
- aggregate=agg[aggregate])
73
-
74
- ctx.save_for_backward(output, point_features, center_features, scores,
75
- knn_idx)
76
- ctx.agg = agg[aggregate]
77
-
78
- return output
79
-
80
- @staticmethod
81
- def backward(ctx, grad_out):
82
- """
83
- Args:
84
- grad_out (torch.Tensor): (B, out_dim, npoint, K)
85
-
86
- Returns:
87
- grad_scores (torch.Tensor): (B, npoint, K, M)
88
- grad_point_features (torch.Tensor): (B, N, M, out_dim)
89
- grad_center_features (torch.Tensor): (B, N, M, out_dim)
90
- """
91
- _, point_features, center_features, scores, knn_idx = ctx.saved_tensors
92
-
93
- agg = ctx.agg
94
-
95
- B, N, M, out_dim = point_features.size()
96
- _, npoint, K, _ = scores.size()
97
-
98
- grad_point_features = point_features.new_zeros(point_features.shape)
99
- grad_center_features = center_features.new_zeros(center_features.shape)
100
- grad_scores = scores.new_zeros(scores.shape)
101
-
102
- ext_module.assign_score_withk_backward(
103
- grad_out.contiguous(),
104
- point_features.contiguous(),
105
- center_features.contiguous(),
106
- scores.contiguous(),
107
- knn_idx.contiguous(),
108
- grad_point_features,
109
- grad_center_features,
110
- grad_scores,
111
- B=B,
112
- N0=N,
113
- N1=npoint,
114
- M=M,
115
- K=K,
116
- O=out_dim,
117
- aggregate=agg)
118
-
119
- return grad_scores, grad_point_features, \
120
- grad_center_features, None, None
121
-
122
-
123
- assign_score_withk = AssignScoreWithK.apply
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Apex-X/ROOPOK/roop/ui.py DELETED
@@ -1,285 +0,0 @@
1
- import os
2
- import sys
3
- import webbrowser
4
- import customtkinter as ctk
5
- from tkinterdnd2 import TkinterDnD, DND_ALL
6
- from typing import Any, Callable, Tuple, Optional
7
- import cv2
8
- from PIL import Image, ImageOps
9
-
10
- import roop.globals
11
- import roop.metadata
12
- from roop.face_analyser import get_one_face
13
- from roop.capturer import get_video_frame, get_video_frame_total
14
- from roop.face_reference import get_face_reference, set_face_reference, clear_face_reference
15
- from roop.predictor import predict_frame, clear_predictor
16
- from roop.processors.frame.core import get_frame_processors_modules
17
- from roop.utilities import is_image, is_video, resolve_relative_path
18
-
19
- ROOT = None
20
- ROOT_HEIGHT = 700
21
- ROOT_WIDTH = 600
22
-
23
- PREVIEW = None
24
- PREVIEW_MAX_HEIGHT = 700
25
- PREVIEW_MAX_WIDTH = 1200
26
-
27
- RECENT_DIRECTORY_SOURCE = None
28
- RECENT_DIRECTORY_TARGET = None
29
- RECENT_DIRECTORY_OUTPUT = None
30
-
31
- preview_label = None
32
- preview_slider = None
33
- source_label = None
34
- target_label = None
35
- status_label = None
36
-
37
-
38
- # todo: remove by native support -> https://github.com/TomSchimansky/CustomTkinter/issues/934
39
- class CTk(ctk.CTk, TkinterDnD.DnDWrapper):
40
- def __init__(self, *args: Any, **kwargs: Any) -> None:
41
- super().__init__(*args, **kwargs)
42
- self.TkdndVersion = TkinterDnD._require(self)
43
-
44
-
45
- def init(start: Callable[[], None], destroy: Callable[[], None]) -> ctk.CTk:
46
- global ROOT, PREVIEW
47
-
48
- ROOT = create_root(start, destroy)
49
- PREVIEW = create_preview(ROOT)
50
-
51
- return ROOT
52
-
53
-
54
- def create_root(start: Callable[[], None], destroy: Callable[[], None]) -> ctk.CTk:
55
- global source_label, target_label, status_label
56
-
57
- ctk.deactivate_automatic_dpi_awareness()
58
- ctk.set_appearance_mode('system')
59
- ctk.set_default_color_theme(resolve_relative_path('ui.json'))
60
-
61
- root = CTk()
62
- root.minsize(ROOT_WIDTH, ROOT_HEIGHT)
63
- root.title(f'{roop.metadata.name} {roop.metadata.version}')
64
- root.configure()
65
- root.protocol('WM_DELETE_WINDOW', lambda: destroy())
66
-
67
- source_label = ctk.CTkLabel(root, text=None, fg_color=ctk.ThemeManager.theme.get('RoopDropArea').get('fg_color'))
68
- source_label.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.25)
69
- source_label.drop_target_register(DND_ALL)
70
- source_label.dnd_bind('<<Drop>>', lambda event: select_source_path(event.data))
71
- if roop.globals.source_path:
72
- select_source_path(roop.globals.source_path)
73
-
74
- target_label = ctk.CTkLabel(root, text=None, fg_color=ctk.ThemeManager.theme.get('RoopDropArea').get('fg_color'))
75
- target_label.place(relx=0.6, rely=0.1, relwidth=0.3, relheight=0.25)
76
- target_label.drop_target_register(DND_ALL)
77
- target_label.dnd_bind('<<Drop>>', lambda event: select_target_path(event.data))
78
- if roop.globals.target_path:
79
- select_target_path(roop.globals.target_path)
80
-
81
- source_button = ctk.CTkButton(root, text='Select a face', cursor='hand2', command=lambda: select_source_path())
82
- source_button.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.1)
83
-
84
- target_button = ctk.CTkButton(root, text='Select a target', cursor='hand2', command=lambda: select_target_path())
85
- target_button.place(relx=0.6, rely=0.4, relwidth=0.3, relheight=0.1)
86
-
87
- keep_fps_value = ctk.BooleanVar(value=roop.globals.keep_fps)
88
- keep_fps_checkbox = ctk.CTkSwitch(root, text='Keep target fps', variable=keep_fps_value, cursor='hand2', command=lambda: setattr(roop.globals, 'keep_fps', not roop.globals.keep_fps))
89
- keep_fps_checkbox.place(relx=0.1, rely=0.6)
90
-
91
- keep_frames_value = ctk.BooleanVar(value=roop.globals.keep_frames)
92
- keep_frames_switch = ctk.CTkSwitch(root, text='Keep temporary frames', variable=keep_frames_value, cursor='hand2', command=lambda: setattr(roop.globals, 'keep_frames', keep_frames_value.get()))
93
- keep_frames_switch.place(relx=0.1, rely=0.65)
94
-
95
- skip_audio_value = ctk.BooleanVar(value=roop.globals.skip_audio)
96
- skip_audio_switch = ctk.CTkSwitch(root, text='Skip target audio', variable=skip_audio_value, cursor='hand2', command=lambda: setattr(roop.globals, 'skip_audio', skip_audio_value.get()))
97
- skip_audio_switch.place(relx=0.6, rely=0.6)
98
-
99
- many_faces_value = ctk.BooleanVar(value=roop.globals.many_faces)
100
- many_faces_switch = ctk.CTkSwitch(root, text='Many faces', variable=many_faces_value, cursor='hand2', command=lambda: setattr(roop.globals, 'many_faces', many_faces_value.get()))
101
- many_faces_switch.place(relx=0.6, rely=0.65)
102
-
103
- start_button = ctk.CTkButton(root, text='Start', cursor='hand2', command=lambda: select_output_path(start))
104
- start_button.place(relx=0.15, rely=0.75, relwidth=0.2, relheight=0.05)
105
-
106
- stop_button = ctk.CTkButton(root, text='Destroy', cursor='hand2', command=lambda: destroy())
107
- stop_button.place(relx=0.4, rely=0.75, relwidth=0.2, relheight=0.05)
108
-
109
- preview_button = ctk.CTkButton(root, text='Preview', cursor='hand2', command=lambda: toggle_preview())
110
- preview_button.place(relx=0.65, rely=0.75, relwidth=0.2, relheight=0.05)
111
-
112
- status_label = ctk.CTkLabel(root, text=None, justify='center')
113
- status_label.place(relx=0.1, rely=0.9, relwidth=0.8)
114
-
115
- donate_label = ctk.CTkLabel(root, text='^_^ Donate to project ^_^', justify='center', cursor='hand2')
116
- donate_label.place(relx=0.1, rely=0.95, relwidth=0.8)
117
- donate_label.configure(text_color=ctk.ThemeManager.theme.get('RoopDonate').get('text_color'))
118
- donate_label.bind('<Button>', lambda event: webbrowser.open('https://github.com/sponsors/s0md3v'))
119
-
120
- return root
121
-
122
-
123
- def create_preview(parent: ctk.CTkToplevel) -> ctk.CTkToplevel:
124
- global preview_label, preview_slider
125
-
126
- preview = ctk.CTkToplevel(parent)
127
- preview.withdraw()
128
- preview.configure()
129
- preview.protocol('WM_DELETE_WINDOW', lambda: toggle_preview())
130
- preview.resizable(width=False, height=False)
131
-
132
- preview_label = ctk.CTkLabel(preview, text=None)
133
- preview_label.pack(fill='both', expand=True)
134
-
135
- preview_slider = ctk.CTkSlider(preview, from_=0, to=0, command=lambda frame_value: update_preview(frame_value))
136
-
137
- preview.bind('<Up>', lambda event: update_face_reference(1))
138
- preview.bind('<Down>', lambda event: update_face_reference(-1))
139
- return preview
140
-
141
-
142
- def update_status(text: str) -> None:
143
- status_label.configure(text=text)
144
- ROOT.update()
145
-
146
-
147
- def select_source_path(source_path: Optional[str] = None) -> None:
148
- global RECENT_DIRECTORY_SOURCE
149
-
150
- if PREVIEW:
151
- PREVIEW.withdraw()
152
- if source_path is None:
153
- source_path = ctk.filedialog.askopenfilename(title='select an source image', initialdir=RECENT_DIRECTORY_SOURCE)
154
- if is_image(source_path):
155
- roop.globals.source_path = source_path
156
- RECENT_DIRECTORY_SOURCE = os.path.dirname(roop.globals.source_path)
157
- image = render_image_preview(roop.globals.source_path, (200, 200))
158
- source_label.configure(image=image)
159
- else:
160
- roop.globals.source_path = None
161
- source_label.configure(image=None)
162
-
163
-
164
- def select_target_path(target_path: Optional[str] = None) -> None:
165
- global RECENT_DIRECTORY_TARGET
166
-
167
- if PREVIEW:
168
- PREVIEW.withdraw()
169
- clear_face_reference()
170
- if target_path is None:
171
- target_path = ctk.filedialog.askopenfilename(title='select an target image or video', initialdir=RECENT_DIRECTORY_TARGET)
172
- if is_image(target_path):
173
- roop.globals.target_path = target_path
174
- RECENT_DIRECTORY_TARGET = os.path.dirname(roop.globals.target_path)
175
- image = render_image_preview(roop.globals.target_path, (200, 200))
176
- target_label.configure(image=image)
177
- elif is_video(target_path):
178
- roop.globals.target_path = target_path
179
- RECENT_DIRECTORY_TARGET = os.path.dirname(roop.globals.target_path)
180
- video_frame = render_video_preview(target_path, (200, 200))
181
- target_label.configure(image=video_frame)
182
- else:
183
- roop.globals.target_path = None
184
- target_label.configure(image=None)
185
-
186
-
187
- def select_output_path(start: Callable[[], None]) -> None:
188
- global RECENT_DIRECTORY_OUTPUT
189
-
190
- if is_image(roop.globals.target_path):
191
- output_path = ctk.filedialog.asksaveasfilename(title='save image output file', defaultextension='.png', initialfile='output.png', initialdir=RECENT_DIRECTORY_OUTPUT)
192
- elif is_video(roop.globals.target_path):
193
- output_path = ctk.filedialog.asksaveasfilename(title='save video output file', defaultextension='.mp4', initialfile='output.mp4', initialdir=RECENT_DIRECTORY_OUTPUT)
194
- else:
195
- output_path = None
196
- if output_path:
197
- roop.globals.output_path = output_path
198
- RECENT_DIRECTORY_OUTPUT = os.path.dirname(roop.globals.output_path)
199
- start()
200
-
201
-
202
- def render_image_preview(image_path: str, size: Tuple[int, int]) -> ctk.CTkImage:
203
- image = Image.open(image_path)
204
- if size:
205
- image = ImageOps.fit(image, size, Image.LANCZOS)
206
- return ctk.CTkImage(image, size=image.size)
207
-
208
-
209
- def render_video_preview(video_path: str, size: Tuple[int, int], frame_number: int = 0) -> ctk.CTkImage:
210
- capture = cv2.VideoCapture(video_path)
211
- if frame_number:
212
- capture.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
213
- has_frame, frame = capture.read()
214
- if has_frame:
215
- image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
216
- if size:
217
- image = ImageOps.fit(image, size, Image.LANCZOS)
218
- return ctk.CTkImage(image, size=image.size)
219
- capture.release()
220
- cv2.destroyAllWindows()
221
-
222
-
223
- def toggle_preview() -> None:
224
- if PREVIEW.state() == 'normal':
225
- PREVIEW.unbind('<Right>')
226
- PREVIEW.unbind('<Left>')
227
- PREVIEW.withdraw()
228
- clear_predictor()
229
- elif roop.globals.source_path and roop.globals.target_path:
230
- init_preview()
231
- update_preview(roop.globals.reference_frame_number)
232
- PREVIEW.deiconify()
233
-
234
-
235
- def init_preview() -> None:
236
- PREVIEW.title('Preview [ ↕ Reference face ]')
237
- if is_image(roop.globals.target_path):
238
- preview_slider.pack_forget()
239
- if is_video(roop.globals.target_path):
240
- video_frame_total = get_video_frame_total(roop.globals.target_path)
241
- if video_frame_total > 0:
242
- PREVIEW.title('Preview [ ↕ Reference face ] [ ↔ Frame number ]')
243
- PREVIEW.bind('<Right>', lambda event: update_frame(int(video_frame_total / 20)))
244
- PREVIEW.bind('<Left>', lambda event: update_frame(int(video_frame_total / -20)))
245
- preview_slider.configure(to=video_frame_total)
246
- preview_slider.pack(fill='x')
247
- preview_slider.set(roop.globals.reference_frame_number)
248
-
249
-
250
- def update_preview(frame_number: int = 0) -> None:
251
- if roop.globals.source_path and roop.globals.target_path:
252
- temp_frame = get_video_frame(roop.globals.target_path, frame_number)
253
- if predict_frame(temp_frame):
254
- sys.exit()
255
- source_face = get_one_face(cv2.imread(roop.globals.source_path))
256
- if not get_face_reference():
257
- reference_frame = get_video_frame(roop.globals.target_path, roop.globals.reference_frame_number)
258
- reference_face = get_one_face(reference_frame, roop.globals.reference_face_position)
259
- set_face_reference(reference_face)
260
- else:
261
- reference_face = get_face_reference()
262
- for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
263
- temp_frame = frame_processor.process_frame(
264
- source_face,
265
- reference_face,
266
- temp_frame
267
- )
268
- image = Image.fromarray(cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB))
269
- image = ImageOps.contain(image, (PREVIEW_MAX_WIDTH, PREVIEW_MAX_HEIGHT), Image.LANCZOS)
270
- image = ctk.CTkImage(image, size=image.size)
271
- preview_label.configure(image=image)
272
-
273
-
274
- def update_face_reference(steps: int) -> None:
275
- clear_face_reference()
276
- reference_frame_number = int(preview_slider.get())
277
- roop.globals.reference_face_position += steps
278
- roop.globals.reference_frame_number = reference_frame_number
279
- update_preview(reference_frame_number)
280
-
281
-
282
- def update_frame(steps: int) -> None:
283
- frame_number = preview_slider.get() + steps
284
- preview_slider.set(frame_number)
285
- update_preview(preview_slider.get())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Apex-X/nono/roop/__init__.py DELETED
File without changes
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/command/install_headers.py DELETED
@@ -1,45 +0,0 @@
1
- """distutils.command.install_headers
2
-
3
- Implements the Distutils 'install_headers' command, to install C/C++ header
4
- files to the Python include directory."""
5
-
6
- from distutils.core import Command
7
-
8
-
9
- # XXX force is never used
10
- class install_headers(Command):
11
-
12
- description = "install C/C++ header files"
13
-
14
- user_options = [
15
- ('install-dir=', 'd', "directory to install header files to"),
16
- ('force', 'f', "force installation (overwrite existing files)"),
17
- ]
18
-
19
- boolean_options = ['force']
20
-
21
- def initialize_options(self):
22
- self.install_dir = None
23
- self.force = 0
24
- self.outfiles = []
25
-
26
- def finalize_options(self):
27
- self.set_undefined_options(
28
- 'install', ('install_headers', 'install_dir'), ('force', 'force')
29
- )
30
-
31
- def run(self):
32
- headers = self.distribution.headers
33
- if not headers:
34
- return
35
-
36
- self.mkpath(self.install_dir)
37
- for header in headers:
38
- (out, _) = self.copy_file(header, self.install_dir)
39
- self.outfiles.append(out)
40
-
41
- def get_inputs(self):
42
- return self.distribution.headers or []
43
-
44
- def get_outputs(self):
45
- return self.outfiles
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_distutils/msvccompiler.py DELETED
@@ -1,695 +0,0 @@
1
- """distutils.msvccompiler
2
-
3
- Contains MSVCCompiler, an implementation of the abstract CCompiler class
4
- for the Microsoft Visual Studio.
5
- """
6
-
7
- # Written by Perry Stoll
8
- # hacked by Robin Becker and Thomas Heller to do a better job of
9
- # finding DevStudio (through the registry)
10
-
11
- import sys
12
- import os
13
- import warnings
14
- from distutils.errors import (
15
- DistutilsExecError,
16
- DistutilsPlatformError,
17
- CompileError,
18
- LibError,
19
- LinkError,
20
- )
21
- from distutils.ccompiler import CCompiler, gen_lib_options
22
- from distutils import log
23
-
24
- _can_read_reg = False
25
- try:
26
- import winreg
27
-
28
- _can_read_reg = True
29
- hkey_mod = winreg
30
-
31
- RegOpenKeyEx = winreg.OpenKeyEx
32
- RegEnumKey = winreg.EnumKey
33
- RegEnumValue = winreg.EnumValue
34
- RegError = winreg.error
35
-
36
- except ImportError:
37
- try:
38
- import win32api
39
- import win32con
40
-
41
- _can_read_reg = True
42
- hkey_mod = win32con
43
-
44
- RegOpenKeyEx = win32api.RegOpenKeyEx
45
- RegEnumKey = win32api.RegEnumKey
46
- RegEnumValue = win32api.RegEnumValue
47
- RegError = win32api.error
48
- except ImportError:
49
- log.info(
50
- "Warning: Can't read registry to find the "
51
- "necessary compiler setting\n"
52
- "Make sure that Python modules winreg, "
53
- "win32api or win32con are installed."
54
- )
55
- pass
56
-
57
- if _can_read_reg:
58
- HKEYS = (
59
- hkey_mod.HKEY_USERS,
60
- hkey_mod.HKEY_CURRENT_USER,
61
- hkey_mod.HKEY_LOCAL_MACHINE,
62
- hkey_mod.HKEY_CLASSES_ROOT,
63
- )
64
-
65
-
66
- warnings.warn(
67
- "msvccompiler is deprecated and slated to be removed "
68
- "in the future. Please discontinue use or file an issue "
69
- "with pypa/distutils describing your use case.",
70
- DeprecationWarning,
71
- )
72
-
73
-
74
- def read_keys(base, key):
75
- """Return list of registry keys."""
76
- try:
77
- handle = RegOpenKeyEx(base, key)
78
- except RegError:
79
- return None
80
- L = []
81
- i = 0
82
- while True:
83
- try:
84
- k = RegEnumKey(handle, i)
85
- except RegError:
86
- break
87
- L.append(k)
88
- i += 1
89
- return L
90
-
91
-
92
- def read_values(base, key):
93
- """Return dict of registry keys and values.
94
-
95
- All names are converted to lowercase.
96
- """
97
- try:
98
- handle = RegOpenKeyEx(base, key)
99
- except RegError:
100
- return None
101
- d = {}
102
- i = 0
103
- while True:
104
- try:
105
- name, value, type = RegEnumValue(handle, i)
106
- except RegError:
107
- break
108
- name = name.lower()
109
- d[convert_mbcs(name)] = convert_mbcs(value)
110
- i += 1
111
- return d
112
-
113
-
114
- def convert_mbcs(s):
115
- dec = getattr(s, "decode", None)
116
- if dec is not None:
117
- try:
118
- s = dec("mbcs")
119
- except UnicodeError:
120
- pass
121
- return s
122
-
123
-
124
- class MacroExpander:
125
- def __init__(self, version):
126
- self.macros = {}
127
- self.load_macros(version)
128
-
129
- def set_macro(self, macro, path, key):
130
- for base in HKEYS:
131
- d = read_values(base, path)
132
- if d:
133
- self.macros["$(%s)" % macro] = d[key]
134
- break
135
-
136
- def load_macros(self, version):
137
- vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
138
- self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir")
139
- self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir")
140
- net = r"Software\Microsoft\.NETFramework"
141
- self.set_macro("FrameworkDir", net, "installroot")
142
- try:
143
- if version > 7.0:
144
- self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
145
- else:
146
- self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
147
- except KeyError:
148
- raise DistutilsPlatformError(
149
- """Python was built with Visual Studio 2003;
150
- extensions must be built with a compiler than can generate compatible binaries.
151
- Visual Studio 2003 was not found on this system. If you have Cygwin installed,
152
- you can try compiling with MingW32, by passing "-c mingw32" to setup.py."""
153
- )
154
-
155
- p = r"Software\Microsoft\NET Framework Setup\Product"
156
- for base in HKEYS:
157
- try:
158
- h = RegOpenKeyEx(base, p)
159
- except RegError:
160
- continue
161
- key = RegEnumKey(h, 0)
162
- d = read_values(base, r"{}\{}".format(p, key))
163
- self.macros["$(FrameworkVersion)"] = d["version"]
164
-
165
- def sub(self, s):
166
- for k, v in self.macros.items():
167
- s = s.replace(k, v)
168
- return s
169
-
170
-
171
- def get_build_version():
172
- """Return the version of MSVC that was used to build Python.
173
-
174
- For Python 2.3 and up, the version number is included in
175
- sys.version. For earlier versions, assume the compiler is MSVC 6.
176
- """
177
- prefix = "MSC v."
178
- i = sys.version.find(prefix)
179
- if i == -1:
180
- return 6
181
- i = i + len(prefix)
182
- s, rest = sys.version[i:].split(" ", 1)
183
- majorVersion = int(s[:-2]) - 6
184
- if majorVersion >= 13:
185
- # v13 was skipped and should be v14
186
- majorVersion += 1
187
- minorVersion = int(s[2:3]) / 10.0
188
- # I don't think paths are affected by minor version in version 6
189
- if majorVersion == 6:
190
- minorVersion = 0
191
- if majorVersion >= 6:
192
- return majorVersion + minorVersion
193
- # else we don't know what version of the compiler this is
194
- return None
195
-
196
-
197
- def get_build_architecture():
198
- """Return the processor architecture.
199
-
200
- Possible results are "Intel" or "AMD64".
201
- """
202
-
203
- prefix = " bit ("
204
- i = sys.version.find(prefix)
205
- if i == -1:
206
- return "Intel"
207
- j = sys.version.find(")", i)
208
- return sys.version[i + len(prefix) : j]
209
-
210
-
211
- def normalize_and_reduce_paths(paths):
212
- """Return a list of normalized paths with duplicates removed.
213
-
214
- The current order of paths is maintained.
215
- """
216
- # Paths are normalized so things like: /a and /a/ aren't both preserved.
217
- reduced_paths = []
218
- for p in paths:
219
- np = os.path.normpath(p)
220
- # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
221
- if np not in reduced_paths:
222
- reduced_paths.append(np)
223
- return reduced_paths
224
-
225
-
226
- class MSVCCompiler(CCompiler):
227
- """Concrete class that implements an interface to Microsoft Visual C++,
228
- as defined by the CCompiler abstract class."""
229
-
230
- compiler_type = 'msvc'
231
-
232
- # Just set this so CCompiler's constructor doesn't barf. We currently
233
- # don't use the 'set_executables()' bureaucracy provided by CCompiler,
234
- # as it really isn't necessary for this sort of single-compiler class.
235
- # Would be nice to have a consistent interface with UnixCCompiler,
236
- # though, so it's worth thinking about.
237
- executables = {}
238
-
239
- # Private class data (need to distinguish C from C++ source for compiler)
240
- _c_extensions = ['.c']
241
- _cpp_extensions = ['.cc', '.cpp', '.cxx']
242
- _rc_extensions = ['.rc']
243
- _mc_extensions = ['.mc']
244
-
245
- # Needed for the filename generation methods provided by the
246
- # base class, CCompiler.
247
- src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
248
- res_extension = '.res'
249
- obj_extension = '.obj'
250
- static_lib_extension = '.lib'
251
- shared_lib_extension = '.dll'
252
- static_lib_format = shared_lib_format = '%s%s'
253
- exe_extension = '.exe'
254
-
255
- def __init__(self, verbose=0, dry_run=0, force=0):
256
- super().__init__(verbose, dry_run, force)
257
- self.__version = get_build_version()
258
- self.__arch = get_build_architecture()
259
- if self.__arch == "Intel":
260
- # x86
261
- if self.__version >= 7:
262
- self.__root = r"Software\Microsoft\VisualStudio"
263
- self.__macros = MacroExpander(self.__version)
264
- else:
265
- self.__root = r"Software\Microsoft\Devstudio"
266
- self.__product = "Visual Studio version %s" % self.__version
267
- else:
268
- # Win64. Assume this was built with the platform SDK
269
- self.__product = "Microsoft SDK compiler %s" % (self.__version + 6)
270
-
271
- self.initialized = False
272
-
273
- def initialize(self):
274
- self.__paths = []
275
- if (
276
- "DISTUTILS_USE_SDK" in os.environ
277
- and "MSSdk" in os.environ
278
- and self.find_exe("cl.exe")
279
- ):
280
- # Assume that the SDK set up everything alright; don't try to be
281
- # smarter
282
- self.cc = "cl.exe"
283
- self.linker = "link.exe"
284
- self.lib = "lib.exe"
285
- self.rc = "rc.exe"
286
- self.mc = "mc.exe"
287
- else:
288
- self.__paths = self.get_msvc_paths("path")
289
-
290
- if len(self.__paths) == 0:
291
- raise DistutilsPlatformError(
292
- "Python was built with %s, "
293
- "and extensions need to be built with the same "
294
- "version of the compiler, but it isn't installed." % self.__product
295
- )
296
-
297
- self.cc = self.find_exe("cl.exe")
298
- self.linker = self.find_exe("link.exe")
299
- self.lib = self.find_exe("lib.exe")
300
- self.rc = self.find_exe("rc.exe") # resource compiler
301
- self.mc = self.find_exe("mc.exe") # message compiler
302
- self.set_path_env_var('lib')
303
- self.set_path_env_var('include')
304
-
305
- # extend the MSVC path with the current path
306
- try:
307
- for p in os.environ['path'].split(';'):
308
- self.__paths.append(p)
309
- except KeyError:
310
- pass
311
- self.__paths = normalize_and_reduce_paths(self.__paths)
312
- os.environ['path'] = ";".join(self.__paths)
313
-
314
- self.preprocess_options = None
315
- if self.__arch == "Intel":
316
- self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GX', '/DNDEBUG']
317
- self.compile_options_debug = [
318
- '/nologo',
319
- '/Od',
320
- '/MDd',
321
- '/W3',
322
- '/GX',
323
- '/Z7',
324
- '/D_DEBUG',
325
- ]
326
- else:
327
- # Win64
328
- self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG']
329
- self.compile_options_debug = [
330
- '/nologo',
331
- '/Od',
332
- '/MDd',
333
- '/W3',
334
- '/GS-',
335
- '/Z7',
336
- '/D_DEBUG',
337
- ]
338
-
339
- self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
340
- if self.__version >= 7:
341
- self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG']
342
- else:
343
- self.ldflags_shared_debug = [
344
- '/DLL',
345
- '/nologo',
346
- '/INCREMENTAL:no',
347
- '/pdb:None',
348
- '/DEBUG',
349
- ]
350
- self.ldflags_static = ['/nologo']
351
-
352
- self.initialized = True
353
-
354
- # -- Worker methods ------------------------------------------------
355
-
356
- def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
357
- # Copied from ccompiler.py, extended to return .res as 'object'-file
358
- # for .rc input file
359
- if output_dir is None:
360
- output_dir = ''
361
- obj_names = []
362
- for src_name in source_filenames:
363
- (base, ext) = os.path.splitext(src_name)
364
- base = os.path.splitdrive(base)[1] # Chop off the drive
365
- base = base[os.path.isabs(base) :] # If abs, chop off leading /
366
- if ext not in self.src_extensions:
367
- # Better to raise an exception instead of silently continuing
368
- # and later complain about sources and targets having
369
- # different lengths
370
- raise CompileError("Don't know how to compile %s" % src_name)
371
- if strip_dir:
372
- base = os.path.basename(base)
373
- if ext in self._rc_extensions:
374
- obj_names.append(os.path.join(output_dir, base + self.res_extension))
375
- elif ext in self._mc_extensions:
376
- obj_names.append(os.path.join(output_dir, base + self.res_extension))
377
- else:
378
- obj_names.append(os.path.join(output_dir, base + self.obj_extension))
379
- return obj_names
380
-
381
- def compile( # noqa: C901
382
- self,
383
- sources,
384
- output_dir=None,
385
- macros=None,
386
- include_dirs=None,
387
- debug=0,
388
- extra_preargs=None,
389
- extra_postargs=None,
390
- depends=None,
391
- ):
392
-
393
- if not self.initialized:
394
- self.initialize()
395
- compile_info = self._setup_compile(
396
- output_dir, macros, include_dirs, sources, depends, extra_postargs
397
- )
398
- macros, objects, extra_postargs, pp_opts, build = compile_info
399
-
400
- compile_opts = extra_preargs or []
401
- compile_opts.append('/c')
402
- if debug:
403
- compile_opts.extend(self.compile_options_debug)
404
- else:
405
- compile_opts.extend(self.compile_options)
406
-
407
- for obj in objects:
408
- try:
409
- src, ext = build[obj]
410
- except KeyError:
411
- continue
412
- if debug:
413
- # pass the full pathname to MSVC in debug mode,
414
- # this allows the debugger to find the source file
415
- # without asking the user to browse for it
416
- src = os.path.abspath(src)
417
-
418
- if ext in self._c_extensions:
419
- input_opt = "/Tc" + src
420
- elif ext in self._cpp_extensions:
421
- input_opt = "/Tp" + src
422
- elif ext in self._rc_extensions:
423
- # compile .RC to .RES file
424
- input_opt = src
425
- output_opt = "/fo" + obj
426
- try:
427
- self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt])
428
- except DistutilsExecError as msg:
429
- raise CompileError(msg)
430
- continue
431
- elif ext in self._mc_extensions:
432
- # Compile .MC to .RC file to .RES file.
433
- # * '-h dir' specifies the directory for the
434
- # generated include file
435
- # * '-r dir' specifies the target directory of the
436
- # generated RC file and the binary message resource
437
- # it includes
438
- #
439
- # For now (since there are no options to change this),
440
- # we use the source-directory for the include file and
441
- # the build directory for the RC file and message
442
- # resources. This works at least for win32all.
443
- h_dir = os.path.dirname(src)
444
- rc_dir = os.path.dirname(obj)
445
- try:
446
- # first compile .MC to .RC and .H file
447
- self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src])
448
- base, _ = os.path.splitext(os.path.basename(src))
449
- rc_file = os.path.join(rc_dir, base + '.rc')
450
- # then compile .RC to .RES file
451
- self.spawn([self.rc] + ["/fo" + obj] + [rc_file])
452
-
453
- except DistutilsExecError as msg:
454
- raise CompileError(msg)
455
- continue
456
- else:
457
- # how to handle this file?
458
- raise CompileError(
459
- "Don't know how to compile {} to {}".format(src, obj)
460
- )
461
-
462
- output_opt = "/Fo" + obj
463
- try:
464
- self.spawn(
465
- [self.cc]
466
- + compile_opts
467
- + pp_opts
468
- + [input_opt, output_opt]
469
- + extra_postargs
470
- )
471
- except DistutilsExecError as msg:
472
- raise CompileError(msg)
473
-
474
- return objects
475
-
476
- def create_static_lib(
477
- self, objects, output_libname, output_dir=None, debug=0, target_lang=None
478
- ):
479
-
480
- if not self.initialized:
481
- self.initialize()
482
- (objects, output_dir) = self._fix_object_args(objects, output_dir)
483
- output_filename = self.library_filename(output_libname, output_dir=output_dir)
484
-
485
- if self._need_link(objects, output_filename):
486
- lib_args = objects + ['/OUT:' + output_filename]
487
- if debug:
488
- pass # XXX what goes here?
489
- try:
490
- self.spawn([self.lib] + lib_args)
491
- except DistutilsExecError as msg:
492
- raise LibError(msg)
493
- else:
494
- log.debug("skipping %s (up-to-date)", output_filename)
495
-
496
- def link( # noqa: C901
497
- self,
498
- target_desc,
499
- objects,
500
- output_filename,
501
- output_dir=None,
502
- libraries=None,
503
- library_dirs=None,
504
- runtime_library_dirs=None,
505
- export_symbols=None,
506
- debug=0,
507
- extra_preargs=None,
508
- extra_postargs=None,
509
- build_temp=None,
510
- target_lang=None,
511
- ):
512
-
513
- if not self.initialized:
514
- self.initialize()
515
- (objects, output_dir) = self._fix_object_args(objects, output_dir)
516
- fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
517
- (libraries, library_dirs, runtime_library_dirs) = fixed_args
518
-
519
- if runtime_library_dirs:
520
- self.warn(
521
- "I don't know what to do with 'runtime_library_dirs': "
522
- + str(runtime_library_dirs)
523
- )
524
-
525
- lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
526
- if output_dir is not None:
527
- output_filename = os.path.join(output_dir, output_filename)
528
-
529
- if self._need_link(objects, output_filename):
530
- if target_desc == CCompiler.EXECUTABLE:
531
- if debug:
532
- ldflags = self.ldflags_shared_debug[1:]
533
- else:
534
- ldflags = self.ldflags_shared[1:]
535
- else:
536
- if debug:
537
- ldflags = self.ldflags_shared_debug
538
- else:
539
- ldflags = self.ldflags_shared
540
-
541
- export_opts = []
542
- for sym in export_symbols or []:
543
- export_opts.append("/EXPORT:" + sym)
544
-
545
- ld_args = (
546
- ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
547
- )
548
-
549
- # The MSVC linker generates .lib and .exp files, which cannot be
550
- # suppressed by any linker switches. The .lib files may even be
551
- # needed! Make sure they are generated in the temporary build
552
- # directory. Since they have different names for debug and release
553
- # builds, they can go into the same directory.
554
- if export_symbols is not None:
555
- (dll_name, dll_ext) = os.path.splitext(
556
- os.path.basename(output_filename)
557
- )
558
- implib_file = os.path.join(
559
- os.path.dirname(objects[0]), self.library_filename(dll_name)
560
- )
561
- ld_args.append('/IMPLIB:' + implib_file)
562
-
563
- if extra_preargs:
564
- ld_args[:0] = extra_preargs
565
- if extra_postargs:
566
- ld_args.extend(extra_postargs)
567
-
568
- self.mkpath(os.path.dirname(output_filename))
569
- try:
570
- self.spawn([self.linker] + ld_args)
571
- except DistutilsExecError as msg:
572
- raise LinkError(msg)
573
-
574
- else:
575
- log.debug("skipping %s (up-to-date)", output_filename)
576
-
577
- # -- Miscellaneous methods -----------------------------------------
578
- # These are all used by the 'gen_lib_options() function, in
579
- # ccompiler.py.
580
-
581
- def library_dir_option(self, dir):
582
- return "/LIBPATH:" + dir
583
-
584
- def runtime_library_dir_option(self, dir):
585
- raise DistutilsPlatformError(
586
- "don't know how to set runtime library search path for MSVC++"
587
- )
588
-
589
- def library_option(self, lib):
590
- return self.library_filename(lib)
591
-
592
- def find_library_file(self, dirs, lib, debug=0):
593
- # Prefer a debugging library if found (and requested), but deal
594
- # with it if we don't have one.
595
- if debug:
596
- try_names = [lib + "_d", lib]
597
- else:
598
- try_names = [lib]
599
- for dir in dirs:
600
- for name in try_names:
601
- libfile = os.path.join(dir, self.library_filename(name))
602
- if os.path.exists(libfile):
603
- return libfile
604
- else:
605
- # Oops, didn't find it in *any* of 'dirs'
606
- return None
607
-
608
- # Helper methods for using the MSVC registry settings
609
-
610
- def find_exe(self, exe):
611
- """Return path to an MSVC executable program.
612
-
613
- Tries to find the program in several places: first, one of the
614
- MSVC program search paths from the registry; next, the directories
615
- in the PATH environment variable. If any of those work, return an
616
- absolute path that is known to exist. If none of them work, just
617
- return the original program name, 'exe'.
618
- """
619
- for p in self.__paths:
620
- fn = os.path.join(os.path.abspath(p), exe)
621
- if os.path.isfile(fn):
622
- return fn
623
-
624
- # didn't find it; try existing path
625
- for p in os.environ['Path'].split(';'):
626
- fn = os.path.join(os.path.abspath(p), exe)
627
- if os.path.isfile(fn):
628
- return fn
629
-
630
- return exe
631
-
632
- def get_msvc_paths(self, path, platform='x86'):
633
- """Get a list of devstudio directories (include, lib or path).
634
-
635
- Return a list of strings. The list will be empty if unable to
636
- access the registry or appropriate registry keys not found.
637
- """
638
- if not _can_read_reg:
639
- return []
640
-
641
- path = path + " dirs"
642
- if self.__version >= 7:
643
- key = r"{}\{:0.1f}\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories".format(
644
- self.__root,
645
- self.__version,
646
- )
647
- else:
648
- key = (
649
- r"%s\6.0\Build System\Components\Platforms"
650
- r"\Win32 (%s)\Directories" % (self.__root, platform)
651
- )
652
-
653
- for base in HKEYS:
654
- d = read_values(base, key)
655
- if d:
656
- if self.__version >= 7:
657
- return self.__macros.sub(d[path]).split(";")
658
- else:
659
- return d[path].split(";")
660
- # MSVC 6 seems to create the registry entries we need only when
661
- # the GUI is run.
662
- if self.__version == 6:
663
- for base in HKEYS:
664
- if read_values(base, r"%s\6.0" % self.__root) is not None:
665
- self.warn(
666
- "It seems you have Visual Studio 6 installed, "
667
- "but the expected registry settings are not present.\n"
668
- "You must at least run the Visual Studio GUI once "
669
- "so that these entries are created."
670
- )
671
- break
672
- return []
673
-
674
- def set_path_env_var(self, name):
675
- """Set environment variable 'name' to an MSVC path type value.
676
-
677
- This is equivalent to a SET command prior to execution of spawned
678
- commands.
679
- """
680
-
681
- if name == "lib":
682
- p = self.get_msvc_paths("library")
683
- else:
684
- p = self.get_msvc_paths(name)
685
- if p:
686
- os.environ[name] = ';'.join(p)
687
-
688
-
689
- if get_build_version() >= 8.0:
690
- log.debug("Importing new compiler from distutils.msvc9compiler")
691
- OldMSVCCompiler = MSVCCompiler
692
- from distutils.msvc9compiler import MSVCCompiler
693
-
694
- # get_build_architecture not really relevant now we support cross-compile
695
- from distutils.msvc9compiler import MacroExpander # noqa: F811
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/install_scripts.py DELETED
@@ -1,70 +0,0 @@
1
- from distutils import log
2
- import distutils.command.install_scripts as orig
3
- from distutils.errors import DistutilsModuleError
4
- import os
5
- import sys
6
-
7
- from pkg_resources import Distribution, PathMetadata
8
- from .._path import ensure_directory
9
-
10
-
11
- class install_scripts(orig.install_scripts):
12
- """Do normal script install, plus any egg_info wrapper scripts"""
13
-
14
- def initialize_options(self):
15
- orig.install_scripts.initialize_options(self)
16
- self.no_ep = False
17
-
18
- def run(self):
19
- import setuptools.command.easy_install as ei
20
-
21
- self.run_command("egg_info")
22
- if self.distribution.scripts:
23
- orig.install_scripts.run(self) # run first to set up self.outfiles
24
- else:
25
- self.outfiles = []
26
- if self.no_ep:
27
- # don't install entry point scripts into .egg file!
28
- return
29
-
30
- ei_cmd = self.get_finalized_command("egg_info")
31
- dist = Distribution(
32
- ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
33
- ei_cmd.egg_name, ei_cmd.egg_version,
34
- )
35
- bs_cmd = self.get_finalized_command('build_scripts')
36
- exec_param = getattr(bs_cmd, 'executable', None)
37
- try:
38
- bw_cmd = self.get_finalized_command("bdist_wininst")
39
- is_wininst = getattr(bw_cmd, '_is_running', False)
40
- except (ImportError, DistutilsModuleError):
41
- is_wininst = False
42
- writer = ei.ScriptWriter
43
- if is_wininst:
44
- exec_param = "python.exe"
45
- writer = ei.WindowsScriptWriter
46
- if exec_param == sys.executable:
47
- # In case the path to the Python executable contains a space, wrap
48
- # it so it's not split up.
49
- exec_param = [exec_param]
50
- # resolve the writer to the environment
51
- writer = writer.best()
52
- cmd = writer.command_spec_class.best().from_param(exec_param)
53
- for args in writer.get_args(dist, cmd.as_header()):
54
- self.write_script(*args)
55
-
56
- def write_script(self, script_name, contents, mode="t", *ignored):
57
- """Write an executable file to the scripts directory"""
58
- from setuptools.command.easy_install import chmod, current_umask
59
-
60
- log.info("Installing %s script to %s", script_name, self.install_dir)
61
- target = os.path.join(self.install_dir, script_name)
62
- self.outfiles.append(target)
63
-
64
- mask = current_umask()
65
- if not self.dry_run:
66
- ensure_directory(target)
67
- f = open(target, "w" + mode)
68
- f.write(contents)
69
- f.close()
70
- chmod(target, 0o777 - mask)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Avator/gradio-hugging-face/README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Gradio Hugging Face
3
- emoji: 😻
4
- colorFrom: blue
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 3.0.11
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Banbri/zcvzcv/src/app/interface/progress/progress-bar.tsx DELETED
@@ -1,57 +0,0 @@
1
- "use client"
2
-
3
- import { CircularProgressbar, buildStyles } from "react-circular-progressbar"
4
- import "react-circular-progressbar/dist/styles.css"
5
-
6
- export function ProgressBar ({
7
- className,
8
- progressPercentage,
9
- text
10
- }: {
11
- className?: string
12
- progressPercentage?: number
13
- text?: string
14
- }) {
15
- return (
16
- <div className={className}>
17
- <CircularProgressbar
18
- // doc: https://www.npmjs.com/package/react-circular-progressbar
19
-
20
- value={progressPercentage || 0}
21
-
22
- // Text to display inside progressbar. Default: ''.
23
- text={text || ""}
24
-
25
- // Width of circular line relative to total width of component, a value from 0-100. Default: 8.
26
- strokeWidth={8}
27
-
28
-
29
- // As a convenience, you can use buildStyles to configure the most common style changes:
30
-
31
- styles={buildStyles({
32
- // Rotation of path and trail, in number of turns (0-1)
33
- rotation: 0,
34
-
35
- // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
36
- strokeLinecap: 'round',
37
-
38
- // Text size
39
- textSize: '20px',
40
-
41
- // How long animation takes to go from one percentage to another, in seconds
42
- pathTransitionDuration: 0.1,
43
-
44
- // Can specify path transition in more detail, or remove it entirely
45
- // pathTransition: 'none',
46
-
47
- // Colors
48
- // pathColor: `rgba(62, 152, 199, ${percentage / 100})`,
49
- textColor: '#f88',
50
- trailColor: '#d6d6d6',
51
- backgroundColor: '#3e98c7',
52
- })}
53
-
54
- />
55
- </div>
56
- )
57
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Autobs Simulador Indonesia Librea Descargar 4k.md DELETED
@@ -1,91 +0,0 @@
1
- <br />
2
- <h1>Simulador de autobús Indonesia librea Descargar 4K: Cómo personalizar su autobús con impresionantes diseños</h1>
3
- <p>¿Te encanta conducir autobuses en entornos indonesios realistas y auténticos? ¿Quieres hacer que tu autobús se vea más atractivo y único con diseños personalizados? Si respondiste sí, entonces deberías probar <strong>Bus Simulator Indonesia</strong>, un juego de simulación popular y divertido que te permite experimentar lo que le gusta ser un conductor de autobús en Indonesia. Y para hacer que tu autobús se destaque entre la multitud, también debes probar <strong>Livery</strong>, una característica que te permite cambiar la apariencia de tu autobús con varias pieles y temas. </p>
4
- <p>En este artículo, le mostraremos todo lo que necesita saber sobre Bus Simulator Indonesia y Livery, incluyendo cómo descargar e instalar el juego, cómo descargar y aplicar Livery, y cómo diseñar su propia Livery. También compartiremos algunos consejos y trucos para crear impresionantes diseños de librea que impresionarán a sus pasajeros y compañeros de viaje. Así que, vamos a empezar! </p>
5
- <h2>autobús simulador indonesia librea descargar 4k</h2><br /><p><b><b>Download</b> &#10004; <a href="https://bltlly.com/2v6JxM">https://bltlly.com/2v6JxM</a></b></p><br /><br />
6
- <h2>¿Qué es Bus Simulator Indonesia? </h2>
7
- <p>Bus Simulator Indonesia (también conocido como BUSSID) es un juego de simulación desarrollado por Maleo, un estudio de juegos de Indonesia. Fue lanzado en 2017 y desde entonces ha ganado millones de fans en todo el mundo. El juego está disponible para dispositivos Android e iOS, así como para PC a través de emulador. </p>
8
- <p>Como su nombre indica, Bus Simulator Indonesia le permite conducir varios tipos de autobuses en ciudades y lugares indonesios realistas y auténticos. Puede elegir entre diferentes modelos de bus, como Srikandi SHD, Arjuna XHD, Bimasena SDD, JB SHD y más. También puede personalizar su autobús con diferentes características, como bocinas, luces, espejos, puertas, etc.</p>
9
- <h3>Características de Bus Simulator Indonesia</h3>
10
- <p>Bus Simulator Indonesia no es solo un juego de conducción simple. Tiene muchas características que lo hacen más divertido y atractivo. Algunas de estas características son:</p>
11
- <ul>
12
-
13
- <li><strong>Control muy fácil e intuitivo</strong>: Puedes controlar tu bus con simples gestos táctiles o inclinar tu dispositivo. También puede ajustar el ángulo de la cámara, la sensibilidad de la dirección, la fuerza del freno, etc.</li>
14
- <li><strong>Ciudades y lugares indonesios auténticos</strong>: Puede conducir su autobús en gráficos 3D realistas y detallados que representan varias ciudades y lugares de Indonesia, como Yakarta, Surabaya, Bali, Sumatra, Aceh, etc.</li>
15
- <li><strong>Autobuses de Indonesia</strong>: Puedes elegir entre diferentes tipos de autobuses que son populares y comunes en Indonesia, como Srikandi SHD, Arjuna XHD, Bimasena SDD, JB SHD, etc.</li>
16
- <li><strong>Fresco y divertido bocinazos</strong>: Usted puede tocar la bocina con diferentes sonidos y efectos, incluyendo el icónico "Om Telolet Om!" bocina que se convirtió en un fenómeno viral en 2016. </li>
17
- <li><strong>Tabla de clasificación y ahorro de datos en línea</strong>: Usted puede competir con otros jugadores en la clasificación y guardar su progreso en línea. </li>
18
- <li><strong>Vehicle mod system</strong>: Puede utilizar su propio modelo 3D utilizando un sistema de modificación de vehículos que le permite importar autobuses personalizados de fuentes externas. </li>
19
- <li><strong>Convoy multijugador en línea <h2>¿Qué es la librea en Bus Simulator Indonesia? </h2>
20
- <p>Livery es una característica que te permite cambiar la apariencia de tu bus con varias pieles y temas. Puedes elegir entre diferentes opciones de librea que están disponibles en el juego, o puedes crear tu propia librea utilizando una plantilla proporcionada por el juego. La librea puede hacer que su autobús se vea más atractivo y único, así como reflejar su personalidad y estilo. </p>
21
- <h3>Tipos de librea en el simulador de autobús Indonesia</h3>
22
- <p>Hay muchos tipos de librea que puede utilizar en Bus Simulator Indonesia, dependiendo de su preferencia y gusto. Algunos de los tipos más populares de librea son:</p>
23
- <ul>
24
-
25
- <li><strong>Librea basada en clubes de fútbol</strong>: Puedes usar librea basada en tus clubes de fútbol favoritos, como Persebaya, Persib, Persija, Arema, etc. Esta librea puede mostrar tu apoyo y lealtad a tu equipo. </li>
26
- <li><strong>Librea basada en diseños personalizados</strong>: Puede utilizar librea que se basan en su propia creatividad e imaginación. Puede crear librea con varios colores, patrones, logotipos, imágenes, etc. Estas libreas pueden hacer que su autobús se vea más único y original. </li>
27
- </ul>
28
- <h3>Beneficios de usar Livery en Bus Simulator Indonesia</h3>
29
- <p>Usar librea en Bus Simulator Indonesia puede tener muchos beneficios para usted como jugador. Algunos de estos beneficios son:</p>
30
- <p></p>
31
- <ul>
32
- <li><strong>Mejora tu experiencia de juego</strong>: Usar librea puede hacer que tu experiencia de juego sea más divertida y agradable. Puede personalizar su bus de acuerdo a su estado de ánimo y preferencia, y conducirlo en diferentes escenarios y entornos. </li>
33
- <li><strong>Exprésate</strong>: Usar librea puede ayudarte a expresarte y a expresar tu personalidad. Puedes usar librea que refleje tus intereses, aficiones, pasiones, etc. También puedes usar librea que transmita tus mensajes, opiniones, emociones, etc.</li>
34
- <li><strong>Impresiona a otros</strong>: Usar librea puede ayudarte a impresionar a otros y ganar su admiración. Puede usar librea que sea llamativa, hermosa, fresca o divertida. También puede usar librea que sea rara, exclusiva o hecha a medida. </li>
35
- </ul>
36
- <h2>Cómo descargar y aplicar Livery en Bus Simulator Indonesia</h2>
37
- <p>Si quieres usar librea en Bus Simulator Indonesia, necesitas descargarlas y aplicarlas primero. Hay dos formas de hacer esto: usando la tienda de libreas del juego o usando fuentes externas. </p>
38
- <h3>Pasos para descargar Livery in Bus Simulator Indonesia</h3>
39
- <p>Para descargar librea de la tienda de librea del juego, debes seguir estos pasos:</p>
40
- <ol>
41
- <li>Abre el juego y toca el icono "Garaje" en el menú principal. </li>
42
-
43
- <li>Verá una lista de opciones de librea disponibles para su modelo de bus. Toque en el que le gusta y pulse en el botón "Descargar". </li>
44
- <li>Espera a que la descarga termine y toca el botón "Aplicar". </li>
45
- <li>Has descargado y aplicado correctamente la librea a tu bus. </li>
46
- </ol>
47
- <p>Para descargar librea de fuentes externas, debe seguir estos pasos:</p>
48
- <ol>
49
- <li>Encontrar un sitio web o una aplicación que proporciona librea para Bus Simulator Indonesia. Por ejemplo, puede utilizar [Gamedaim]( 1 ), [Raina]( 2 ), o [Segitekno]( 3 ). </li>
50
- <li>Navega por las colecciones de librea y elige la que más te guste. Asegúrate de que la librea sea compatible con tu modelo de bus. </li>
51
- <li>Toque en el botón "Descargar" o enlace y guarde el archivo en su dispositivo. </li>
52
- <li>Abre el juego y toca el icono "Garaje" en el menú principal. </li>
53
- <li> Seleccione el modelo de bus que desea utilizar y toque en el icono "Librea" en la esquina inferior derecha. </li>
54
- <li>Toque en el botón "Importar" en la esquina superior derecha y seleccione el archivo que descargó de su dispositivo. </li>
55
- <li>Has descargado y aplicado correctamente la librea a tu bus. </li>
56
- </ol>
57
- <h3>Pasos para aplicar Librea en Bus Simulator Indonesia</h3>
58
- <p>Si ya has descargado alguna librea de cualquiera de las fuentes, puedes aplicarla cuando quieras. Para aplicar librea que ya ha descargado, debe seguir estos pasos:</p>
59
- <ol>
60
- <li>Abre el juego y toca el icono "Garaje" en el menú principal. </li>
61
- <li> Seleccione el modelo de bus que desea utilizar y toque en el icono "Librea" en la esquina inferior derecha. </li>
62
- <li>Verá una lista de opciones de librea descargadas para su modelo de bus. Toque en el que desea usar y toque en el botón "Aplicar". </li>
63
- <li> Ha aplicado correctamente la librea a su bus. </li>
64
- </ol>
65
- <h2>Consejos y trucos para diseñar su propia librea en Bus Simulator Indonesia</h2>
66
-
67
- <p>Aquí hay algunos consejos y trucos para diseñar su propia librea en Bus Simulator Indonesia:</p>
68
- <h3>Elija la plantilla correcta para su modelo de bus</h3>
69
- <p>Antes de empezar a diseñar su librea, asegúrese de elegir la plantilla correcta para su modelo de bus. Los diferentes modelos de bus tienen diferentes plantillas, por lo que debe coincidir con ellos en consecuencia. Por ejemplo, si quieres diseñar una librea para Srikandi SHD, necesitas usar la plantilla llamada "Srikandi SHD.png". Si usa una plantilla incorrecta, su librea puede no encajar correctamente o verse distorsionada en su autobús. </p>
70
- <h3>Utilice aplicaciones de edición de fotos o software para crear su librea</h3>
71
- <p>Una vez que haya elegido la plantilla correcta, puede usar cualquier aplicación de edición de fotos o software que soporte formato PNG para crear su librea. Puede usar varias herramientas y características para editar la plantilla, como recortar, cambiar el tamaño, rotar, voltear, cortar, pegar, rellenar, dibujar, borrar, etc. También puede agregar varios efectos y filtros para mejorar su librea, como brillo, contraste, saturación, matiz, desenfoque, etc.</p>
72
- <h3>Sé creativo y original con tu diseño de librea</h3>
73
- <p>El consejo más importante para diseñar tu propia librea es ser creativo y original. Puedes usar cualquier color, patrón, logos, imágenes, textos, etc. que te guste y que se adapte a tu modelo de bus. También puede usar referencias de compañías de autobuses reales, clubes de fútbol, diseños personalizados, etc. Sin embargo, asegúrese de no copiar o plagiar los diseños de librea de otras personas. También debes evitar usar contenido inapropiado u ofensivo que pueda violar los términos de servicio del juego o dañar los sentimientos de otros jugadores. </p>
74
- <h2>Conclusión</h2>
75
-
76
- <p>Para descargar y aplicar Livery en Bus Simulator Indonesia, puede usar la tienda de libreas del juego o fuentes externas. También puede diseñar su propia librea utilizando cualquier aplicación de edición de fotos o software que soporte formato PNG. Sin embargo, debe elegir la plantilla correcta para su modelo de bus y ser creativo y original con su diseño de Livery. </p>
77
- <p>Esperamos que este artículo te haya ayudado a aprender más sobre Bus Simulator Indonesia y Livery. Si usted tiene alguna pregunta o retroalimentación, por favor no dude en dejar un comentario a continuación. Gracias por leer y feliz juego! </p>
78
- <h2>Preguntas frecuentes</h2>
79
- <p>Aquí hay algunas preguntas frecuentes sobre Bus Simulator Indonesia y Livery:</p>
80
- <ol>
81
- <li><strong>¿Cómo actualizo Bus Simulator Indonesia? </strong></li>
82
- <p>Para actualizar Bus Simulator Indonesia, es necesario ir a la Google Play Store o App Store y comprobar si hay una nueva versión disponible. Si hay, toque en el "Actualizar" botón y esperar a que la descarga y la instalación para terminar. Alternativamente, también puedes descargar el último archivo APK desde el sitio web oficial del juego e instalarlo manualmente. </p>
83
- <li><strong>¿Cómo elimino Livery en Bus Simulator Indonesia? </strong></li>
84
- <p>Para eliminar Livery en Bus Simulator Indonesia, es necesario ir al menú "Garaje" y toque en el "Librea" icono. Luego, toque en el botón "Eliminar" en la esquina superior derecha y seleccione la librea que desea eliminar. Toque en el botón "Sí" para confirmar. </p> <li><strong> ¿Cómo comparto librea en Bus Simulator Indonesia? </strong></li>
85
- <p>Para compartir la librea en Bus Simulator Indonesia, es necesario ir al menú "Garaje" y toque en el icono "Librea". Luego, toca el botón "Compartir" en la esquina superior derecha y selecciona la librea que deseas compartir. Puede optar por compartir su librea a través de las redes sociales, correo electrónico, Bluetooth, etc.</p>
86
- <li><strong>¿Cómo puedo obtener más monedas en Bus Simulator Indonesia? </strong></li>
87
-
88
- <li><strong>¿Cómo me uno a un convoy en Bus Simulator Indonesia? </strong></li>
89
- <p>Para unirse a un convoy en Bus Simulator Indonesia, debe ir al menú "Multijugador" y tocar el botón "Unirse al convoy". Puedes elegir unirte a un convoy público o privado. Si te unes a un convoy público, serás emparejado con otros jugadores al azar. Si se une a un convoy privado, tendrá que introducir un código proporcionado por el líder del convoy. </p> 64aa2da5cf<br />
90
- <br />
91
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Descargar Gratis Templo Ejecutar Juego Para Pc.md DELETED
@@ -1,74 +0,0 @@
1
-
2
- <h1>Cómo descargar gratis Temple Run juego para PC</h1>
3
- <p>Temple Run es uno de los juegos móviles más populares de todos los tiempos, con más de mil millones de descargas en todo el mundo. Es un juego de corredor sin fin donde tienes que escapar de un templo con un ídolo maldito, evitando obstáculos, lagunas y monos que te persiguen. El juego es rápido, adictivo y divertido, y también se puede jugar en su PC.</p>
4
- <h2>descargar gratis templo ejecutar juego para pc</h2><br /><p><b><b>DOWNLOAD</b> ->>> <a href="https://bltlly.com/2v6JXR">https://bltlly.com/2v6JXR</a></b></p><br /><br />
5
- <p>En este artículo, le mostraremos cómo descargar gratis Temple Run juego para PC utilizando diferentes métodos. Ya sea que quieras reproducirlo en tu navegador, descargarlo desde la Microsoft Store, obtenerlo desde el sitio web oficial o comprarlo desde Steam, lo tenemos cubierto. Solo sigue estos sencillos pasos y disfruta de esta emocionante aventura en tu ordenador. </p>
6
- <h2>Descarga desde Microsoft Store</h2>
7
- <p>Microsoft Store ofrece una variedad de juegos gratuitos y de pago que puedes descargar directamente desde la tienda. Si tiene Windows 10 o posterior, ya tiene acceso a Microsoft Store en su PC. Así es como puede descargar Temple Run desde allí:</p>
8
- <ol>
9
- <li>Abra la tienda de Microsoft haciendo clic en su icono en la barra de tareas o buscándolo en el menú Inicio. </li>
10
- <li>Buscar templo Ejecutar en el cuadro de búsqueda en la esquina superior derecha de la tienda. </li>
11
- <li>Haga clic en la ficha del juego para ver más información al respecto. </li>
12
- <li>Seleccione Obtener o Instalar para comenzar a descargar el juego gratis. </li>
13
- <li>Espere a que la descarga termine y inicie el juego desde su menú Inicio o escritorio. </li>
14
- </ol>
15
- <h2>Descargar de Poki.com</h2>
16
- <p>Poki.com es un sitio web que te permite jugar miles de juegos en línea gratis sin descargar nada. Puedes jugar en tu navegador usando tu teclado, ratón o pantalla táctil. Uno de los juegos disponibles en Poki.com es Temple Run 2, que es la secuela de Temple Run con gráficos mejorados, nuevos mapas y más características. Así es como puedes jugar Temple Run 2 en Poki.com:</p>
17
- <p></p>
18
- <ol>
19
-
20
- <li>Buscar Temple Run 2 en el cuadro de búsqueda en la esquina superior derecha del sitio web. </li>
21
- <li>Haga clic en la ficha del juego para ver más información al respecto. </li>
22
- <li>Seleccione Jugar ahora para comenzar a jugar el juego en su navegador. </li>
23
- <li>Disfruta del juego y trata de correr tan lejos como puedas. </li>
24
- </ol>
25
- <h2>Descarga del sitio web de Imangi Studios</h2>
26
- <p>Imangi Studios es el desarrollador de Temple Run y Temple Run 2. Puedes visitar su sitio web oficial para aprender más sobre sus juegos, su equipo y sus noticias. También puedes descargar sus juegos para PC desde su sitio web. Así es como puedes hacerlo:</p>
27
- <ol>
28
- <li>Ir a [Sitio web de Imangi Studios] usando su navegador web preferido. </li>
29
- <li>Haga clic en Juegos en la barra de menú superior para ver su lista de juegos. </li>
30
- <li>Elige Temple Run o Temple Run 2 dependiendo del que quieras jugar. </li>
31
- <li>Haga clic en Descargar para PC para descargar el archivo de instalación del juego. </li>
32
- <li>Guarde el archivo en la ubicación deseada y ejecute la configuración. </li>
33
- <li>Siga las instrucciones en la pantalla e instale el juego en su PC.</li>
34
- <li> Iniciar el juego desde el menú Inicio o el escritorio y divertirse. </li>
35
- </ol>
36
- <h2>Descargar desde Steam</h2>
37
- <p>Steam es una popular plataforma en línea que ofrece una variedad de juegos, software y otros contenidos digitales. Puedes comprar, descargar y jugar juegos en Steam usando tu PC, Mac o Linux. También puedes chatear con otros jugadores, unirte a comunidades y acceder a otras funciones. Para jugar a Temple Run o Temple Run 2 en Steam, necesitas tener Steam instalado en tu PC y tener una cuenta. Así es como puedes descargar Temple Run o Temple Run 2 desde Steam:</p>
38
- <ol>
39
- <li>Descarga e instala Steam en tu PC desde [sitio web de Steam]. </li>
40
- <li>Crea una cuenta o inicia sesión en Steam usando tu correo electrónico y contraseña. </li>
41
- <li>Buscar Temple Run o Temple Run 2 en la tienda de vapor usando el cuadro de búsqueda en la parte superior de la página. </li>
42
- <li>Haga clic en la ficha del juego para ver más información al respecto. </li>
43
-
44
- <li>Proceda a realizar la compra y complete la compra usando su método de pago preferido. </li>
45
- <li>Vaya a su biblioteca e instale el juego en su PC haciendo clic en Instalar.</li>
46
- <li>Inicie el juego desde Steam haciendo clic en Play.</li>
47
- </ol>
48
- <h2>Consejos y trucos para jugar Temple Run en PC</h2>
49
- <p>Jugar Temple Run en PC puede ser una experiencia diferente que jugar en tu dispositivo móvil. Es posible que necesite ajustar algunos ajustes, aprender algunos controles y practicar algunas habilidades. Aquí hay algunos consejos y trucos que pueden ayudarle a jugar Temple Run mejor en su PC:</p>
50
- <ul>
51
- <li> Utilice los controles del teclado o del ratón para mover, saltar, deslizarse y girar. Puede usar las teclas de flecha o las teclas WASD para moverse a la izquierda, derecha, arriba y abajo. También puede utilizar el ratón para deslizar el dedo en esas direcciones. Alternativamente, puede usar un controlador si tiene uno conectado a su PC.</li>
52
- <li>Recoger monedas y potenciadores para aumentar su puntuación y habilidades. Las monedas se pueden utilizar para comprar nuevos personajes, trajes, potenciadores y otros artículos en la tienda. Los potenciadores pueden darte beneficios temporales como aumento de velocidad, imán de monedas, escudo o multiplicador de puntuación. Trata de recoger tantas monedas y potenciadores como puedas mientras corres. </li>
53
- <li>Evite obstáculos, lagunas y monos que lo ralentizarán o terminarán su carrera. Los obstáculos incluyen árboles, rocas, fuego, trampas, paredes y más. Los huecos son agujeros o acantilados por los que necesitas saltar o deslizarte. Los monos son enemigos que te perseguirán después de que saques el ídolo del templo. Te alcanzarán si desaceleras o cometes un error. Trata de evitar estos peligros moviéndote rápida y cuidadosamente. </li>
54
-
55
- <li>Diviértete y desafíate a batir tus propios récords. El objetivo principal de Temple Run es correr tan lejos como puedas sin ser atrapado o caerte. El juego hará un seguimiento de su distancia, puntuación, monedas recogidas, power-ups utilizados, y otras estadísticas. Puedes ver tus mejores carreras en la tabla de clasificación y compararlas con otros jugadores de todo el mundo. También puedes desafiarte a batir tus propios récords y mejorar tus habilidades. Diviértete y disfruta de la emoción de Temple Run en tu PC.</li>
56
- </ul>
57
- <h1>Conclusión</h1>
58
- <p>Temple Run es un juego que puedes jugar gratis en tu PC usando diferentes métodos. Puedes descargarlo desde Microsoft Store, reproducirlo online en Poki.com, obtenerlo desde el sitio web de Imangi Studios o comprarlo desde Steam. También puedes usar algunos consejos y trucos para jugar mejor en tu PC, como usar controles de teclado o ratón, recoger monedas y potenciadores, evitar obstáculos, lagunas y monos, completar objetivos y logros, y divertirte y desafiarte. Temple Run es un juego que te mantendrá entretenido y comprometido durante horas. Pruébalo hoy y mira hasta dónde puedes correr. </p>
59
- <h2>Preguntas frecuentes</h2>
60
- <p>Aquí hay algunas preguntas frecuentes sobre Temple Run y cómo descargarlo para PC:</p>
61
- <ol>
62
- <li><b>Temple Run es gratis para jugar? </b></li>
63
- <p>Sí, Temple Run es gratis para jugar en la mayoría de las plataformas, incluyendo PC. Puedes descargarlo gratis desde Microsoft Store, reproducirlo online en Poki.com, o obtenerlo desde el sitio web de Imangi Studios. Sin embargo, si quieres jugar en Steam, necesitas comprarlo por una pequeña tarifa. </p>
64
- <li><b>¿Cuáles son las diferencias entre Temple Run y Temple Run 2?</b></li>
65
- <p>Temple Run 2 es la secuela de Temple Run con algunas mejoras y adiciones. Tiene mejores gráficos, más mapas, más personajes, más potenciadores, más obstáculos, más logros y más características. Sin embargo, el modo de juego y el concepto siguen siendo los mismos: tienes que correr tan lejos como puedas evitando peligros. </p>
66
-
67
- <p>Sí, puede jugar Temple Run sin conexión si lo descarga en su PC. No necesita una conexión a Internet para jugar el juego una vez que lo instale. Sin embargo, si quieres jugar online en Poki.com, necesitas una conexión a Internet para acceder al sitio web. </p>
68
- <li><b>¿Puedo sincronizar mi progreso entre dispositivos? </b></li>
69
- <p>Sí, puedes sincronizar tu progreso entre dispositivos si usas la misma cuenta o método de inicio de sesión. Por ejemplo, si usas Facebook para iniciar sesión en Temple Run en tu dispositivo móvil, también puedes usar Facebook para iniciar sesión en Temple Run en tu PC y ver tu progreso allí. </p>
70
- <li><b>¿Cómo puedo contactar a los desarrolladores de Temple Run? </b></li>
71
- <p>Puede ponerse en contacto con los desarrolladores de Temple Run visitando su sitio web oficial y haciendo clic en Contáctenos en la parte inferior de la página. También puedes seguirlos en plataformas de redes sociales como Facebook, Twitter, Instagram o YouTube.</p>
72
- </ol></p> 64aa2da5cf<br />
73
- <br />
74
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/boto3/ec2/deletetags.py DELETED
@@ -1,37 +0,0 @@
1
- # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License"). You
4
- # may not use this file except in compliance with the License. A copy of
5
- # the License is located at
6
- #
7
- # https://aws.amazon.com/apache2.0/
8
- #
9
- # or in the "license" file accompanying this file. This file is
10
- # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11
- # ANY KIND, either express or implied. See the License for the specific
12
- # language governing permissions and limitations under the License.
13
- from boto3.resources.action import CustomModeledAction
14
-
15
-
16
- def inject_delete_tags(event_emitter, **kwargs):
17
- action_model = {
18
- 'request': {
19
- 'operation': 'DeleteTags',
20
- 'params': [
21
- {
22
- 'target': 'Resources[0]',
23
- 'source': 'identifier',
24
- 'name': 'Id',
25
- }
26
- ],
27
- }
28
- }
29
- action = CustomModeledAction(
30
- 'delete_tags', action_model, delete_tags, event_emitter
31
- )
32
- action.inject(**kwargs)
33
-
34
-
35
- def delete_tags(self, **kwargs):
36
- kwargs['Resources'] = [self.id]
37
- return self.meta.client.delete_tags(**kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/pyparsing/exceptions.py DELETED
@@ -1,267 +0,0 @@
1
- # exceptions.py
2
-
3
- import re
4
- import sys
5
- import typing
6
-
7
- from .util import col, line, lineno, _collapse_string_to_ranges
8
- from .unicode import pyparsing_unicode as ppu
9
-
10
-
11
- class ExceptionWordUnicode(ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic):
12
- pass
13
-
14
-
15
- _extract_alphanums = _collapse_string_to_ranges(ExceptionWordUnicode.alphanums)
16
- _exception_word_extractor = re.compile("([" + _extract_alphanums + "]{1,16})|.")
17
-
18
-
19
- class ParseBaseException(Exception):
20
- """base exception class for all parsing runtime exceptions"""
21
-
22
- # Performance tuning: we construct a *lot* of these, so keep this
23
- # constructor as small and fast as possible
24
- def __init__(
25
- self,
26
- pstr: str,
27
- loc: int = 0,
28
- msg: typing.Optional[str] = None,
29
- elem=None,
30
- ):
31
- self.loc = loc
32
- if msg is None:
33
- self.msg = pstr
34
- self.pstr = ""
35
- else:
36
- self.msg = msg
37
- self.pstr = pstr
38
- self.parser_element = self.parserElement = elem
39
- self.args = (pstr, loc, msg)
40
-
41
- @staticmethod
42
- def explain_exception(exc, depth=16):
43
- """
44
- Method to take an exception and translate the Python internal traceback into a list
45
- of the pyparsing expressions that caused the exception to be raised.
46
-
47
- Parameters:
48
-
49
- - exc - exception raised during parsing (need not be a ParseException, in support
50
- of Python exceptions that might be raised in a parse action)
51
- - depth (default=16) - number of levels back in the stack trace to list expression
52
- and function names; if None, the full stack trace names will be listed; if 0, only
53
- the failing input line, marker, and exception string will be shown
54
-
55
- Returns a multi-line string listing the ParserElements and/or function names in the
56
- exception's stack trace.
57
- """
58
- import inspect
59
- from .core import ParserElement
60
-
61
- if depth is None:
62
- depth = sys.getrecursionlimit()
63
- ret = []
64
- if isinstance(exc, ParseBaseException):
65
- ret.append(exc.line)
66
- ret.append(" " * (exc.column - 1) + "^")
67
- ret.append("{}: {}".format(type(exc).__name__, exc))
68
-
69
- if depth > 0:
70
- callers = inspect.getinnerframes(exc.__traceback__, context=depth)
71
- seen = set()
72
- for i, ff in enumerate(callers[-depth:]):
73
- frm = ff[0]
74
-
75
- f_self = frm.f_locals.get("self", None)
76
- if isinstance(f_self, ParserElement):
77
- if frm.f_code.co_name not in ("parseImpl", "_parseNoCache"):
78
- continue
79
- if id(f_self) in seen:
80
- continue
81
- seen.add(id(f_self))
82
-
83
- self_type = type(f_self)
84
- ret.append(
85
- "{}.{} - {}".format(
86
- self_type.__module__, self_type.__name__, f_self
87
- )
88
- )
89
-
90
- elif f_self is not None:
91
- self_type = type(f_self)
92
- ret.append("{}.{}".format(self_type.__module__, self_type.__name__))
93
-
94
- else:
95
- code = frm.f_code
96
- if code.co_name in ("wrapper", "<module>"):
97
- continue
98
-
99
- ret.append("{}".format(code.co_name))
100
-
101
- depth -= 1
102
- if not depth:
103
- break
104
-
105
- return "\n".join(ret)
106
-
107
- @classmethod
108
- def _from_exception(cls, pe):
109
- """
110
- internal factory method to simplify creating one type of ParseException
111
- from another - avoids having __init__ signature conflicts among subclasses
112
- """
113
- return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
114
-
115
- @property
116
- def line(self) -> str:
117
- """
118
- Return the line of text where the exception occurred.
119
- """
120
- return line(self.loc, self.pstr)
121
-
122
- @property
123
- def lineno(self) -> int:
124
- """
125
- Return the 1-based line number of text where the exception occurred.
126
- """
127
- return lineno(self.loc, self.pstr)
128
-
129
- @property
130
- def col(self) -> int:
131
- """
132
- Return the 1-based column on the line of text where the exception occurred.
133
- """
134
- return col(self.loc, self.pstr)
135
-
136
- @property
137
- def column(self) -> int:
138
- """
139
- Return the 1-based column on the line of text where the exception occurred.
140
- """
141
- return col(self.loc, self.pstr)
142
-
143
- def __str__(self) -> str:
144
- if self.pstr:
145
- if self.loc >= len(self.pstr):
146
- foundstr = ", found end of text"
147
- else:
148
- # pull out next word at error location
149
- found_match = _exception_word_extractor.match(self.pstr, self.loc)
150
- if found_match is not None:
151
- found = found_match.group(0)
152
- else:
153
- found = self.pstr[self.loc : self.loc + 1]
154
- foundstr = (", found %r" % found).replace(r"\\", "\\")
155
- else:
156
- foundstr = ""
157
- return "{}{} (at char {}), (line:{}, col:{})".format(
158
- self.msg, foundstr, self.loc, self.lineno, self.column
159
- )
160
-
161
- def __repr__(self):
162
- return str(self)
163
-
164
- def mark_input_line(self, marker_string: str = None, *, markerString=">!<") -> str:
165
- """
166
- Extracts the exception line from the input string, and marks
167
- the location of the exception with a special symbol.
168
- """
169
- markerString = marker_string if marker_string is not None else markerString
170
- line_str = self.line
171
- line_column = self.column - 1
172
- if markerString:
173
- line_str = "".join(
174
- (line_str[:line_column], markerString, line_str[line_column:])
175
- )
176
- return line_str.strip()
177
-
178
- def explain(self, depth=16) -> str:
179
- """
180
- Method to translate the Python internal traceback into a list
181
- of the pyparsing expressions that caused the exception to be raised.
182
-
183
- Parameters:
184
-
185
- - depth (default=16) - number of levels back in the stack trace to list expression
186
- and function names; if None, the full stack trace names will be listed; if 0, only
187
- the failing input line, marker, and exception string will be shown
188
-
189
- Returns a multi-line string listing the ParserElements and/or function names in the
190
- exception's stack trace.
191
-
192
- Example::
193
-
194
- expr = pp.Word(pp.nums) * 3
195
- try:
196
- expr.parse_string("123 456 A789")
197
- except pp.ParseException as pe:
198
- print(pe.explain(depth=0))
199
-
200
- prints::
201
-
202
- 123 456 A789
203
- ^
204
- ParseException: Expected W:(0-9), found 'A' (at char 8), (line:1, col:9)
205
-
206
- Note: the diagnostic output will include string representations of the expressions
207
- that failed to parse. These representations will be more helpful if you use `set_name` to
208
- give identifiable names to your expressions. Otherwise they will use the default string
209
- forms, which may be cryptic to read.
210
-
211
- Note: pyparsing's default truncation of exception tracebacks may also truncate the
212
- stack of expressions that are displayed in the ``explain`` output. To get the full listing
213
- of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``
214
- """
215
- return self.explain_exception(self, depth)
216
-
217
- markInputline = mark_input_line
218
-
219
-
220
- class ParseException(ParseBaseException):
221
- """
222
- Exception thrown when a parse expression doesn't match the input string
223
-
224
- Example::
225
-
226
- try:
227
- Word(nums).set_name("integer").parse_string("ABC")
228
- except ParseException as pe:
229
- print(pe)
230
- print("column: {}".format(pe.column))
231
-
232
- prints::
233
-
234
- Expected integer (at char 0), (line:1, col:1)
235
- column: 1
236
-
237
- """
238
-
239
-
240
- class ParseFatalException(ParseBaseException):
241
- """
242
- User-throwable exception thrown when inconsistent parse content
243
- is found; stops all parsing immediately
244
- """
245
-
246
-
247
- class ParseSyntaxException(ParseFatalException):
248
- """
249
- Just like :class:`ParseFatalException`, but thrown internally
250
- when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates
251
- that parsing is to stop immediately because an unbacktrackable
252
- syntax error has been found.
253
- """
254
-
255
-
256
- class RecursiveGrammarException(Exception):
257
- """
258
- Exception thrown by :class:`ParserElement.validate` if the
259
- grammar could be left-recursive; parser may need to enable
260
- left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`
261
- """
262
-
263
- def __init__(self, parseElementList):
264
- self.parseElementTrace = parseElementList
265
-
266
- def __str__(self) -> str:
267
- return "RecursiveGrammarException: {}".format(self.parseElementTrace)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_importlib.py DELETED
@@ -1,47 +0,0 @@
1
- import sys
2
-
3
-
4
- def disable_importlib_metadata_finder(metadata):
5
- """
6
- Ensure importlib_metadata doesn't provide older, incompatible
7
- Distributions.
8
-
9
- Workaround for #3102.
10
- """
11
- try:
12
- import importlib_metadata
13
- except ImportError:
14
- return
15
- except AttributeError:
16
- import warnings
17
-
18
- msg = (
19
- "`importlib-metadata` version is incompatible with `setuptools`.\n"
20
- "This problem is likely to be solved by installing an updated version of "
21
- "`importlib-metadata`."
22
- )
23
- warnings.warn(msg) # Ensure a descriptive message is shown.
24
- raise # This exception can be suppressed by _distutils_hack
25
-
26
- if importlib_metadata is metadata:
27
- return
28
- to_remove = [
29
- ob
30
- for ob in sys.meta_path
31
- if isinstance(ob, importlib_metadata.MetadataPathFinder)
32
- ]
33
- for item in to_remove:
34
- sys.meta_path.remove(item)
35
-
36
-
37
- if sys.version_info < (3, 10):
38
- from setuptools.extern import importlib_metadata as metadata
39
- disable_importlib_metadata_finder(metadata)
40
- else:
41
- import importlib.metadata as metadata # noqa: F401
42
-
43
-
44
- if sys.version_info < (3, 9):
45
- from setuptools.extern import importlib_resources as resources
46
- else:
47
- import importlib.resources as resources # noqa: F401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BilalSardar/facrec/app.py DELETED
@@ -1,92 +0,0 @@
1
- import cv2
2
- import numpy as np
3
- import os
4
- import pickle
5
- from deepface import DeepFace
6
- import gradio as gr
7
- from datetime import datetime
8
- import fast_colorthief
9
- import webcolors
10
- from PIL import Image
11
-
12
-
13
-
14
- thres = 0.45
15
- classNames= []
16
- classFile = 'coco.names'
17
- with open(classFile,'rt') as f:
18
- #classNames = f.read().rstrip('n').split('n')
19
- classNames = f.readlines()
20
-
21
-
22
- # remove new line characters
23
- classNames = [x.strip() for x in classNames]
24
- print(classNames)
25
- configPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
26
- weightsPath = 'frozen_inference_graph.pb'
27
- net = cv2.dnn_DetectionModel(weightsPath,configPath)
28
- net.setInputSize(320,320)
29
- net.setInputScale(1.0/ 127.5)
30
- net.setInputMean((127.5, 127.5, 127.5))
31
- net.setInputSwapRB(True)
32
-
33
-
34
-
35
- def main(image):
36
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
37
- rgb=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
38
- names=[]
39
-
40
-
41
- #object
42
- try:
43
- classIds, confs, bbox = net.detect(image,confThreshold=thres)
44
- except Exception as err:
45
- print(err)
46
- print(classIds,bbox)
47
- try:
48
- if len(classIds) != 0:
49
- for classId, confidence,box in zip(classIds.flatten(),confs.flatten(),bbox):
50
- if names.count(classNames[classId-1]) == 0:
51
- names.append(classNames[classId-1])
52
- except Exception as err:
53
- print(err)
54
- #emotion
55
-
56
- try:
57
- face_analysis_2=DeepFace.analyze(image, actions = ['emotion'], enforce_detection=False)
58
- names.append(face_analysis_2[0]["dominant_emotion"])
59
- except:
60
- print("No face")
61
- names.append("No Face")
62
-
63
- # #Colour
64
-
65
- colourimage = Image.fromarray(image)
66
- colourimage = colourimage.convert('RGBA')
67
- colourimage = np.array(colourimage).astype(np.uint8)
68
- palette=fast_colorthief.get_palette(colourimage)
69
-
70
-
71
- for i in range(len(palette)):
72
- diff={}
73
- for color_hex, color_name in webcolors.CSS3_HEX_TO_NAMES.items():
74
- r, g, b = webcolors.hex_to_rgb(color_hex)
75
- diff[sum([(r - palette[i][0])**2,
76
- (g - palette[i][1])**2,
77
- (b - palette[i][2])**2])]= color_name
78
- if names.count(diff[min(diff.keys())])==0:
79
- names.append(diff[min(diff.keys())])
80
-
81
-
82
-
83
-
84
- return ' '.join(names)
85
- interface = gr.Interface(fn=main,
86
- inputs=["image"],
87
- outputs=[gr.inputs.Textbox(label='Names of person in image')],
88
- title='Color Object Emotion ',
89
- description='This Space:\n \n2) Detect Emotion \n3) Detect Colors.\n4) Object Detection \n')
90
-
91
-
92
- interface.launch(inline=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/system/detail/adl/copy.h DELETED
@@ -1,44 +0,0 @@
1
- /*
2
- * Copyright 2008-2013 NVIDIA Corporation
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
-
17
- #pragma once
18
-
19
- #include <thrust/detail/config.h>
20
-
21
- // the purpose of this header is to #include the copy.h header
22
- // of the sequential, host, and device systems. It should be #included in any
23
- // code which uses adl to dispatch copy
24
-
25
- #include <thrust/system/detail/sequential/copy.h>
26
-
27
- // SCons can't see through the #defines below to figure out what this header
28
- // includes, so we fake it out by specifying all possible files we might end up
29
- // including inside an #if 0.
30
- #if 0
31
- #include <thrust/system/cpp/detail/copy.h>
32
- #include <thrust/system/cuda/detail/copy.h>
33
- #include <thrust/system/omp/detail/copy.h>
34
- #include <thrust/system/tbb/detail/copy.h>
35
- #endif
36
-
37
- #define __THRUST_HOST_SYSTEM_COPY_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/copy.h>
38
- #include __THRUST_HOST_SYSTEM_COPY_HEADER
39
- #undef __THRUST_HOST_SYSTEM_COPY_HEADER
40
-
41
- #define __THRUST_DEVICE_SYSTEM_COPY_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/copy.h>
42
- #include __THRUST_DEVICE_SYSTEM_COPY_HEADER
43
- #undef __THRUST_DEVICE_SYSTEM_COPY_HEADER
44
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/SPOTER_Sign_Language_Recognition/spoter/spoter_model.py DELETED
@@ -1,70 +0,0 @@
1
-
2
- import copy
3
- import torch
4
-
5
- import torch.nn as nn
6
- from typing import Optional
7
-
8
-
9
- def _get_clones(mod, n):
10
- return nn.ModuleList([copy.deepcopy(mod) for _ in range(n)])
11
-
12
-
13
- class SPOTERTransformerDecoderLayer(nn.TransformerDecoderLayer):
14
- """
15
- Edited TransformerDecoderLayer implementation omitting the redundant self-attention operation as opposed to the
16
- standard implementation.
17
- """
18
-
19
- def __init__(self, d_model, nhead, dim_feedforward, dropout, activation):
20
- super(SPOTERTransformerDecoderLayer, self).__init__(d_model, nhead, dim_feedforward, dropout, activation)
21
-
22
- del self.self_attn
23
-
24
- def forward(self, tgt: torch.Tensor, memory: torch.Tensor, tgt_mask: Optional[torch.Tensor] = None,
25
- memory_mask: Optional[torch.Tensor] = None, tgt_key_padding_mask: Optional[torch.Tensor] = None,
26
- memory_key_padding_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
27
-
28
- tgt = tgt + self.dropout1(tgt)
29
- tgt = self.norm1(tgt)
30
- tgt2 = self.multihead_attn(tgt, memory, memory, attn_mask=memory_mask,
31
- key_padding_mask=memory_key_padding_mask)[0]
32
- tgt = tgt + self.dropout2(tgt2)
33
- tgt = self.norm2(tgt)
34
- tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
35
- tgt = tgt + self.dropout3(tgt2)
36
- tgt = self.norm3(tgt)
37
-
38
- return tgt
39
-
40
-
41
- class SPOTER(nn.Module):
42
- """
43
- Implementation of the SPOTER (Sign POse-based TransformER) architecture for sign language recognition from sequence
44
- of skeletal data.
45
- """
46
-
47
- def __init__(self, num_classes, hidden_dim=55):
48
- super().__init__()
49
-
50
- self.row_embed = nn.Parameter(torch.rand(50, hidden_dim))
51
- self.pos = nn.Parameter(torch.cat([self.row_embed[0].unsqueeze(0).repeat(1, 1, 1)], dim=-1).flatten(0, 1).unsqueeze(0))
52
- self.class_query = nn.Parameter(torch.rand(1, hidden_dim))
53
- self.transformer = nn.Transformer(hidden_dim, 9, 6, 6)
54
- self.linear_class = nn.Linear(hidden_dim, num_classes)
55
-
56
- # Deactivate the initial attention decoder mechanism
57
- custom_decoder_layer = SPOTERTransformerDecoderLayer(self.transformer.d_model, self.transformer.nhead, 2048,
58
- 0.1, "relu")
59
- self.transformer.decoder.layers = _get_clones(custom_decoder_layer, self.transformer.decoder.num_layers)
60
-
61
- def forward(self, inputs):
62
- h = torch.unsqueeze(inputs.flatten(start_dim=1), 1).float()
63
- h = self.transformer(self.pos + h, self.class_query.unsqueeze(0)).transpose(0, 1)
64
- res = self.linear_class(h)
65
-
66
- return res
67
-
68
-
69
- if __name__ == "__main__":
70
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Carterclear/swarm-agents/app.py DELETED
@@ -1,161 +0,0 @@
1
- import gradio as gr
2
- import os
3
- import json
4
- import requests
5
-
6
- #Streaming endpoint
7
- API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream"
8
-
9
- #Huggingface provided GPT4 OpenAI API Key
10
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
11
-
12
- #Inferenec function
13
- def predict(system_msg, inputs, top_p, temperature, chat_counter, chatbot=[], history=[]):
14
-
15
- headers = {
16
- "Content-Type": "application/json",
17
- "Authorization": f"Bearer {OPENAI_API_KEY}"
18
- }
19
- print(f"system message is ^^ {system_msg}")
20
- if system_msg.strip() == '':
21
- initial_message = [{"role": "user", "content": f"{inputs}"},]
22
- multi_turn_message = []
23
- else:
24
- initial_message= [{"role": "system", "content": system_msg},
25
- {"role": "user", "content": f"{inputs}"},]
26
- multi_turn_message = [{"role": "system", "content": system_msg},]
27
-
28
- if chat_counter == 0 :
29
- payload = {
30
- "model": "gpt-3.5-turbo",
31
- "messages": initial_message ,
32
- "temperature" : 1.0,
33
- "top_p":1.0,
34
- "n" : 1,
35
- "stream": True,
36
- "presence_penalty":0,
37
- "frequency_penalty":0,
38
- }
39
- print(f"chat_counter - {chat_counter}")
40
- else: #if chat_counter != 0 :
41
- messages=multi_turn_message # Of the type of - [{"role": "system", "content": system_msg},]
42
- for data in chatbot:
43
- user = {}
44
- user["role"] = "user"
45
- user["content"] = data[0]
46
- assistant = {}
47
- assistant["role"] = "assistant"
48
- assistant["content"] = data[1]
49
- messages.append(user)
50
- messages.append(assistant)
51
- temp = {}
52
- temp["role"] = "user"
53
- temp["content"] = inputs
54
- messages.append(temp)
55
- #messages
56
- payload = {
57
- "model": "gpt-3.5-turbo",
58
- "messages": messages, # Of the type of [{"role": "user", "content": f"{inputs}"}],
59
- "temperature" : temperature, #1.0,
60
- "top_p": top_p, #1.0,
61
- "n" : 1,
62
- "stream": True,
63
- "presence_penalty":0,
64
- "frequency_penalty":0,}
65
-
66
- chat_counter+=1
67
-
68
- history.append(inputs)
69
- print(f"Logging : payload is - {payload}")
70
- # make a POST request to the API endpoint using the requests.post method, passing in stream=True
71
- response = requests.post(API_URL, headers=headers, json=payload, stream=True)
72
- print(f"Logging : response code - {response}")
73
- token_counter = 0
74
- partial_words = ""
75
-
76
- counter=0
77
- for chunk in response.iter_lines():
78
- #Skipping first chunk
79
- if counter == 0:
80
- counter+=1
81
- continue
82
- # check whether each line is non-empty
83
- if chunk.decode() :
84
- chunk = chunk.decode()
85
- # decode each line as response data is in bytes
86
- if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
87
- partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
88
- if token_counter == 0:
89
- history.append(" " + partial_words)
90
- else:
91
- history[-1] = partial_words
92
- chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
93
- token_counter+=1
94
- yield chat, history, chat_counter, response # resembles {chatbot: chat, state: history}
95
-
96
- #Resetting to blank
97
- def reset_textbox():
98
- return gr.update(value='')
99
-
100
- #to set a component as visible=False
101
- def set_visible_false():
102
- return gr.update(visible=False)
103
-
104
- #to set a component as visible=True
105
- def set_visible_true():
106
- return gr.update(visible=True)
107
-
108
- title = """<h1 align="center">🔍 Swarm Intelligence Agents 🐜🔎</h1>"""
109
-
110
- #display message for themes feature
111
- theme_addon_msg = """<center>🌟 he swarm of agents combines a huge number of parallel agents divided into roles, including examiners, QA, evaluators, managers, analytics, and googlers.
112
- <br>🏆The agents use smart task decomposition and optimization processes to ensure accurate and efficient research on any topic.🎨</center>
113
- """
114
-
115
- #Using info to add additional information about System message in GPT4
116
- system_msg_info = """Swarm pre-configured for best practices using whitelists of top internet resources'"""
117
-
118
- #Modifying existing Gradio Theme
119
- theme = gr.themes.Soft(primary_hue="zinc", secondary_hue="green", neutral_hue="green",
120
- text_size=gr.themes.sizes.text_lg)
121
-
122
- with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;} #chatbot {height: 520px; overflow: auto;}""",
123
- theme=theme) as demo:
124
- gr.HTML(title)
125
- gr.HTML("""<h3 align="center">🔥Using a swarm of automated agents, we can perform fast and accurate research on any topic. 🚀🐝. 🎉🥳🎉You don't need to spent tons of hours during reseachy🙌</h1>""")
126
- gr.HTML(theme_addon_msg)
127
- gr.HTML('''<center><a href="https://huggingface.co/spaces/swarm-agents/swarm-agents?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
128
-
129
- with gr.Column(elem_id = "col_container"):
130
- #GPT4 API Key is provided by Huggingface
131
- with gr.Accordion(label="System message:", open=False):
132
- system_msg = gr.Textbox(label="Instruct the AI Assistant to set its beaviour", info = system_msg_info, value="")
133
- accordion_msg = gr.HTML(value="🚧 To set System message you will have to refresh the app", visible=False)
134
- chatbot = gr.Chatbot(label='Swarm Intelligence Search', elem_id="chatbot")
135
- inputs = gr.Textbox(placeholder= "Enter your search query here...", label= "Type an input and press Enter")
136
- state = gr.State([])
137
- with gr.Row():
138
- with gr.Column(scale=7):
139
- b1 = gr.Button().style(full_width=True)
140
- with gr.Column(scale=3):
141
- server_status_code = gr.Textbox(label="Status code from OpenAI server", )
142
-
143
- #top_p, temperature
144
- with gr.Accordion("Parameters", open=False):
145
- top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
146
- temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
147
- chat_counter = gr.Number(value=0, visible=False, precision=0)
148
-
149
- #Event handling
150
- inputs.submit( predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code],) #openai_api_key
151
- b1.click( predict, [system_msg, inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code],) #openai_api_key
152
-
153
- inputs.submit(set_visible_false, [], [system_msg])
154
- b1.click(set_visible_false, [], [system_msg])
155
- inputs.submit(set_visible_true, [], [accordion_msg])
156
- b1.click(set_visible_true, [], [accordion_msg])
157
-
158
- b1.click(reset_textbox, [], [inputs])
159
- inputs.submit(reset_textbox, [], [inputs])
160
-
161
- demo.queue(max_size=99, concurrency_count=20).launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cecil8352/vits-models/monotonic_align/core.py DELETED
@@ -1,36 +0,0 @@
1
- import numba
2
-
3
-
4
- @numba.jit(numba.void(numba.int32[:, :, ::1], numba.float32[:, :, ::1], numba.int32[::1], numba.int32[::1]),
5
- nopython=True, nogil=True)
6
- def maximum_path_jit(paths, values, t_ys, t_xs):
7
- b = paths.shape[0]
8
- max_neg_val = -1e9
9
- for i in range(int(b)):
10
- path = paths[i]
11
- value = values[i]
12
- t_y = t_ys[i]
13
- t_x = t_xs[i]
14
-
15
- v_prev = v_cur = 0.0
16
- index = t_x - 1
17
-
18
- for y in range(t_y):
19
- for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)):
20
- if x == y:
21
- v_cur = max_neg_val
22
- else:
23
- v_cur = value[y - 1, x]
24
- if x == 0:
25
- if y == 0:
26
- v_prev = 0.
27
- else:
28
- v_prev = max_neg_val
29
- else:
30
- v_prev = value[y - 1, x - 1]
31
- value[y, x] += max(v_prev, v_cur)
32
-
33
- for y in range(t_y - 1, -1, -1):
34
- path[y, index] = 1
35
- if index != 0 and (index == y or value[y - 1, index] < value[y - 1, index - 1]):
36
- index = index - 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cicooo/vits-uma-genshin-honkai/text/__init__.py DELETED
@@ -1,57 +0,0 @@
1
- """ from https://github.com/keithito/tacotron """
2
- from text import cleaners
3
- from text.symbols import symbols
4
-
5
-
6
- # Mappings from symbol to numeric ID and vice versa:
7
- _symbol_to_id = {s: i for i, s in enumerate(symbols)}
8
- _id_to_symbol = {i: s for i, s in enumerate(symbols)}
9
-
10
-
11
- def text_to_sequence(text, symbols, cleaner_names):
12
- '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
13
- Args:
14
- text: string to convert to a sequence
15
- cleaner_names: names of the cleaner functions to run the text through
16
- Returns:
17
- List of integers corresponding to the symbols in the text
18
- '''
19
- _symbol_to_id = {s: i for i, s in enumerate(symbols)}
20
- sequence = []
21
-
22
- clean_text = _clean_text(text, cleaner_names)
23
- for symbol in clean_text:
24
- if symbol not in _symbol_to_id.keys():
25
- continue
26
- symbol_id = _symbol_to_id[symbol]
27
- sequence += [symbol_id]
28
- return sequence, clean_text
29
-
30
-
31
- def cleaned_text_to_sequence(cleaned_text):
32
- '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
33
- Args:
34
- text: string to convert to a sequence
35
- Returns:
36
- List of integers corresponding to the symbols in the text
37
- '''
38
- sequence = [_symbol_to_id[symbol] for symbol in cleaned_text if symbol in _symbol_to_id.keys()]
39
- return sequence
40
-
41
-
42
- def sequence_to_text(sequence):
43
- '''Converts a sequence of IDs back to a string'''
44
- result = ''
45
- for symbol_id in sequence:
46
- s = _id_to_symbol[symbol_id]
47
- result += s
48
- return result
49
-
50
-
51
- def _clean_text(text, cleaner_names):
52
- for name in cleaner_names:
53
- cleaner = getattr(cleaners, name)
54
- if not cleaner:
55
- raise Exception('Unknown cleaner: %s' % name)
56
- text = cleaner(text)
57
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CikeyQI/Yunzai/Dockerfile DELETED
@@ -1,38 +0,0 @@
1
- # 使用基于 Node.js 18 的镜像
2
- FROM node:18
3
-
4
- # 安装 Redis
5
- RUN apt-get update && apt-get install -y redis-server
6
-
7
- # 安装 Chromium
8
- RUN apt install chromium -y
9
-
10
- # 将工作目录设置为 app 目录
11
- WORKDIR /app
12
-
13
- # 将项目文件复制到容器中
14
- COPY ./Yunzai /app
15
- COPY ./application.yaml /app
16
-
17
- # 安装插件
18
- RUN git clone --depth 1 https://github.com/TimeRainStarSky/Yunzai-genshin plugins/genshin
19
- RUN git clone --depth 1 https://github.com/yoimiya-kokomi/miao-plugin plugins/miao-plugin
20
- RUN git clone --depth 1 https://github.com/TimeRainStarSky/TRSS-Plugin plugins/TRSS-Plugin
21
- RUN git clone --depth 1 https://github.com/ap-plugin/mj-plugin.git plugins/mj-plugin
22
- RUN git clone --depth 1 https://github.com/ap-plugin/ap-plugin.git plugins/ap-plugin
23
- RUN git clone --depth 1 https://github.com/Ctrlcvs/xiaoyao-cvs-plugin.git plugins/xiaoyao-cvs-plugin/
24
- RUN git clone --depth=1 https://github.com/yeyang52/yenai-plugin.git plugins/yenai-plugin
25
- RUN git clone --depth=1 https://github.com/guoba-yunzai/guoba-plugin.git plugins/Guoba-Plugin
26
-
27
- # 拷贝 Guoba 配置文件
28
- COPY ./application.yaml ./plugins/Guoba-Plugin/config/
29
-
30
- # 给予权限
31
- RUN chmod -R 777 /app
32
-
33
- # 安装依赖
34
- RUN npm install -g pnpm
35
- RUN pnpm install
36
-
37
- # 启动应用程序
38
- CMD ["node", "app.js"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Clebersla/RVC_V2_Huggingface_Version/lib/infer_pack/transforms.py DELETED
@@ -1,209 +0,0 @@
1
- import torch
2
- from torch.nn import functional as F
3
-
4
- import numpy as np
5
-
6
-
7
- DEFAULT_MIN_BIN_WIDTH = 1e-3
8
- DEFAULT_MIN_BIN_HEIGHT = 1e-3
9
- DEFAULT_MIN_DERIVATIVE = 1e-3
10
-
11
-
12
- def piecewise_rational_quadratic_transform(
13
- inputs,
14
- unnormalized_widths,
15
- unnormalized_heights,
16
- unnormalized_derivatives,
17
- inverse=False,
18
- tails=None,
19
- tail_bound=1.0,
20
- min_bin_width=DEFAULT_MIN_BIN_WIDTH,
21
- min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
22
- min_derivative=DEFAULT_MIN_DERIVATIVE,
23
- ):
24
- if tails is None:
25
- spline_fn = rational_quadratic_spline
26
- spline_kwargs = {}
27
- else:
28
- spline_fn = unconstrained_rational_quadratic_spline
29
- spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
30
-
31
- outputs, logabsdet = spline_fn(
32
- inputs=inputs,
33
- unnormalized_widths=unnormalized_widths,
34
- unnormalized_heights=unnormalized_heights,
35
- unnormalized_derivatives=unnormalized_derivatives,
36
- inverse=inverse,
37
- min_bin_width=min_bin_width,
38
- min_bin_height=min_bin_height,
39
- min_derivative=min_derivative,
40
- **spline_kwargs
41
- )
42
- return outputs, logabsdet
43
-
44
-
45
- def searchsorted(bin_locations, inputs, eps=1e-6):
46
- bin_locations[..., -1] += eps
47
- return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
48
-
49
-
50
- def unconstrained_rational_quadratic_spline(
51
- inputs,
52
- unnormalized_widths,
53
- unnormalized_heights,
54
- unnormalized_derivatives,
55
- inverse=False,
56
- tails="linear",
57
- tail_bound=1.0,
58
- min_bin_width=DEFAULT_MIN_BIN_WIDTH,
59
- min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
60
- min_derivative=DEFAULT_MIN_DERIVATIVE,
61
- ):
62
- inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
63
- outside_interval_mask = ~inside_interval_mask
64
-
65
- outputs = torch.zeros_like(inputs)
66
- logabsdet = torch.zeros_like(inputs)
67
-
68
- if tails == "linear":
69
- unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
70
- constant = np.log(np.exp(1 - min_derivative) - 1)
71
- unnormalized_derivatives[..., 0] = constant
72
- unnormalized_derivatives[..., -1] = constant
73
-
74
- outputs[outside_interval_mask] = inputs[outside_interval_mask]
75
- logabsdet[outside_interval_mask] = 0
76
- else:
77
- raise RuntimeError("{} tails are not implemented.".format(tails))
78
-
79
- (
80
- outputs[inside_interval_mask],
81
- logabsdet[inside_interval_mask],
82
- ) = rational_quadratic_spline(
83
- inputs=inputs[inside_interval_mask],
84
- unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
85
- unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
86
- unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
87
- inverse=inverse,
88
- left=-tail_bound,
89
- right=tail_bound,
90
- bottom=-tail_bound,
91
- top=tail_bound,
92
- min_bin_width=min_bin_width,
93
- min_bin_height=min_bin_height,
94
- min_derivative=min_derivative,
95
- )
96
-
97
- return outputs, logabsdet
98
-
99
-
100
- def rational_quadratic_spline(
101
- inputs,
102
- unnormalized_widths,
103
- unnormalized_heights,
104
- unnormalized_derivatives,
105
- inverse=False,
106
- left=0.0,
107
- right=1.0,
108
- bottom=0.0,
109
- top=1.0,
110
- min_bin_width=DEFAULT_MIN_BIN_WIDTH,
111
- min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
112
- min_derivative=DEFAULT_MIN_DERIVATIVE,
113
- ):
114
- if torch.min(inputs) < left or torch.max(inputs) > right:
115
- raise ValueError("Input to a transform is not within its domain")
116
-
117
- num_bins = unnormalized_widths.shape[-1]
118
-
119
- if min_bin_width * num_bins > 1.0:
120
- raise ValueError("Minimal bin width too large for the number of bins")
121
- if min_bin_height * num_bins > 1.0:
122
- raise ValueError("Minimal bin height too large for the number of bins")
123
-
124
- widths = F.softmax(unnormalized_widths, dim=-1)
125
- widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
126
- cumwidths = torch.cumsum(widths, dim=-1)
127
- cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
128
- cumwidths = (right - left) * cumwidths + left
129
- cumwidths[..., 0] = left
130
- cumwidths[..., -1] = right
131
- widths = cumwidths[..., 1:] - cumwidths[..., :-1]
132
-
133
- derivatives = min_derivative + F.softplus(unnormalized_derivatives)
134
-
135
- heights = F.softmax(unnormalized_heights, dim=-1)
136
- heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
137
- cumheights = torch.cumsum(heights, dim=-1)
138
- cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
139
- cumheights = (top - bottom) * cumheights + bottom
140
- cumheights[..., 0] = bottom
141
- cumheights[..., -1] = top
142
- heights = cumheights[..., 1:] - cumheights[..., :-1]
143
-
144
- if inverse:
145
- bin_idx = searchsorted(cumheights, inputs)[..., None]
146
- else:
147
- bin_idx = searchsorted(cumwidths, inputs)[..., None]
148
-
149
- input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
150
- input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
151
-
152
- input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
153
- delta = heights / widths
154
- input_delta = delta.gather(-1, bin_idx)[..., 0]
155
-
156
- input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
157
- input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
158
-
159
- input_heights = heights.gather(-1, bin_idx)[..., 0]
160
-
161
- if inverse:
162
- a = (inputs - input_cumheights) * (
163
- input_derivatives + input_derivatives_plus_one - 2 * input_delta
164
- ) + input_heights * (input_delta - input_derivatives)
165
- b = input_heights * input_derivatives - (inputs - input_cumheights) * (
166
- input_derivatives + input_derivatives_plus_one - 2 * input_delta
167
- )
168
- c = -input_delta * (inputs - input_cumheights)
169
-
170
- discriminant = b.pow(2) - 4 * a * c
171
- assert (discriminant >= 0).all()
172
-
173
- root = (2 * c) / (-b - torch.sqrt(discriminant))
174
- outputs = root * input_bin_widths + input_cumwidths
175
-
176
- theta_one_minus_theta = root * (1 - root)
177
- denominator = input_delta + (
178
- (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
179
- * theta_one_minus_theta
180
- )
181
- derivative_numerator = input_delta.pow(2) * (
182
- input_derivatives_plus_one * root.pow(2)
183
- + 2 * input_delta * theta_one_minus_theta
184
- + input_derivatives * (1 - root).pow(2)
185
- )
186
- logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
187
-
188
- return outputs, -logabsdet
189
- else:
190
- theta = (inputs - input_cumwidths) / input_bin_widths
191
- theta_one_minus_theta = theta * (1 - theta)
192
-
193
- numerator = input_heights * (
194
- input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
195
- )
196
- denominator = input_delta + (
197
- (input_derivatives + input_derivatives_plus_one - 2 * input_delta)
198
- * theta_one_minus_theta
199
- )
200
- outputs = input_cumheights + numerator / denominator
201
-
202
- derivative_numerator = input_delta.pow(2) * (
203
- input_derivatives_plus_one * theta.pow(2)
204
- + 2 * input_delta * theta_one_minus_theta
205
- + input_derivatives * (1 - theta).pow(2)
206
- )
207
- logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
208
-
209
- return outputs, logabsdet
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cletrason/Cletrason-toad-in-the-mario-movie/Trainer.py DELETED
The diff for this file is too large to render. See raw diff
 
spaces/Cyril666/ContourNet-ABI/maskrcnn_benchmark/data/datasets/evaluation/word/util/thread_.py DELETED
@@ -1,62 +0,0 @@
1
- import threading
2
- from threading import Thread
3
-
4
- def get_current_thread():
5
- return threading.current_thread()
6
-
7
- def get_current_thread_name():
8
- return get_current_thread().getName()
9
-
10
- def is_alive(t):
11
- return t.is_alive()
12
-
13
- def create_and_start(name, target, daemon = True):
14
- t = Thread(target= target)
15
- t.daemon = True
16
- t.setName(name)
17
- t.start()
18
- return t
19
-
20
-
21
-
22
- class ThreadPool(object):
23
- def __init__(self, capacity = 10):
24
- import threadpool
25
- self.num_threads = capacity
26
- self.pool = threadpool.ThreadPool(10)
27
-
28
- def add(self, fn, args):
29
- import threadpool
30
- if type(args) == list:
31
- args = [(args, None)]
32
- elif type(args) == dict:
33
- args = [(None, args)]
34
- else:
35
- raise ValueError, "Unsuported args,", type(args)
36
- request = threadpool.makeRequests(fn, args)[0]
37
- self.pool.putRequest(request, block = False)
38
- self.pool.poll()
39
-
40
- def join(self):
41
- self.pool.wait()
42
-
43
- class ProcessPool(object):
44
- """
45
- Remember that function in function is not supported by multiprocessing.
46
- """
47
- def __init__(self, capacity = 8):
48
- from multiprocessing import Pool
49
-
50
- self.capacity = capacity
51
- self.pool = Pool(capacity)
52
-
53
- def add(self, fn, args):
54
- self.pool.apply_async(fn, args)
55
- # self.pool.poll()
56
- # self.pool.poll
57
-
58
- def join(self):
59
- self.pool.close()
60
- self.pool.join()
61
-
62
-