parquet-converter commited on
Commit
5a523ba
·
1 Parent(s): 222d235

Update parquet files (step 59 of 121)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. spaces/123Kumar/vits-uma-genshin-honkai123/attentions.py +0 -300
  2. spaces/17TheWord/vits-models/README.md +0 -14
  3. spaces/1acneusushi/gradio-2dmoleculeeditor/data/AutoCAD 2013 English Win 64bit.exe Whats New and Improved in AutoCAD 2013 Compared to Previous Versions.md +0 -117
  4. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Department 720p Download REPACK Movies.md +0 -29
  5. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Food Chemical Codex 8th Edition PDF Download A Comprehensive Guide to Food Standards and Specifications.md +0 -79
  6. spaces/1gistliPinn/ChatGPT4/Examples/Apex True Dbinput Pro 60 20.md +0 -6
  7. spaces/1gistliPinn/ChatGPT4/Examples/Bangla Book Tazkiratul Awliya Pdf Rapidshare.md +0 -14
  8. spaces/1gistliPinn/ChatGPT4/Examples/Ciudad De Dios 1080p Torrent HOT!.md +0 -6
  9. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Become the Ultimate Imposter with this Among Us Hack Download Now and Enjoy.md +0 -114
  10. spaces/1phancelerku/anime-remove-background/Download 2 Lite Music and Video Players and Stream Your Favorite Content.md +0 -120
  11. spaces/1phancelerku/anime-remove-background/Download Craftsman Crafting and Building APK and Create Your Own World.md +0 -124
  12. spaces/1phancelerku/anime-remove-background/Download Dr. Driving 2 for PC and Experience Realistic Driving Challenges.md +0 -128
  13. spaces/1phancelerku/anime-remove-background/Download PES 2020 Lite APK for Android Play PES 2021 with Just 50 MB of Storage.md +0 -126
  14. spaces/1phancelerku/anime-remove-background/Explore Upland A City of History Culture and Adventure.md +0 -104
  15. spaces/1toTree/lora_test/ppdiffusers/pipelines/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py +0 -110
  16. spaces/1toTree/lora_test/ppdiffusers/version.py +0 -17
  17. spaces/7hao/bingo/src/components/turn-counter.tsx +0 -23
  18. spaces/A00001/bingothoo/src/lib/hooks/use-copy-to-clipboard.tsx +0 -33
  19. spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/vocoder/hifigan/hifigan.py +0 -338
  20. spaces/AILab-CVC/SEED-LLaMA/models/seed_llama_tokenizer.py +0 -213
  21. spaces/AIWaves/SOP_Generation-single/gradio_base.py +0 -574
  22. spaces/AIatUIUC/CodeLATS/executors/factory.py +0 -8
  23. spaces/ASJMO/freegpt/g4f/Provider/Providers/Yqcloud.py +0 -39
  24. spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov5/__init__.py +0 -0
  25. spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_1_ClothesKeyPoint/mmpose_1_x/configs/fashion_2d_keypoint/topdown_heatmap/deepfashion2/td_hm_res50_4xb64-150e_deepfashion2_short_sleeved_dress_256x192.py +0 -172
  26. spaces/Abhaykoul/Prompt_generator_for_helpingAI-tti/app.py +0 -53
  27. spaces/AchyuthGamer/OpenGPT/g4f/Provider/HuggingChat.py +0 -104
  28. spaces/AgProfile/chatbotopenaihere/README.md +0 -12
  29. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/GetChildrenSizers.js +0 -17
  30. spaces/AkiKagura/Marco-Generation/README.md +0 -13
  31. spaces/Alesmikes/elvire01/README.md +0 -13
  32. spaces/Altinas/vits-uma-genshin-honkais/text/cleaners.py +0 -475
  33. spaces/Ameaou/academic-chatgpt3.1/crazy_functions/test_project/cpp/cppipc/shm.cpp +0 -103
  34. spaces/Amon1/ChatGPTForAcadamic/crazy_functions/test_project/cpp/cppipc/prod_cons.h +0 -433
  35. spaces/AndrewMetaBlock/emilyalsentzer-Bio_ClinicalBERT/README.md +0 -13
  36. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/stable_diffusion_jax_how_to.md +0 -251
  37. spaces/Andy1621/uniformer_image_segmentation/configs/deeplabv3/deeplabv3_r50-d8_480x480_40k_pascal_context.py +0 -10
  38. spaces/Andy1621/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r101-d8_512x512_20k_voc12aug.py +0 -2
  39. spaces/Artrajz/vits-simple-api/vits-simple-api-installer-latest.sh +0 -273
  40. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.py +0 -519
  41. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/_vendor/pyparsing/testing.py +0 -331
  42. spaces/Audio-AGI/AudioSep/models/CLAP/open_clip/utils.py +0 -361
  43. spaces/Basit12345/basit123/app.py +0 -25
  44. spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/pyparsing/diagram/__init__.py +0 -642
  45. spaces/Billyosoro/ESRGAN/scripts/generate_meta_info_pairdata.py +0 -49
  46. spaces/CVPR/Demo-Balanced-MSE/app.py +0 -300
  47. spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/models/mcan/mca.py +0 -189
  48. spaces/CVPR/LIVE/pybind11/include/pybind11/stl.h +0 -388
  49. spaces/CVPR/LIVE/thrust/thrust/detail/complex/csinh.h +0 -205
  50. spaces/CVPR/LIVE/thrust/thrust/iterator/detail/discard_iterator_base.h +0 -65
spaces/123Kumar/vits-uma-genshin-honkai123/attentions.py DELETED
@@ -1,300 +0,0 @@
1
- import math
2
- import torch
3
- from torch import nn
4
- from torch.nn import functional as F
5
-
6
- import commons
7
- from modules import LayerNorm
8
-
9
-
10
- class Encoder(nn.Module):
11
- def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
12
- super().__init__()
13
- self.hidden_channels = hidden_channels
14
- self.filter_channels = filter_channels
15
- self.n_heads = n_heads
16
- self.n_layers = n_layers
17
- self.kernel_size = kernel_size
18
- self.p_dropout = p_dropout
19
- self.window_size = window_size
20
-
21
- self.drop = nn.Dropout(p_dropout)
22
- self.attn_layers = nn.ModuleList()
23
- self.norm_layers_1 = nn.ModuleList()
24
- self.ffn_layers = nn.ModuleList()
25
- self.norm_layers_2 = nn.ModuleList()
26
- for i in range(self.n_layers):
27
- self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
28
- self.norm_layers_1.append(LayerNorm(hidden_channels))
29
- self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
30
- self.norm_layers_2.append(LayerNorm(hidden_channels))
31
-
32
- def forward(self, x, x_mask):
33
- attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
34
- x = x * x_mask
35
- for i in range(self.n_layers):
36
- y = self.attn_layers[i](x, x, attn_mask)
37
- y = self.drop(y)
38
- x = self.norm_layers_1[i](x + y)
39
-
40
- y = self.ffn_layers[i](x, x_mask)
41
- y = self.drop(y)
42
- x = self.norm_layers_2[i](x + y)
43
- x = x * x_mask
44
- return x
45
-
46
-
47
- class Decoder(nn.Module):
48
- def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
49
- super().__init__()
50
- self.hidden_channels = hidden_channels
51
- self.filter_channels = filter_channels
52
- self.n_heads = n_heads
53
- self.n_layers = n_layers
54
- self.kernel_size = kernel_size
55
- self.p_dropout = p_dropout
56
- self.proximal_bias = proximal_bias
57
- self.proximal_init = proximal_init
58
-
59
- self.drop = nn.Dropout(p_dropout)
60
- self.self_attn_layers = nn.ModuleList()
61
- self.norm_layers_0 = nn.ModuleList()
62
- self.encdec_attn_layers = nn.ModuleList()
63
- self.norm_layers_1 = nn.ModuleList()
64
- self.ffn_layers = nn.ModuleList()
65
- self.norm_layers_2 = nn.ModuleList()
66
- for i in range(self.n_layers):
67
- self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
68
- self.norm_layers_0.append(LayerNorm(hidden_channels))
69
- self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
70
- self.norm_layers_1.append(LayerNorm(hidden_channels))
71
- self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
72
- self.norm_layers_2.append(LayerNorm(hidden_channels))
73
-
74
- def forward(self, x, x_mask, h, h_mask):
75
- """
76
- x: decoder input
77
- h: encoder output
78
- """
79
- self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
80
- encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
81
- x = x * x_mask
82
- for i in range(self.n_layers):
83
- y = self.self_attn_layers[i](x, x, self_attn_mask)
84
- y = self.drop(y)
85
- x = self.norm_layers_0[i](x + y)
86
-
87
- y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
88
- y = self.drop(y)
89
- x = self.norm_layers_1[i](x + y)
90
-
91
- y = self.ffn_layers[i](x, x_mask)
92
- y = self.drop(y)
93
- x = self.norm_layers_2[i](x + y)
94
- x = x * x_mask
95
- return x
96
-
97
-
98
- class MultiHeadAttention(nn.Module):
99
- def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
100
- super().__init__()
101
- assert channels % n_heads == 0
102
-
103
- self.channels = channels
104
- self.out_channels = out_channels
105
- self.n_heads = n_heads
106
- self.p_dropout = p_dropout
107
- self.window_size = window_size
108
- self.heads_share = heads_share
109
- self.block_length = block_length
110
- self.proximal_bias = proximal_bias
111
- self.proximal_init = proximal_init
112
- self.attn = None
113
-
114
- self.k_channels = channels // n_heads
115
- self.conv_q = nn.Conv1d(channels, channels, 1)
116
- self.conv_k = nn.Conv1d(channels, channels, 1)
117
- self.conv_v = nn.Conv1d(channels, channels, 1)
118
- self.conv_o = nn.Conv1d(channels, out_channels, 1)
119
- self.drop = nn.Dropout(p_dropout)
120
-
121
- if window_size is not None:
122
- n_heads_rel = 1 if heads_share else n_heads
123
- rel_stddev = self.k_channels**-0.5
124
- self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
125
- self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
126
-
127
- nn.init.xavier_uniform_(self.conv_q.weight)
128
- nn.init.xavier_uniform_(self.conv_k.weight)
129
- nn.init.xavier_uniform_(self.conv_v.weight)
130
- if proximal_init:
131
- with torch.no_grad():
132
- self.conv_k.weight.copy_(self.conv_q.weight)
133
- self.conv_k.bias.copy_(self.conv_q.bias)
134
-
135
- def forward(self, x, c, attn_mask=None):
136
- q = self.conv_q(x)
137
- k = self.conv_k(c)
138
- v = self.conv_v(c)
139
-
140
- x, self.attn = self.attention(q, k, v, mask=attn_mask)
141
-
142
- x = self.conv_o(x)
143
- return x
144
-
145
- def attention(self, query, key, value, mask=None):
146
- # reshape [b, d, t] -> [b, n_h, t, d_k]
147
- b, d, t_s, t_t = (*key.size(), query.size(2))
148
- query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
149
- key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
150
- value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
151
-
152
- scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
153
- if self.window_size is not None:
154
- assert t_s == t_t, "Relative attention is only available for self-attention."
155
- key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
156
- rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
157
- scores_local = self._relative_position_to_absolute_position(rel_logits)
158
- scores = scores + scores_local
159
- if self.proximal_bias:
160
- assert t_s == t_t, "Proximal bias is only available for self-attention."
161
- scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
162
- if mask is not None:
163
- scores = scores.masked_fill(mask == 0, -1e4)
164
- if self.block_length is not None:
165
- assert t_s == t_t, "Local attention is only available for self-attention."
166
- block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
167
- scores = scores.masked_fill(block_mask == 0, -1e4)
168
- p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
169
- p_attn = self.drop(p_attn)
170
- output = torch.matmul(p_attn, value)
171
- if self.window_size is not None:
172
- relative_weights = self._absolute_position_to_relative_position(p_attn)
173
- value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
174
- output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
175
- output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
176
- return output, p_attn
177
-
178
- def _matmul_with_relative_values(self, x, y):
179
- """
180
- x: [b, h, l, m]
181
- y: [h or 1, m, d]
182
- ret: [b, h, l, d]
183
- """
184
- ret = torch.matmul(x, y.unsqueeze(0))
185
- return ret
186
-
187
- def _matmul_with_relative_keys(self, x, y):
188
- """
189
- x: [b, h, l, d]
190
- y: [h or 1, m, d]
191
- ret: [b, h, l, m]
192
- """
193
- ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
194
- return ret
195
-
196
- def _get_relative_embeddings(self, relative_embeddings, length):
197
- max_relative_position = 2 * self.window_size + 1
198
- # Pad first before slice to avoid using cond ops.
199
- pad_length = max(length - (self.window_size + 1), 0)
200
- slice_start_position = max((self.window_size + 1) - length, 0)
201
- slice_end_position = slice_start_position + 2 * length - 1
202
- if pad_length > 0:
203
- padded_relative_embeddings = F.pad(
204
- relative_embeddings,
205
- commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
206
- else:
207
- padded_relative_embeddings = relative_embeddings
208
- used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
209
- return used_relative_embeddings
210
-
211
- def _relative_position_to_absolute_position(self, x):
212
- """
213
- x: [b, h, l, 2*l-1]
214
- ret: [b, h, l, l]
215
- """
216
- batch, heads, length, _ = x.size()
217
- # Concat columns of pad to shift from relative to absolute indexing.
218
- x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
219
-
220
- # Concat extra elements so to add up to shape (len+1, 2*len-1).
221
- x_flat = x.view([batch, heads, length * 2 * length])
222
- x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
223
-
224
- # Reshape and slice out the padded elements.
225
- x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
226
- return x_final
227
-
228
- def _absolute_position_to_relative_position(self, x):
229
- """
230
- x: [b, h, l, l]
231
- ret: [b, h, l, 2*l-1]
232
- """
233
- batch, heads, length, _ = x.size()
234
- # padd along column
235
- x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
236
- x_flat = x.view([batch, heads, length**2 + length*(length -1)])
237
- # add 0's in the beginning that will skew the elements after reshape
238
- x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
239
- x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
240
- return x_final
241
-
242
- def _attention_bias_proximal(self, length):
243
- """Bias for self-attention to encourage attention to close positions.
244
- Args:
245
- length: an integer scalar.
246
- Returns:
247
- a Tensor with shape [1, 1, length, length]
248
- """
249
- r = torch.arange(length, dtype=torch.float32)
250
- diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
251
- return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
252
-
253
-
254
- class FFN(nn.Module):
255
- def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
256
- super().__init__()
257
- self.in_channels = in_channels
258
- self.out_channels = out_channels
259
- self.filter_channels = filter_channels
260
- self.kernel_size = kernel_size
261
- self.p_dropout = p_dropout
262
- self.activation = activation
263
- self.causal = causal
264
-
265
- if causal:
266
- self.padding = self._causal_padding
267
- else:
268
- self.padding = self._same_padding
269
-
270
- self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
271
- self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
272
- self.drop = nn.Dropout(p_dropout)
273
-
274
- def forward(self, x, x_mask):
275
- x = self.conv_1(self.padding(x * x_mask))
276
- if self.activation == "gelu":
277
- x = x * torch.sigmoid(1.702 * x)
278
- else:
279
- x = torch.relu(x)
280
- x = self.drop(x)
281
- x = self.conv_2(self.padding(x * x_mask))
282
- return x * x_mask
283
-
284
- def _causal_padding(self, x):
285
- if self.kernel_size == 1:
286
- return x
287
- pad_l = self.kernel_size - 1
288
- pad_r = 0
289
- padding = [[0, 0], [0, 0], [pad_l, pad_r]]
290
- x = F.pad(x, commons.convert_pad_shape(padding))
291
- return x
292
-
293
- def _same_padding(self, x):
294
- if self.kernel_size == 1:
295
- return x
296
- pad_l = (self.kernel_size - 1) // 2
297
- pad_r = self.kernel_size // 2
298
- padding = [[0, 0], [0, 0], [pad_l, pad_r]]
299
- x = F.pad(x, commons.convert_pad_shape(padding))
300
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/17TheWord/vits-models/README.md DELETED
@@ -1,14 +0,0 @@
1
- ---
2
- title: Vits Models
3
- emoji: 🏃
4
- colorFrom: pink
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 3.17.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- duplicated_from: sayashi/vits-models
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/AutoCAD 2013 English Win 64bit.exe Whats New and Improved in AutoCAD 2013 Compared to Previous Versions.md DELETED
@@ -1,117 +0,0 @@
1
- <br />
2
- <h1>AutoCAD 2013: A Comprehensive Review</h1>
3
- <p>Are you looking for a powerful and versatile software to create 2D and 3D designs? Do you want to improve your productivity and efficiency with new tools and features? If so, you might want to check out AutoCAD 2013, the latest version of the popular CAD software from Autodesk. In this article, we will review AutoCAD 2013 and highlight some of its key features and benefits. We will also show you how to use some of the new tools and commands to create section and detail views, work with objects, and manage your files.</p>
4
- <h2>Introduction</h2>
5
- <h3>What is AutoCAD 2013?</h3>
6
- <p>AutoCAD 2013 is a computer-aided design (CAD) software that allows you to create 2D and 3D drawings for various purposes. You can use AutoCAD 2013 to design buildings, products, landscapes, mechanical parts, electrical circuits, and more. You can also use AutoCAD 2013 to edit, annotate, dimension, print, and share your drawings with others.</p>
7
- <h2>AutoCAD.2013.English.Win.64bit.exe</h2><br /><p><b><b>Download</b> &#10026;&#10026;&#10026; <a href="https://byltly.com/2uKwfo">https://byltly.com/2uKwfo</a></b></p><br /><br />
8
- <h3>Why use AutoCAD 2013?</h3>
9
- <p>AutoCAD 2013 is a powerful and versatile software that can help you with various design tasks. Here are some of the reasons why you might want to use AutoCAD 2013:</p>
10
- <ul>
11
- <li>It has a user-friendly interface that allows you to access various tools and commands easily.</li>
12
- <li>It has a wide range of drawing and editing tools that allow you to create accurate and detailed drawings.</li>
13
- <li>It has many new features that enhance your productivity and efficiency, such as command line enhancements, in-canvas property preview, file tabs, array tool improvements, offset tool preview, point cloud support, and Autodesk 360 integration.</li>
14
- <li>It supports various file formats and compatibility with other software, such as DWG, DXF, DWF, PDF, JPG, PNG, BMP, TIFF, STEP, IGES, STL, SAT, SKP, FBX, RVT, IPT, IAM, CATPART, CATPRODUCT, NX, JT, PROE/CREO.</li>
15
- <li>It allows you to create section and detail views from your 3D models directly in AutoCAD 2013.</li>
16
- <li>It allows you to collaborate and share your drawings with others through Autodesk 360 cloud service.</li>
17
- </ul>
18
- <h2>The interface</h2>
19
- <h3>What's new in AutoCAD 2013 interface?</h3>
20
- <p>AutoCAD 2013 has some changes in its interface that make it more user-friendly and efficient. Here are some of the new features in AutoCAD 2013 interface:</p>
21
- <h4>Command line</h4>
22
- <p>The command line is one of the most important tools in AutoCAD. It allows you to enter commands and options quickly and accurately. In AutoCAD 2013, the command line has been improved with several enhancements:</p>
23
- <ul>
24
- <li>You can dock or undock the command line as you prefer. You can also resize it or move it around the screen.</li>
25
- <li>You can see clickable options on the command line when you enter a command. You can also use the arrow keys or the mouse wheel to scroll through the options.</li>
26
- <li>You can see synonyms for commands on the command line. For example, if you type "L", you will see "LINE" as well as "PLINE" (polyline) and "MLINE" (multiline).</li>
27
- <li>You can see tooltips for commands on the command line. For example, if you hover over "LINE", you will see a brief description of what the command does.</li>
28
- <li>You can customize the appearance of the command line by changing its color scheme or font size.</li>
29
- </ul>
30
- <h4>In-canvas property preview</h4>
31
- <p>In-canvas property preview is a new feature that allows you to see live updates when you try to change the properties of objects. For example, if you select an object and try to change its color or layer on the properties palette or the ribbon panel, you will see how it looks on the drawing area before applying the change. This feature can help you make better design decisions and avoid mistakes.</p>
32
- <h4>Welcome screen</h4>
33
- <p>The welcome screen is a new feature that appears when you start AutoCAD 2013 for the first time or when you close all drawings. It provides quick access to various resources and tasks that can help you get started with AutoCAD 2013. On the welcome screen, you can:</p>
34
- <ul>
35
- <li>Create a new drawing or open an existing one.</li>
36
- <li>Access online learning materials such as tutorials, videos, tips & tricks.</li>
37
- <li>Access online services such as Autodesk Exchange Apps store or Autodesk Knowledge Network.</li>
38
- <li>Access recent documents or folders.</li>
39
- <li>Change your user profile or workspace settings.</li>
40
- </ul>
41
- <h2>Create section and detail views</h2>
42
- <h3>How to create section views in AutoCAD 2013?</h3>
43
- <p>A section view is a view that shows a cross-section of an object or a part of it. It can help you show hidden details or dimensions that are not visible in other views. In AutoCAD 2013, you can create section views from your 3D models directly in AutoCAD using these steps:</p>
44
- <ol>
45
- <li>Create a section plane using the SECTIONPLANE command. You can specify various options such as orientation, alignment, location, size, and name of the section plane.</li>
46
- <li>Create a section view using the SECTIONVIEW command. You can specify various options such as style, label, scale, and location of the section view.</li>
47
- <li>Edit or update the section view using the SECTIONVIEWEDIT command. You can modify various properties such as visibility, color, linetype, hatch pattern, and boundary of the section view.</li>
48
- </ol>
49
- <h4>Section plane tool</h4>
50
- <p>The section plane tool allows you to create a section plane that defines the cutting plane for a section view. You can access this tool from the Home tab > Section panel > Section Plane button or by typing SECTIONPLANE on the command line. When you use this tool, you will see various options on the command line or on the ribbon panel:</p>
51
- <p>How to install AutoCAD 2013 English version on Windows 64-bit system<br />
52
- AutoCAD 2013 English Win 64-bit download link<br />
53
- AutoCAD 2013 English Win 64-bit crack file<br />
54
- AutoCAD 2013 English Win 64-bit serial number<br />
55
- AutoCAD 2013 English Win 64-bit activation code<br />
56
- AutoCAD 2013 English Win 64-bit keygen<br />
57
- AutoCAD 2013 English Win 64-bit patch<br />
58
- AutoCAD 2013 English Win 64-bit license key<br />
59
- AutoCAD 2013 English Win 64-bit product key<br />
60
- AutoCAD 2013 English Win 64-bit free trial<br />
61
- AutoCAD 2013 English Win 64-bit full version<br />
62
- AutoCAD 2013 English Win 64-bit offline installer<br />
63
- AutoCAD 2013 English Win 64-bit system requirements<br />
64
- AutoCAD 2013 English Win 64-bit features<br />
65
- AutoCAD 2013 English Win 64-bit tutorial<br />
66
- AutoCAD 2013 English Win 64-bit user guide<br />
67
- AutoCAD 2013 English Win 64-bit tips and tricks<br />
68
- AutoCAD 2013 English Win 64-bit best practices<br />
69
- AutoCAD 2013 English Win 64-bit shortcuts<br />
70
- AutoCAD 2013 English Win 64-bit commands<br />
71
- AutoCAD 2013 English Win 64-bit tools and functions<br />
72
- AutoCAD 2013 English Win 64-bit plugins and extensions<br />
73
- AutoCAD 2013 English Win 64-bit templates and blocks<br />
74
- AutoCAD 2013 English Win 64-bit drawings and designs<br />
75
- AutoCAD 2013 English Win 64-bit projects and examples<br />
76
- AutoCAD 2013 English Win 64-bit problems and solutions<br />
77
- AutoCAD 2013 English Win 64-bit errors and fixes<br />
78
- AutoCAD 2013 English Win 64-bit updates and upgrades<br />
79
- AutoCAD 2013 English Win 64-bit compatibility and interoperability<br />
80
- AutoCAD 2013 English Win 64-bit comparison and review<br />
81
- AutoCAD 2013 English Win 64-bit alternatives and competitors<br />
82
- AutoCAD 2013 English Win 64-bit advantages and disadvantages<br />
83
- AutoCAD 2013 English Win 64-bit pros and cons<br />
84
- AutoCAD 2013 English Win 64-bit benefits and drawbacks<br />
85
- AutoCAD 2013 English Win</p>
86
- <ul>
87
- <li>Orient: This option allows you to specify how to orient the section plane relative to your model. You can choose from horizontal, vertical, aligned, or angled orientations.</li>
88
- <li>Align: This option allows you to align the section plane with an existing object such as a face, an edge, a curve, or a point. You can also use this option to flip or rotate the section plane after alignment.</li>
89
- <li>Location: This option allows you to specify where to place the section plane relative to your model. You can choose from center, offset, or two points locations.</li>
90
- <li>Size: This option allows you to specify how big or small the section plane should be. You can choose from automatic, fixed, or custom sizes.</li>
91
- <li>Name: This option allows you to assign a name to your section plane for easy identification. You can also rename your section plane later using this option.</li>
92
- </ul>
93
- <h4>Section view style manager</h4>
94
- <p>The section view style manager allows you to create and manage different styles for your section views. A style defines how your section view looks like in terms of visibility, color, linetype, hatch pattern, and boundary. You can access this tool from the Annotate tab > Section panel > Section View Style button or by typing SECTIONVIEWSTYLE on the command line. When you use this tool, you will see the Section View Style Manager dialog box where you can create, copy, edit, or delete section view styles. You can also specify a default section view style for your drawing.</p>
95
- <h4>Section view label and scale</h4>
96
- <p>The section view label and scale are the text elements that appear on the section view to identify it and show its scale factor. You can customize the appearance and content of the section view label and scale using label styles. You can access label styles from the Annotate tab > Section panel > Section View Label button or by typing SECTIONVIEWLABEL on the command line. When you use this tool, you will see the Section View Label Style dialog box where you can create, copy, edit, or delete label styles. You can also specify a default label style for your section views.</p>
97
- <h3>How to create detail views in AutoCAD 2013?</h3>
98
- <p>A detail view is a view that shows a magnified portion of an object or a part of it. It can help you show small details or dimensions that are not clear in other views. In AutoCAD 2013, you can create detail views from your 2D drawings or 3D models directly in AutoCAD using these steps:</p>
99
- <ol>
100
- <li>Create a detail boundary using the DETAIL command. You can specify various options such as shape, size, and location of the detail boundary.</li>
101
- <li>Create a detail view using the DETAILVIEW command. You can specify various options such as style, label, scale, and location of the detail view.</li>
102
- <li>Edit or update the detail view using the DETAILVIEWEDIT command. You can modify various properties such as visibility, color, linetype, hatch pattern, and boundary of the detail view.</li>
103
- </ol>
104
- <h4>Detail view tool</h4>
105
- <p>The detail view tool allows you to create a detail boundary that defines the area to be magnified for a detail view. You can access this tool from the Home tab > Section panel > Detail button or by typing DETAIL on the command line. When you use this tool, you will see various options on the command line or on the ribbon panel:</p>
106
- <ul>
107
- <li>Shape: This option allows you to specify the shape of the detail boundary. You can choose from circular, rectangular, or polygonal shapes.</li>
108
- <li>Size: This option allows you to specify the size of the detail boundary. You can choose from automatic, fixed, or custom sizes.</li>
109
- <li>Location: This option allows you to specify where to place the detail boundary relative to your drawing. You can choose from center, offset, or two points locations.</li>
110
- <li>Name: This option allows you to assign a name to your detail boundary for easy identification. You can also rename your detail boundary later using this option.</li>
111
- </ul>
112
- <h4>Detail view style manager</h4>
113
- <p>The detail view style manager allows you to create and manage different styles for your detail views. A style defines how your detail view looks like in terms of visibility, color, linetype, hatch pattern, and boundary. You can access this tool from the Annotate tab > Section panel > Detail View Style button or by typing DETAILVIEWSTYLE on the command line. When you use this tool, you will see the Detail View Style Manager dialog box where you can create, copy, edit, or delete detail view styles. You can also specify a default detail view style for your drawing.</p>
114
- <h4>Detail view label and scale</h4>
115
- <p>The detail view label and scale are the text elements that appear on the detail view to identify it and show its scale factor. You can customize the appearance and content of the detail view label and scale using label styles. You can access label styles from the Annotate tab > Section panel > Detail View Label button or by typing DETAILVIEWLABEL on the command line. When you use this tool, you will see the Detail View Label Style dialog box where you can create, copy, edit, or delete label styles. You can also specify a default label style for your detail views.</p> 0a6ba089eb<br />
116
- <br />
117
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Department 720p Download REPACK Movies.md DELETED
@@ -1,29 +0,0 @@
1
- <br />
2
- <h1>How to Download Department Movie in 720p Quality</h1>
3
- <p>If you are looking for a way to download Department movie in 720p quality, you have come to the right place. Department is a 2012 Hindi action film directed by Ram Gopal Varma, starring Amitabh Bachchan, Sanjay Dutt and Rana Daggubati. The film follows a special police unit that deals with underworld crimes and corruption.</p>
4
- <h2>Department 720p Download Movies</h2><br /><p><b><b>DOWNLOAD</b> --->>> <a href="https://byltly.com/2uKxnm">https://byltly.com/2uKxnm</a></b></p><br /><br />
5
- <p>Department movie is available for download on YTS.MX, a popular torrent site that offers high-quality movies in small file sizes. YTS.MX is the only new official domain for YIFY Movies, a group that releases movies encoded with x264 codec and MP4 container for best compatibility with all devices.</p>
6
- <p>To download Department movie in 720p quality from YTS.MX, you need to follow these steps:</p>
7
- <ol>
8
- <li>Visit <a href="https://yts.mx/">https://yts.mx/</a> and search for Department movie.</li>
9
- <li>Select the movie from the search results and click on the download button.</li>
10
- <li>Choose the 720p quality option and click on the magnet link or torrent file.</li>
11
- <li>Open the magnet link or torrent file with your preferred torrent client, such as uTorrent or BitTorrent.</li>
12
- <li>Wait for the download to complete and enjoy watching Department movie in 720p quality.</li>
13
- </ol>
14
- <p>Downloading Department movie in 720p quality from YTS.MX is easy and fast. However, you should be aware of the risks involved in using torrent sites, such as malware, viruses, legal issues and ISP throttling. Therefore, it is recommended that you use a VPN service to protect your privacy and security while downloading movies from torrent sites.</p>
15
- <p>A VPN service will encrypt your internet traffic and hide your IP address from your ISP and other third parties. This way, you can download Department movie in 720p quality from YTS.MX without worrying about being tracked or blocked. You can also access geo-restricted content and bypass censorship with a VPN service.</p>
16
- <p>There are many VPN services available online, but not all of them are reliable and trustworthy. Some of them may keep logs of your activities, sell your data to advertisers or expose you to malware. Therefore, you should choose a VPN service that has a good reputation, fast speed, strong encryption and no-logs policy.</p>
17
- <p>One of the best VPN services that meets these criteria is ExpressVPN. ExpressVPN is a leading VPN provider that offers high-speed servers in over 94 countries, AES-256 encryption, kill switch feature, split tunneling feature and strict no-logs policy. ExpressVPN also has a 30-day money-back guarantee and 24/7 customer support.</p>
18
- <p></p>
19
- <p>To use ExpressVPN to download Department movie in 720p quality from YTS.MX, you need to follow these steps:</p>
20
- <ol>
21
- <li>Visit <a href="https://www.expressvpn.com/">https://www.expressvpn.com/</a> and sign up for an account.</li>
22
- <li>Download and install the ExpressVPN app on your device.</li>
23
- <li>Launch the app and connect to a server of your choice.</li>
24
- <li>Visit <a href="https://yts.mx/">https://yts.mx/</a> and download Department movie in 720p quality as described above.</li>
25
- <li>Enjoy watching Department movie in 720p quality with ExpressVPN.</li>
26
- </ol>
27
- <p>Downloading Department movie in 720p quality from YTS.MX is a great way to enjoy this action-packed film. However, you should always use a VPN service like ExpressVPN to protect yourself from online threats and restrictions while downloading movies from torrent sites. ExpressVPN will ensure that you have a safe and smooth downloading experience.</p> 81aa517590<br />
28
- <br />
29
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Food Chemical Codex 8th Edition PDF Download A Comprehensive Guide to Food Standards and Specifications.md DELETED
@@ -1,79 +0,0 @@
1
-
2
- <h1>Food Chemical Codex 8th Edition PDF Download: What You Need to Know</h1>
3
- <p>If you are involved in the food industry, you may have heard of the Food Chemicals Codex (FCC), a compendium of internationally recognized standards for determining the purity and quality of food ingredients. The FCC is a valuable resource for authenticating a wide variety of ingredients, including processing aids, preservatives, flavorings, colorants, and nutrients.</p>
4
- <h2>food chemical codex 8th edition pdf download</h2><br /><p><b><b>Download File</b> &hArr; <a href="https://byltly.com/2uKwKu">https://byltly.com/2uKwKu</a></b></p><br /><br />
5
- <p>But did you know that the FCC has been updated to its eighth edition, which was published in March 2012? And did you know that you can access the FCC 8th edition online as a PDF file? In this article, we will tell you everything you need to know about the FCC 8th edition PDF download, including its main features, updates, benefits, and applications. Read on to find out more!</p>
6
- <h2>Introduction</h2>
7
- <h3>What is Food Chemical Codex (FCC)?</h3>
8
- <p>The Food Chemicals Codex (FCC) is a compendium of internationally recognized standards for determining the purity and quality of food ingredients. It is published by the U.S. Pharmacopeial Convention (USP), a scientific nonprofit organization that sets standards for medicines, dietary supplements, and food ingredients.</p>
9
- <p>The FCC contains monographs that provide specifications for identity, strength, quality, and purity of food ingredients. It also contains appendices that provide general information on methods of analysis, processes, and procedures. The FCC is updated regularly with new and revised monographs and appendices to reflect the latest scientific knowledge and industry practices.</p>
10
- <h3>Why is FCC important for food quality and safety?</h3>
11
- <p>The FCC is important for food quality and safety because it helps ensure that food ingredients are authentic, consistent, and safe for consumption. By following the FCC standards, food manufacturers and suppliers can verify the identity and quality of their ingredients, prevent adulteration and contamination, comply with regulatory requirements, and protect consumer health.</p>
12
- <p>The FCC is also important for food regulators and inspectors who use it as a reference for enforcing food laws and regulations. The FCC helps them to identify and evaluate food ingredients, detect fraud and mislabeling, monitor compliance with standards, and ensure public health protection.</p>
13
- <h3>How to access FCC 8th edition online?</h3>
14
- <p>The FCC 8th edition is available online as a PDF file that can be downloaded from the USP website. To access the FCC 8th edition PDF download, you need to register for a free account on the USP website. Once you register, you can log in and go to the <a href="https://nap.nationalacademies.org/resource/fcc/">Food Chemicals Codex page</a>. There you will find links to download the FCC monographs in PDF format.</p>
15
- <p>The FCC 8th edition PDF download includes all the monographs that were published in the book version of the FCC 8th edition, as well as the first three supplements that were published later. The supplements contain new and revised monographs and appendices that were added after the publication of the book version. The USP website also provides errata, commentary, revisions, and notices related to the FCC 8th edition.</p>
16
- <h2>FCC 8th Edition: Main Features and Updates</h2>
17
- <h3>New and revised monographs</h3>
18
- <p>The FCC 8th edition contains over 1,200 monographs that provide specifications for identity, strength, quality, and purity of food ingredients. The monographs cover a wide range of categories such as acids, alcohols, antioxidants, aromatic chemicals, baking powders, bases, biological products, carbohydrates, colors, dairy products, emulsifiers, enzymes, fats, fibers, flavors, gums, hydrocolloids, minerals, oils, preservatives, proteins, salts, spices, starches, sweeteners, vitamins, and yeast products.</p>
19
- <p>Food Chemicals Codex PDF Monographs Download[^1^]<br />
20
- FCC 8th Edition Book Errata[^2^]<br />
21
- Food Chemicals Codex (FCC) Online[^3^]<br />
22
- FCC 8th Edition Commentary[^2^] [^3^]<br />
23
- FCC 8th Edition Revisions[^2^] [^3^]<br />
24
- FCC 8th Edition First Supplement[^2^]<br />
25
- FCC 8th Edition Second Supplement[^2^]<br />
26
- FCC 8th Edition Third Supplement[^2^]<br />
27
- Food Chemicals Codex Aspartame Monograph[^1^]<br />
28
- Food Chemicals Codex Autolyzed Yeast Monograph[^1^]<br />
29
- Food Chemicals Codex beta-Cyclodextrin Monograph[^1^]<br />
30
- Food Chemicals Codex Calcium Lignosulfonate Monograph[^1^]<br />
31
- Food Chemicals Codex Calcium Phosphate Monograph[^1^]<br />
32
- Food Chemicals Codex Calcium Silicate Monograph[^1^]<br />
33
- Food Chemicals Codex Carbon Dioxide Monograph[^1^]<br />
34
- Food Chemicals Codex Sodium Carboxymethylcellulose Monograph[^1^]<br />
35
- Food Chemicals Codex Dioctyl Sodium Sulfosuccinate Monograph[^1^]<br />
36
- Food Chemicals Codex Dextrin Monograph[^1^]<br />
37
- Food Chemicals Codex Enzyme-Modified Fat Monograph[^1^]<br />
38
- Food Chemicals Codex Konjac Flour Monograph[^1^]<br />
39
- Food Chemicals Codex L-Glutamic Acid Monograph[^1^]<br />
40
- Food Chemicals Codex Magnesium Phosphate Monograph[^1^]<br />
41
- Food Chemicals Codex Niacin Monograph[^1^]<br />
42
- Food Chemicals Codex Niacinamide Monograph[^1^]<br />
43
- Food Chemicals Codex Pectins Monograph[^1^]<br />
44
- Food Chemicals Codex Potassium Phosphate Monograph[^1^]<br />
45
- Food Chemicals Codex Sodium Acid Pyrophosphate Monograph[^1^]<br />
46
- Food Chemicals Codex Sodium Lignosulfonate Monograph[^1^]<br />
47
- Food Chemicals Codex Sodium Tripolyphosphate Monograph[^1^]<br />
48
- Food Chemicals Codex Spice Oleoresins Monograph[^1^]<br />
49
- Food Chemicals Codex Sugar Beet Fiber Monograph[^1^]<br />
50
- Free Adobe Acrobat Reader Download for FCC PDF Files<br />
51
- How to Configure Browser to Save PDF Files<br />
52
- FCC 8th Edition New CFSAN URL Notice<br />
53
- Amended Appendix Section Titles for FCC 8th Edition<br />
54
- Commentary on FCC 8th Edition First Supplement<br />
55
- Commentary on FCC 8th Edition Second Supplement<br />
56
- Commentary on FCC 8th Edition Third Supplement<br />
57
- Revisions for FCC 8th Edition First Supplement<br />
58
- Revisions for FCC 8th Edition Second Supplement<br />
59
- Revisions for FCC 8th Edition Third Supplement<br />
60
- How to Access FCC Online Subscription<br />
61
- How to Search FCC Online Database<br />
62
- How to Submit Comments on FCC Online Revisions<br />
63
- How to Contact FCC Online Support<br />
64
- Benefits of Using FCC Online Service<br />
65
- Features of FCC Online Platform<br />
66
- FCC Online User Guide and FAQ<br />
67
- FCC Online Terms and Conditions</p>
68
- <p>The FCC 8th edition also includes new and revised monographs that reflect the latest scientific knowledge and industry practices. Some examples of new monographs are aspartame, beta-cyclodextrin, calcium lignosulfonate, dioctyl sodium sulfosuccinate, enzyme-modified fat, konjac flour, magnesium phosphate dibasic, niacinamide, potassium phosphate dibasic, sodium acid pyrophosphate, sodium lignosulfonate, sodium tripolyphosphate, spice oleoresins, and sugar beet fiber.</p>
69
- <h3>New and revised appendices</h3>
70
- <p>The FCC 8th edition contains over 40 appendices that provide general information on methods of analysis, processes, and procedures related to food ingredients. The appendices cover topics such as acidity or alkalinity measurement, aflatoxins detection, arsenic determination, ash content determination, color measurement, fatty acid composition analysis, heavy metals testing, iodine value calculation, lead determination, microbiological examination, moisture content determination, nitrogen determination by Kjeldahl method optical rotation measurement pH measurement refractive index measurement solubility test specific gravity measurement sulfur dioxide determination and viscosity measurement.</p>
71
- <p>The FCC 8th edition also includes new and revised appendices that reflect the latest scientific knowledge and industry practices. Some examples of new appendices are A-1 General Information on Methods of Analysis A-2 General Information on Processes A-4 General Information on Procedures A-5 General Information on Reference Materials A-6 General Information on Reagents A-7 General Information on Solutions A-9 General Information on Units A-10 General Information on Validation A-11 General Information on Verification and A-12 General Information on Water.</p>
72
- <h3>New and revised general tests and assays</h3>
73
- <p>The FCC 8th edition contains over 100 general tests and assays that provide methods for determining various properties or characteristics of food ingredients. The general tests and assays cover aspects such as acidity or alkalinity test alcohol content test antioxidant activity assay ash test bacterial endotoxins test carbohydrate content test color test enzymatic activity assay fat content test fiber content test flavor test heavy metals test iodine value test lead content test microbial limit test moisture content test nitrogen content test optical rotation test pH test protein content test refractive index test solubility test specific gravity test sulfur dioxide content test and viscosity test.</p>
74
- <p>The FCC 8th edition also includes new and revised general tests and assays that reflect the latest scientific knowledge and industry practices. Some examples of new general tests and assays are Aflatoxins Test Arsenic Test Calcium Test Chloride Test Copper Test Iron Test Magnesium Test Mercury Test Phosphorus Test Potassium Test Selenium Test Sodium Test Zinc Test and Vitamin Assays.</p>
75
- <h3>New and revised commentary</h3>
76
- <p>The FCC 8th edition contains commentary that provides explanations or clarifications on various aspects of the monographs or appendices. The commentary covers topics such as changes or updates made to the monographs or appendices rationale or justification for the changes or updates references or sources used for the changes or updates and additional information or guidance related to the monographs or appendices.</p>
77
- <p>The FCC 8th edition also includes new and revised commentary that reflect the latest scientific knowledge and industry practices. Some examples of new or revised commentary are Commentary on Aspartame Monograph Commentary on Beta-Cyclodextrin Monograph Commentary on Calcium Lignosulfonate Monograph</p> 0a6ba089eb<br />
78
- <br />
79
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Apex True Dbinput Pro 60 20.md DELETED
@@ -1,6 +0,0 @@
1
- <h2>Apex True Dbinput Pro 60 20</h2><br /><p><b><b>Download File</b> > <a href="https://imgfil.com/2uxXuV">https://imgfil.com/2uxXuV</a></b></p><br /><br />
2
- <br />
3
- as shown in Fig. 8. When it is not in the unlocked position, use the screwdriver pro‑ ... Storage temperature range: –20 °C to 60 °C (–4 °F to 140 °F). Relative ... moves from the probe towards the base, the apex or in both directions. ... amplification curves for 40, 65 and 90 dB input level, the Target curve and the Crossover. 4d29de3e1b<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Bangla Book Tazkiratul Awliya Pdf Rapidshare.md DELETED
@@ -1,14 +0,0 @@
1
- <h2>Bangla Book Tazkiratul Awliya Pdf Rapidshare</h2><br /><p><b><b>Download Zip</b> &mdash;&mdash;&mdash;>>> <a href="https://imgfil.com/2uy1OA">https://imgfil.com/2uy1OA</a></b></p><br /><br />
2
- <br />
3
- You can raise money and awareness for a cause you care about ! We provide you with an incredible. Bangla Book Tazkiratul Awliya Pdf -
4
-
5
- Download Bangla Book Tazkiratul Awliya Pdf for free with 1-click to support an animal cause close to your home &amp; support others! You can raise money and awareness for a cause you care about ! We provide you with an incredible platform to raise money and awareness for any cause. Your money goes directly to the fund raiser. You can create a unique page for any cause you want.
6
-
7
- Bangla Book Tazkiratul Awliya Pdf is a great fundraising tool for organizations, education institutions, philanthropic organizations, and non-profit organizations (NPOs). 1-Click on a button and raise money for an NPO near you, have a matching fundraiser, provide a listing of your supporters on your website. Search by charity name, by location, or a hashtag, to find a cause near you and even fundraise on behalf of a cause you love. If you're looking for a powerful, free online fundraising platform for your organization, you've found it. The easy fundraising platform powered by WordPress, WooCommerce, and integrated with PayPal, Stripe, and more. Your page can include a site map, social media links, event details, and more. On your page, you can link to additional information about the cause you support including a biography of the charity, photo galleries, and more. Every page is mobile-friendly so that you can make the best use of the fundraising tools available on your mobile device. All these features combined with the awesome design of the platform, and you have a perfect way to fundraise.
8
-
9
- Bangla Book Tazkiratul Awliya Pdf is a free, fully featured fundraising platform that helps you easily raise money for any cause. From helping teachers raise money for their schools to helping your local health food store raise money for cancer research, we’ve helped people just like you raise over $18 million for more than 1,000 causes. On your page you can link to additional information about the cause you support including a biography of the charity, photo galleries, and more.
10
-
11
- All your data is secure 4fefd39f24<br />
12
- <br />
13
- <br />
14
- <p></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Ciudad De Dios 1080p Torrent HOT!.md DELETED
@@ -1,6 +0,0 @@
1
- <h2>ciudad de dios 1080p torrent</h2><br /><p><b><b>DOWNLOAD</b> &#10026; <a href="https://imgfil.com/2uxZs7">https://imgfil.com/2uxZs7</a></b></p><br /><br />
2
- <br />
3
- Año 2015 HDRip torrent gratis en Español "'Ciudad de Dios' ofrece una dura, ... Mire una película en línea o vea los mejores videos HD de 1080p gratis en su ... 1fdad05405<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Become the Ultimate Imposter with this Among Us Hack Download Now and Enjoy.md DELETED
@@ -1,114 +0,0 @@
1
-
2
- <h1>Download Hack Among Us Always Imposter: How to Be the Impostor Every Time</h1>
3
- <p>Among Us is a multiplayer game that has taken the gaming world by storm. It is a game of deception, betrayal, and teamwork, where you have to work with your crewmates to complete tasks on a spaceship, while avoiding being killed by one or more impostors. But what if you want to be the impostor every time? Is there a way to download hack among us always imposter and enjoy the thrill of sabotaging and murdering your friends? In this article, we will answer these questions and more.</p>
4
- <h2>download hack among us always imposter</h2><br /><p><b><b>Download Zip</b> &#9881;&#9881;&#9881; <a href="https://urlin.us/2uT0Rj">https://urlin.us/2uT0Rj</a></b></p><br /><br />
5
- <h2>What is Among Us and Why is it So Popular?</h2>
6
- <p>Among Us is a game developed by Innersloth, a small indie studio based in Washington. It was released in 2018, but it gained massive popularity in 2020, thanks to streamers and youtubers who showcased its fun and chaotic gameplay. According to Google Play Store, it has over 500 million downloads on Android devices alone.</p>
7
- <h3>The Gameplay of Among Us</h3>
8
- <p>The game can be played online or over local WiFi with 4 to 15 players. Each player is assigned a role of either a crewmate or an impostor. The crewmates have to work together to complete tasks on the spaceship, such as fixing wires, scanning cards, or fueling engines. The impostors have to blend in with the crewmates, while secretly killing them one by one. They can also use sabotages to cause chaos and divert attention, such as turning off lights, locking doors, or triggering alarms.</p>
9
- <p>The game ends when either the crewmates complete all their tasks, the impostors kill enough crewmates, or the crewmates vote out all the impostors. The crewmates can call emergency meetings or report dead bodies to discuss and vote on who they think is the impostor. The impostors can lie, accuse, or manipulate their way out of suspicion.</p>
10
- <h3>The Appeal of Being an Impostor</h3>
11
- <p>While being a crewmate is fun and challenging, many players prefer to be the impostor, as it offers more excitement and variety. Being an impostor requires strategy, creativity, and deception skills. You have to plan your kills carefully, avoid being seen or caught, and convince others that you are innocent. You also have to deal with the pressure and adrenaline of being hunted and exposed. Being an impostor is like playing a game of cat and mouse, where you are both the hunter and the prey.</p>
12
- <p>How to download always impostor mod apk for among us android<br />
13
- Among us hack always impostor mod menu download pc<br />
14
- Among us cheats and hacks for pc and android<br />
15
- Download among us hack with everything unlocked<br />
16
- Among us mod menu with wallhack and impostor detector<br />
17
- How to install among us hack always impostor on windows<br />
18
- Among us hack apk always impostor latest version<br />
19
- Among us mod apk always impostor no ads<br />
20
- Download among us hack for free with unlimited skins and pets<br />
21
- Among us hack always impostor ios download<br />
22
- How to get among us hack always impostor on mac<br />
23
- Among us mod menu with speed hack and ghost mode<br />
24
- Download among us hack with no kill cooldown and sabotage<br />
25
- Among us mod apk always impostor with anti ban<br />
26
- Download among us hack for android with fake impostor option<br />
27
- Among us hack always impostor online play<br />
28
- How to use among us hack always impostor on steam<br />
29
- Among us mod menu with vote hack and end game option<br />
30
- Download among us hack with task completed and vision hack<br />
31
- Among us mod apk always impostor with voice chat<br />
32
- Download among us hack for pc with custom game settings<br />
33
- Among us mod menu with teleport and vent hack<br />
34
- Download among us hack with instant win and infinite emergency meetings<br />
35
- Among us mod apk always impostor with chat hack<br />
36
- Download among us hack for ios with unlock all maps and hats<br />
37
- Among us mod menu with kill all and no clip option<br />
38
- Download among us hack with radar and zoom hack<br />
39
- Among us mod apk always impostor with auto update<br />
40
- Download among us hack for mac with god mode and invisible option<br />
41
- Among us mod menu with fake vote and report option<br />
42
- Download among us hack with door lock and camera hack<br />
43
- Among us mod apk always impostor with mini crewmate option<br />
44
- Download among us hack for windows with color changer and name changer option<br />
45
- Among us mod menu with force start and force vote option<br />
46
- Download among us hack with admin panel and role changer option<br />
47
- Among us mod apk always impostor with no root required<br />
48
- Download among us hack for online multiplayer mode<br />
49
- Among us mod menu with show roles and show dead bodies option<br />
50
- Download among us hack with easy installation and uninstallation option<br />
51
- Among us mod apk always impostor with support for all devices</p>
52
- <h2>How to Download Hack Among Us Always Imposter for Android</h2>
53
- <p>If you are an Android user who wants to be the impostor every time in Among Us, there is a way to do that. You can download hack among us always imposter by installing a modded version of the game called Always Impostor Mod APK. This is an application that replaces the original game and allows you to access some extra features that are not available in the official version.</p>
54
- <h3>The Features of the Always Impostor Mod APK</h3>
55
- <p>Some of the features that you can enjoy with the Always Impostor Mod APK are:</p>
56
- <ul>
57
- <li>Always be the impostor in every game.</li>
58
- <li>Know who are the other impostors or crewmates.</li>
59
- <li>No advertisements.</li>
60
- <li>End votes or games whenever you want.</li>
61
- <li>See ghosts and completed tasks.</li>
62
- <li>Use any cosmetic item in the game.</li>
63
- <li>Edit your vision distance.</li>
64
- <li>And many more.</li>
65
- </ul>
66
- <h3>The Steps to Install the Always Impostor Mod APK</h3>
67
- <p>To install the Always Impostor Mod APK, you need to follow these steps:</p>
68
- <ol>
69
- <li>Download the Always Impostor Mod APK file from a trusted source. You can search for it online or use this link. Make sure you have enough storage space on your device.</li>
70
- <li>Enable the installation of unknown sources on your device. To do this, go to Settings > Security > Unknown Sources and toggle it on.</li>
71
- <li>Locate the downloaded file on your device and tap on it to start the installation process. Follow the instructions on the screen and wait for it to finish.</li>
72
- <li>Launch the Always Impostor Mod APK and enjoy being the impostor every time in Among Us.</li>
73
- </ol>
74
- <p>Note: This modded version of the game may not be compatible with the latest updates or features of the official version. It may also cause some glitches or errors in the game. Use it at your own risk and discretion.</p>
75
- <h2>How to Increase Your Chances of Being an Impostor in Among Us Online Game</h2>
76
- <p>If you are not an Android user or you prefer to play the official version of Among Us online, you may wonder if there is a way to increase your chances of being an impostor in the game. While there is no guaranteed method to do that, there are some factors that affect your impostor probability and some tips that can boost your impostor rate.</p>
77
- <h3>The Factors that Affect Your Impostor Probability</h3>
78
- <p>The impostor probability is the likelihood of being assigned as an impostor in a game of Among Us. It depends on two main factors: the number of players and the number of impostors in a game. The formula for calculating the impostor probability is:</p>
79
- <p><code>Impostor Probability = (Number of Impostors / Number of Players) x 100%</code></p>
80
- <p>For example, if you play a game with 10 players and 2 impostors, your impostor probability is:</p>
81
- <p><code>(2 / 10) x 100% = 20%</code></p>
82
- <p>This means that you have a 20% chance of being an impostor in that game. The higher the number of impostors and the lower the number of players, the higher your impostor probability.</p>
83
- <h3>The Tips to Boost Your Impostor Rate</h3>
84
- <p>Based on the formula above, you can increase your chances of being an impostor by following these tips:</p>
85
- <ul>
86
- <li>Join games with more impostors and fewer players. For example, a game with 5 players and 2 impostors has a 40% impostor probability, which is higher than a game with 10 players and 2 impostors.</li>
87
- <li>Create your own game and set the number of impostors and players as you wish. You can also invite your friends to join your game and have fun together.</li>
88
- <li>Leave and rejoin games until you get the impostor role. This may take some time and patience, but it can work if you are determined to be an impostor.</li>
89
- <li>Play more games and hope for the best. The more games you play, the more chances you have to be an impostor. However, this also depends on your luck and randomness.</li>
90
- </ul>
91
- <h2>Conclusion</h2>
92
- <p>Being an impostor in Among Us is a thrilling and enjoyable experience that many players want to have. If you are an Android user who wants to be the impostor every time, you can download hack among us always imposter by installing the Always Impostor Mod APK. If you prefer to play the official version of Among Us online, you can increase your chances of being an impostor by joining or creating games with more impostors and fewer players, leaving and rejoining games until you get the impostor role, or playing more games and hoping for the best. Remember to have fun and respect other players while playing Among Us.</p>
93
- <h2>FAQs</h2>
94
- <h4>What is Among Us?</h4>
95
- <p>Among Us is a multiplayer game of deception, betrayal, and teamwork, where you have to work with your crewmates to complete tasks on a spaceship, while avoiding being killed by one or more impostors.</p>
96
- <h4>How can I be the impostor every time in Among Us?</h4>
97
- <p>If you are an Android user, you can download hack among us always imposter by installing the Always Impostor Mod APK. If you prefer to play the official version of Among Us online, you can increase your chances of being an impostor by joining or creating games with more impostors and fewer players, leaving and rejoining games until you get the impostor role, or playing more games and hoping for the best.</p>
98
- <h4>Is it safe to download hack among us always imposter?</h4>
99
- <p>It depends on the source and the quality of the modded version of the game. Some sources may be malicious or contain viruses that can harm your device or steal your data. Some modded versions may not be compatible with the latest updates or features of the official version. They may also cause some glitches or errors in the game. Use it at your own risk and discretion.</p>
100
- <h4>How can I play Among Us with my friends?</h4>
101
- <p>You can play Among Us with your friends by either joining or creating a game online or over local WiFi. You can invite your friends to join your game by sharing the game code or the invite link. You can also customize the game settings, such as the map, the number of impostors, the task difficulty, and the voting time.</p>
102
- <h4>What are some tips to be a good impostor in Among Us?</h4>
103
- <p>Some tips to be a good impostor in Among Us are:</p>
104
- <ul>
105
- <li>Act like a crewmate and pretend to do tasks.</li>
106
- <li>Kill when no one is around or when you have an alibi.</li>
107
- <li>Vent to escape or move around quickly, but be careful not to be seen.</li>
108
- <li>Sabotage to create distractions, split up the crewmates, or prevent them from completing tasks.</li>
109
- <li>Lie, accuse, or manipulate others during meetings and votes.</li>
110
- <li>Use your impostor vision to see in the dark or through walls.</li>
111
- <li>Communicate and cooperate with your fellow impostors if there are more than one.</li>
112
- </ul></p> 197e85843d<br />
113
- <br />
114
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download 2 Lite Music and Video Players and Stream Your Favorite Content.md DELETED
@@ -1,120 +0,0 @@
1
-
2
- <h1>Download 2 Lite: What Is It and Why You Need It</h1>
3
- <p>Do you want to download files from the internet quickly and easily? Do you want to save your storage space and data plan? Do you want to enjoy your downloaded files on any device and network? If you answered yes to any of these questions, then you need Download 2 Lite.</p>
4
- <h2>What is Download 2 Lite?</h2>
5
- <h3>A simple and fast app for downloading files</h3>
6
- <p>Download 2 Lite is a free app that lets you download any file from the internet with just a few taps. You can download videos, music, images, documents, and more with Download 2 Lite. You can also choose the quality and format of the file before downloading it. Download 2 Lite is designed to be simple, fast, and user-friendly.</p>
7
- <h2>download 2 lite</h2><br /><p><b><b>Download</b> <a href="https://jinyurl.com/2uNLaH">https://jinyurl.com/2uNLaH</a></b></p><br /><br />
8
- <h3>A lightweight version of Download 2</h3>
9
- <p>Download 2 Lite is a lightweight version of Download 2, a popular app for downloading files. Download 2 Lite has all the essential features of Download 2, but it is much smaller in size and consumes less data. Download 2 Lite is ideal for users who have limited storage space or data plan, or who want a faster and smoother downloading experience.</p>
10
- <h2>Why you need Download 2 Lite?</h2>
11
- <h3>It saves your time and data</h3>
12
- <p>Download 2 Lite is optimized for speed and efficiency. It downloads files faster than other apps by using advanced algorithms and techniques. It also reduces your data usage by compressing the files before downloading them. You can save up to 50% of your data with Download 2 Lite.</p>
13
- <h3>It works on any device and network</h3>
14
- <p>Download 2 Lite is compatible with all Android devices, from old to new, from low-end to high-end. It also works on any network, from 2G to 5G, from Wi-Fi to mobile data. You can download files with Download 2 Lite anytime, anywhere, without any hassle.</p>
15
- <h3>It supports multiple formats and sources</h3>
16
- <p>Download 2 Lite supports a wide range of formats for downloading files, such as MP4, MP3, JPG, PDF, ZIP, and more. You can also download files from various sources, such as websites, social media platforms, cloud services, streaming sites, and more. You can download anything you want with Download 2 Lite.</p>
17
- <h2>How to use Download 2 Lite?</h2>
18
- <h3>Download and install the app from the official website or Google Play Store</h3>
19
- <p>You can download and install Download 2 Lite from its official website or Google Play Store. The app is free and safe to use. The installation process is quick and easy.</p>
20
- <p>download 2 lite apk<br />
21
- download 2 lite app<br />
22
- download 2 lite for android<br />
23
- download 2 lite facebook<br />
24
- download 2 lite free<br />
25
- download 2 lite game<br />
26
- download 2 lite mod<br />
27
- download 2 lite online<br />
28
- download 2 lite pc<br />
29
- download 2 lite pro<br />
30
- download 2 lite simulator<br />
31
- download 2 lite update<br />
32
- download 2 lite version<br />
33
- download 2 lite video<br />
34
- download 2 lite windows<br />
35
- download facebook lite 2 accounts<br />
36
- download facebook lite 2.0 apk<br />
37
- download facebook lite 2023<br />
38
- download facebook lite android 2.3.6 apk<br />
39
- download facebook lite for android 2.3.5<br />
40
- download facebook lite for android version 2.3.6<br />
41
- download facebook lite for ios 12.4.2<br />
42
- download facebook lite for iphone ios 12.4.2<br />
43
- download facebook lite for nokia asha 200<br />
44
- download facebook lite for nokia x2<br />
45
- download facebook lite for samsung galaxy y s5360<br />
46
- download facebook lite for windows phone lumia 520<br />
47
- download facebook lite java jar nokia c2<br />
48
- download facebook lite mod apk unlimited likes and followers<br />
49
- download facebook lite mod apk versi terbaru 2023<br />
50
- download facebook lite old version apk pure<br />
51
- download facebook lite old version uptodown<br />
52
- download facebook lite transparan apk terbaru 2023<br />
53
- how to download construction simulator 2 lite on pc<br />
54
- how to download construction simulator 2 us pc full version free windows 10/8/7 laptop computer desktop online offline installer setup file no crack needed updated link working in june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june july august september october november december january february march april may june</p>
55
- <h3>Open the app and enter the URL of the file you want to download</h3>
56
- <p>Once you have installed the app, open it and enter the URL of the file you want to download in the search bar. You can also copy and paste the URL from another app or browser.</p>
57
- <h3>Choose the quality and format of the file and start the download</h3>
58
- <p>After entering the URL, you will see a list of options for choosing the quality and format of the file. You can select the one that suits your needs and preferences <p>Then, tap on the download button and wait for the file to be downloaded. You can see the progress and status of the download in the notification bar or in the app itself.</p>
59
- <h2>Features and benefits of Download 2 Lite</h2>
60
- <h4>Table: Comparison of Download 2 Lite and Download 2</h4>
61
- <table>
62
- <tr>
63
- <th>Feature</th>
64
- <th>Download 2 Lite</th>
65
- <th>Download 2</th>
66
- </tr>
67
- <tr>
68
- <td>Size</td>
69
- <td>5 MB</td>
70
- <td>25 MB</td>
71
- </tr>
72
- <tr>
73
- <td>Data usage</td>
74
- <td>50% less</td>
75
- <td>Normal</td>
76
- </tr>
77
- <tr>
78
- <td>Speed</td>
79
- <td>Faster</td>
80
- <td>Normal</td>
81
- </tr>
82
- <tr>
83
- <td>Format support</td>
84
- <td>All essential formats</td>
85
- <td>All formats</td>
86
- </tr>
87
- <tr>
88
- <td>Source support</td>
89
- <td>All popular sources</td>
90
- <td>All sources</td>
91
- </tr>
92
- <tr>
93
- <td>Extra features</td>
94
- <td>None</td>
95
- <td>Video player, file manager, etc.</td>
96
- </tr>
97
- </table>
98
- <h3>Fast and reliable downloads</h3>
99
- <p>Download 2 Lite offers fast and reliable downloads for all types of files. It uses advanced algorithms and techniques to optimize the download speed and quality. It also resumes the download automatically if it is interrupted by network issues or other factors. You can download files with Download 2 Lite without any worries.</p>
100
- <h3>Low storage and data usage</h3>
101
- <p>Download 2 Lite is a lightweight app that takes up very little storage space on your device. It also consumes very little data when downloading files. It compresses the files before downloading them and reduces the data usage by up to 50%. You can download more files with Download 2 Lite without affecting your storage or data plan.</p>
102
- <h3>Wide compatibility and support</h3>
103
- <p>Download 2 Lite is compatible with all Android devices and networks. It works on any device, from old to new, from low-end to high-end. It also works on any network, from 2G to 5G, from Wi-Fi to mobile data. You can download files with Download 2 Lite anytime, anywhere, without any hassle. Download 2 Lite also supports a wide range of formats and sources for downloading files. You can download videos, music, images, documents, and more with Download 2 Lite. You can also download files from various sources, such as websites, social media platforms, cloud services, streaming sites, and more. You can download anything you want with Download 2 Lite.</p>
104
- <h2>Conclusion</h2>
105
- <p>Download 2 Lite is a simple and fast app for downloading files from the internet. It is a lightweight version of Download 2 that has all the essential features but is much smaller in size and consumes less data. It saves your time and data, works on any device and network, and supports multiple formats and sources. If you want to download files quickly and easily, you need Download 2 Lite.</p>
106
- <h2>FAQs</h2>
107
- <p>Here are some frequently asked questions about Download 2 Lite:</p>
108
- <ul>
109
- <li><b>Is Download 2 Lite safe to use?</b></li>
110
- <p>Yes, Download 2 Lite is safe to use. It does not contain any malware or viruses. It also does not collect or share any personal information from your device. You can use Download 2 Lite with confidence.</p>
111
- <li><b>How can I update Download 2 Lite?</b></li>
112
- <p>You can update Download 2 Lite from its official website or Google Play Store. The app will notify you when there is a new version available. You can also check for updates manually in the app settings.</p>
113
- <li><b>Can I download multiple files at once with Download 2 Lite?</b></li>
114
- <p>Yes, you can download multiple files at once with Download 2 Lite. You can add as many files as you want to the download queue and start them all at once or one by one. You can also pause or cancel any download at any time.</p>
115
- <li><b>Where can I find the downloaded files on my device?</b></li>
116
- <p>You can find the downloaded files on your device in the default download folder or in the folder you have chosen in the app settings. You can also access the downloaded files from the app itself by tapping on the file icon.</p>
117
- <li><b>How can I contact the developer of Download 2 Lite?</b></li>
118
- <p>You can contact the developer of Download 2 Lite by sending an email to [email protected] or by visiting their website at www.download2lite.com. You can also leave a feedback or a review on the app store or Google Play Store. The developer appreciates your feedback and suggestions.</p> 401be4b1e0<br />
119
- <br />
120
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download Craftsman Crafting and Building APK and Create Your Own World.md DELETED
@@ -1,124 +0,0 @@
1
- <br />
2
- <h1>Craftsman: Building Craft APK - A Free Alternative to Minecraft</h1>
3
- <p>If you are a fan of sandbox games, you might have heard of Minecraft, the popular game that lets you create and explore a pixelated world. But did you know that there is a free alternative to Minecraft that you can play on your Android device? It's called Craftsman: Building Craft APK, and it's a fun and creative game that lets you design houses, castles, and other structures with your friends or alone.</p>
4
- <h2>craftsman building craft apk</h2><br /><p><b><b>DOWNLOAD</b> &ndash;&ndash;&ndash;&ndash;&ndash;>>> <a href="https://jinyurl.com/2uNTy5">https://jinyurl.com/2uNTy5</a></b></p><br /><br />
5
- <h2>What is Craftsman: Building Craft APK?</h2>
6
- <p>Craftsman: Building Craft APK is a free video game for Android devices that is inspired by Minecraft . It has a similar graphic style based on cubes and a similar gameplay mechanic that involves mining, crafting, building, and exploring. However, this game does not require Minecraft Launcher or other launchers to run. You can simply download and install the APK file from a trusted source and start playing right away.</p>
7
- <h3>Features of Craftsman: Building Craft APK</h3>
8
- <p>Some of the features that Craftsman: Building Craft APK offers are:</p>
9
- <ul>
10
- <li>A large and open world that you can customize and explore.</li>
11
- <li>A variety of blocks and materials that you can use to create different structures.</li>
12
- <li>A creative mode that lets you build without limits and a survival mode that challenges you to survive in a hostile environment.</li>
13
- <li>A multiplayer mode that lets you play with your friends online or offline.</li>
14
- <li>A simple and intuitive interface that makes it easy to control and navigate the game.</li>
15
- </ul>
16
- <h3>How to download and install Craftsman: Building Craft APK</h3>
17
- <p>To download and install Craftsman: Building Craft APK on your Android device, you need to follow these steps:</p>
18
- <ol>
19
- <li>Go to a reliable website that offers the APK file for Craftsman: Building Craft, such as [FileHippo](^2^) or [Softonic](^1^).</li>
20
- <li>Click on the download button and wait for the file to be downloaded on your device.</li>
21
- <li>Once the download is complete, locate the file in your device's file manager and tap on it to start the installation process.</li>
22
- <li>Allow the installation of unknown sources if prompted by your device's settings.</li>
23
- <li>Follow the instructions on the screen and wait for the installation to finish.</li>
24
- <li>Launch the game from your app drawer and enjoy playing Craftsman: Building Craft.</li>
25
- </ol>
26
- <h2>Why play Craftsman: Building Craft APK?</h2>
27
- <p>Craftsman: Building Craft APK is a great game for anyone who loves sandbox games and wants to unleash their creativity. Here are some reasons why you should play this game:</p>
28
- <h3>Pros and cons of Craftsman: Building Craft APK</h3>
29
- <table style="border-collapse: collapse; width: 100%;">
30
- <tbody>
31
- <tr style="height: 23px;">
32
- <td style="width: 50%; height: 23px; text-align: center;"><strong>Pros</strong></td>
33
- <td style="width: 50%; height: 23px; text-align: center;"><strong>Cons</strong></td>
34
- </tr>
35
- <tr style="height: 23px;">
36
- <td style="width: 50%; height: 23px;">- It's free to play and does not require any additional launchers or purchases.</td>
37
- <td style="width: 50%; height: 23px;">- It's not an official Minecraft product and may have some bugs or glitches.</td>
38
- </tr>
39
- <tr style="height: 23px;">
40
- <td style="width: 50%; height: 23px;">- It has a lot of features and options that let you create and explore different worlds.</td>
41
- <td style="width: 50%; height: 23px;">- It may not be - It may not be compatible with some devices or Android versions.</td>
42
- </tr>
43
- <tr style="height: 23px;">
44
- <td style="width: 50%; height: 23px;">- It has a multiplayer mode that lets you play with your friends online or offline.</td>
45
- <td style="width: 50%; height: 23px;">- It may not have the same level of quality or updates as Minecraft.</td>
46
- </tr>
47
- </tbody>
48
- </table>
49
- <h3>Tips and tricks for playing Craftsman: Building Craft APK</h3>
50
- <p>If you want to have a better experience playing Craftsman: Building Craft APK, here are some tips and tricks that you can use:</p>
51
- <p>craftsman building craft apk download<br />
52
- craftsman building craft apk mod<br />
53
- craftsman building craft apk latest version<br />
54
- craftsman building craft apk android<br />
55
- craftsman building craft apk free<br />
56
- craftsman building craft apk offline<br />
57
- craftsman building craft apk update<br />
58
- craftsman building craft apk for pc<br />
59
- craftsman building craft apk 2023<br />
60
- craftsman building craft apk hack<br />
61
- craftsman building craft apk online<br />
62
- craftsman building craft apk no ads<br />
63
- craftsman building craft apk unlimited money<br />
64
- craftsman building craft apk old version<br />
65
- craftsman building craft apk pure<br />
66
- craftsman building craft apk uptodown<br />
67
- craftsman building craft apk 1.9.215<br />
68
- craftsman building craft apk rexdl<br />
69
- craftsman building craft apk revdl<br />
70
- craftsman building craft apk apkpure<br />
71
- craftsman building craft apk filehippo<br />
72
- craftsman building craft apk softonic<br />
73
- craftsman building craft apk play store<br />
74
- craftsman building craft apk ios<br />
75
- craftsman building craft apk install<br />
76
- craftsman building craft apk game<br />
77
- craftsman building craft apk review<br />
78
- craftsman building craft apk cheats<br />
79
- craftsman building craft apk tips<br />
80
- craftsman building craft apk guide<br />
81
- craftsman building craft apk wiki<br />
82
- craftsman building craft apk gameplay<br />
83
- craftsman building craft apk features<br />
84
- craftsman building craft apk requirements<br />
85
- craftsman building craft apk size<br />
86
- craftsman building craft apk screenshots<br />
87
- craftsman building craft apk videos<br />
88
- craftsman building craft apk youtube<br />
89
- craftsman building craft apk reddit<br />
90
- craftsman building craft apk quora<br />
91
- craftsman building craft apk facebook<br />
92
- craftsman building craft apk twitter<br />
93
- craftsman building craft apk instagram<br />
94
- craftsman building craft apk pinterest<br />
95
- craftsman building craft apk tiktok<br />
96
- craftsman building craft apk discord<br />
97
- craftsman building craft apk forum<br />
98
- craftsman building craft apk blog<br />
99
- craftsman building craft apk news</p>
100
- <ul>
101
- <li>Use the creative mode to experiment with different blocks and materials and learn how to craft and build.</li>
102
- <li>Use the survival mode to test your skills and challenge yourself to survive in a harsh environment.</li>
103
- <li>Use the multiplayer mode to collaborate with your friends and share your creations with them.</li>
104
- <li>Use the settings menu to adjust the graphics, sound, controls, and other options according to your preference.</li>
105
- <li>Use the map and compass to navigate the world and find your way back to your base.</li>
106
- </ul>
107
- <h2>Conclusion</h2>
108
- <p>Craftsman: Building Craft APK is a free alternative to Minecraft that lets you create and explore a pixelated world on your Android device. It has a lot of features and options that make it a fun and creative game for anyone who loves sandbox games. You can download and install it easily from a trusted source and start playing right away. Whether you want to build your dream house, explore a vast world, or survive in a hostile environment, Craftsman: Building Craft APK has something for you.</p>
109
- <h3>FAQs</h3>
110
- <p>Here are some frequently asked questions about Craftsman: Building Craft APK:</p>
111
- <ol>
112
- <li><strong>Is Craftsman: Building Craft APK safe to download and install?</strong></li>
113
- <p>Yes, as long as you download and install it from a reliable website that offers the APK file, such as [FileHippo] or [Softonic]. You should also scan the file with an antivirus software before installing it on your device.</p>
114
- <li><strong>Is Craftsman: Building Craft APK legal to play?</strong></li>
115
- <p>Yes, Craftsman: Building Craft APK is legal to play as long as you do not use it for any illegal or malicious purposes. However, you should be aware that this game is not an official Minecraft product and is not affiliated with Mojang or Microsoft in any way. Therefore, you should not expect the same level of quality or support as Minecraft.</p>
116
- <li><strong>Can I play Craftsman: Building Craft APK offline?</strong></li>
117
- <p>Yes, you can play Craftsman: Building Craft APK offline without an internet connection. However, if you want to play with your friends online, you will need an internet connection and a valid account.</p>
118
- <li><strong>Can I play Craftsman: Building Craft APK on PC?</strong></li>
119
- <p>No, Craftsman: Building Craft APK is only available for Android devices. If you want to play it on PC, you will need to use an Android emulator such as [BlueStacks] or [NoxPlayer]. However, this may affect the performance and compatibility of the game.</p>
120
- <li><strong>How can I update Craftsman: Building Craft APK?</strong></li>
121
- <p>To update Craftsman: Building Craft APK, you will need to download and install the latest version of the APK file from the same source that you used before. You should also backup your game data before updating to avoid losing any progress or settings.</p>
122
- </ol></p> 197e85843d<br />
123
- <br />
124
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download Dr. Driving 2 for PC and Experience Realistic Driving Challenges.md DELETED
@@ -1,128 +0,0 @@
1
- <br />
2
- <h1>How to Download Dr. Driving 2 for PC</h1>
3
- <p>Dr. Driving 2 is a popular driving simulation game that lets you experience realistic driving scenarios, stunning graphics, challenging levels, and online multiplayer modes. If you are a fan of this game and want to play it on a bigger screen with better controls, you might be wondering how to download Dr. Driving 2 for PC.</p>
4
- <p>In this article, we will show you two ways to play Dr. Driving 2 on your PC, depending on whether you have Windows 11 or not. We will also introduce you to some of the best features and requirements of this game, as well as some frequently asked questions.</p>
5
- <h2>download dr driving 2 for pc</h2><br /><p><b><b>Download Zip</b> ::: <a href="https://jinyurl.com/2uNTic">https://jinyurl.com/2uNTic</a></b></p><br /><br />
6
- <h2>What is Dr. Driving 2?</h2>
7
- <p>Dr. Driving 2 is the sequel to the hit mobile driving simulation game Dr. Driving, which has over 50 million downloads on Google Play Store. Dr. Driving 2 takes the driving simulation gameplay to a new level with super stunning graphics, challenging multi-stage levels, and real-time online multiplayer. You can drive various cars, complete missions, earn coins, upgrade your vehicles, and compete with other players from around the world.</p>
8
- <h3>Features of Dr. Driving 2</h3>
9
- <p>Some of the features that make Dr. Driving 2 an amazing game are:</p>
10
- <ul>
11
- <li>Realistic driving physics and mechanics</li>
12
- <li>Beautiful and detailed environments</li>
13
- <li>Different game modes, such as Career, Online Match, Tournament, and Daily Challenge</li>
14
- <li>Over 100 cars to choose from, each with different performance and customization options</li>
15
- <li>Over 1000 levels to test your driving skills and knowledge</li>
16
- <li>Leaderboards and achievements to track your progress and rank</li>
17
- <li>Social features, such as chat, friend list, and clan system</li>
18
- </ul>
19
- <h3>Requirements for Dr. Driving 2</h3>
20
- <p>To play Dr. Driving 2 on your mobile device, you need to have:</p>
21
- <ul>
22
- <li>An Android device with version 4.1 or higher or an iOS device with version 9.0 or higher </li>
23
- <li>At least 100 MB of free storage space</li>
24
- <li>A stable internet connection</li>
25
- </ul>
26
- <p>To play Dr. Driving 2 on your PC, you need to have:</p>
27
- <ul>
28
- <li>A Windows PC with Windows 10 (v2004) or Windows 11</li>
29
- <li>A solid state drive (SSD) with at least 10 GB of available storage space</li>
30
- <li>An Intel UHD Graphics 630 GPU or comparable</li>
31
- <li>A processor with at least four CPU physical cores (some games require an Intel CPU)</li>
32
- <li>At least 8 GB of RAM</li>
33
- <li>A Windows admin account</li>
34
- <li>Hardware virtualization turned on</li>
35
- </ul>
36
- <h2>How to Play Dr. Driving 2 on PC with Windows 11</h2>
37
- <p>If you have Windows 11 installed on your PC, you can play Android games natively without using any third-party emulators. This is because Windows 11 has a feature called Windows Subsystem for Android, which allows you to run Android apps inside Windows. However, this feature is still in beta testing and not available for everyone. You need to join the Windows Insider Program and opt for the Dev Channel to get access to it. You also need to install Google Play Games Beta and Amazon Appstore on your PC to download and play Dr. Driving 2. Here are the steps to do so:</p>
38
- <h3>Step 1: Install Google Play Games Beta on your PC</h3>
39
- <p>Google Play Games Beta is a service that lets you play Android games on your PC with Windows 11. It also syncs your game progress, achievements, and friends across devices. To install it, you need to:</p>
40
- <ol>
41
- <li>Go to the [Google Play Games Beta page] and click on the "Join the beta" button.</li>
42
- <li>Sign in with your Google account and accept the terms and conditions.</li>
43
- <li>Wait for a confirmation email from Google and follow the instructions to download and install Google Play Games Beta on your PC.</li>
44
- </ol>
45
- <h3>Step 2: Install Amazon Appstore on your PC</h3>
46
- <p>Amazon Appstore is an alternative app store that offers a variety of Android apps and games, including Dr. Driving 2. To install it, you need to:</p>
47
- <ol>
48
- <li>Go to the [Amazon Appstore page] and click on the "Download Amazon Appstore" button.</li>
49
- <li>Open the downloaded file and follow the instructions to install Amazon Appstore on your PC.</li>
50
- <li>Sign in with your Amazon account or create one if you don't have one.</li>
51
- </ol>
52
- <h3>Step 3: Download Dr. Driving 2 from Amazon Appstore</h3>
53
- <p>Once you have installed both Google Play Games Beta and Amazon Appstore on your PC, you can download Dr. Driving 2 from the latter. To do so, you need to:</p>
54
- <p>How to download dr driving 2 for pc with gameloop emulator<br />
55
- Dr driving 2 pc game free download full version<br />
56
- Dr driving 2 online multiplayer on pc<br />
57
- Dr driving 2 pc gameplay and review<br />
58
- Best settings for dr driving 2 on pc<br />
59
- Dr driving 2 pc system requirements and compatibility<br />
60
- Dr driving 2 tips and tricks for pc players<br />
61
- Dr driving 2 mod apk download for pc<br />
62
- Dr driving 2 cheats and hacks for pc<br />
63
- Dr driving 2 vs dr driving 1 comparison on pc<br />
64
- Dr driving 2 new features and updates on pc<br />
65
- Dr driving 2 best cars and upgrades on pc<br />
66
- Dr driving 2 challenges and missions on pc<br />
67
- Dr driving 2 graphics and sound quality on pc<br />
68
- Dr driving 2 alternatives and similar games on pc<br />
69
- How to play dr driving 2 with keyboard and mouse on pc<br />
70
- How to install dr driving 2 on windows 10 pc<br />
71
- How to fix dr driving 2 not working on pc<br />
72
- How to transfer dr driving 2 data from android to pc<br />
73
- How to record dr driving 2 gameplay on pc<br />
74
- How to stream dr driving 2 on twitch or youtube from pc<br />
75
- How to connect dr driving 2 with facebook or google play on pc<br />
76
- How to earn coins and gems in dr driving 2 on pc<br />
77
- How to unlock all levels and stages in dr driving 2 on pc<br />
78
- How to customize your car and driver in dr driving 2 on pc<br />
79
- How to change language and region in dr driving 2 on pc<br />
80
- How to join or create a clan in dr driving 2 on pc<br />
81
- How to chat and communicate with other players in dr driving 2 on pc<br />
82
- How to invite and play with friends in dr driving 2 on pc<br />
83
- How to rank up and level up in dr driving 2 on pc<br />
84
- How to get free rewards and bonuses in dr driving 2 on pc<br />
85
- How to access the shop and store in dr driving 2 on pc<br />
86
- How to use the leaderboard and achievements in dr driving 2 on pc<br />
87
- How to enable or disable notifications and sounds in dr driving 2 on pc<br />
88
- How to contact the support team or report a bug in dr driving 2 on pc<br />
89
- Dr driving 2 fun facts and trivia for pc users<br />
90
- Dr driving 2 user reviews and ratings for pc version<br />
91
- Dr driving 2 download size and speed for pc platform<br />
92
- Dr driving 2 minimum and recommended specifications for pc devices<br />
93
- Dr driving 2 pros and cons for playing on pc screen</p>
94
- <ol>
95
- <li>Open Amazon Appstore on your PC and search for "Dr. Driving 2" in the search bar.</li>
96
- <li>Select the game from the results and click on the "Get" button.</li>
97
- <li>Wait for the game to download and install on your PC.</li>
98
- </ol>
99
- <h3>Step 4: Launch Dr. Driving 2 and enjoy</h3>
100
- <p>After installing Dr. Driving 2 on your PC, you can launch it from either Google Play Games Beta or Amazon Appstore. You will see a window that shows the game running inside Windows Subsystem for Android. You can use your mouse, keyboard, or gamepad to control the game. You can also adjust the settings, such as resolution, frame rate, sound, and graphics, from the menu bar at the top of the window. Enjoy playing Dr. Driving 2 on your PC with Windows 11!</p>
101
- <h2>How to Play Dr. Driving 2 on PC with Android Emulators</h2>
102
- <p>If you don't have Windows 11 or don't want to use Windows Subsystem for Android, you can still play Dr. Driving 2 on your PC with Android emulators. Android emulators are software that simulate an Android device on your PC, allowing you to run Android apps and games. There are many Android emulators available for Windows, but not all of them are compatible with Dr. Driving 2. Here are some of the best Android emulators for Dr. Driving 2 that we recommend:</p>
103
- <h3>What are Android Emulators?</h3>
104
- <p>An Android emulator is a software program that mimics an Android device on a computer. It allows users to run Android apps and games on their PCs without having to own an actual Android device. Android emulators are useful for various purposes, such as testing apps, playing games, accessing blocked websites, and more. However, they also have some drawbacks, such as consuming more resources, causing compatibility issues, and posing security risks. Therefore, users should be careful when choosing and using an Android emulator.</p>
105
- <h3>Best Android Emulators for Dr. Driving 2</h3>
106
- <h4>Bluestacks 5 / MSI App Player</h4>
107
- <p>Bluestacks 5 is one of the most popular and powerful Android emulators for Windows. It has a sleek interface, fast performance, high compatibility, and rich features. It also supports Google Play Store, keyboard and mouse controls, gamepad support, multi-instance mode, screen recording, streaming, and more. Bluestacks 5 is compatible with Dr. Driving 2 and can run it smoothly on most PCs. You can download Bluestacks 5 from its [official website].</p>
108
- <p>MSI App Player is a customized version of Bluestacks 5 that is designed for MSI gaming laptops. It has the same features and performance as Bluestacks 5, but with some additional benefits, such as MSI keyboard lighting, MSI True Color, and MSI Dragon Center. MSI App Player is also compatible with Dr. Driving 2 and can run it smoothly on MSI gaming laptops. You can download MSI App Player from its [official website].</p>
109
- <h4>Nox Player</h4>
110
- <p>Nox Player is another popular and powerful Android emulator for Windows. It has a simple interface, fast performance, high compatibility, and rich features. It also supports Google Play Store, keyboard and mouse controls, gamepad support, multi-instance mode, screen recording, streaming, and more. Nox Player is compatible with Dr. Driving 2 and can run it smoothly on most PCs. You can download Nox Player from its [official website].</p>
111
- <h4>Gameloop</h4>
112
- <p>Gameloop is a specialized Android emulator for Windows that focuses on gaming. It has a modern interface, optimized performance, high compatibility, and rich features. It also supports Google Play Store, keyboard and mouse controls, gamepad support, multi-instance mode, screen recording, streaming, and more. Gameloop is compatible with Dr. Driving 2 and can run it smoothly on most PCs. You can download Gameloop from its [official website].</p>
113
- <h2>Conclusion</h2>
114
- <p>Dr. Driving 2 is a fun and realistic driving simulation game that you can play on your PC with Windows 11 or Android emulators. In this article, we showed you two ways to download and play Dr. Driving 2 on your PC, depending on whether you have Windows 11 or not. We also introduced you to some of the best features and requirements of this game, as well as some frequently asked questions.</p>
115
- <p>We hope you enjoyed this article and found it helpful. If you have any questions or feedback, please feel free to leave a comment below. Happy driving!</p>
116
- <h2>FAQs</h2>
117
- <h3>Is Dr. Driving 2 free to play?</h3>
118
- <p>Yes, Dr. Driving 2 is free to play on both mobile devices and PCs. However, it contains ads and in-app purchases that can enhance your gameplay experience.</p>
119
- <h3>Can I play Dr. Driving 2 offline?</h3>
120
- <p>No, Dr. Driving 2 requires an internet connection to play. You need to connect to the internet to access the game modes, levels, cars, and other features.</p>
121
- <h3>Can I play Dr. Driving 2 with my friends?</h3>
122
- <p>Yes, Dr. Driving 2 supports online multiplayer modes that allow you to play with your friends or other players from around the world. You can join or create a clan, chat with other players, challenge them to races or tournaments, and earn rewards.</p>
123
- <h3>How can I save my progress in Dr. Driving 2?</h3>
124
- <p>You can save your progress in Dr. Driving 2 by signing in with your Google account or Facebook account. This will sync your game data across devices and platforms.</p>
125
- <h3>How can I contact the developer of Dr. Driving 2?</h3>
126
- <p>You can contact the developer of Dr. Driving 2 by sending an email to [[email protected]]. You can also visit their [official website] or follow them on [Facebook] or [Twitter] for more information.</p> 401be4b1e0<br />
127
- <br />
128
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download PES 2020 Lite APK for Android Play PES 2021 with Just 50 MB of Storage.md DELETED
@@ -1,126 +0,0 @@
1
- <br />
2
- <h1>PES 2020 Lite 50 MB APK: How to Download and Play the Free Version of the Popular Football Game</h1>
3
- <p>If you are a fan of football games, you might have heard of PES 2020, the latest installment of the eFootball Pro Evolution Soccer series by Konami. PES 2020 is a realistic and immersive football simulator that offers a variety of game modes, clubs, players, stadiums and features. However, if you don't want to spend money on buying the full-game, you can still enjoy a free-to-play version called PES 2020 Lite.</p>
4
- <h2>pes 2020 lite 50 mb apk</h2><br /><p><b><b>Download File</b> &#187;&#187;&#187; <a href="https://jinyurl.com/2uNM4m">https://jinyurl.com/2uNM4m</a></b></p><br /><br />
5
- <p>PES 2020 Lite is a reduced version of PES 2020 that allows you to play online matches with other users who have either the full-game or the lite version. You can also create your own team in myClub mode with a limited number of clubs available. In this article, we will explain what PES 2020 Lite is, how to download and install it on different platforms, and what are the pros and cons of playing it.</p>
6
- <h2>What is PES 2020 Lite?</h2>
7
- <p>PES 2020 Lite is a free-to-play version of PES 2020 that was released on December 9, 2019 for PS4, Xbox One and PC Steam. It is basically a demo version of the full-game that lets you try out some of its features and modes. You can play offline matches in local match, CO-OP and training modes, or online matches in myClub and eFootball modes. You can also edit some settings and customize your team in edit mode (only available for PS4 and Steam).</p>
8
- <h3>Features of PES 2020 Lite</h3>
9
- <p>PES 2020 Lite has some features that are similar to the full-game, such as:</p>
10
- <ul>
11
- <li>The gameplay engine that delivers realistic and dynamic football action</li>
12
- <li>The graphics and animations that create lifelike players and stadiums</li>
13
- <li>The commentary and sound effects that enhance the atmosphere of the matches</li>
14
- <li>The licenses and partnerships with official leagues, clubs and players</li>
15
- <li>The updates and events that keep the game fresh and exciting</li>
16
- </ul>
17
- <p>However, PES 2020 Lite also has some limitations that differentiate it from the full-game, such as:</p>
18
- <ul>
19
- <li>The game modes that are only available in the full-game are master league, become a legend, matchday (offline), online divisions, online CO-OP (online) and random selection match</li>
20
- <li>The clubs that are only available in kick-off mode are FC Barcelona, FC Bayern München, Manchester United, Juventus, Arsenal, Palmeiras, Flamengo, São Paulo, Corinthians, Vasco da Gama, Boca Juniors, Colo-Colo and River Plate</li>
21
- <li>The stadiums that are only available are Allianz Arena (FC Bayern Munich), Allianz Parque (Palmeiras) and Allianz Stadium (Juventus)</li>
22
- </ul>
23
- <h3>How to download PES 2020 Lite for PS4, Xbox One and PC Steam</h3>
24
- <p>If you want to play PES 2020 Lite on your PS4, Xbox One or PC Steam, you can download it for free from the following links:</p>
25
- <table>
26
- <tr><th>Platform</th><th>Download Link</th></tr>
27
- <tr><td>Playstation 4</td><td><a href="(^1^)">PES 2020 Lite for PlayStation 4</a></td <tr><td>Xbox One</td><td><a href="">PES 2020 Lite for Xbox One</a></td></tr>
28
- <tr><td>PC Steam</td><td><a href="">PES 2020 Lite for PC Steam</a></td></tr>
29
- </table>
30
- <p>After downloading the game, you can launch it from your console or PC and start playing. You will need an internet connection and a Konami ID to access some of the online features. You can also link your game data with your eFootball PES 2020 mobile app if you have one.</p>
31
- <p>pes 2020 lite free download<br />
32
- pes 2020 lite for pc steam<br />
33
- pes 2020 lite myclub mode<br />
34
- pes 2020 lite kick off mode<br />
35
- pes 2020 lite clubs and stadiums<br />
36
- pes 2020 lite faq and features<br />
37
- pes 2020 lite file size and system requirements<br />
38
- pes 2020 lite save data transfer<br />
39
- pes 2020 lite youtube gameplay<br />
40
- pes 2020 lite mediafire link<br />
41
- pes 2020 lite apk mod<br />
42
- pes 2020 lite offline mode<br />
43
- pes 2020 lite online match<br />
44
- pes 2020 lite edit mode<br />
45
- pes 2020 lite efootball mode<br />
46
- pes 2020 lite matchday mode<br />
47
- pes 2020 lite allianz arena<br />
48
- pes 2020 lite boca juniors<br />
49
- pes 2020 lite fc barcelona<br />
50
- pes 2020 lite fc bayern münchen<br />
51
- pes 2020 lite juventus<br />
52
- pes 2020 lite manchester united<br />
53
- pes 2020 lite arsenal<br />
54
- pes 2020 lite palmeiras<br />
55
- pes 2020 lite flamengo<br />
56
- pes 2020 lite são paulo<br />
57
- pes 2020 lite corinthians<br />
58
- pes 2020 lite vasco da gama<br />
59
- pes 2020 lite colo-colo<br />
60
- pes 2020 lite river plate<br />
61
- pes 2020 lite net energy gain experiment<br />
62
- pes 2020 lite holy grail fusion experiment<br />
63
- pes 2020 lite mini sun experiment<br />
64
- pes 2020 lite nuclear fusion reaction temperature<br />
65
- pes 2020 lite kstar facility korea institute of fusion energy<br />
66
- pes 2020 lite fifplay website review<br />
67
- pes 2020 lite sahte forvet youtube channel review<br />
68
- pes 2020 lite weebly website review<br />
69
- pes 2020 lite screenshot and video tutorial<br />
70
- pes 2020 lite download and installation guide<br />
71
- pes 2020 lite tips and tricks for beginners<br />
72
- pes 2020 lite best players and teams to use in myclub mode <br />
73
- pes 2020 lite how to earn myclub coins and gp fast <br />
74
- pes 2020 lite how to improve your skills and tactics in kick off mode <br />
75
- pes 2020 lite how to customize your team and players in edit mode <br />
76
- pes 2020 lite how to participate and win in efootball mode <br />
77
- pes 2020 lite how to enjoy matchday mode with your friends <br />
78
- pes 2020 lite how to fix common errors and issues in the game <br />
79
- pes 2020 lite how to update the game to the latest version <br />
80
- pes 2020 lite how to contact the game support team for help </p>
81
- <h3>How to install PES 2020 Lite on Android devices</h3>
82
- <p>If you want to play PES 2020 Lite on your Android device, you will need to download and install an APK file that is not available on the Google Play Store. This is because PES 2020 Lite is not an official app by Konami, but a modified version of PES 2020 mobile that has been compressed to reduce the file size. Therefore, you will need to follow these steps to install it:</p>
83
- <ol>
84
- <li>Download the PES 2020 Lite 50 MB APK file from this link: <a href="">PES 2020 Lite 50 MB APK</a></li>
85
- <li>Download the OBB data file from this link: <a href="">PES 2020 Lite OBB Data</a></li>
86
- <li>Enable the installation of apps from unknown sources on your device settings</li>
87
- <li>Install the APK file on your device</li>
88
- <li>Extract the OBB data file using a file manager app and copy the folder "jp.konami.pesam" to the path "Android/OBB" on your device storage</li>
89
- <li>Launch the game and enjoy playing PES 2020 Lite on your Android device</li>
90
- </ol>
91
- <p>Note that you will also need an internet connection and a Konami ID to play the game online. You may also encounter some errors or bugs while playing, as this is not an official app by Konami.</p>
92
- <h2>Pros and cons of PES 2020 Lite</h2>
93
- <p>PES 2020 Lite is a great option for those who want to experience PES 2020 without spending any money. However, it also has some drawbacks that you should be aware of before playing. Here are some of the pros and cons of PES 2020 Lite:</p>
94
- <h3>Pros</h3>
95
- <h4>Free to play</h4>
96
- <p>The biggest advantage of PES 2020 Lite is that it is free to play. You don't need to pay anything to download and play the game, unlike the full-game that costs around $60. You can enjoy playing online matches with other users who have either the full-game or the lite version, and create your own team in myClub mode with a limited number of clubs available.</p>
97
- <h4>Online matches with full-game users</h4>
98
- <p>PES 2020 Lite allows you to play online matches with other users who have either the full-game or the lite version. This means that you can compete with a large and diverse player base, and test your skills against different opponents. You can also participate in online events and tournaments that are held regularly by Konami.</p>
99
- <h4>MyClub mode with limited clubs</h4>
100
- <p>PES 2020 Lite gives you access to myClub mode, which is one of the most popular modes in PES 2020. In myClub mode, you can create your own team by signing players, managers, coaches and scouts. You can also customize your team's kits, badges, formations and tactics. However, in PES 2020 Lite, you can only choose from a limited number of clubs, such as FC Barcelona, Manchester United, Juventus and Bayern Munich.</p>
101
- <h3>Cons</h3>
102
- <h4>Limited game modes and clubs</h4>
103
- <p>The biggest disadvantage of PES 2020 Lite is that it has limited game modes and clubs compared to the full-game. You cannot play some of the most popular modes in PES 2020, such as master league, become a legend, matchday (offline), online divisions, online CO-OP (online) and random selection match. You also cannot choose from all the clubs that are available in kick-off mode, such as Arsenal, Liverpool, Real Madrid, PSG and more.</p>
104
- <h4>No data transfer to full-game</h4>
105
- <p>PES 2020 Lite does not allow you to transfer your data to the full-game if you decide to buy it later. This means that you will lose all your progress and achievements in PES 2020 Lite, such as your myClub team, your online match records, your edit data and your coins. You will have to start from scratch if you buy the full-game, which can be frustrating and discouraging.</p>
106
- <h4>Large file size</h4>
107
- <p>PES 2020 Lite may be a free-to-play version of PES 2020, but it still requires a lot of storage space on your device. The game size is around 40 GB for PS4, Xbox One and PC Steam, and around 1.5 GB for Android devices. This means that you will need to have enough free space on your device to download and install the game, and also to update it regularly. You may also experience some lag or slow loading times if your device is not powerful enough to run the game smoothly.</p>
108
- <h2>Frequently asked questions about PES 2020 Lite</h2>
109
- <p>Here are some of the most common questions that users have about PES 2020 Lite:</p>
110
- <ol>
111
- <li><b>Is PES 2020 Lite worth playing?</b></li>
112
- <p>PES 2020 Lite is worth playing if you are looking for a free-to-play football game that offers realistic and immersive gameplay, graphics and sound. You can play online matches with other users who have either the full-game or the lite version, and create your own team in myClub mode with a limited number of clubs available. However, you should also be aware of the limitations and drawbacks of PES 2020 Lite, such as the limited game modes and clubs, the no data transfer to full-game, and the large file size.</p>
113
- <li><b>Can I play PES 2020 Lite offline?</b></li>
114
- <p>PES 2020 Lite can be played offline in local match, CO-OP and training modes. However, you will need an internet connection to play online matches in myClub and eFootball modes, and to access some of the online features and events. You will also need an internet connection to download and update the game.</p>
115
- <li><b>How can I get more coins in PES 2020 Lite?</b></li>
116
- <p>Coins are the premium currency in PES 2020 Lite that can be used to buy players, managers, scouts and other items in myClub mode. You can get more coins by completing achievements, participating in events, logging in daily, or buying them with real money.</p>
117
- <li><b>How can I play with friends in PES 2020 Lite?</b></li>
118
- <p>You can play with friends in PES 2020 Lite by inviting them to join your room in online CO-OP mode (only available for PS4, Xbox One and PC Steam), or by adding them as friends in myClub mode and challenging them to friendly matches.</p>
119
- <li><b>How can I update PES 2020 Lite?</b></li>
120
- <p>You can update PES 2020 Lite by downloading the latest version of the game from the links provided above, or by launching the game and following the instructions on the screen. You will need an internet connection to update the game.</p>
121
- </ol>
122
- <h2>Conclusion</h2>
123
- <p>PES 2020 Lite is a free-to-play version of PES 2020 that lets you enjoy some of its features and modes without spending any money. You can play online matches with other users who have either the full-game or the lite version, and create your own team in myClub mode with a limited number of clubs available. However, you should also be aware of the limitations and drawbacks of PES 2020 Lite, such as the limited game modes and clubs, the no data transfer to full-game, and the large file size. If you want to experience PES 2020 fully, you will need to buy the full-game.</p>
124
- <p>We hope that this article has helped you understand what PES 2020 Lite is, how to download and install it on different platforms, and what are the pros and cons of playing it. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!</p> 197e85843d<br />
125
- <br />
126
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Explore Upland A City of History Culture and Adventure.md DELETED
@@ -1,104 +0,0 @@
1
-
2
- <h1>Upland: A Blockchain Game Where You Can Rebuild the World</h1>
3
- <p>Have you ever dreamed of owning a piece of land in your favorite city? Or maybe you want to create your own neighborhood, business, or arcade in a virtual world? If so, you might want to check out <a href="(^1^)">Upland</a>, a blockchain game that lets you buy, sell, and trade virtual properties mapped to the real world.</p>
4
- <p>Upland is a property-trading, city-building metaverse that uses blockchain technology to ensure true ownership of digital assets. By playing Upland, you can explore cities, collect properties, earn UPX coins and USD, and connect with other players. You can also participate in various activities and events that make Upland an immersive and fun experience.</p>
5
- <h2>upland</h2><br /><p><b><b>Download</b> &#9913; <a href="https://jinyurl.com/2uNLgJ">https://jinyurl.com/2uNLgJ</a></b></p><br /><br />
6
- <p>In this article, we will give you an overview of what Upland is, how it works, and what are the benefits of playing it. We will also cover some of the features, future plans, and FAQs about Upland. So, if you are ready to rebuild the world with Upland, read on!</p>
7
- <h2>Upland Features</h2>
8
- <p>Upland is more than just a game. It is a metaverse that offers a range of features and possibilities for players. Here are some of the main features that make Upland unique and enjoyable.</p>
9
- <h3>Property Trading</h3>
10
- <p>One of the core features of Upland is property trading. In Upland, you can buy, sell, and trade virtual properties that are mapped to real-world addresses. Each property is represented by a non-fungible token (NFT) on the EOS blockchain, which means that you have full ownership and control over your digital assets.</p>
11
- <p>To buy a property in Upland, you need to use UPX coins, which are the native currency of the game. You can earn UPX coins by exploring the map, completing collections, participating in events, or buying them with fiat or crypto. You can also sell your properties for UPX coins or USD on the open marketplace.</p>
12
- <p>By trading properties in Upland, you can increase your net worth, level up your status, unlock new features, and earn passive income. You can also use your properties to create businesses, services, or attractions that add value to the metaverse.</p>
13
- <h3>City Building</h3>
14
- <p>Another feature of Upland is city building. In Upland, you can explore different cities around the world and collect properties that match your preferences. You can also discover landmarks, monuments, historical sites, and other points of interest that make each city unique.</p>
15
- <p>upland hunting<br />
16
- upland game birds<br />
17
- upland software<br />
18
- upland cotton<br />
19
- upland brewery<br />
20
- upland real estate<br />
21
- upland boots<br />
22
- upland bike<br />
23
- upland dog vest<br />
24
- upland farms<br />
25
- upland weather<br />
26
- upland ca zip code<br />
27
- upland hills country club<br />
28
- upland animal shelter<br />
29
- upland high school<br />
30
- upland rice<br />
31
- upland plants<br />
32
- upland park hotel<br />
33
- upland bird hunting gear<br />
34
- upland definition geography<br />
35
- upland vs lowland whisky<br />
36
- upland sandpiper<br />
37
- upland meadows crossword clue<br />
38
- upland outfitters maine<br />
39
- upland journal forum<br />
40
- upland vest with hydration bladder<br />
41
- upland game bird season california<br />
42
- upland sour ale project<br />
43
- upland apartments for rent<br />
44
- upland police department<br />
45
- upland optics perception hd 10x42mm binoculars<br />
46
- upland golf course scorecard<br />
47
- upland lemon festival 2023 dates<br />
48
- upland hardwood forest ecosystem<br />
49
- upland heath and moorlands management plan<br />
50
- upland erosion control methods<br />
51
- upland bird dog training tips<br />
52
- upland grass seed mixtures<br />
53
- upland habitat restoration projects<br />
54
- upland quail hunting preserves near me<br />
55
- upland public library hours of operation<br />
56
- upland unified school district calendar 2023 2024 <br />
57
- upland mountain biking trails map <br />
58
- upland water company pay bill online <br />
59
- upland youth soccer league registration <br />
60
- upland farmers market vendors list <br />
61
- upland fire department station 164 <br />
62
- upland dental group and implant center <br />
63
- upland christian academy tuition fees <br />
64
- upland community church live stream</p>
65
- <p>Currently, Upland has launched several cities in the US, such as San Francisco, New York, Fresno, Bakersfield, Oakland, Cleveland, Chicago, Kansas City, Santa Clara, Manhattan Beach. More cities are planned to be added in the future.</p>
66
- <p>Besides exploring cities, you can also create and join neighborhoods and communities in Upland. You can collaborate with other players to develop and improve your areas, share ideas and tips, and have fun together. You can also join Upland's official Discord server, where you can chat with other players, get support, and stay updated on the latest news and announcements.</p>
67
- <h3>Metaverse Activities</h3>
68
- <p>The last feature of Upland that we will discuss is metaverse activities. In Upland, you can do more than just buying and selling properties. You can also engage in various activities and events that make the game more interactive and enjoyable.</p>
69
- <p>Some of the activities that you can do in Upland are:</p>
70
- <ul>
71
- <li>Collecting NFTs: You can collect different types of NFTs in Upland, such as cars, planes, trains, art, sports cards, and more. You can use your NFTs to customize your avatar, travel faster, or display them in your properties.</li>
72
- <li>Playing mini-games: You can play mini-games in Upland, such as treasure hunts, scavenger hunts, quizzes, puzzles, and more. You can win prizes, UPX coins, NFTs, or badges by playing these games.</li>
73
- <li>Competing in leaderboards: You can compete with other players in Upland's leaderboards, such as net worth, collections, earnings, visits, and more. You can earn rewards, recognition, and bragging rights by ranking high on these leaderboards.</li>
74
- </ul>
75
- <p>Besides these activities, you can also participate in various events and challenges that are regularly organized by Upland's team or community. These events and challenges can range from themed collections, property auctions, trivia contests, scavenger hunts, and more. You can have fun, meet new people, and win amazing prizes by joining these events and challenges.</p>
76
- <h2>Upland Future Plans</h2>
77
- <p>Upland is not just a game that is already finished. It is a game that is constantly evolving and improving. Upland's team has a vision to create a metaverse that is rich in content, features, and possibilities for players.</p>
78
- <p>Some of the future plans that Upland has are:</p>
79
- <ul>
80
- <li>Expanding to more cities and countries: Upland plans to launch more cities and countries in the future, such as Los Angeles, London, Paris, Tokyo, Berlin, and more. This will allow players to explore more places and cultures in the metaverse.</li>
81
- <li>Adding more functionality and utility to properties: Upland plans to add more functionality and utility to properties in the future, such as allowing players to build structures, businesses, services, or attractions on their properties. This will allow players to create more value and income from their properties.</li>
82
- <li>Integrating with other platforms and projects: Upland plans to integrate with other platforms and projects in the future, such as Decentraland, Sandbox, CryptoKitties, NBA Top Shot, and more. This will allow players to access more content and features from other platforms and projects in the metaverse.</li>
83
- </ul>
84
- <p>These are just some of the future plans that Upland has. There are more plans and ideas that are being developed and discussed by Upland's team and community. You can follow Upland's <a href="">blog</a>, <a href="">Twitter</a>, or <a href="">Discord</a> to stay updated on the latest developments and updates for Upland.</p>
85
- <h2>Conclusion</h2>
86
- <p>Upland is a blockchain game that lets you buy, sell, and trade virtual properties mapped to the real world. You can also explore cities, collect properties, earn UPX coins and USD, and connect with other players. You can also participate in various activities and events that make Upland an immersive and fun experience.</p>
87
- <p>Upland is more than just a game. It is a metaverse that offers a range of features and possibilities for players. Upland is also a game that is constantly evolving and improving, with more cities, countries, functionality, utility, and integration planned for the future.</p>
88
- <p>If you are interested in playing Upland, you can join the game by visiting their <a href="">website</a> and signing up with your email or phone number. You will also need an EOS account to play Upland, which you can create for free using the Wombat wallet app. Once you have your account, you can start playing Upland and rebuild the world with your own vision.</p>
89
- <h2>FAQs</h2>
90
- <p>Here are some of the frequently asked questions about Upland:</p>
91
- <ol>
92
- <li><b>What is the difference between upland and lowland in geography?</b></li>
93
- <p>In geography, upland and lowland are terms that describe the elevation of land. Upland refers to land that is higher than the surrounding area, such as hills, mountains, or plateaus. Lowland refers to land that is lower than the surrounding area, such as plains, valleys, or coasts.</p>
94
- <li><b>What is the difference between upland and lowland in ecology?</b></li>
95
- <p>In ecology, upland and lowland are terms that describe the habitat of plants and animals. Upland refers to habitats that are dry, cool, and have poor soil quality, such as grasslands, heathlands, or moorlands. Lowland refers to habitats that are wet, warm, and have rich soil quality, such as forests, wetlands, or marshes.</p>
96
- <li><b>What is the difference between upland and lowland in blockchain gaming?</b></li>
97
- <p>In blockchain gaming, upland and lowland are terms that describe the status of players in Upland. Upland refers to players who have verified their identity and have access to all the features and benefits of the game. Lowland refers to players who have not verified their identity and have limited access to some of the features and benefits of the game.</p>
98
- <li><b>How can I join Upland and start playing?</b></li>
99
- <p>You can join Upland by visiting their <a href="">website</a> and signing up with your email or phone number. You will also need an EOS account to play Upland, which you can create for free using the Wombat wallet app. Once you have your account, you can start playing Upland and rebuild the world with your own vision.</p>
100
- <li><b>Where can I find more information and resources about Upland?</b></li>
101
- <p>You can find more information and resources about Upland by visiting their <a href="">blog</a>, <a href="">Twitter</a>, or <a href="">Discord</a>. You can also check out their <a href="">wiki</a>, <a href="">FAQs</a>, or <a href="">support page</a>. You can also watch some of their <a href="">videos</a> or listen to some of their <a href="">podcasts</a>.</p>
102
- </ol></p> 197e85843d<br />
103
- <br />
104
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1toTree/lora_test/ppdiffusers/pipelines/latent_diffusion_uncond/pipeline_latent_diffusion_uncond.py DELETED
@@ -1,110 +0,0 @@
1
- # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
- # Copyright 2022 The HuggingFace Team. All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- import inspect
17
- from typing import List, Optional, Tuple, Union
18
-
19
- import paddle
20
-
21
- from ...models import UNet2DModel, VQModel
22
- from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
23
- from ...schedulers import DDIMScheduler
24
-
25
-
26
- class LDMPipeline(DiffusionPipeline):
27
- r"""
28
- This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
29
- library implements for all the pipelines (such as downloading or saving, running on a particular xxxx, etc.)
30
-
31
- Parameters:
32
- vqvae ([`VQModel`]):
33
- Vector-quantized (VQ) Model to encode and decode images to and from latent representations.
34
- unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image latents.
35
- scheduler ([`SchedulerMixin`]):
36
- [`DDIMScheduler`] is to be used in combination with `unet` to denoise the encoded image latents.
37
- """
38
-
39
- def __init__(self, vqvae: VQModel, unet: UNet2DModel, scheduler: DDIMScheduler):
40
- super().__init__()
41
- self.register_modules(vqvae=vqvae, unet=unet, scheduler=scheduler)
42
-
43
- @paddle.no_grad()
44
- def __call__(
45
- self,
46
- batch_size: int = 1,
47
- generator: Optional[Union[paddle.Generator, List[paddle.Generator]]] = None,
48
- eta: float = 0.0,
49
- num_inference_steps: int = 50,
50
- output_type: Optional[str] = "pil",
51
- return_dict: bool = True,
52
- **kwargs,
53
- ) -> Union[Tuple, ImagePipelineOutput]:
54
- r"""
55
- Args:
56
- batch_size (`int`, *optional*, defaults to 1):
57
- Number of images to generate.
58
- generator (`paddle.Generator`, *optional*):
59
- One or a list of paddle generator(s) to make generation deterministic.
60
- num_inference_steps (`int`, *optional*, defaults to 50):
61
- The number of denoising steps. More denoising steps usually lead to a higher quality image at the
62
- expense of slower inference.
63
- output_type (`str`, *optional*, defaults to `"pil"`):
64
- The output format of the generate image. Choose between
65
- [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
66
- return_dict (`bool`, *optional*, defaults to `True`):
67
- Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.
68
-
69
- Returns:
70
- [`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if
71
- `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the
72
- generated images.
73
- """
74
-
75
- latents = paddle.randn(
76
- (batch_size, self.unet.in_channels, self.unet.sample_size, self.unet.sample_size),
77
- generator=generator,
78
- )
79
-
80
- # scale the initial noise by the standard deviation required by the scheduler
81
- latents = latents * self.scheduler.init_noise_sigma
82
-
83
- self.scheduler.set_timesteps(num_inference_steps)
84
-
85
- # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
86
- accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
87
-
88
- extra_kwargs = {}
89
- if accepts_eta:
90
- extra_kwargs["eta"] = eta
91
-
92
- for t in self.progress_bar(self.scheduler.timesteps):
93
- latent_model_input = self.scheduler.scale_model_input(latents, t)
94
- # predict the noise residual
95
- noise_prediction = self.unet(latent_model_input, t).sample
96
- # compute the previous noisy sample x_t -> x_t-1
97
- latents = self.scheduler.step(noise_prediction, t, latents, **extra_kwargs).prev_sample
98
-
99
- # decode the image latents with the VAE
100
- image = self.vqvae.decode(latents).sample
101
-
102
- image = (image / 2 + 0.5).clip(0, 1)
103
- image = image.transpose([0, 2, 3, 1]).cast("float32").numpy()
104
- if output_type == "pil":
105
- image = self.numpy_to_pil(image)
106
-
107
- if not return_dict:
108
- return (image,)
109
-
110
- return ImagePipelineOutput(images=image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1toTree/lora_test/ppdiffusers/version.py DELETED
@@ -1,17 +0,0 @@
1
- # Copyright (c) 2022 PaddlePaddle Authors. 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
- # this file will be generated by tools
16
- # please not modify it.
17
- VERSION = "0.0.0"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/7hao/bingo/src/components/turn-counter.tsx DELETED
@@ -1,23 +0,0 @@
1
- import React from 'react'
2
- import { Throttling } from '@/lib/bots/bing/types'
3
-
4
- export interface TurnCounterProps {
5
- throttling?: Throttling
6
- }
7
-
8
- export function TurnCounter({ throttling }: TurnCounterProps) {
9
- if (!throttling) {
10
- return null
11
- }
12
-
13
- return (
14
- <div className="turn-counter">
15
- <div className="text">
16
- <span>{throttling.numUserMessagesInConversation}</span>
17
- <span> 共 </span>
18
- <span>{throttling.maxNumUserMessagesInConversation}</span>
19
- </div>
20
- <div className="indicator"></div>
21
- </div>
22
- )
23
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/A00001/bingothoo/src/lib/hooks/use-copy-to-clipboard.tsx DELETED
@@ -1,33 +0,0 @@
1
- 'use client'
2
-
3
- import * as React from 'react'
4
-
5
- export interface useCopyToClipboardProps {
6
- timeout?: number
7
- }
8
-
9
- export function useCopyToClipboard({
10
- timeout = 2000
11
- }: useCopyToClipboardProps) {
12
- const [isCopied, setIsCopied] = React.useState<Boolean>(false)
13
-
14
- const copyToClipboard = (value: string) => {
15
- if (typeof window === 'undefined' || !navigator.clipboard?.writeText) {
16
- return
17
- }
18
-
19
- if (!value) {
20
- return
21
- }
22
-
23
- navigator.clipboard.writeText(value).then(() => {
24
- setIsCopied(true)
25
-
26
- setTimeout(() => {
27
- setIsCopied(false)
28
- }, timeout)
29
- })
30
- }
31
-
32
- return { isCopied, copyToClipboard }
33
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGC-Audio/AudioGPT/text_to_speech/modules/vocoder/hifigan/hifigan.py DELETED
@@ -1,338 +0,0 @@
1
- import torch
2
- import torch.nn.functional as F
3
- import torch.nn as nn
4
- from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
5
- from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
6
- import numpy as np
7
-
8
- LRELU_SLOPE = 0.1
9
-
10
-
11
- def init_weights(m, mean=0.0, std=0.01):
12
- classname = m.__class__.__name__
13
- if classname.find("Conv") != -1:
14
- m.weight.data.normal_(mean, std)
15
-
16
-
17
- def apply_weight_norm(m):
18
- classname = m.__class__.__name__
19
- if classname.find("Conv") != -1:
20
- weight_norm(m)
21
-
22
-
23
- def get_padding(kernel_size, dilation=1):
24
- return int((kernel_size * dilation - dilation) / 2)
25
-
26
-
27
- class ResBlock1(torch.nn.Module):
28
- def __init__(self, h, channels, kernel_size=3, dilation=(1, 3, 5)):
29
- super(ResBlock1, self).__init__()
30
- self.h = h
31
- self.convs1 = nn.ModuleList([
32
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
33
- padding=get_padding(kernel_size, dilation[0]))),
34
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
35
- padding=get_padding(kernel_size, dilation[1]))),
36
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
37
- padding=get_padding(kernel_size, dilation[2])))
38
- ])
39
- self.convs1.apply(init_weights)
40
-
41
- self.convs2 = nn.ModuleList([
42
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
43
- padding=get_padding(kernel_size, 1))),
44
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
45
- padding=get_padding(kernel_size, 1))),
46
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
47
- padding=get_padding(kernel_size, 1)))
48
- ])
49
- self.convs2.apply(init_weights)
50
-
51
- def forward(self, x):
52
- for c1, c2 in zip(self.convs1, self.convs2):
53
- xt = F.leaky_relu(x, LRELU_SLOPE)
54
- xt = c1(xt)
55
- xt = F.leaky_relu(xt, LRELU_SLOPE)
56
- xt = c2(xt)
57
- x = xt + x
58
- return x
59
-
60
- def remove_weight_norm(self):
61
- for l in self.convs1:
62
- remove_weight_norm(l)
63
- for l in self.convs2:
64
- remove_weight_norm(l)
65
-
66
-
67
- class ResBlock2(torch.nn.Module):
68
- def __init__(self, h, channels, kernel_size=3, dilation=(1, 3)):
69
- super(ResBlock2, self).__init__()
70
- self.h = h
71
- self.convs = nn.ModuleList([
72
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
73
- padding=get_padding(kernel_size, dilation[0]))),
74
- weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
75
- padding=get_padding(kernel_size, dilation[1])))
76
- ])
77
- self.convs.apply(init_weights)
78
-
79
- def forward(self, x):
80
- for c in self.convs:
81
- xt = F.leaky_relu(x, LRELU_SLOPE)
82
- xt = c(xt)
83
- x = xt + x
84
- return x
85
-
86
- def remove_weight_norm(self):
87
- for l in self.convs:
88
- remove_weight_norm(l)
89
-
90
-
91
- class Conv1d1x1(Conv1d):
92
- """1x1 Conv1d with customized initialization."""
93
-
94
- def __init__(self, in_channels, out_channels, bias):
95
- """Initialize 1x1 Conv1d module."""
96
- super(Conv1d1x1, self).__init__(in_channels, out_channels,
97
- kernel_size=1, padding=0,
98
- dilation=1, bias=bias)
99
-
100
-
101
- class HifiGanGenerator(torch.nn.Module):
102
- def __init__(self, h, c_out=1):
103
- super(HifiGanGenerator, self).__init__()
104
- self.h = h
105
- self.num_kernels = len(h['resblock_kernel_sizes'])
106
- self.num_upsamples = len(h['upsample_rates'])
107
-
108
- self.conv_pre = weight_norm(Conv1d(80, h['upsample_initial_channel'], 7, 1, padding=3))
109
- resblock = ResBlock1 if h['resblock'] == '1' else ResBlock2
110
-
111
- self.ups = nn.ModuleList()
112
- for i, (u, k) in enumerate(zip(h['upsample_rates'], h['upsample_kernel_sizes'])):
113
- c_cur = h['upsample_initial_channel'] // (2 ** (i + 1))
114
- self.ups.append(weight_norm(
115
- ConvTranspose1d(c_cur * 2, c_cur, k, u, padding=(k - u) // 2)))
116
- self.resblocks = nn.ModuleList()
117
- for i in range(len(self.ups)):
118
- ch = h['upsample_initial_channel'] // (2 ** (i + 1))
119
- for j, (k, d) in enumerate(zip(h['resblock_kernel_sizes'], h['resblock_dilation_sizes'])):
120
- self.resblocks.append(resblock(h, ch, k, d))
121
-
122
- self.conv_post = weight_norm(Conv1d(ch, c_out, 7, 1, padding=3))
123
- self.ups.apply(init_weights)
124
- self.conv_post.apply(init_weights)
125
-
126
- def forward(self, x, f0=None):
127
- x = self.conv_pre(x)
128
- for i in range(self.num_upsamples):
129
- x = F.leaky_relu(x, LRELU_SLOPE)
130
- x = self.ups[i](x)
131
- xs = None
132
- for j in range(self.num_kernels):
133
- if xs is None:
134
- xs = self.resblocks[i * self.num_kernels + j](x)
135
- else:
136
- xs += self.resblocks[i * self.num_kernels + j](x)
137
- x = xs / self.num_kernels
138
- x = F.leaky_relu(x)
139
- x = self.conv_post(x)
140
- x = torch.tanh(x)
141
-
142
- return x
143
-
144
- def remove_weight_norm(self):
145
- print('Removing weight norm...')
146
- for l in self.ups:
147
- remove_weight_norm(l)
148
- for l in self.resblocks:
149
- l.remove_weight_norm()
150
- remove_weight_norm(self.conv_pre)
151
- remove_weight_norm(self.conv_post)
152
-
153
-
154
- class DiscriminatorP(torch.nn.Module):
155
- def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False, use_cond=False, c_in=1):
156
- super(DiscriminatorP, self).__init__()
157
- self.use_cond = use_cond
158
- if use_cond:
159
- from text_to_speech.utils.commons.hparams import hparams
160
- t = hparams['hop_size']
161
- self.cond_net = torch.nn.ConvTranspose1d(80, 1, t * 2, stride=t, padding=t // 2)
162
- c_in = 2
163
-
164
- self.period = period
165
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
166
- self.convs = nn.ModuleList([
167
- norm_f(Conv2d(c_in, 32, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
168
- norm_f(Conv2d(32, 128, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
169
- norm_f(Conv2d(128, 512, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
170
- norm_f(Conv2d(512, 1024, (kernel_size, 1), (stride, 1), padding=(get_padding(5, 1), 0))),
171
- norm_f(Conv2d(1024, 1024, (kernel_size, 1), 1, padding=(2, 0))),
172
- ])
173
- self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
174
-
175
- def forward(self, x, mel):
176
- fmap = []
177
- if self.use_cond:
178
- x_mel = self.cond_net(mel)
179
- x = torch.cat([x_mel, x], 1)
180
- # 1d to 2d
181
- b, c, t = x.shape
182
- if t % self.period != 0: # pad first
183
- n_pad = self.period - (t % self.period)
184
- x = F.pad(x, (0, n_pad), "reflect")
185
- t = t + n_pad
186
- x = x.view(b, c, t // self.period, self.period)
187
-
188
- for l in self.convs:
189
- x = l(x)
190
- x = F.leaky_relu(x, LRELU_SLOPE)
191
- fmap.append(x)
192
- x = self.conv_post(x)
193
- fmap.append(x)
194
- x = torch.flatten(x, 1, -1)
195
-
196
- return x, fmap
197
-
198
-
199
- class MultiPeriodDiscriminator(torch.nn.Module):
200
- def __init__(self, use_cond=False, c_in=1):
201
- super(MultiPeriodDiscriminator, self).__init__()
202
- self.discriminators = nn.ModuleList([
203
- DiscriminatorP(2, use_cond=use_cond, c_in=c_in),
204
- DiscriminatorP(3, use_cond=use_cond, c_in=c_in),
205
- DiscriminatorP(5, use_cond=use_cond, c_in=c_in),
206
- DiscriminatorP(7, use_cond=use_cond, c_in=c_in),
207
- DiscriminatorP(11, use_cond=use_cond, c_in=c_in),
208
- ])
209
-
210
- def forward(self, y, y_hat, mel=None):
211
- y_d_rs = []
212
- y_d_gs = []
213
- fmap_rs = []
214
- fmap_gs = []
215
- for i, d in enumerate(self.discriminators):
216
- y_d_r, fmap_r = d(y, mel)
217
- y_d_g, fmap_g = d(y_hat, mel)
218
- y_d_rs.append(y_d_r)
219
- fmap_rs.append(fmap_r)
220
- y_d_gs.append(y_d_g)
221
- fmap_gs.append(fmap_g)
222
-
223
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
224
-
225
-
226
- class DiscriminatorS(torch.nn.Module):
227
- def __init__(self, use_spectral_norm=False, use_cond=False, upsample_rates=None, c_in=1):
228
- super(DiscriminatorS, self).__init__()
229
- self.use_cond = use_cond
230
- if use_cond:
231
- t = np.prod(upsample_rates)
232
- self.cond_net = torch.nn.ConvTranspose1d(80, 1, t * 2, stride=t, padding=t // 2)
233
- c_in = 2
234
- norm_f = weight_norm if use_spectral_norm == False else spectral_norm
235
- self.convs = nn.ModuleList([
236
- norm_f(Conv1d(c_in, 128, 15, 1, padding=7)),
237
- norm_f(Conv1d(128, 128, 41, 2, groups=4, padding=20)),
238
- norm_f(Conv1d(128, 256, 41, 2, groups=16, padding=20)),
239
- norm_f(Conv1d(256, 512, 41, 4, groups=16, padding=20)),
240
- norm_f(Conv1d(512, 1024, 41, 4, groups=16, padding=20)),
241
- norm_f(Conv1d(1024, 1024, 41, 1, groups=16, padding=20)),
242
- norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
243
- ])
244
- self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
245
-
246
- def forward(self, x, mel):
247
- if self.use_cond:
248
- x_mel = self.cond_net(mel)
249
- x = torch.cat([x_mel, x], 1)
250
- fmap = []
251
- for l in self.convs:
252
- x = l(x)
253
- x = F.leaky_relu(x, LRELU_SLOPE)
254
- fmap.append(x)
255
- x = self.conv_post(x)
256
- fmap.append(x)
257
- x = torch.flatten(x, 1, -1)
258
-
259
- return x, fmap
260
-
261
-
262
- class MultiScaleDiscriminator(torch.nn.Module):
263
- def __init__(self, use_cond=False, c_in=1):
264
- super(MultiScaleDiscriminator, self).__init__()
265
- from text_to_speech.utils.commons.hparams import hparams
266
- self.discriminators = nn.ModuleList([
267
- DiscriminatorS(use_spectral_norm=True, use_cond=use_cond,
268
- upsample_rates=[4, 4, hparams['hop_size'] // 16],
269
- c_in=c_in),
270
- DiscriminatorS(use_cond=use_cond,
271
- upsample_rates=[4, 4, hparams['hop_size'] // 32],
272
- c_in=c_in),
273
- DiscriminatorS(use_cond=use_cond,
274
- upsample_rates=[4, 4, hparams['hop_size'] // 64],
275
- c_in=c_in),
276
- ])
277
- self.meanpools = nn.ModuleList([
278
- AvgPool1d(4, 2, padding=1),
279
- AvgPool1d(4, 2, padding=1)
280
- ])
281
-
282
- def forward(self, y, y_hat, mel=None):
283
- y_d_rs = []
284
- y_d_gs = []
285
- fmap_rs = []
286
- fmap_gs = []
287
- for i, d in enumerate(self.discriminators):
288
- if i != 0:
289
- y = self.meanpools[i - 1](y)
290
- y_hat = self.meanpools[i - 1](y_hat)
291
- y_d_r, fmap_r = d(y, mel)
292
- y_d_g, fmap_g = d(y_hat, mel)
293
- y_d_rs.append(y_d_r)
294
- fmap_rs.append(fmap_r)
295
- y_d_gs.append(y_d_g)
296
- fmap_gs.append(fmap_g)
297
-
298
- return y_d_rs, y_d_gs, fmap_rs, fmap_gs
299
-
300
-
301
- def feature_loss(fmap_r, fmap_g):
302
- loss = 0
303
- for dr, dg in zip(fmap_r, fmap_g):
304
- for rl, gl in zip(dr, dg):
305
- loss += torch.mean(torch.abs(rl - gl))
306
-
307
- return loss * 2
308
-
309
-
310
- def discriminator_loss(disc_real_outputs, disc_generated_outputs):
311
- r_losses = 0
312
- g_losses = 0
313
- for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
314
- r_loss = torch.mean((1 - dr) ** 2)
315
- g_loss = torch.mean(dg ** 2)
316
- r_losses += r_loss
317
- g_losses += g_loss
318
- r_losses = r_losses / len(disc_real_outputs)
319
- g_losses = g_losses / len(disc_real_outputs)
320
- return r_losses, g_losses
321
-
322
-
323
- def cond_discriminator_loss(outputs):
324
- loss = 0
325
- for dg in outputs:
326
- g_loss = torch.mean(dg ** 2)
327
- loss += g_loss
328
- loss = loss / len(outputs)
329
- return loss
330
-
331
-
332
- def generator_loss(disc_outputs):
333
- loss = 0
334
- for dg in disc_outputs:
335
- l = torch.mean((1 - dg) ** 2)
336
- loss += l
337
- loss = loss / len(disc_outputs)
338
- return loss
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AILab-CVC/SEED-LLaMA/models/seed_llama_tokenizer.py DELETED
@@ -1,213 +0,0 @@
1
- import torch.nn as nn
2
- import torch
3
- # import math
4
- # from torchvision import transforms
5
- import os
6
- # from timm.models import create_model
7
- from typing import Any, Dict, List, Optional, Union
8
- from transformers import LlamaTokenizer
9
- from diffusers import DiffusionPipeline
10
- # from torchvision.transforms.functional import pil_to_tensor
11
-
12
- # import torch
13
- from PIL import Image
14
- from torchvision import transforms
15
-
16
- # from qformer.qformer_quantizer import Blip2QformerQuantizer
17
- # from diffusers import StableUnCLIPImg2ImgPipeline
18
- from .pipeline_stable_unclip_img2img import StableUnCLIPImg2ImgPipeline
19
-
20
- WEIGHTS_NAME = 'seed_quantizer.pt'
21
- DIFFUSION_NAME = 'diffusion_model'
22
-
23
-
24
- class ImageTokenizer(nn.Module):
25
- def __init__(self,
26
- model_path,
27
- diffusion_model_path=None,
28
- load_diffusion=False,
29
- image_size=224,
30
- device='cuda',
31
- fp16=True,
32
- **kwargs):
33
- super().__init__()
34
- from .seed_qformer.qformer_quantizer import Blip2QformerQuantizer
35
-
36
- model = Blip2QformerQuantizer.from_pretrained(pretrained_model_path=model_path,
37
- vit_precision='fp16' if fp16 else 'fp32',
38
- **kwargs).eval()
39
- if diffusion_model_path is not None and load_diffusion:
40
- # diffusion_model = DiffusionPipeline.from_pretrained(diffusion_model_path,
41
- # torch_dtype=torch.float16 if fp16 else torch.float32)
42
- diffusion_model = StableUnCLIPImg2ImgPipeline.from_pretrained(diffusion_model_path,
43
- torch_dtype=torch.float16 if fp16 else torch.float32)
44
- self.diffusion_model = diffusion_model.to(device)
45
- else:
46
- self.diffusion_model = None
47
-
48
- model = model.to(device)
49
-
50
- processor = transforms.Compose([
51
- transforms.Resize((image_size, image_size), interpolation=3),
52
- # transforms.Resize(image_size, interpolation=3),
53
- # transforms.CenterCrop(image_size),
54
- transforms.ToTensor(),
55
- transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
56
- ])
57
-
58
- if fp16:
59
- model = model.half()
60
-
61
- shape_latents = torch.Size([1, 4, 96, 96])
62
- self.latents = torch.randn(shape_latents, generator=None, device=device, dtype=torch.float16, layout=torch.strided)
63
-
64
- shape_noise = torch.Size([1, 1024])
65
- self.noise = torch.randn(shape_noise, generator=None, device=device, dtype=torch.float16, layout=torch.strided)
66
-
67
- self.model = model
68
- self.processor = processor
69
- self.device = device
70
- self.fp16 = fp16
71
-
72
- def __len__(self):
73
- return self.model.n_embed
74
-
75
- def encode(self, image_torch):
76
- '''Convert a batch of img to code
77
- Args:
78
- model: The tokenizer model.
79
- img: [b, c, h, w]
80
- '''
81
- if len(image_torch.shape) == 3:
82
- image_torch = image_torch.unsqueeze(0)
83
-
84
- # img = image_torch.to(self.device)
85
- img = image_torch
86
- if self.fp16:
87
- img = img.half()
88
- with torch.no_grad():
89
- id, _ = self.model.get_codebook_indices(img)
90
- return id.view(img.shape[0], -1)
91
-
92
- def decode(self, indices, negative_indices=None, guidance_scale=10, num_inference_steps=20):
93
- image_embeds = self.model.get_codebook_entry(indices)
94
- # image = self.diffusion_model(image_embeds=image_embed,
95
- # noise_level=0,
96
- # num_inference_steps=20,
97
- # latents=self.latents,
98
- # noise=self.noise).images
99
- if negative_indices is not None:
100
- assert indices.shape == negative_indices.shape, 'Negative indices must have the same shape with indices'
101
- negative_image_embeds = self.model.get_codebook_entry(negative_indices)
102
- else:
103
- negative_image_embeds = None
104
-
105
- image = self.diffusion_model(
106
- image_embeds=image_embeds,
107
- negative_image_embeds=negative_image_embeds,
108
- guidance_scale=guidance_scale,
109
- noise_level=0,
110
- num_inference_steps=num_inference_steps,
111
- latents=self.latents,
112
- ).images
113
- return image
114
-
115
-
116
- class SeedLlamaTokenizer(LlamaTokenizer):
117
- def __init__(self,
118
- vocab_file,
119
- unk_token="<unk>",
120
- bos_token="<s>",
121
- eos_token="</s>",
122
- pad_token=None,
123
- sp_model_kwargs: Optional[Dict[str, Any]] = None,
124
- add_bos_token=True,
125
- add_eos_token=False,
126
- clean_up_tokenization_spaces=False,
127
- device='cuda',
128
- fp16=True,
129
- load_diffusion=False,
130
- encoder_url=None,
131
- diffusion_path=None,
132
- **kwargs):
133
- super().__init__(vocab_file, unk_token, bos_token, eos_token, pad_token, sp_model_kwargs, add_bos_token, add_eos_token,
134
- clean_up_tokenization_spaces, **kwargs)
135
- self.device = device
136
- self.fp16 = fp16
137
- self.pad_token = self.unk_token
138
- self.load_diffusion = load_diffusion
139
- self.encoder_url = encoder_url
140
- self.diffusion_path = diffusion_path
141
-
142
- self.load_image_tokenizer()
143
-
144
- def load_image_tokenizer(self):
145
- if not hasattr(self, '_image_tokenizer'):
146
- if self.encoder_url is not None:
147
- model_path = self.encoder_url
148
- else:
149
- assert hasattr(self, 'name_or_path') and os.path.exists(self.name_or_path)
150
- model_path = os.path.join(self.name_or_path, WEIGHTS_NAME)
151
- # diffusion_model_path = os.path.join(self.name_or_path, DIFFUSION_NAME)
152
- # diffusion_model_path = 'stabilityai/stable-diffusion-2-1-unclip'
153
- self._image_tokenizer = ImageTokenizer(model_path=model_path,
154
- diffusion_model_path=self.diffusion_path,
155
- load_diffusion=self.load_diffusion,
156
- device=self.device,
157
- fp16=self.fp16)
158
-
159
- @property
160
- def image_tokenizer(self):
161
- if not hasattr(self, '_image_tokenizer'):
162
- if self.encoder_url is not None:
163
- model_path = self.encoder_url
164
- else:
165
- assert hasattr(self, 'name_or_path') and os.path.exists(self.name_or_path)
166
- model_path = os.path.join(self.name_or_path, WEIGHTS_NAME)
167
- # diffusion_model_path = os.path.join(self.name_or_path, DIFFUSION_NAME)
168
- # diffusion_model_path = 'stabilityai/stable-diffusion-2-1-unclip'
169
- self._image_tokenizer = ImageTokenizer(model_path=model_path,
170
- diffusion_model_path=self.diffusion_path,
171
- load_diffusion=self.load_diffusion,
172
- device=self.device,
173
- fp16=self.fp16)
174
- return self._image_tokenizer
175
-
176
- @property
177
- def num_image_tokens(self):
178
- return 8192 # self.image_tokenizer.num_tokens # allow not load
179
-
180
- def to(self, device):
181
- self.device = device
182
- if hasattr(self, '_image_tokenizer'):
183
- self._image_tokenizer.to(device=device)
184
-
185
- def encode_image(
186
- self,
187
- image_path=None,
188
- image_pil=None,
189
- image_torch=None,
190
- image_size: int = 224,
191
- ):
192
- assert (image_path is None) + (image_pil is None) + (image_torch is None) == 2
193
-
194
- # need_norm_to_1 = False
195
- if image_path is not None:
196
- image_pil = Image.open(image_path).convert('RGB')
197
-
198
- if image_pil is not None:
199
- image_torch = self.image_tokenizer.processor(image_pil)
200
-
201
- image_torch = image_torch.to(self.device)
202
- return self.image_tokenizer.encode(image_torch)
203
-
204
- def decode_image(self, indices, negative_indices=None, guidance_scale=10):
205
- indices = indices.to(self.device)
206
- if negative_indices is not None:
207
- negative_indices = negative_indices.to(self.device)
208
- image = self.image_tokenizer.decode(
209
- indices,
210
- negative_indices=negative_indices,
211
- guidance_scale=guidance_scale,
212
- )
213
- return image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIWaves/SOP_Generation-single/gradio_base.py DELETED
@@ -1,574 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2023 The AIWaves Inc. team.
3
-
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
-
17
- # Emoji comes from this website:
18
- # https://emojipedia.org/
19
- import subprocess
20
- from gradio_config import GradioConfig as gc
21
- import gradio as gr
22
- from typing import List, Tuple, Any
23
- import time
24
- import socket
25
- import psutil
26
- import os
27
- from abc import abstractmethod
28
- import openai
29
-
30
- def test_apikey_connection(api_key=None, model="gpt-3.5-turbo"):
31
- openai.api_key = api_key if api_key is not None else os.environ["API_KEY"]
32
- if "PROXY" in os.environ:
33
- openai.proxy = os.environ["PROXY"]
34
- messages = [{"role": "user", "content": "what's your name?"}]
35
- try:
36
- response = openai.ChatCompletion.create(
37
- model=model,
38
- messages=messages,
39
- )
40
- return True
41
- except:
42
- return False
43
-
44
- def convert2list4agentname(sop):
45
- """
46
- Extract the agent names of all states
47
- return:
48
- only name: [name1, name2, ...]
49
- agent_name: [name1(role1), name2(role2), ...]
50
- """
51
- only_name = []
52
- agent_name = []
53
- roles_to_names = sop.roles_to_names
54
- for state_name,roles_names in roles_to_names.items():
55
- for role,name in roles_names.items():
56
- agent_name.append(f"{name}({role})")
57
- only_name.append(name)
58
- agent_name = list(set(agent_name))
59
- agent_name.sort()
60
- return agent_name, only_name
61
-
62
- def is_port_in_use(port):
63
- """Check if the port is available"""
64
- for conn in psutil.net_connections():
65
- if conn.laddr.port == port:
66
- return True
67
- return False
68
-
69
- def check_port(port):
70
- """Determine available ports"""
71
- if os.path.isfile("PORT.txt"):
72
- port = int(open("PORT.txt","r",encoding='utf-8').readlines()[0])
73
- else:
74
- for i in range(10):
75
- if is_port_in_use(port+i) == False:
76
- port += i
77
- break
78
- with open("PORT.txt", "w") as f:
79
- f.writelines(str(port))
80
- return port
81
-
82
- # Determine some heads
83
- SPECIAL_SIGN = {
84
- "START": "<START>",
85
- "SPLIT": "<SELFDEFINESEP>",
86
- "END": "<ENDSEP>"
87
- }
88
- HOST = "127.0.0.1"
89
- # The starting port number for the search.
90
- PORT = 15000
91
- PORT = check_port(PORT)
92
-
93
- def print_log(message:str):
94
- print(f"[{time.ctime()}]{message}")
95
-
96
- global_dialog = {
97
- "user": [],
98
- "agent": {},
99
- "system": []
100
- }
101
-
102
- class UIHelper:
103
- """Static Class"""
104
-
105
- @classmethod
106
- def wrap_css(cls, content, name) -> str:
107
- """
108
- Description:
109
- Wrap CSS around each output, and return it in HTML format for rendering with Markdown.
110
- Input:
111
- content: Output content
112
- name: Whose output is it
113
- Output:
114
- HTML
115
- """
116
- assert name in gc.OBJECT_INFO, \
117
- f"The current name `{name}` is not registered with an image. The names of the currently registered agents are in `{gc.OBJECT_INFO.keys()}`. Please use `GradioConfig.add_agent()` from `Gradio_Config/gradio_config.py` to bind the name of the new agent."
118
- output = ""
119
- info = gc.OBJECT_INFO[name]
120
- if info["id"] == "USER":
121
- output = gc.BUBBLE_CSS["USER"].format(
122
- info["bubble_color"], # Background-color
123
- info["text_color"], # Color of the agent's name
124
- name, # Agent name
125
- info["text_color"], # Font color
126
- info["font_size"], # Font size
127
- content, # Content
128
- info["head_url"] # URL of the avatar
129
- )
130
- elif info["id"] == "SYSTEM":
131
- output = gc.BUBBLE_CSS["SYSTEM"].format(
132
- info["bubble_color"], # Background-color
133
- info["font_size"], # Font size
134
- info["text_color"], # Font color
135
- name, # Agent name
136
- content # Content
137
- )
138
- elif info["id"] == "AGENT":
139
- output = gc.BUBBLE_CSS["AGENT"].format(
140
- info["head_url"], # URL of the avatar
141
- info["bubble_color"], # Background-color
142
- info["text_color"], # Font color
143
- name, # Agent name
144
- info["text_color"], # Font color
145
- info["font_size"], # Font size
146
- content, # Content
147
- )
148
- else:
149
- assert False, f"Id `{info['id']}` is invalid. The valid id is in ['SYSTEM', 'AGENT', 'USER']"
150
- return output
151
-
152
- @classmethod
153
- def novel_filter(cls, content, agent_name):
154
-
155
- """比如<CONTENT>...</CONTENT>,就应该输出CONTENT:..."""
156
- IS_RECORDER = agent_name.lower() in ["recorder", "summary"]
157
- if IS_RECORDER:
158
- BOLD_FORMAT = """<div style="color: #000000; display:inline">
159
- <b>{}</b>
160
- </div>
161
- <span style="color: black;">
162
- """
163
- else:
164
- BOLD_FORMAT = "<b>{}</b>"
165
- CENTER_FORMAT = """<div style="background-color: #F0F0F0; text-align: center; padding: 5px; color: #000000">
166
- <b>{}</b>
167
- </div>
168
- """
169
- START_FORMAT = "<{}>"
170
- END_FORMAT = "</{}>"
171
- mapping = {
172
- "TARGET": "🎯 Current Target: ",
173
- "NUMBER": "🍖 Required Number: ",
174
- "THOUGHT": "🤔 Overall Thought: ",
175
- "FIRST NAME": "⚪ First Name: ",
176
- "LAST NAME": "⚪ Last Name: ",
177
- "ROLE": "🤠 Character Properties: ",
178
- "RATIONALES": "🤔 Design Rationale: ",
179
- "BACKGROUND": "🚊 Character Background: ",
180
- "ID": "🔴 ID: ",
181
- "TITLE": "🧩 Chapter Title: ",
182
- "ABSTRACT": "🎬 Abstract: ",
183
- "CHARACTER INVOLVED": "☃️ Character Involved: ",
184
- "ADVICE": "💬 Advice:",
185
- "NAME": "📛 Name: ",
186
- "GENDER": "👩‍👩‍👦‍👦 Gender: ",
187
- "AGE": "⏲️ Age: ",
188
- "WORK": "👨‍🔧 Work: ",
189
- "PERSONALITY": "🧲 Character Personality: ",
190
- "SPEECH STYLE": "🗣️ Speaking Style: ",
191
- "RELATION": "🏠 Relation with Others: ",
192
- "WORD COUNT": "🎰 Word Count: ",
193
- "CHARACTER DESIGN": "📈 Character Design: ",
194
- "CHARACTER REQUIRE": "📈 Character Require: ",
195
- "CHARACTER NAME": "📈 Character Naming Analysis: ",
196
- "CHARACTER NOW": "📈 Character Now: ",
197
- "OUTLINE DESIGN": "📈 Outline Design: ",
198
- "OUTLINE REQUIRE": "📈 Outline Require: ",
199
- "OUTLINE NOW": "📈 Outline Now: ",
200
- "SUB TASK": "🎯 Current Sub Task: ",
201
- "CHARACTER ADVICE": "💬 Character Design Advice: ",
202
- "OUTLINE ADVANTAGE": "📈 Outline Advantage: ",
203
- "OUTLINE DISADVANTAGE": "📈 Outline Disadvantage: ",
204
- "OUTLINE ADVICE": "💬 Outline Advice: ",
205
- "NEXT": "➡️ Next Advice: ",
206
- "TOTAL NUMBER": "🔢 Total Number: "
207
- }
208
- for i in range(1, 10):
209
- mapping[f"CHARACTER {i}"] = f"🦄 Character {i}"
210
- mapping[f"SECTION {i}"] = f"🏷️ Chapter {i}"
211
- for key in mapping:
212
- if key in [f"CHARACTER {i}" for i in range(1, 10)] \
213
- or key in [f"SECTION {i}" for i in range(1, 10)] \
214
- :
215
- content = content.replace(
216
- START_FORMAT.format(key), CENTER_FORMAT.format(mapping[key])
217
- )
218
- elif key in ["TOTAL NUMBER"]:
219
- content = content.replace(
220
- START_FORMAT.format(key), CENTER_FORMAT.format(mapping[key]) + """<span style="color: black;">"""
221
- )
222
- content = content.replace(
223
- END_FORMAT.format(key), "</span>"
224
- )
225
- else:
226
- content = content.replace(
227
- START_FORMAT.format(key), BOLD_FORMAT.format(mapping[key])
228
- )
229
-
230
- content = content.replace(
231
- END_FORMAT.format(key), "</span>" if IS_RECORDER else ""
232
- )
233
- return content
234
-
235
- @classmethod
236
- def singleagent_filter(cls, content, agent_name):
237
- return content
238
-
239
- @classmethod
240
- def debate_filter(cls, content, agent_name):
241
- return content
242
-
243
- @classmethod
244
- def code_filter(cls, content, agent_name):
245
- # return content.replace("```python", "<pre><code>").replace("```","</pre></code>")
246
- return content
247
-
248
- @classmethod
249
- def general_filter(cls, content, agent_name):
250
- return content
251
-
252
- @classmethod
253
- def filter(cls, content: str, agent_name: str, ui_name: str):
254
- """
255
- Description:
256
- Make certain modifications to the output content to enhance its aesthetics when content is showed in gradio.
257
- Input:
258
- content: output content
259
- agent_name: Whose output is it
260
- ui_name: What UI is currently launching
261
- Output:
262
- Modified content
263
- """
264
- mapping = {
265
- "SingleAgentUI": cls.singleagent_filter,
266
- "DebateUI": cls.debate_filter,
267
- "NovelUI": cls.novel_filter,
268
- "CodeUI": cls.code_filter,
269
- "GeneralUI": cls.general_filter
270
- }
271
- if ui_name in mapping:
272
- return mapping[ui_name](content, agent_name)
273
- else:
274
- return content
275
-
276
- class Client:
277
- """
278
- For inter-process communication, this is the client.
279
- `gradio_backend.PY` serves as the backend, while `run_gradio` is the frontend.
280
- Communication between the frontend and backend is accomplished using Sockets.
281
- """
282
- # =======================Radio Const String======================
283
- SINGLE_MODE = "Single Mode"
284
- AUTO_MODE = "Auto Mode"
285
- MODE_LABEL = "Select the execution mode"
286
- MODE_INFO = "Single mode refers to when the current agent output ends, it will stop running until you click to continue. Auto mode refers to when you complete the input, all agents will continue to output until the task ends."
287
- # ===============================================================
288
- mode = AUTO_MODE
289
- FIRST_RUN:bool = True
290
- # if last agent is user, then next agent will be executed automatically rather than click button
291
- LAST_USER:bool = False
292
-
293
- receive_server = None
294
- send_server = None
295
- current_node = None
296
- cache = {}
297
-
298
- def __init__(self, host=HOST, port=PORT, bufsize=1024):
299
- assert Client.mode in [Client.SINGLE_MODE, Client.AUTO_MODE]
300
- self.SIGN = SPECIAL_SIGN
301
- self.bufsize = bufsize
302
- assert bufsize > 0
303
- self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
304
- self.client_socket.connect((host, port))
305
- while True:
306
- data = self.client_socket.recv(self.bufsize).decode('utf-8')
307
- if data == "hi":
308
- self.client_socket.send("hello agent".encode('utf-8'))
309
- time.sleep(1)
310
- elif data == "check":
311
- break
312
- print_log("Client: connecting successfully......")
313
-
314
- def start_server(self):
315
- while True:
316
- message = yield
317
- if message == 'exit':
318
- break
319
- self.send_message(message=message)
320
-
321
- def send_message(self, message):
322
- """Send the message to the server."""
323
- if isinstance(message, list) or isinstance(message, dict):
324
- message = str(message)
325
- assert isinstance(message, str)
326
- message = message + self.SIGN["SPLIT"]
327
- self.client_socket.send(message.encode('utf-8'))
328
-
329
- def receive_message(self, end_identifier: str = None, split_identifier: str = SPECIAL_SIGN["SPLIT"]) -> List:
330
- """Receive messages from the server, and it will block the process. Supports receiving long text."""
331
- remaining = ""
332
- while True:
333
- # receive message
334
- dataset = self.client_socket.recv(self.bufsize)
335
- try:
336
- # If decoding fails, it indicates that the current transmission is a long text.
337
- dataset = dataset.decode('utf-8')
338
- except UnicodeDecodeError:
339
- if not isinstance(remaining, bytes):
340
- remaining = remaining.encode('utf-8')
341
- assert isinstance(dataset, bytes)
342
- remaining += dataset
343
- try:
344
- dataset = remaining.decode('utf-8')
345
- remaining = ""
346
- except UnicodeDecodeError:
347
- continue
348
- assert isinstance(remaining, str)
349
- dataset = remaining + dataset
350
- list_dataset = dataset.split(split_identifier)
351
- if len(list_dataset) == 1:
352
- # If there is only one result from the split, it indicates that the current sequence itself has not yet ended.
353
- remaining = list_dataset[0]
354
- continue
355
- else:
356
- remaining = list_dataset[-1]
357
- # Receive successfully
358
- list_dataset = list_dataset[:-1]
359
- return_value = []
360
- for item in list_dataset:
361
- if end_identifier is not None and item == end_identifier:
362
- break
363
- return_value.append(item)
364
- identifier = yield return_value
365
- if identifier is not None:
366
- end_identifier, split_identifier = identifier
367
-
368
- def listening_for_start_(self):
369
- """
370
- When the server starts, the client is automatically launched.
371
- At this point, process synchronization is required,
372
- such as sending client data to the server for rendering,
373
- then the server sending the modified data back to the client,
374
- and simultaneously sending a startup command.
375
- Once the client receives the data, it will start running.
376
- """
377
- Client.receive_server = self.receive_message()
378
- # Waiting for information from the server.
379
- data: list = next(Client.receive_server)
380
- assert len(data) == 1
381
- data = eval(data[0])
382
- assert isinstance(data, dict)
383
- Client.cache.update(data)
384
- # Waiting for start command from the server.
385
- data:list = Client.receive_server.send(None)
386
- assert len(data) == 1
387
- assert data[0] == "<START>"
388
-
389
- class WebUI:
390
- """
391
- The base class for the frontend, which encapsulates some functions for process information synchronization.
392
- When a new frontend needs to be created, you should inherit from this class,
393
- then implement the `construct_ui()` method and set up event listeners.
394
- Finally, execute `run()` to load it.
395
- """
396
-
397
- def receive_message(
398
- self,
399
- end_identifier:str=None,
400
- split_identifier:str=SPECIAL_SIGN["SPLIT"]
401
- )->List:
402
- """This is the same as in Client class."""
403
- yield "hello"
404
- remaining = ""
405
- while True:
406
- dataset = self.client_socket.recv(self.bufsize)
407
- try:
408
- dataset = dataset.decode('utf-8')
409
- except UnicodeDecodeError:
410
- if not isinstance(remaining, bytes):
411
- remaining = remaining.encode('utf-8')
412
- assert isinstance(dataset, bytes)
413
- remaining += dataset
414
- try:
415
- dataset = remaining.decode('utf-8')
416
- remaining = ""
417
- except UnicodeDecodeError:
418
- continue
419
- assert isinstance(remaining, str)
420
- dataset = remaining + dataset
421
- list_dataset = dataset.split(split_identifier)
422
- if len(list_dataset) == 1:
423
- remaining = list_dataset[0]
424
- continue
425
- else:
426
- remaining = list_dataset[-1]
427
- list_dataset = list_dataset[:-1]
428
- return_value = []
429
- for item in list_dataset:
430
- if end_identifier is not None and item == end_identifier:
431
- break
432
- return_value.append(item)
433
- identifier = yield return_value
434
- if identifier is not None:
435
- end_identifier, split_identifier = identifier
436
-
437
- def send_message(self, message:str):
438
- """Send message to client."""
439
- SEP = self.SIGN["SPLIT"]
440
- self.client_socket.send(
441
- (message+SEP).encode("utf-8")
442
- )
443
-
444
- def _connect(self):
445
- # check
446
- if self.server_socket:
447
- self.server_socket.close()
448
- assert not os.path.isfile("PORT.txt")
449
- self.socket_port = check_port(PORT)
450
- # Step1. initialize
451
- self.server_socket = socket.socket(
452
- socket.AF_INET, socket.SOCK_STREAM
453
- )
454
- # Step2. binding ip and port
455
- self.server_socket.bind((self.socket_host, self.socket_port))
456
- # Step3. run client
457
- self._start_client()
458
-
459
- # Step4. listening for connect
460
- self.server_socket.listen(1)
461
-
462
- # Step5. test connection
463
- client_socket, client_address = self.server_socket.accept()
464
- print_log("server: establishing connection......")
465
- self.client_socket = client_socket
466
- while True:
467
- client_socket.send("hi".encode('utf-8'))
468
- time.sleep(1)
469
- data = client_socket.recv(self.bufsize).decode('utf-8')
470
- if data == "hello agent":
471
- client_socket.send("check".encode('utf-8'))
472
- print_log("server: connect successfully")
473
- break
474
- assert os.path.isfile("PORT.txt")
475
- os.remove("PORT.txt")
476
- if self.receive_server:
477
- del self.receive_server
478
- self.receive_server = self.receive_message()
479
- assert next(self.receive_server) == "hello"
480
-
481
- @abstractmethod
482
- def render_and_register_ui(self):
483
- # You need to implement this function.
484
- # The function's purpose is to bind the name of the agent with an image.
485
- # The name of the agent is stored in `self.cache[]`,
486
- # and the function for binding is in the method `add_agents` of the class `GradioConfig` in `Gradio_Config/gradio_config.py``.
487
- # This function will be executed in `self.first_recieve_from_client()`
488
- pass
489
-
490
- def first_recieve_from_client(self, reset_mode:bool=False):
491
- """
492
- This function is used to receive information from the client and is typically executed during the initialization of the class.
493
- If `reset_mode` is False, it will bind the name of the agent with an image.
494
- """
495
- self.FIRST_RECIEVE_FROM_CLIENT = True
496
- data_list:List = self.receive_server.send(None)
497
- assert len(data_list) == 1
498
- data = eval(data_list[0])
499
- assert isinstance(data, dict)
500
- self.cache.update(data)
501
- if not reset_mode:
502
- self.render_and_register_ui()
503
-
504
- def _second_send(self, message:dict):
505
- # Send the modified message.
506
- # It will be executed in `self.send_start_cmd()` automatically.
507
- self.send_message(str(message))
508
-
509
- def _third_send(self):
510
- # Send start command.
511
- # It will be executed in `self.send_start_cmd()` automatically.
512
- self.send_message(self.SIGN['START'])
513
-
514
- def send_start_cmd(self, message:dict={"hello":"hello"}):
515
- # If you have no message to send, you can ignore the args `message`.
516
- assert self.FIRST_RECIEVE_FROM_CLIENT, "Please make sure you have executed `self.first_recieve_from_client()` manually."
517
- self._second_send(message=message)
518
- time.sleep(1)
519
- self._third_send()
520
- self.FIRST_RECIEVE_FROM_CLIENT = False
521
-
522
- def __init__(
523
- self,
524
- client_cmd: list, # ['python','test.py','--a','b','--c','d']
525
- socket_host: str = HOST,
526
- socket_port: int = PORT,
527
- bufsize: int = 1024,
528
- ui_name: str = ""
529
- ):
530
- self.ui_name = ui_name
531
- self.server_socket = None
532
- self.SIGN = SPECIAL_SIGN
533
- self.socket_host = socket_host
534
- self.socket_port = socket_port
535
- self.bufsize = bufsize
536
- self.client_cmd = client_cmd
537
-
538
- self.receive_server = None
539
- self.cache = {}
540
- assert self.bufsize > 0
541
- self._connect()
542
-
543
- def _start_client(self):
544
- print(f"server: executing `{' '.join(self.client_cmd)}` ...")
545
- self.backend = subprocess.Popen(self.client_cmd)
546
-
547
- def _close_client(self):
548
- print(f"server: killing `{' '.join(self.client_cmd)}` ...")
549
- self.backend.terminate()
550
-
551
- def reset(self):
552
- print("server: restarting ...")
553
- self._close_client()
554
- time.sleep(1)
555
- self._connect()
556
-
557
- def render_bubble(self, rendered_data, agent_response, node_name, render_node_name:bool=True):
558
- # Rendered bubbles (HTML format) are used for gradio output.
559
- output = f"**{node_name}**<br>" if render_node_name else ""
560
- for item in agent_response:
561
- for agent_name in item:
562
- content = item[agent_name].replace("\n", "<br>")
563
- content = UIHelper.filter(content, agent_name, self.ui_name)
564
- output = f"{output}<br>{UIHelper.wrap_css(content, agent_name)}"
565
- rendered_data[-1] = [rendered_data[-1][0], output]
566
- return rendered_data
567
-
568
- def run(self,share: bool = True):
569
- self.demo.queue()
570
- self.demo.launch(share=share)
571
-
572
-
573
- if __name__ == '__main__':
574
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIatUIUC/CodeLATS/executors/factory.py DELETED
@@ -1,8 +0,0 @@
1
- from .py_executor import PyExecutor
2
- from .executor_types import Executor
3
-
4
- def executor_factory(lang: str) -> Executor:
5
- if lang == "py" or lang == "python":
6
- return PyExecutor()
7
- else:
8
- raise ValueError(f"Invalid language for executor: {lang}")
 
 
 
 
 
 
 
 
 
spaces/ASJMO/freegpt/g4f/Provider/Providers/Yqcloud.py DELETED
@@ -1,39 +0,0 @@
1
- import os
2
- import time
3
- import requests
4
-
5
- from ...typing import sha256, Dict, get_type_hints
6
- url = 'https://chat9.yqcloud.top/'
7
- model = [
8
- 'gpt-3.5-turbo',
9
- ]
10
- supports_stream = True
11
- needs_auth = False
12
-
13
-
14
- def _create_completion(model: str, messages: list, stream: bool, chatId: str, **kwargs):
15
-
16
- headers = {
17
- 'authority': 'api.aichatos.cloud',
18
- 'origin': 'https://chat9.yqcloud.top',
19
- 'referer': 'https://chat9.yqcloud.top/',
20
- 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
21
- }
22
-
23
- json_data = {
24
- 'prompt': str(messages),
25
- 'userId': f'#/chat/{chatId}',
26
- 'network': True,
27
- 'apikey': '',
28
- 'system': '',
29
- 'withoutContext': False,
30
- }
31
- response = requests.post('https://api.aichatos.cloud/api/generateStream',
32
- headers=headers, json=json_data, stream=True)
33
- for token in response.iter_content(chunk_size=2046):
34
- yield (token.decode('utf-8'))
35
-
36
-
37
- params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \
38
- '(%s)' % ', '.join(
39
- [f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_0_ClothesDetection/mmyolo/configs/yolov5/__init__.py DELETED
File without changes
spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_1_ClothesKeyPoint/mmpose_1_x/configs/fashion_2d_keypoint/topdown_heatmap/deepfashion2/td_hm_res50_4xb64-150e_deepfashion2_short_sleeved_dress_256x192.py DELETED
@@ -1,172 +0,0 @@
1
- _base_ = [
2
- '../../../_base_/default_runtime.py',
3
- '../../../_base_/datasets/deepfashion2.py'
4
- ]
5
-
6
- default_hooks = dict(checkpoint=dict(save_best='PCK', rule='greater'))
7
-
8
- resume = False # 断点恢复
9
- load_from = None # 模型权重加载
10
- train_cfg = dict(by_epoch=True, max_epochs=150, val_interval=10) # 训练轮数,测试间隔
11
- param_scheduler = [
12
- dict( # warmup策略
13
- type='LinearLR',
14
- begin=0,
15
- end=500,
16
- start_factor=0.001,
17
- by_epoch=False),
18
- dict( # scheduler
19
- type='MultiStepLR',
20
- begin=0,
21
- end=150,
22
- milestones=[100, 130],
23
- gamma=0.1,
24
- by_epoch=True)
25
- ]
26
- optim_wrapper = dict(optimizer=dict(type='Adam', lr=0.0005)) # 优化器和学习率
27
- auto_scale_lr = dict(base_batch_size=512) # 根据batch_size自动缩放学习率
28
-
29
- backend_args = dict(backend='local') # 数据加载后端设置,默认从本地硬盘加载
30
- dataset_type = 'DeepFashion2Dataset' # 数据集类名 DeepFashionDataset
31
- data_mode = 'topdown' # 算法结构类型,用于指定标注信息加载策略
32
- data_root = 'data/deepfashion2/' # 数据存放路径
33
- # 定义数据编解码器,用于生成target和对pred进行解码,同时包含了输入图片和输出heatmap尺寸等信息
34
- codec = dict(
35
- type='MSRAHeatmap', input_size=(192, 256), heatmap_size=(48, 64), sigma=2)
36
-
37
- train_pipeline = [
38
- dict(type='LoadImage'),
39
- dict(type='GetBBoxCenterScale'),
40
- dict(type='RandomFlip', direction='horizontal'),
41
- dict(
42
- type='RandomBBoxTransform',
43
- shift_prob=0,
44
- rotate_factor=60,
45
- scale_factor=(0.75, 1.25)),
46
- dict(type='TopdownAffine', input_size=codec['input_size']),
47
- dict(type='GenerateTarget', encoder=codec),
48
- dict(type='PackPoseInputs')
49
- ]
50
- val_pipeline = [ # 测试时数据增强
51
- dict(type='LoadImage', backend_args=backend_args), # 加载图片
52
- dict(type='GetBBoxCenterScale'), # 根据bbox获取center和scale
53
- dict(type='TopdownAffine', input_size=codec['input_size']), # 根据变换矩阵更新目标数据
54
- dict(type='PackPoseInputs') # 对target进行打包用于训练
55
- ]
56
- train_dataloader = dict( # 训练数据加载
57
- batch_size=64, # 批次大小
58
- num_workers=6, # 数据加载进程数
59
- persistent_workers=True, # 在不活跃时维持进程不终止,避免反复启动进程的开销
60
- sampler=dict(type='DefaultSampler', shuffle=True), # 采样策略,打乱数据
61
- dataset=dict(
62
- type=dataset_type, # 数据集类名
63
- data_root=data_root, # 数据集路径
64
- data_mode=data_mode, # 算法类型
65
- ann_file='train/deepfashion2_short_sleeved_dress.json', # 标注文件路径
66
- data_prefix=dict(img='train/image/'), # 图像路径
67
- pipeline=train_pipeline # 数据流水线
68
- ))
69
- val_dataloader = dict(
70
- batch_size=32,
71
- num_workers=6,
72
- persistent_workers=True, # 在不活跃时维持进程不终止,避免反复启动进程的开销
73
- drop_last=False,
74
- sampler=dict(type='DefaultSampler', shuffle=False), # 采样策略,不进行打乱
75
- dataset=dict(
76
- type=dataset_type, # 数据集类名
77
- data_root=data_root, # 数据集路径
78
- data_mode=data_mode, # 算法类型
79
- ann_file='validation/deepfashion2_short_sleeved_dress.json', # 标注文件路径
80
- data_prefix=dict(img='validation/image/'), # 图像路径
81
- test_mode=True, # 测试模式开关
82
- pipeline=val_pipeline # 数据流水线
83
- ))
84
- test_dataloader = val_dataloader # 默认情况下不区分验证集和测试集,用户根据需要来自行定义
85
-
86
- channel_cfg = dict(
87
- num_output_channels=294,
88
- dataset_joints=294,
89
- dataset_channel=[
90
- [
91
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
92
- 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
93
- 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
94
- 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
95
- 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
96
- 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
97
- 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
98
- 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128,
99
- 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
100
- 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,
101
- 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167,
102
- 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180,
103
- 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
104
- 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206,
105
- 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
106
- 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,
107
- 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245,
108
- 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258,
109
- 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271,
110
- 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
111
- 285, 286, 287, 288, 289, 290, 291, 292, 293
112
- ],
113
- ],
114
- inference_channel=[
115
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
116
- 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
117
- 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
118
- 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
119
- 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
120
- 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
121
- 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
122
- 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
123
- 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
124
- 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
125
- 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
126
- 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
127
- 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
128
- 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
129
- 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
130
- 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
131
- 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
132
- 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
133
- 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
134
- 290, 291, 292, 293
135
- ])
136
-
137
- model = dict(
138
- type='TopdownPoseEstimator', # 模型结构决定了算法流程
139
- data_preprocessor=dict( # 数据归一化和通道顺序调整,作为模型的一部分
140
- type='PoseDataPreprocessor',
141
- mean=[123.675, 116.28, 103.53],
142
- std=[58.395, 57.12, 57.375],
143
- bgr_to_rgb=True),
144
- backbone=dict(
145
- type='ResNet',
146
- depth=50,
147
- init_cfg=dict(
148
- type='Pretrained', # 预训练参数,只加载backbone权重用于迁移学习
149
- checkpoint='torchvision://resnet50')),
150
- head=dict( # 模型头部
151
- type='HeatmapHead',
152
- in_channels=2048,
153
- out_channels=channel_cfg['num_output_channels'],
154
- # deconv_out_channels=None,
155
- loss=dict(type='KeypointMSELoss', use_target_weight=True), # 损失函数
156
- decoder=codec), # 解码器,将heatmap解码成坐标值
157
- test_cfg=dict(
158
- flip_test=True, # 开启测试时水平翻转集成
159
- flip_mode='heatmap', # 对heatmap进行翻转
160
- shift_heatmap=True, # 对翻转后的结果进行平移提高精度
161
- ))
162
-
163
- val_evaluator = [
164
- dict(type='PCKAccuracy', thr=0.2),
165
- dict(type='AUC'),
166
- dict(type='EPE'),
167
- ]
168
- test_evaluator = val_evaluator # 默认情况下不区分验证集和测试集,用户根据需要来自行定义
169
-
170
- visualizer = dict(
171
- vis_backends=[dict(type='LocalVisBackend'),
172
- dict(type='WandbVisBackend')])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Abhaykoul/Prompt_generator_for_helpingAI-tti/app.py DELETED
@@ -1,53 +0,0 @@
1
- from transformers import pipeline, set_seed
2
- import gradio as grad, random, re
3
-
4
-
5
- gpt2_pipe = pipeline('text-generation', model='Gustavosta/MagicPrompt-Stable-Diffusion', tokenizer='gpt2')
6
- with open("ideas.txt", "r") as f:
7
- line = f.readlines()
8
-
9
-
10
- def generate(starting_text):
11
- seed = random.randint(100, 1000000)
12
- set_seed(seed)
13
-
14
- if starting_text == "":
15
- starting_text: str = line[random.randrange(0, len(line))].replace("\n", "").lower().capitalize()
16
- starting_text: str = re.sub(r"[,:\-–.!;?_]", '', starting_text)
17
-
18
- response = gpt2_pipe(starting_text, max_length=(len(starting_text) + random.randint(60, 90)), num_return_sequences=4)
19
- response_list = []
20
- for x in response:
21
- resp = x['generated_text'].strip()
22
- if resp != starting_text and len(resp) > (len(starting_text) + 4) and resp.endswith((":", "-", "—")) is False:
23
- response_list.append(resp+'\n')
24
-
25
- response_end = "\n".join(response_list)
26
- response_end = re.sub('[^ ]+\.[^ ]+','', response_end)
27
- response_end = response_end.replace("<", "").replace(">", "")
28
-
29
- if response_end != "":
30
- return response_end
31
-
32
-
33
- txt = grad.Textbox(lines=1, label="Initial Text", placeholder="English Text here")
34
- out = grad.Textbox(lines=4, label="Generated Prompts")
35
-
36
- examples = []
37
- for x in range(8):
38
- examples.append(line[random.randrange(0, len(line))].replace("\n", "").lower().capitalize())
39
-
40
- title = "HelpingAI TTI Prompt Generator"
41
- description = 'This is a of the model series: "MagicPrompt", in this case, aimed at: "HelpingAI-TTI". To use it, simply submit your text or click on one of the examples'
42
-
43
- grad.Interface(fn=generate,
44
- inputs=txt,
45
- outputs=out,
46
- examples=examples,
47
- title=title,
48
- description=description,
49
- article='',
50
- allow_flagging='never',
51
- cache_examples=False,
52
- theme="default").launch(enable_queue=True, debug=True)
53
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AchyuthGamer/OpenGPT/g4f/Provider/HuggingChat.py DELETED
@@ -1,104 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import json
4
-
5
- from aiohttp import ClientSession
6
-
7
- from ..typing import AsyncGenerator
8
- from .base_provider import AsyncGeneratorProvider, format_prompt, get_cookies
9
-
10
-
11
- class HuggingChat(AsyncGeneratorProvider):
12
- url = "https://huggingface.co/chat"
13
- needs_auth = True
14
- working = True
15
- model = "OpenAssistant/oasst-sft-6-llama-30b-xor"
16
-
17
- @classmethod
18
- async def create_async_generator(
19
- cls,
20
- model: str,
21
- messages: list[dict[str, str]],
22
- stream: bool = True,
23
- proxy: str = None,
24
- cookies: dict = None,
25
- **kwargs
26
- ) -> AsyncGenerator:
27
- model = model if model else cls.model
28
- if proxy and "://" not in proxy:
29
- proxy = f"http://{proxy}"
30
- if not cookies:
31
- cookies = get_cookies(".huggingface.co")
32
-
33
- headers = {
34
- 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
35
- }
36
- async with ClientSession(
37
- cookies=cookies,
38
- headers=headers
39
- ) as session:
40
- async with session.post(f"{cls.url}/conversation", proxy=proxy, json={"model": model}) as response:
41
- conversation_id = (await response.json())["conversationId"]
42
-
43
- send = {
44
- "inputs": format_prompt(messages),
45
- "parameters": {
46
- "temperature": 0.2,
47
- "truncate": 1000,
48
- "max_new_tokens": 1024,
49
- "stop": ["</s>"],
50
- "top_p": 0.95,
51
- "repetition_penalty": 1.2,
52
- "top_k": 50,
53
- "return_full_text": False,
54
- **kwargs
55
- },
56
- "stream": stream,
57
- "options": {
58
- "id": "9e9b8bc4-6604-40c6-994e-8eb78fa32e37",
59
- "response_id": "04ce2602-3bea-45e8-8efc-cef00680376a",
60
- "is_retry": False,
61
- "use_cache": False,
62
- "web_search_id": ""
63
- }
64
- }
65
- async with session.post(f"{cls.url}/conversation/{conversation_id}", proxy=proxy, json=send) as response:
66
- if not stream:
67
- data = await response.json()
68
- if "error" in data:
69
- raise RuntimeError(data["error"])
70
- elif isinstance(data, list):
71
- yield data[0]["generated_text"].strip()
72
- else:
73
- raise RuntimeError(f"Response: {data}")
74
- else:
75
- start = "data:"
76
- first = True
77
- async for line in response.content:
78
- line = line.decode("utf-8")
79
- if line.startswith(start):
80
- line = json.loads(line[len(start):-1])
81
- if "token" not in line:
82
- raise RuntimeError(f"Response: {line}")
83
- if not line["token"]["special"]:
84
- if first:
85
- yield line["token"]["text"].lstrip()
86
- first = False
87
- else:
88
- yield line["token"]["text"]
89
-
90
- async with session.delete(f"{cls.url}/conversation/{conversation_id}", proxy=proxy) as response:
91
- response.raise_for_status()
92
-
93
-
94
- @classmethod
95
- @property
96
- def params(cls):
97
- params = [
98
- ("model", "str"),
99
- ("messages", "list[dict[str, str]]"),
100
- ("stream", "bool"),
101
- ("proxy", "str"),
102
- ]
103
- param = ", ".join([": ".join(p) for p in params])
104
- return f"g4f.provider.{cls.__name__} supports: ({param})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgProfile/chatbotopenaihere/README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: Chatbotopenaihere
3
- emoji: 👀
4
- colorFrom: red
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 3.39.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/fixwidthsizer/GetChildrenSizers.js DELETED
@@ -1,17 +0,0 @@
1
- var GetChildrenSizers = function (out) {
2
- if (out === undefined) {
3
- out = [];
4
- }
5
- var children = this.sizerChildren, child;
6
- for (var i = 0, cnt = children.length; i < cnt; i++) {
7
- child = children[i];
8
- if (child === '\n') {
9
- continue;
10
- }
11
- if (child.isRexSizer) {
12
- out.push(child);
13
- }
14
- }
15
- return out;
16
- }
17
- export default GetChildrenSizers;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AkiKagura/Marco-Generation/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: Marco Generation
3
- emoji: 💻
4
- colorFrom: yellow
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 3.8
8
- app_file: app.py
9
- pinned: false
10
- license: creativeml-openrail-m
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Alesmikes/elvire01/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: QnA
3
- emoji: 📈
4
- colorFrom: indigo
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 3.24.1
8
- app_file: app.py
9
- pinned: false
10
- duplicated_from: GenAIDemo/Luludemo
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Altinas/vits-uma-genshin-honkais/text/cleaners.py DELETED
@@ -1,475 +0,0 @@
1
- """ from https://github.com/keithito/tacotron """
2
-
3
- '''
4
- Cleaners are transformations that run over the input text at both training and eval time.
5
-
6
- Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
7
- hyperparameter. Some cleaners are English-specific. You'll typically want to use:
8
- 1. "english_cleaners" for English text
9
- 2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
10
- the Unidecode library (https://pypi.python.org/pypi/Unidecode)
11
- 3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
12
- the symbols in symbols.py to match your data).
13
- '''
14
-
15
- import re
16
- from unidecode import unidecode
17
- import pyopenjtalk
18
- from jamo import h2j, j2hcj
19
- from pypinyin import lazy_pinyin, BOPOMOFO
20
- import jieba, cn2an
21
-
22
-
23
- # This is a list of Korean classifiers preceded by pure Korean numerals.
24
- _korean_classifiers = '군데 권 개 그루 닢 대 두 마리 모 모금 뭇 발 발짝 방 번 벌 보루 살 수 술 시 쌈 움큼 정 짝 채 척 첩 축 켤레 톨 통'
25
-
26
- # Regular expression matching whitespace:
27
- _whitespace_re = re.compile(r'\s+')
28
-
29
- # Regular expression matching Japanese without punctuation marks:
30
- _japanese_characters = re.compile(r'[A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]')
31
-
32
- # Regular expression matching non-Japanese characters or punctuation marks:
33
- _japanese_marks = re.compile(r'[^A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]')
34
-
35
- # List of (regular expression, replacement) pairs for abbreviations:
36
- _abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
37
- ('mrs', 'misess'),
38
- ('mr', 'mister'),
39
- ('dr', 'doctor'),
40
- ('st', 'saint'),
41
- ('co', 'company'),
42
- ('jr', 'junior'),
43
- ('maj', 'major'),
44
- ('gen', 'general'),
45
- ('drs', 'doctors'),
46
- ('rev', 'reverend'),
47
- ('lt', 'lieutenant'),
48
- ('hon', 'honorable'),
49
- ('sgt', 'sergeant'),
50
- ('capt', 'captain'),
51
- ('esq', 'esquire'),
52
- ('ltd', 'limited'),
53
- ('col', 'colonel'),
54
- ('ft', 'fort'),
55
- ]]
56
-
57
- # List of (hangul, hangul divided) pairs:
58
- _hangul_divided = [(re.compile('%s' % x[0]), x[1]) for x in [
59
- ('ㄳ', 'ㄱㅅ'),
60
- ('ㄵ', 'ㄴㅈ'),
61
- ('ㄶ', 'ㄴㅎ'),
62
- ('ㄺ', 'ㄹㄱ'),
63
- ('ㄻ', 'ㄹㅁ'),
64
- ('ㄼ', 'ㄹㅂ'),
65
- ('ㄽ', 'ㄹㅅ'),
66
- ('ㄾ', 'ㄹㅌ'),
67
- ('ㄿ', 'ㄹㅍ'),
68
- ('ㅀ', 'ㄹㅎ'),
69
- ('ㅄ', 'ㅂㅅ'),
70
- ('ㅘ', 'ㅗㅏ'),
71
- ('ㅙ', 'ㅗㅐ'),
72
- ('ㅚ', 'ㅗㅣ'),
73
- ('ㅝ', 'ㅜㅓ'),
74
- ('ㅞ', 'ㅜㅔ'),
75
- ('ㅟ', 'ㅜㅣ'),
76
- ('ㅢ', 'ㅡㅣ'),
77
- ('ㅑ', 'ㅣㅏ'),
78
- ('ㅒ', 'ㅣㅐ'),
79
- ('ㅕ', 'ㅣㅓ'),
80
- ('ㅖ', 'ㅣㅔ'),
81
- ('ㅛ', 'ㅣㅗ'),
82
- ('ㅠ', 'ㅣㅜ')
83
- ]]
84
-
85
- # List of (Latin alphabet, hangul) pairs:
86
- _latin_to_hangul = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
87
- ('a', '에이'),
88
- ('b', '비'),
89
- ('c', '시'),
90
- ('d', '디'),
91
- ('e', '이'),
92
- ('f', '에프'),
93
- ('g', '지'),
94
- ('h', '에이치'),
95
- ('i', '아이'),
96
- ('j', '제이'),
97
- ('k', '케이'),
98
- ('l', '엘'),
99
- ('m', '엠'),
100
- ('n', '엔'),
101
- ('o', '오'),
102
- ('p', '피'),
103
- ('q', '큐'),
104
- ('r', '아르'),
105
- ('s', '에스'),
106
- ('t', '티'),
107
- ('u', '유'),
108
- ('v', '브이'),
109
- ('w', '더블유'),
110
- ('x', '엑스'),
111
- ('y', '와이'),
112
- ('z', '제트')
113
- ]]
114
-
115
- # List of (Latin alphabet, bopomofo) pairs:
116
- _latin_to_bopomofo = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
117
- ('a', 'ㄟˉ'),
118
- ('b', 'ㄅㄧˋ'),
119
- ('c', 'ㄙㄧˉ'),
120
- ('d', 'ㄉㄧˋ'),
121
- ('e', 'ㄧˋ'),
122
- ('f', 'ㄝˊㄈㄨˋ'),
123
- ('g', 'ㄐㄧˋ'),
124
- ('h', 'ㄝˇㄑㄩˋ'),
125
- ('i', 'ㄞˋ'),
126
- ('j', 'ㄐㄟˋ'),
127
- ('k', 'ㄎㄟˋ'),
128
- ('l', 'ㄝˊㄛˋ'),
129
- ('m', 'ㄝˊㄇㄨˋ'),
130
- ('n', 'ㄣˉ'),
131
- ('o', 'ㄡˉ'),
132
- ('p', 'ㄆㄧˉ'),
133
- ('q', 'ㄎㄧㄡˉ'),
134
- ('r', 'ㄚˋ'),
135
- ('s', 'ㄝˊㄙˋ'),
136
- ('t', 'ㄊㄧˋ'),
137
- ('u', 'ㄧㄡˉ'),
138
- ('v', 'ㄨㄧˉ'),
139
- ('w', 'ㄉㄚˋㄅㄨˋㄌㄧㄡˋ'),
140
- ('x', 'ㄝˉㄎㄨˋㄙˋ'),
141
- ('y', 'ㄨㄞˋ'),
142
- ('z', 'ㄗㄟˋ')
143
- ]]
144
-
145
-
146
- # List of (bopomofo, romaji) pairs:
147
- _bopomofo_to_romaji = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [
148
- ('ㄅㄛ', 'p⁼wo'),
149
- ('ㄆㄛ', 'pʰwo'),
150
- ('ㄇㄛ', 'mwo'),
151
- ('ㄈㄛ', 'fwo'),
152
- ('ㄅ', 'p⁼'),
153
- ('ㄆ', 'pʰ'),
154
- ('ㄇ', 'm'),
155
- ('ㄈ', 'f'),
156
- ('ㄉ', 't⁼'),
157
- ('ㄊ', 'tʰ'),
158
- ('ㄋ', 'n'),
159
- ('ㄌ', 'l'),
160
- ('ㄍ', 'k⁼'),
161
- ('ㄎ', 'kʰ'),
162
- ('ㄏ', 'h'),
163
- ('ㄐ', 'ʧ⁼'),
164
- ('ㄑ', 'ʧʰ'),
165
- ('ㄒ', 'ʃ'),
166
- ('ㄓ', 'ʦ`⁼'),
167
- ('ㄔ', 'ʦ`ʰ'),
168
- ('ㄕ', 's`'),
169
- ('ㄖ', 'ɹ`'),
170
- ('ㄗ', 'ʦ⁼'),
171
- ('ㄘ', 'ʦʰ'),
172
- ('ㄙ', 's'),
173
- ('ㄚ', 'a'),
174
- ('ㄛ', 'o'),
175
- ('ㄜ', 'ə'),
176
- ('ㄝ', 'e'),
177
- ('ㄞ', 'ai'),
178
- ('ㄟ', 'ei'),
179
- ('ㄠ', 'au'),
180
- ('ㄡ', 'ou'),
181
- ('ㄧㄢ', 'yeNN'),
182
- ('ㄢ', 'aNN'),
183
- ('ㄧㄣ', 'iNN'),
184
- ('ㄣ', 'əNN'),
185
- ('ㄤ', 'aNg'),
186
- ('ㄧㄥ', 'iNg'),
187
- ('ㄨㄥ', 'uNg'),
188
- ('ㄩㄥ', 'yuNg'),
189
- ('ㄥ', 'əNg'),
190
- ('ㄦ', 'əɻ'),
191
- ('ㄧ', 'i'),
192
- ('ㄨ', 'u'),
193
- ('ㄩ', 'ɥ'),
194
- ('ˉ', '→'),
195
- ('ˊ', '↑'),
196
- ('ˇ', '↓↑'),
197
- ('ˋ', '↓'),
198
- ('˙', ''),
199
- (',', ','),
200
- ('。', '.'),
201
- ('!', '!'),
202
- ('?', '?'),
203
- ('—', '-')
204
- ]]
205
-
206
-
207
- def expand_abbreviations(text):
208
- for regex, replacement in _abbreviations:
209
- text = re.sub(regex, replacement, text)
210
- return text
211
-
212
-
213
- def lowercase(text):
214
- return text.lower()
215
-
216
-
217
- def collapse_whitespace(text):
218
- return re.sub(_whitespace_re, ' ', text)
219
-
220
-
221
- def convert_to_ascii(text):
222
- return unidecode(text)
223
-
224
-
225
- def japanese_to_romaji_with_accent(text):
226
- '''Reference https://r9y9.github.io/ttslearn/latest/notebooks/ch10_Recipe-Tacotron.html'''
227
- sentences = re.split(_japanese_marks, text)
228
- marks = re.findall(_japanese_marks, text)
229
- text = ''
230
- for i, sentence in enumerate(sentences):
231
- if re.match(_japanese_characters, sentence):
232
- if text!='':
233
- text+=' '
234
- labels = pyopenjtalk.extract_fullcontext(sentence)
235
- for n, label in enumerate(labels):
236
- phoneme = re.search(r'\-([^\+]*)\+', label).group(1)
237
- if phoneme not in ['sil','pau']:
238
- text += phoneme.replace('ch','ʧ').replace('sh','ʃ').replace('cl','Q')
239
- else:
240
- continue
241
- n_moras = int(re.search(r'/F:(\d+)_', label).group(1))
242
- a1 = int(re.search(r"/A:(\-?[0-9]+)\+", label).group(1))
243
- a2 = int(re.search(r"\+(\d+)\+", label).group(1))
244
- a3 = int(re.search(r"\+(\d+)/", label).group(1))
245
- if re.search(r'\-([^\+]*)\+', labels[n + 1]).group(1) in ['sil','pau']:
246
- a2_next=-1
247
- else:
248
- a2_next = int(re.search(r"\+(\d+)\+", labels[n + 1]).group(1))
249
- # Accent phrase boundary
250
- if a3 == 1 and a2_next == 1:
251
- text += ' '
252
- # Falling
253
- elif a1 == 0 and a2_next == a2 + 1 and a2 != n_moras:
254
- text += '↓'
255
- # Rising
256
- elif a2 == 1 and a2_next == 2:
257
- text += '↑'
258
- if i<len(marks):
259
- text += unidecode(marks[i]).replace(' ','')
260
- return text
261
-
262
-
263
- def latin_to_hangul(text):
264
- for regex, replacement in _latin_to_hangul:
265
- text = re.sub(regex, replacement, text)
266
- return text
267
-
268
-
269
- def divide_hangul(text):
270
- for regex, replacement in _hangul_divided:
271
- text = re.sub(regex, replacement, text)
272
- return text
273
-
274
-
275
- def hangul_number(num, sino=True):
276
- '''Reference https://github.com/Kyubyong/g2pK'''
277
- num = re.sub(',', '', num)
278
-
279
- if num == '0':
280
- return '영'
281
- if not sino and num == '20':
282
- return '스무'
283
-
284
- digits = '123456789'
285
- names = '일이삼사오육칠팔구'
286
- digit2name = {d: n for d, n in zip(digits, names)}
287
-
288
- modifiers = '한 두 세 네 다섯 여섯 일곱 여덟 아홉'
289
- decimals = '열 스물 서른 마흔 쉰 예순 일흔 여든 아흔'
290
- digit2mod = {d: mod for d, mod in zip(digits, modifiers.split())}
291
- digit2dec = {d: dec for d, dec in zip(digits, decimals.split())}
292
-
293
- spelledout = []
294
- for i, digit in enumerate(num):
295
- i = len(num) - i - 1
296
- if sino:
297
- if i == 0:
298
- name = digit2name.get(digit, '')
299
- elif i == 1:
300
- name = digit2name.get(digit, '') + '십'
301
- name = name.replace('일십', '십')
302
- else:
303
- if i == 0:
304
- name = digit2mod.get(digit, '')
305
- elif i == 1:
306
- name = digit2dec.get(digit, '')
307
- if digit == '0':
308
- if i % 4 == 0:
309
- last_three = spelledout[-min(3, len(spelledout)):]
310
- if ''.join(last_three) == '':
311
- spelledout.append('')
312
- continue
313
- else:
314
- spelledout.append('')
315
- continue
316
- if i == 2:
317
- name = digit2name.get(digit, '') + '백'
318
- name = name.replace('일백', '백')
319
- elif i == 3:
320
- name = digit2name.get(digit, '') + '천'
321
- name = name.replace('일천', '천')
322
- elif i == 4:
323
- name = digit2name.get(digit, '') + '만'
324
- name = name.replace('일만', '만')
325
- elif i == 5:
326
- name = digit2name.get(digit, '') + '십'
327
- name = name.replace('일십', '십')
328
- elif i == 6:
329
- name = digit2name.get(digit, '') + '백'
330
- name = name.replace('일백', '백')
331
- elif i == 7:
332
- name = digit2name.get(digit, '') + '천'
333
- name = name.replace('일천', '천')
334
- elif i == 8:
335
- name = digit2name.get(digit, '') + '억'
336
- elif i == 9:
337
- name = digit2name.get(digit, '') + '십'
338
- elif i == 10:
339
- name = digit2name.get(digit, '') + '백'
340
- elif i == 11:
341
- name = digit2name.get(digit, '') + '천'
342
- elif i == 12:
343
- name = digit2name.get(digit, '') + '조'
344
- elif i == 13:
345
- name = digit2name.get(digit, '') + '십'
346
- elif i == 14:
347
- name = digit2name.get(digit, '') + '백'
348
- elif i == 15:
349
- name = digit2name.get(digit, '') + '천'
350
- spelledout.append(name)
351
- return ''.join(elem for elem in spelledout)
352
-
353
-
354
- def number_to_hangul(text):
355
- '''Reference https://github.com/Kyubyong/g2pK'''
356
- tokens = set(re.findall(r'(\d[\d,]*)([\uac00-\ud71f]+)', text))
357
- for token in tokens:
358
- num, classifier = token
359
- if classifier[:2] in _korean_classifiers or classifier[0] in _korean_classifiers:
360
- spelledout = hangul_number(num, sino=False)
361
- else:
362
- spelledout = hangul_number(num, sino=True)
363
- text = text.replace(f'{num}{classifier}', f'{spelledout}{classifier}')
364
- # digit by digit for remaining digits
365
- digits = '0123456789'
366
- names = '영일이삼사오육칠팔구'
367
- for d, n in zip(digits, names):
368
- text = text.replace(d, n)
369
- return text
370
-
371
-
372
- def number_to_chinese(text):
373
- numbers = re.findall(r'\d+(?:\.?\d+)?', text)
374
- for number in numbers:
375
- text = text.replace(number, cn2an.an2cn(number),1)
376
- return text
377
-
378
-
379
- def chinese_to_bopomofo(text):
380
- text=text.replace('、',',').replace(';',',').replace(':',',')
381
- words=jieba.lcut(text,cut_all=False)
382
- text=''
383
- for word in words:
384
- bopomofos=lazy_pinyin(word,BOPOMOFO)
385
- if not re.search('[\u4e00-\u9fff]',word):
386
- text+=word
387
- continue
388
- for i in range(len(bopomofos)):
389
- if re.match('[\u3105-\u3129]',bopomofos[i][-1]):
390
- bopomofos[i]+='ˉ'
391
- if text!='':
392
- text+=' '
393
- text+=''.join(bopomofos)
394
- return text
395
-
396
-
397
- def latin_to_bopomofo(text):
398
- for regex, replacement in _latin_to_bopomofo:
399
- text = re.sub(regex, replacement, text)
400
- return text
401
-
402
-
403
- def bopomofo_to_romaji(text):
404
- for regex, replacement in _bopomofo_to_romaji:
405
- text = re.sub(regex, replacement, text)
406
- return text
407
-
408
-
409
- def basic_cleaners(text):
410
- '''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
411
- text = lowercase(text)
412
- text = collapse_whitespace(text)
413
- return text
414
-
415
-
416
- def transliteration_cleaners(text):
417
- '''Pipeline for non-English text that transliterates to ASCII.'''
418
- text = convert_to_ascii(text)
419
- text = lowercase(text)
420
- text = collapse_whitespace(text)
421
- return text
422
-
423
-
424
- def japanese_cleaners(text):
425
- text=japanese_to_romaji_with_accent(text)
426
- if re.match('[A-Za-z]',text[-1]):
427
- text += '.'
428
- return text
429
-
430
-
431
- def japanese_cleaners2(text):
432
- return japanese_cleaners(text).replace('ts','ʦ').replace('...','…')
433
-
434
-
435
- def korean_cleaners(text):
436
- '''Pipeline for Korean text'''
437
- text = latin_to_hangul(text)
438
- text = number_to_hangul(text)
439
- text = j2hcj(h2j(text))
440
- text = divide_hangul(text)
441
- if re.match('[\u3131-\u3163]',text[-1]):
442
- text += '.'
443
- return text
444
-
445
-
446
- def chinese_cleaners(text):
447
- '''Pipeline for Chinese text'''
448
- text=number_to_chinese(text)
449
- text=chinese_to_bopomofo(text)
450
- text=latin_to_bopomofo(text)
451
- if re.match('[ˉˊˇˋ˙]',text[-1]):
452
- text += '。'
453
- return text
454
-
455
-
456
- def zh_ja_mixture_cleaners(text):
457
- chinese_texts=re.findall(r'\[ZH\].*?\[ZH\]',text)
458
- japanese_texts=re.findall(r'\[JA\].*?\[JA\]',text)
459
- for chinese_text in chinese_texts:
460
- cleaned_text=number_to_chinese(chinese_text[4:-4])
461
- cleaned_text=chinese_to_bopomofo(cleaned_text)
462
- cleaned_text=latin_to_bopomofo(cleaned_text)
463
- cleaned_text=bopomofo_to_romaji(cleaned_text)
464
- cleaned_text=re.sub('i[aoe]',lambda x:'y'+x.group(0)[1:],cleaned_text)
465
- cleaned_text=re.sub('u[aoəe]',lambda x:'w'+x.group(0)[1:],cleaned_text)
466
- cleaned_text=re.sub('([ʦsɹ]`[⁼ʰ]?)([→↓↑]+)',lambda x:x.group(1)+'ɹ`'+x.group(2),cleaned_text).replace('ɻ','ɹ`')
467
- cleaned_text=re.sub('([ʦs][⁼ʰ]?)([→↓↑]+)',lambda x:x.group(1)+'ɹ'+x.group(2),cleaned_text)
468
- text = text.replace(chinese_text,cleaned_text+' ',1)
469
- for japanese_text in japanese_texts:
470
- cleaned_text=japanese_to_romaji_with_accent(japanese_text[4:-4]).replace('ts','ʦ').replace('u','ɯ').replace('...','…')
471
- text = text.replace(japanese_text,cleaned_text+' ',1)
472
- text=text[:-1]
473
- if re.match('[A-Za-zɯɹəɥ→↓↑]',text[-1]):
474
- text += '.'
475
- return text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ameaou/academic-chatgpt3.1/crazy_functions/test_project/cpp/cppipc/shm.cpp DELETED
@@ -1,103 +0,0 @@
1
-
2
- #include <string>
3
- #include <utility>
4
-
5
- #include "libipc/shm.h"
6
-
7
- #include "libipc/utility/pimpl.h"
8
- #include "libipc/memory/resource.h"
9
-
10
- namespace ipc {
11
- namespace shm {
12
-
13
- class handle::handle_ : public pimpl<handle_> {
14
- public:
15
- shm::id_t id_ = nullptr;
16
- void* m_ = nullptr;
17
-
18
- ipc::string n_;
19
- std::size_t s_ = 0;
20
- };
21
-
22
- handle::handle()
23
- : p_(p_->make()) {
24
- }
25
-
26
- handle::handle(char const * name, std::size_t size, unsigned mode)
27
- : handle() {
28
- acquire(name, size, mode);
29
- }
30
-
31
- handle::handle(handle&& rhs)
32
- : handle() {
33
- swap(rhs);
34
- }
35
-
36
- handle::~handle() {
37
- release();
38
- p_->clear();
39
- }
40
-
41
- void handle::swap(handle& rhs) {
42
- std::swap(p_, rhs.p_);
43
- }
44
-
45
- handle& handle::operator=(handle rhs) {
46
- swap(rhs);
47
- return *this;
48
- }
49
-
50
- bool handle::valid() const noexcept {
51
- return impl(p_)->m_ != nullptr;
52
- }
53
-
54
- std::size_t handle::size() const noexcept {
55
- return impl(p_)->s_;
56
- }
57
-
58
- char const * handle::name() const noexcept {
59
- return impl(p_)->n_.c_str();
60
- }
61
-
62
- std::int32_t handle::ref() const noexcept {
63
- return shm::get_ref(impl(p_)->id_);
64
- }
65
-
66
- void handle::sub_ref() noexcept {
67
- shm::sub_ref(impl(p_)->id_);
68
- }
69
-
70
- bool handle::acquire(char const * name, std::size_t size, unsigned mode) {
71
- release();
72
- impl(p_)->id_ = shm::acquire((impl(p_)->n_ = name).c_str(), size, mode);
73
- impl(p_)->m_ = shm::get_mem(impl(p_)->id_, &(impl(p_)->s_));
74
- return valid();
75
- }
76
-
77
- std::int32_t handle::release() {
78
- if (impl(p_)->id_ == nullptr) return -1;
79
- return shm::release(detach());
80
- }
81
-
82
- void* handle::get() const {
83
- return impl(p_)->m_;
84
- }
85
-
86
- void handle::attach(id_t id) {
87
- if (id == nullptr) return;
88
- release();
89
- impl(p_)->id_ = id;
90
- impl(p_)->m_ = shm::get_mem(impl(p_)->id_, &(impl(p_)->s_));
91
- }
92
-
93
- id_t handle::detach() {
94
- auto old = impl(p_)->id_;
95
- impl(p_)->id_ = nullptr;
96
- impl(p_)->m_ = nullptr;
97
- impl(p_)->s_ = 0;
98
- impl(p_)->n_.clear();
99
- return old;
100
- }
101
-
102
- } // namespace shm
103
- } // namespace ipc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Amon1/ChatGPTForAcadamic/crazy_functions/test_project/cpp/cppipc/prod_cons.h DELETED
@@ -1,433 +0,0 @@
1
- #pragma once
2
-
3
- #include <atomic>
4
- #include <utility>
5
- #include <cstring>
6
- #include <type_traits>
7
- #include <cstdint>
8
-
9
- #include "libipc/def.h"
10
-
11
- #include "libipc/platform/detail.h"
12
- #include "libipc/circ/elem_def.h"
13
- #include "libipc/utility/log.h"
14
- #include "libipc/utility/utility.h"
15
-
16
- namespace ipc {
17
-
18
- ////////////////////////////////////////////////////////////////
19
- /// producer-consumer implementation
20
- ////////////////////////////////////////////////////////////////
21
-
22
- template <typename Flag>
23
- struct prod_cons_impl;
24
-
25
- template <>
26
- struct prod_cons_impl<wr<relat::single, relat::single, trans::unicast>> {
27
-
28
- template <std::size_t DataSize, std::size_t AlignSize>
29
- struct elem_t {
30
- std::aligned_storage_t<DataSize, AlignSize> data_ {};
31
- };
32
-
33
- alignas(cache_line_size) std::atomic<circ::u2_t> rd_; // read index
34
- alignas(cache_line_size) std::atomic<circ::u2_t> wt_; // write index
35
-
36
- constexpr circ::u2_t cursor() const noexcept {
37
- return 0;
38
- }
39
-
40
- template <typename W, typename F, typename E>
41
- bool push(W* /*wrapper*/, F&& f, E* elems) {
42
- auto cur_wt = circ::index_of(wt_.load(std::memory_order_relaxed));
43
- if (cur_wt == circ::index_of(rd_.load(std::memory_order_acquire) - 1)) {
44
- return false; // full
45
- }
46
- std::forward<F>(f)(&(elems[cur_wt].data_));
47
- wt_.fetch_add(1, std::memory_order_release);
48
- return true;
49
- }
50
-
51
- /**
52
- * In single-single-unicast, 'force_push' means 'no reader' or 'the only one reader is dead'.
53
- * So we could just disconnect all connections of receiver, and return false.
54
- */
55
- template <typename W, typename F, typename E>
56
- bool force_push(W* wrapper, F&&, E*) {
57
- wrapper->elems()->disconnect_receiver(~static_cast<circ::cc_t>(0u));
58
- return false;
59
- }
60
-
61
- template <typename W, typename F, typename R, typename E>
62
- bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) {
63
- auto cur_rd = circ::index_of(rd_.load(std::memory_order_relaxed));
64
- if (cur_rd == circ::index_of(wt_.load(std::memory_order_acquire))) {
65
- return false; // empty
66
- }
67
- std::forward<F>(f)(&(elems[cur_rd].data_));
68
- std::forward<R>(out)(true);
69
- rd_.fetch_add(1, std::memory_order_release);
70
- return true;
71
- }
72
- };
73
-
74
- template <>
75
- struct prod_cons_impl<wr<relat::single, relat::multi , trans::unicast>>
76
- : prod_cons_impl<wr<relat::single, relat::single, trans::unicast>> {
77
-
78
- template <typename W, typename F, typename E>
79
- bool force_push(W* wrapper, F&&, E*) {
80
- wrapper->elems()->disconnect_receiver(1);
81
- return false;
82
- }
83
-
84
- template <typename W, typename F, typename R,
85
- template <std::size_t, std::size_t> class E, std::size_t DS, std::size_t AS>
86
- bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E<DS, AS>* elems) {
87
- byte_t buff[DS];
88
- for (unsigned k = 0;;) {
89
- auto cur_rd = rd_.load(std::memory_order_relaxed);
90
- if (circ::index_of(cur_rd) ==
91
- circ::index_of(wt_.load(std::memory_order_acquire))) {
92
- return false; // empty
93
- }
94
- std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff));
95
- if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) {
96
- std::forward<F>(f)(buff);
97
- std::forward<R>(out)(true);
98
- return true;
99
- }
100
- ipc::yield(k);
101
- }
102
- }
103
- };
104
-
105
- template <>
106
- struct prod_cons_impl<wr<relat::multi , relat::multi, trans::unicast>>
107
- : prod_cons_impl<wr<relat::single, relat::multi, trans::unicast>> {
108
-
109
- using flag_t = std::uint64_t;
110
-
111
- template <std::size_t DataSize, std::size_t AlignSize>
112
- struct elem_t {
113
- std::aligned_storage_t<DataSize, AlignSize> data_ {};
114
- std::atomic<flag_t> f_ct_ { 0 }; // commit flag
115
- };
116
-
117
- alignas(cache_line_size) std::atomic<circ::u2_t> ct_; // commit index
118
-
119
- template <typename W, typename F, typename E>
120
- bool push(W* /*wrapper*/, F&& f, E* elems) {
121
- circ::u2_t cur_ct, nxt_ct;
122
- for (unsigned k = 0;;) {
123
- cur_ct = ct_.load(std::memory_order_relaxed);
124
- if (circ::index_of(nxt_ct = cur_ct + 1) ==
125
- circ::index_of(rd_.load(std::memory_order_acquire))) {
126
- return false; // full
127
- }
128
- if (ct_.compare_exchange_weak(cur_ct, nxt_ct, std::memory_order_acq_rel)) {
129
- break;
130
- }
131
- ipc::yield(k);
132
- }
133
- auto* el = elems + circ::index_of(cur_ct);
134
- std::forward<F>(f)(&(el->data_));
135
- // set flag & try update wt
136
- el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
137
- while (1) {
138
- auto cac_ct = el->f_ct_.load(std::memory_order_acquire);
139
- if (cur_ct != wt_.load(std::memory_order_relaxed)) {
140
- return true;
141
- }
142
- if ((~cac_ct) != cur_ct) {
143
- return true;
144
- }
145
- if (!el->f_ct_.compare_exchange_strong(cac_ct, 0, std::memory_order_relaxed)) {
146
- return true;
147
- }
148
- wt_.store(nxt_ct, std::memory_order_release);
149
- cur_ct = nxt_ct;
150
- nxt_ct = cur_ct + 1;
151
- el = elems + circ::index_of(cur_ct);
152
- }
153
- return true;
154
- }
155
-
156
- template <typename W, typename F, typename E>
157
- bool force_push(W* wrapper, F&&, E*) {
158
- wrapper->elems()->disconnect_receiver(1);
159
- return false;
160
- }
161
-
162
- template <typename W, typename F, typename R,
163
- template <std::size_t, std::size_t> class E, std::size_t DS, std::size_t AS>
164
- bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E<DS, AS>* elems) {
165
- byte_t buff[DS];
166
- for (unsigned k = 0;;) {
167
- auto cur_rd = rd_.load(std::memory_order_relaxed);
168
- auto cur_wt = wt_.load(std::memory_order_acquire);
169
- auto id_rd = circ::index_of(cur_rd);
170
- auto id_wt = circ::index_of(cur_wt);
171
- if (id_rd == id_wt) {
172
- auto* el = elems + id_wt;
173
- auto cac_ct = el->f_ct_.load(std::memory_order_acquire);
174
- if ((~cac_ct) != cur_wt) {
175
- return false; // empty
176
- }
177
- if (el->f_ct_.compare_exchange_weak(cac_ct, 0, std::memory_order_relaxed)) {
178
- wt_.store(cur_wt + 1, std::memory_order_release);
179
- }
180
- k = 0;
181
- }
182
- else {
183
- std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff));
184
- if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) {
185
- std::forward<F>(f)(buff);
186
- std::forward<R>(out)(true);
187
- return true;
188
- }
189
- ipc::yield(k);
190
- }
191
- }
192
- }
193
- };
194
-
195
- template <>
196
- struct prod_cons_impl<wr<relat::single, relat::multi, trans::broadcast>> {
197
-
198
- using rc_t = std::uint64_t;
199
-
200
- enum : rc_t {
201
- ep_mask = 0x00000000ffffffffull,
202
- ep_incr = 0x0000000100000000ull
203
- };
204
-
205
- template <std::size_t DataSize, std::size_t AlignSize>
206
- struct elem_t {
207
- std::aligned_storage_t<DataSize, AlignSize> data_ {};
208
- std::atomic<rc_t> rc_ { 0 }; // read-counter
209
- };
210
-
211
- alignas(cache_line_size) std::atomic<circ::u2_t> wt_; // write index
212
- alignas(cache_line_size) rc_t epoch_ { 0 }; // only one writer
213
-
214
- circ::u2_t cursor() const noexcept {
215
- return wt_.load(std::memory_order_acquire);
216
- }
217
-
218
- template <typename W, typename F, typename E>
219
- bool push(W* wrapper, F&& f, E* elems) {
220
- E* el;
221
- for (unsigned k = 0;;) {
222
- circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
223
- if (cc == 0) return false; // no reader
224
- el = elems + circ::index_of(wt_.load(std::memory_order_relaxed));
225
- // check all consumers have finished reading this element
226
- auto cur_rc = el->rc_.load(std::memory_order_acquire);
227
- circ::cc_t rem_cc = cur_rc & ep_mask;
228
- if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch_)) {
229
- return false; // has not finished yet
230
- }
231
- // consider rem_cc to be 0 here
232
- if (el->rc_.compare_exchange_weak(
233
- cur_rc, epoch_ | static_cast<rc_t>(cc), std::memory_order_release)) {
234
- break;
235
- }
236
- ipc::yield(k);
237
- }
238
- std::forward<F>(f)(&(el->data_));
239
- wt_.fetch_add(1, std::memory_order_release);
240
- return true;
241
- }
242
-
243
- template <typename W, typename F, typename E>
244
- bool force_push(W* wrapper, F&& f, E* elems) {
245
- E* el;
246
- epoch_ += ep_incr;
247
- for (unsigned k = 0;;) {
248
- circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
249
- if (cc == 0) return false; // no reader
250
- el = elems + circ::index_of(wt_.load(std::memory_order_relaxed));
251
- // check all consumers have finished reading this element
252
- auto cur_rc = el->rc_.load(std::memory_order_acquire);
253
- circ::cc_t rem_cc = cur_rc & ep_mask;
254
- if (cc & rem_cc) {
255
- ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc);
256
- cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers
257
- if (cc == 0) return false; // no reader
258
- }
259
- // just compare & exchange
260
- if (el->rc_.compare_exchange_weak(
261
- cur_rc, epoch_ | static_cast<rc_t>(cc), std::memory_order_release)) {
262
- break;
263
- }
264
- ipc::yield(k);
265
- }
266
- std::forward<F>(f)(&(el->data_));
267
- wt_.fetch_add(1, std::memory_order_release);
268
- return true;
269
- }
270
-
271
- template <typename W, typename F, typename R, typename E>
272
- bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E* elems) {
273
- if (cur == cursor()) return false; // acquire
274
- auto* el = elems + circ::index_of(cur++);
275
- std::forward<F>(f)(&(el->data_));
276
- for (unsigned k = 0;;) {
277
- auto cur_rc = el->rc_.load(std::memory_order_acquire);
278
- if ((cur_rc & ep_mask) == 0) {
279
- std::forward<R>(out)(true);
280
- return true;
281
- }
282
- auto nxt_rc = cur_rc & ~static_cast<rc_t>(wrapper->connected_id());
283
- if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) {
284
- std::forward<R>(out)((nxt_rc & ep_mask) == 0);
285
- return true;
286
- }
287
- ipc::yield(k);
288
- }
289
- }
290
- };
291
-
292
- template <>
293
- struct prod_cons_impl<wr<relat::multi, relat::multi, trans::broadcast>> {
294
-
295
- using rc_t = std::uint64_t;
296
- using flag_t = std::uint64_t;
297
-
298
- enum : rc_t {
299
- rc_mask = 0x00000000ffffffffull,
300
- ep_mask = 0x00ffffffffffffffull,
301
- ep_incr = 0x0100000000000000ull,
302
- ic_mask = 0xff000000ffffffffull,
303
- ic_incr = 0x0000000100000000ull
304
- };
305
-
306
- template <std::size_t DataSize, std::size_t AlignSize>
307
- struct elem_t {
308
- std::aligned_storage_t<DataSize, AlignSize> data_ {};
309
- std::atomic<rc_t > rc_ { 0 }; // read-counter
310
- std::atomic<flag_t> f_ct_ { 0 }; // commit flag
311
- };
312
-
313
- alignas(cache_line_size) std::atomic<circ::u2_t> ct_; // commit index
314
- alignas(cache_line_size) std::atomic<rc_t> epoch_ { 0 };
315
-
316
- circ::u2_t cursor() const noexcept {
317
- return ct_.load(std::memory_order_acquire);
318
- }
319
-
320
- constexpr static rc_t inc_rc(rc_t rc) noexcept {
321
- return (rc & ic_mask) | ((rc + ic_incr) & ~ic_mask);
322
- }
323
-
324
- constexpr static rc_t inc_mask(rc_t rc) noexcept {
325
- return inc_rc(rc) & ~rc_mask;
326
- }
327
-
328
- template <typename W, typename F, typename E>
329
- bool push(W* wrapper, F&& f, E* elems) {
330
- E* el;
331
- circ::u2_t cur_ct;
332
- rc_t epoch = epoch_.load(std::memory_order_acquire);
333
- for (unsigned k = 0;;) {
334
- circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
335
- if (cc == 0) return false; // no reader
336
- el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed));
337
- // check all consumers have finished reading this element
338
- auto cur_rc = el->rc_.load(std::memory_order_relaxed);
339
- circ::cc_t rem_cc = cur_rc & rc_mask;
340
- if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch)) {
341
- return false; // has not finished yet
342
- }
343
- else if (!rem_cc) {
344
- auto cur_fl = el->f_ct_.load(std::memory_order_acquire);
345
- if ((cur_fl != cur_ct) && cur_fl) {
346
- return false; // full
347
- }
348
- }
349
- // consider rem_cc to be 0 here
350
- if (el->rc_.compare_exchange_weak(
351
- cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast<rc_t>(cc), std::memory_order_relaxed) &&
352
- epoch_.compare_exchange_weak(epoch, epoch, std::memory_order_acq_rel)) {
353
- break;
354
- }
355
- ipc::yield(k);
356
- }
357
- // only one thread/process would touch here at one time
358
- ct_.store(cur_ct + 1, std::memory_order_release);
359
- std::forward<F>(f)(&(el->data_));
360
- // set flag & try update wt
361
- el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
362
- return true;
363
- }
364
-
365
- template <typename W, typename F, typename E>
366
- bool force_push(W* wrapper, F&& f, E* elems) {
367
- E* el;
368
- circ::u2_t cur_ct;
369
- rc_t epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr;
370
- for (unsigned k = 0;;) {
371
- circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
372
- if (cc == 0) return false; // no reader
373
- el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed));
374
- // check all consumers have finished reading this element
375
- auto cur_rc = el->rc_.load(std::memory_order_acquire);
376
- circ::cc_t rem_cc = cur_rc & rc_mask;
377
- if (cc & rem_cc) {
378
- ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc);
379
- cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers
380
- if (cc == 0) return false; // no reader
381
- }
382
- // just compare & exchange
383
- if (el->rc_.compare_exchange_weak(
384
- cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast<rc_t>(cc), std::memory_order_relaxed)) {
385
- if (epoch == epoch_.load(std::memory_order_acquire)) {
386
- break;
387
- }
388
- else if (push(wrapper, std::forward<F>(f), elems)) {
389
- return true;
390
- }
391
- epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr;
392
- }
393
- ipc::yield(k);
394
- }
395
- // only one thread/process would touch here at one time
396
- ct_.store(cur_ct + 1, std::memory_order_release);
397
- std::forward<F>(f)(&(el->data_));
398
- // set flag & try update wt
399
- el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
400
- return true;
401
- }
402
-
403
- template <typename W, typename F, typename R, typename E, std::size_t N>
404
- bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E(& elems)[N]) {
405
- auto* el = elems + circ::index_of(cur);
406
- auto cur_fl = el->f_ct_.load(std::memory_order_acquire);
407
- if (cur_fl != ~static_cast<flag_t>(cur)) {
408
- return false; // empty
409
- }
410
- ++cur;
411
- std::forward<F>(f)(&(el->data_));
412
- for (unsigned k = 0;;) {
413
- auto cur_rc = el->rc_.load(std::memory_order_acquire);
414
- if ((cur_rc & rc_mask) == 0) {
415
- std::forward<R>(out)(true);
416
- el->f_ct_.store(cur + N - 1, std::memory_order_release);
417
- return true;
418
- }
419
- auto nxt_rc = inc_rc(cur_rc) & ~static_cast<rc_t>(wrapper->connected_id());
420
- bool last_one = false;
421
- if ((last_one = (nxt_rc & rc_mask) == 0)) {
422
- el->f_ct_.store(cur + N - 1, std::memory_order_release);
423
- }
424
- if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) {
425
- std::forward<R>(out)(last_one);
426
- return true;
427
- }
428
- ipc::yield(k);
429
- }
430
- }
431
- };
432
-
433
- } // namespace ipc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AndrewMetaBlock/emilyalsentzer-Bio_ClinicalBERT/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: Emilyalsentzer-Bio ClinicalBERT
3
- emoji: 🐢
4
- colorFrom: red
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 3.20.1
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/using-diffusers/stable_diffusion_jax_how_to.md DELETED
@@ -1,251 +0,0 @@
1
- # 🧨 Stable Diffusion in JAX / Flax !
2
-
3
- [[open-in-colab]]
4
-
5
- 🤗 Hugging Face [Diffusers](https://github.com/huggingface/diffusers) supports Flax since version `0.5.1`! This allows for super fast inference on Google TPUs, such as those available in Colab, Kaggle or Google Cloud Platform.
6
-
7
- This notebook shows how to run inference using JAX / Flax. If you want more details about how Stable Diffusion works or want to run it in GPU, please refer to [this notebook](https://huggingface.co/docs/diffusers/stable_diffusion).
8
-
9
- First, make sure you are using a TPU backend. If you are running this notebook in Colab, select `Runtime` in the menu above, then select the option "Change runtime type" and then select `TPU` under the `Hardware accelerator` setting.
10
-
11
- Note that JAX is not exclusive to TPUs, but it shines on that hardware because each TPU server has 8 TPU accelerators working in parallel.
12
-
13
- ## Setup
14
-
15
- First make sure diffusers is installed.
16
-
17
- ```py
18
- # uncomment to install the necessary libraries in Colab
19
- #!pip install jax==0.3.25 jaxlib==0.3.25 flax transformers ftfy
20
- #!pip install diffusers
21
- ```
22
-
23
- ```python
24
- import jax.tools.colab_tpu
25
-
26
- jax.tools.colab_tpu.setup_tpu()
27
- import jax
28
- ```
29
-
30
- ```python
31
- num_devices = jax.device_count()
32
- device_type = jax.devices()[0].device_kind
33
-
34
- print(f"Found {num_devices} JAX devices of type {device_type}.")
35
- assert (
36
- "TPU" in device_type
37
- ), "Available device is not a TPU, please select TPU from Edit > Notebook settings > Hardware accelerator"
38
- ```
39
-
40
- ```python out
41
- Found 8 JAX devices of type Cloud TPU.
42
- ```
43
-
44
- Then we import all the dependencies.
45
-
46
- ```python
47
- import numpy as np
48
- import jax
49
- import jax.numpy as jnp
50
-
51
- from pathlib import Path
52
- from jax import pmap
53
- from flax.jax_utils import replicate
54
- from flax.training.common_utils import shard
55
- from PIL import Image
56
-
57
- from huggingface_hub import notebook_login
58
- from diffusers import FlaxStableDiffusionPipeline
59
- ```
60
-
61
- ## Model Loading
62
-
63
- TPU devices support `bfloat16`, an efficient half-float type. We'll use it for our tests, but you can also use `float32` to use full precision instead.
64
-
65
- ```python
66
- dtype = jnp.bfloat16
67
- ```
68
-
69
- Flax is a functional framework, so models are stateless and parameters are stored outside them. Loading the pre-trained Flax pipeline will return both the pipeline itself and the model weights (or parameters). We are using a `bf16` version of the weights, which leads to type warnings that you can safely ignore.
70
-
71
- ```python
72
- pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
73
- "CompVis/stable-diffusion-v1-4",
74
- revision="bf16",
75
- dtype=dtype,
76
- )
77
- ```
78
-
79
- ## Inference
80
-
81
- Since TPUs usually have 8 devices working in parallel, we'll replicate our prompt as many times as devices we have. Then we'll perform inference on the 8 devices at once, each responsible for generating one image. Thus, we'll get 8 images in the same amount of time it takes for one chip to generate a single one.
82
-
83
- After replicating the prompt, we obtain the tokenized text ids by invoking the `prepare_inputs` function of the pipeline. The length of the tokenized text is set to 77 tokens, as required by the configuration of the underlying CLIP Text model.
84
-
85
- ```python
86
- prompt = "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of field, close up, split lighting, cinematic"
87
- prompt = [prompt] * jax.device_count()
88
- prompt_ids = pipeline.prepare_inputs(prompt)
89
- prompt_ids.shape
90
- ```
91
-
92
- ```python out
93
- (8, 77)
94
- ```
95
-
96
- ### Replication and parallelization
97
-
98
- Model parameters and inputs have to be replicated across the 8 parallel devices we have. The parameters dictionary is replicated using `flax.jax_utils.replicate`, which traverses the dictionary and changes the shape of the weights so they are repeated 8 times. Arrays are replicated using `shard`.
99
-
100
- ```python
101
- p_params = replicate(params)
102
- ```
103
-
104
- ```python
105
- prompt_ids = shard(prompt_ids)
106
- prompt_ids.shape
107
- ```
108
-
109
- ```python out
110
- (8, 1, 77)
111
- ```
112
-
113
- That shape means that each one of the `8` devices will receive as an input a `jnp` array with shape `(1, 77)`. `1` is therefore the batch size per device. In TPUs with sufficient memory, it could be larger than `1` if we wanted to generate multiple images (per chip) at once.
114
-
115
- We are almost ready to generate images! We just need to create a random number generator to pass to the generation function. This is the standard procedure in Flax, which is very serious and opinionated about random numbers – all functions that deal with random numbers are expected to receive a generator. This ensures reproducibility, even when we are training across multiple distributed devices.
116
-
117
- The helper function below uses a seed to initialize a random number generator. As long as we use the same seed, we'll get the exact same results. Feel free to use different seeds when exploring results later in the notebook.
118
-
119
- ```python
120
- def create_key(seed=0):
121
- return jax.random.PRNGKey(seed)
122
- ```
123
-
124
- We obtain a rng and then "split" it 8 times so each device receives a different generator. Therefore, each device will create a different image, and the full process is reproducible.
125
-
126
- ```python
127
- rng = create_key(0)
128
- rng = jax.random.split(rng, jax.device_count())
129
- ```
130
-
131
- JAX code can be compiled to an efficient representation that runs very fast. However, we need to ensure that all inputs have the same shape in subsequent calls; otherwise, JAX will have to recompile the code, and we wouldn't be able to take advantage of the optimized speed.
132
-
133
- The Flax pipeline can compile the code for us if we pass `jit = True` as an argument. It will also ensure that the model runs in parallel in the 8 available devices.
134
-
135
- The first time we run the following cell it will take a long time to compile, but subequent calls (even with different inputs) will be much faster. For example, it took more than a minute to compile in a TPU v2-8 when I tested, but then it takes about **`7s`** for future inference runs.
136
-
137
- ```
138
- %%time
139
- images = pipeline(prompt_ids, p_params, rng, jit=True)[0]
140
- ```
141
-
142
- ```python out
143
- CPU times: user 56.2 s, sys: 42.5 s, total: 1min 38s
144
- Wall time: 1min 29s
145
- ```
146
-
147
- The returned array has shape `(8, 1, 512, 512, 3)`. We reshape it to get rid of the second dimension and obtain 8 images of `512 × 512 × 3` and then convert them to PIL.
148
-
149
- ```python
150
- images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
151
- images = pipeline.numpy_to_pil(images)
152
- ```
153
-
154
- ### Visualization
155
-
156
- Let's create a helper function to display images in a grid.
157
-
158
- ```python
159
- def image_grid(imgs, rows, cols):
160
- w, h = imgs[0].size
161
- grid = Image.new("RGB", size=(cols * w, rows * h))
162
- for i, img in enumerate(imgs):
163
- grid.paste(img, box=(i % cols * w, i // cols * h))
164
- return grid
165
- ```
166
-
167
- ```python
168
- image_grid(images, 2, 4)
169
- ```
170
-
171
- ![img](https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/stable_diffusion_jax_how_to_cell_38_output_0.jpeg)
172
-
173
-
174
- ## Using different prompts
175
-
176
- We don't have to replicate the _same_ prompt in all the devices. We can do whatever we want: generate 2 prompts 4 times each, or even generate 8 different prompts at once. Let's do that!
177
-
178
- First, we'll refactor the input preparation code into a handy function:
179
-
180
- ```python
181
- prompts = [
182
- "Labrador in the style of Hokusai",
183
- "Painting of a squirrel skating in New York",
184
- "HAL-9000 in the style of Van Gogh",
185
- "Times Square under water, with fish and a dolphin swimming around",
186
- "Ancient Roman fresco showing a man working on his laptop",
187
- "Close-up photograph of young black woman against urban background, high quality, bokeh",
188
- "Armchair in the shape of an avocado",
189
- "Clown astronaut in space, with Earth in the background",
190
- ]
191
- ```
192
-
193
- ```python
194
- prompt_ids = pipeline.prepare_inputs(prompts)
195
- prompt_ids = shard(prompt_ids)
196
-
197
- images = pipeline(prompt_ids, p_params, rng, jit=True).images
198
- images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
199
- images = pipeline.numpy_to_pil(images)
200
-
201
- image_grid(images, 2, 4)
202
- ```
203
-
204
- ![img](https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/stable_diffusion_jax_how_to_cell_43_output_0.jpeg)
205
-
206
-
207
- ## How does parallelization work?
208
-
209
- We said before that the `diffusers` Flax pipeline automatically compiles the model and runs it in parallel on all available devices. We'll now briefly look inside that process to show how it works.
210
-
211
- JAX parallelization can be done in multiple ways. The easiest one revolves around using the `jax.pmap` function to achieve single-program, multiple-data (SPMD) parallelization. It means we'll run several copies of the same code, each on different data inputs. More sophisticated approaches are possible, we invite you to go over the [JAX documentation](https://jax.readthedocs.io/en/latest/index.html) and the [`pjit` pages](https://jax.readthedocs.io/en/latest/jax-101/08-pjit.html?highlight=pjit) to explore this topic if you are interested!
212
-
213
- `jax.pmap` does two things for us:
214
- - Compiles (or `jit`s) the code, as if we had invoked `jax.jit()`. This does not happen when we call `pmap`, but the first time the pmapped function is invoked.
215
- - Ensures the compiled code runs in parallel in all the available devices.
216
-
217
- To show how it works we `pmap` the `_generate` method of the pipeline, which is the private method that runs generates images. Please, note that this method may be renamed or removed in future releases of `diffusers`.
218
-
219
- ```python
220
- p_generate = pmap(pipeline._generate)
221
- ```
222
-
223
- After we use `pmap`, the prepared function `p_generate` will conceptually do the following:
224
- * Invoke a copy of the underlying function `pipeline._generate` in each device.
225
- * Send each device a different portion of the input arguments. That's what sharding is used for. In our case, `prompt_ids` has shape `(8, 1, 77, 768)`. This array will be split in `8` and each copy of `_generate` will receive an input with shape `(1, 77, 768)`.
226
-
227
- We can code `_generate` completely ignoring the fact that it will be invoked in parallel. We just care about our batch size (`1` in this example) and the dimensions that make sense for our code, and don't have to change anything to make it work in parallel.
228
-
229
- The same way as when we used the pipeline call, the first time we run the following cell it will take a while, but then it will be much faster.
230
-
231
- ```
232
- %%time
233
- images = p_generate(prompt_ids, p_params, rng)
234
- images = images.block_until_ready()
235
- images.shape
236
- ```
237
-
238
- ```python out
239
- CPU times: user 1min 15s, sys: 18.2 s, total: 1min 34s
240
- Wall time: 1min 15s
241
- ```
242
-
243
- ```python
244
- images.shape
245
- ```
246
-
247
- ```python out
248
- (8, 1, 512, 512, 3)
249
- ```
250
-
251
- We use `block_until_ready()` to correctly measure inference time, because JAX uses asynchronous dispatch and returns control to the Python loop as soon as it can. You don't need to use that in your code; blocking will occur automatically when you want to use the result of a computation that has not yet been materialized.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_segmentation/configs/deeplabv3/deeplabv3_r50-d8_480x480_40k_pascal_context.py DELETED
@@ -1,10 +0,0 @@
1
- _base_ = [
2
- '../_base_/models/deeplabv3_r50-d8.py',
3
- '../_base_/datasets/pascal_context.py', '../_base_/default_runtime.py',
4
- '../_base_/schedules/schedule_40k.py'
5
- ]
6
- model = dict(
7
- decode_head=dict(num_classes=60),
8
- auxiliary_head=dict(num_classes=60),
9
- test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(320, 320)))
10
- optimizer = dict(type='SGD', lr=0.004, momentum=0.9, weight_decay=0.0001)
 
 
 
 
 
 
 
 
 
 
 
spaces/Andy1621/uniformer_image_segmentation/configs/deeplabv3plus/deeplabv3plus_r101-d8_512x512_20k_voc12aug.py DELETED
@@ -1,2 +0,0 @@
1
- _base_ = './deeplabv3plus_r50-d8_512x512_20k_voc12aug.py'
2
- model = dict(pretrained='open-mmlab://resnet101_v1c', backbone=dict(depth=101))
 
 
 
spaces/Artrajz/vits-simple-api/vits-simple-api-installer-latest.sh DELETED
@@ -1,273 +0,0 @@
1
- INSTALL_DIR=/usr/local/vits-simple-api
2
-
3
- RED='\033[0;31m'
4
- GREEN='\033[0;32m'
5
- YELLOW='\033[0;33m'
6
- PLAIN='\033[0m'
7
-
8
- declare -A EN_MESSAGES
9
- declare -A ZH_MESSAGES
10
-
11
- EN_MESSAGES=(
12
- ["ATTEMPT_DOWNLOAD"]="Attempting to download"
13
- ["FROM"]="from"
14
- ["DOWNLOAD_FAIL"]="Failed to download"
15
- ["FROM_ALL_URLS"]="from all provided URLs."
16
- ["DOWNLOADING"]="Downloading..."
17
- ["VERIFYING"]="Verifying..."
18
- ["UNZIPPING"]="Unzipping..."
19
- ["CHOOSE_VERSION"]="Which version of docker-compose.yaml do you want to download?"
20
- ["DOCKER_CPU"]="docker-compose.yaml (CPU version)"
21
- ["DOCKER_GPU"]="docker-compose-gpu.yaml (GPU version)"
22
- ["ENTER_CHOICE"]="Enter your choice (1 or 2): "
23
- ["INVALID_CHOICE"]="Invalid choice. Please enter 1 or 2."
24
- ["DOWNLOAD_CONFIG"]="Downloading configuration file shortly..."
25
- ["PULL_IMAGE"]="Do you want to start pulling the image? Enter 1 for yes or 2 for no"
26
- ["DOWNLOAD_DICT"]="Do you want to download the pyopenjtalk dictionary file? Enter 1 for yes or 2 for no"
27
- ["MUST_DOWNLOAD_JP"]="Japanese model must be downloaded."
28
- ["DOWNLOAD_VITS_CHINESE"]="Do you want to download the bert model for vits_chinese? Enter 1 for yes, 2 for no."
29
- ["MUST_DOWNLOAD_VITS_CHINESE"]="Using vits_chinese requires downloading these models, which will take up about 410MB."
30
- ["DOWNLOAD_BERT_VITS2"]="Do you want to download chinese-roberta-wwm-ext-large? Enter 1 for yes or 2 for no"
31
- ["MUST_DOWNLOAD_BERT_VITS2"]="To use Bert-VITS2, you must download these models, which will take up about 1.63GB."
32
- ["DOWNLOADED"]="File is downloaded correctly."
33
- ["CORRUPTED"]="The file may not have been downloaded, or the download might be incomplete, and it could also be corrupted."
34
- ["INSTALL_COMPLETE"]="The upgrade or installation has been completed."
35
- ["CONFIG_DIR"]="The configuration file directory is"
36
- ["IMPORT_NOTICE"]="If the vits model is not imported, it cannot be used. Import the model in the configuration file directory."
37
- ["RESTART_NOTICE"]="After modifying the configuration file, restart the docker container for the modification to take effect."
38
- ["ISSUE_NOTICE"]="If you have any questions, please put them in the issues."
39
- ["GITHUB_LINK"]="https://github.com/Artrajz/vits-simple-api"
40
- )
41
-
42
- ZH_MESSAGES=(
43
- ["ATTEMPT_DOWNLOAD"]="正在尝试下载"
44
- ["FROM"]="从"
45
- ["DOWNLOAD_FAIL"]="都下载失败"
46
- ["FROM_ALL_URLS"]="从所有提供的URLs"
47
- ["DOWNLOADING"]="正在下载..."
48
- ["VERIFYING"]="正在校验"
49
- ["UNZIPPING"]="正在解压..."
50
- ["CHOOSE_VERSION"]="你想下载哪个版本的docker-compose.yaml?"
51
- ["DOCKER_CPU"]="docker-compose.yaml (CPU版本)"
52
- ["DOCKER_GPU"]="docker-compose-gpu.yaml (GPU版本)"
53
- ["ENTER_CHOICE"]="请输入您的选择 (1 或 2): "
54
- ["INVALID_CHOICE"]="无效选择。 请重新输入 1 或 2。"
55
- ["DOWNLOAD_CONFIG"]="即将下载配置文件..."
56
- ["PULL_IMAGE"]="是否要开始拉取镜像?输入1表示是,2表示否。"
57
- ["DOWNLOAD_DICT"]="是否要下载pyopenjtalk的词典文件?输入1表示是,2表示否。"
58
- ["MUST_DOWNLOAD_JP"]="使用日语模型必须下载该词典文件,将占用大约102MB。"
59
- ["DOWNLOAD_VITS_CHINESE"]="是否要下载vits_chinese的bert模型?输入1表示是,2表示否。"
60
- ["MUST_DOWNLOAD_VITS_CHINESE"]="使用vits_chinese必须下载这些模型,将占用大约410MB。"
61
- ["DOWNLOAD_BERT_VITS2"]="是否要下载chinese-roberta-wwm-ext-large?输入1表示是,2表示否。"
62
- ["MUST_DOWNLOAD_BERT_VITS2"]="使用Bert-VITS2必须下载这些模型,将占用大约1.63GB。"
63
- ["DOWNLOADED"]="文件已正确下载。"
64
- ["CORRUPTED"]="文件可能未下载,或下载不完整,也有可能已损坏。"
65
- ["INSTALL_COMPLETE"]="更新或安装已完成。"
66
- ["CONFIG_DIR"]="配置文件目录是"
67
- ["IMPORT_NOTICE"]="如果vits模型没有被导入,它是无法使用的。请在配置文件目录中导入模型。"
68
- ["RESTART_NOTICE"]="修改配置文件后,请重启docker容器以使修改生效。"
69
- ["ISSUE_NOTICE"]="如果你有任何问题,请在issues中提出,或者加入q群提问。"
70
- ["GITHUB_LINK"]="https://github.com/Artrajz/vits-simple-api"
71
- )
72
-
73
- echo -e "${PLAIN}${GREEN}Choose a language/选择语言: ${PLAIN}"
74
- echo "1. English"
75
- echo "2. 中文"
76
- read -p "Enter your choice (1 or 2): " choice_language
77
-
78
- declare -A MESSAGES
79
- if [ "$choice_language" -eq 1 ]; then
80
- for key in "${!EN_MESSAGES[@]}"; do
81
- MESSAGES["$key"]="${EN_MESSAGES[$key]}"
82
- done
83
- else
84
- for key in "${!ZH_MESSAGES[@]}"; do
85
- MESSAGES["$key"]="${ZH_MESSAGES[$key]}"
86
- done
87
- fi
88
-
89
- mkdir -p $INSTALL_DIR
90
- cd $INSTALL_DIR
91
-
92
- download_with_fallback() {
93
- local filename=$1
94
- shift # Shift arguments to the left to handle URLs
95
-
96
- local success=0
97
- local url
98
- for url in "$@"; do
99
- echo -e "${YELLOW}${MESSAGES["ATTEMPT_DOWNLOAD"]} $filename ${MESSAGES["FROM"]} $url\n${PLAIN}"
100
- if wget -O "$INSTALL_DIR/$filename" "$url"; then
101
- success=1
102
- break
103
- fi
104
- done
105
-
106
- if [ "$success" -ne 1 ]; then
107
- echo -e "${RED} $filename ${MESSAGES["FROM_ALL_URLS"]} ${MESSAGES["DOWNLOAD_FAIL"]}${PLAIN}"
108
- exit 1
109
- fi
110
- }
111
-
112
- version_gt() {
113
- test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"
114
- }
115
-
116
- while true; do
117
- echo -e "${GREEN}${MESSAGES["CHOOSE_VERSION"]}${PLAIN}"
118
- echo -e "1. ${MESSAGES["DOCKER_CPU"]}"
119
- echo -e "2. ${MESSAGES["DOCKER_GPU"]}"
120
- read -p "${MESSAGES["ENTER_CHOICE"]}" choice_gpu
121
- case $choice_gpu in
122
- 1)
123
- echo -e "${MESSAGES["DOWNLOADING"]}"
124
- download_with_fallback docker-compose.yaml \
125
- "https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/docker-compose.yaml" \
126
- "https://ghproxy.com/https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/docker-compose.yaml"
127
- break
128
- ;;
129
- 2)
130
- echo -e "${MESSAGES["DOWNLOADING"]}"
131
- download_with_fallback docker-compose.yaml \
132
- "https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/docker-compose-gpu.yaml" \
133
- "https://ghproxy.com/https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/docker-compose-gpu.yaml"
134
- break
135
- ;;
136
- *)
137
- echo -e "${RED}${MESSAGES["INVALID_CHOICE"]}${PLAIN}"
138
- ;;
139
- esac
140
- done
141
-
142
- if [ "$choice_gpu" -eq 2 ]; then
143
- DOCKER_VERSION=$(docker version --format '{{.Server.Version}}')
144
- MIN_DOCKER_VERSION="19.03"
145
-
146
- if version_gt $MIN_DOCKER_VERSION $DOCKER_VERSION; then
147
- echo -e "${RED}Your Docker version ($DOCKER_VERSION) does not support GPU. You need at least version $MIN_DOCKER_VERSION.${PLAIN}"
148
- exit 1
149
- fi
150
- fi
151
-
152
- if ! command -v docker-compose &>/dev/null; then
153
- echo -e "${RED}docker-compose could not be found.${PLAIN}"
154
- exit 1
155
- fi
156
-
157
- echo -e "${GREEN}${MESSAGES["PULL_IMAGE"]}${PLAIN}"
158
- read -p "${MESSAGES["ENTER_CHOICE"]}" choice_pull
159
-
160
- if [ "$choice_pull" -eq 1 ]; then
161
- docker compose pull
162
- docker compose up -d
163
- fi
164
-
165
- echo -e "${YELLOW}${MESSAGES["DOWNLOAD_CONFIG"]}${PLAIN}"
166
-
167
- if [ ! -f config.py ]; then
168
- download_with_fallback config.py \
169
- "https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/config.py" \
170
- "https://ghproxy.com/https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/config.py"
171
- fi
172
-
173
- if [ ! -f gunicorn_config.py ]; then
174
- download_with_fallback gunicorn_config.py \
175
- "https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/gunicorn_config.py" \
176
- "https://ghproxy.com/https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/gunicorn_config.py"
177
- fi
178
-
179
- download_with_fallback config.example.py \
180
- "https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/config.py" \
181
- "https://ghproxy.com/https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/config.py"
182
-
183
- download_with_fallback gunicorn_config.example.py \
184
- "https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/gunicorn_config.py" \
185
- "https://ghproxy.com/https://raw.githubusercontent.com/Artrajz/vits-simple-api/main/gunicorn_config.py"
186
-
187
- echo -e "${GREEN}${MESSAGES["DOWNLOAD_DICT"]}${PLAIN}"
188
- echo -e "${GREEN}${MESSAGES["MUST_DOWNLOAD_JP"]}${PLAIN}"
189
- read -p "${MESSAGES["ENTER_CHOICE"]}" choice_download_pyopenjtalk
190
-
191
- if [ "$choice_download_pyopenjtalk" -eq 1 ]; then
192
- mkdir -p pyopenjtalk
193
- echo -e "${MESSAGES["DOWNLOADING"]}"
194
- download_with_fallback open_jtalk_dic_utf_8-1.11.tar.gz \
195
- "https://github.com/r9y9/open_jtalk/releases/download/v1.11.1/open_jtalk_dic_utf_8-1.11.tar.gz" \
196
- "https://ghproxy.com/https://github.com/r9y9/open_jtalk/releases/download/v1.11.1/open_jtalk_dic_utf_8-1.11.tar.gz"
197
- echo -e "${MESSAGES["UNZIPPING"]}"
198
- tar -xzvf open_jtalk_dic_utf_8-1.11.tar.gz -C pyopenjtalk/
199
- rm open_jtalk_dic_utf_8-1.11.tar.gz
200
- fi
201
-
202
- echo -e "${GREEN}${MESSAGES["DOWNLOAD_VITS_CHINESE"]}${PLAIN}"
203
- echo -e "${GREEN}${MESSAGES["MUST_DOWNLOAD_VITS_CHINESE"]}${PLAIN}"
204
- read -p "${MESSAGES["ENTER_CHOICE"]}" choice_download_vits_chinese
205
-
206
- if [ "$choice_download_vits_chinese" -eq 1 ]; then
207
- mkdir -p vits/bert
208
-
209
- EXPECTED_MD5="dea78034433141adc8002404aa1b3184"
210
- FILE_PATH="vits/bert/prosody_model.pt"
211
- echo -e "${MESSAGES["VERIFYING"]}$FILE_PATH"
212
- ACTUAL_MD5=$(md5sum $FILE_PATH | awk '{print $1}')
213
-
214
- if [ "$EXPECTED_MD5" == "$ACTUAL_MD5" ]; then
215
- echo "${MESSAGES["DOWNLOADED"]}"
216
- else
217
- echo "${MESSAGES["CORRUPTED"]}"
218
- download_with_fallback vits/bert/prosody_model.pt \
219
- "https://huggingface.co/spaces/maxmax20160403/vits_chinese/resolve/main/bert/prosody_model.pt"
220
- fi
221
-
222
- fi
223
-
224
- echo -e "${GREEN}${MESSAGES["DOWNLOAD_BERT_VITS2"]}${PLAIN}"
225
- echo -e "${GREEN}${MESSAGES["MUST_DOWNLOAD_BERT_VITS2"]}${PLAIN}"
226
- read -p "${MESSAGES["ENTER_CHOICE"]}" choice_download_bert_vits2
227
-
228
- if [ "$choice_download_bert_vits2" -eq 1 ]; then
229
- mkdir -p bert_vits2/bert/chinese-roberta-wwm-ext-large
230
-
231
- EXPECTED_MD5="15d7435868fef1bd4222ff7820149a2a"
232
- FILE_PATH="bert_vits2/bert/chinese-roberta-wwm-ext-large/pytorch_model.bin"
233
- echo -e "${MESSAGES["VERIFYING"]}$FILE_PATH"
234
- ACTUAL_MD5=$(md5sum $FILE_PATH | awk '{print $1}')
235
-
236
- if [ "$EXPECTED_MD5" == "$ACTUAL_MD5" ]; then
237
- echo "${MESSAGES["DOWNLOADED"]}"
238
- else
239
- echo ${MESSAGES["CORRUPTED"]}
240
- download_with_fallback bert_vits2/bert/chinese-roberta-wwm-ext-large/pytorch_model.bin \
241
- "https://huggingface.co/hfl/chinese-roberta-wwm-ext-large/resolve/main/pytorch_model.bin"
242
- fi
243
-
244
- mkdir -p bert_vits2/bert/bert-base-japanese-v3
245
-
246
- EXPECTED_MD5="6d0f8f3503dae04df0711b6175ef0c8e"
247
- FILE_PATH="bert_vits2/bert/bert-base-japanese-v3/pytorch_model.bin"
248
- echo -e "${MESSAGES["VERIFYING"]}$FILE_PATH"
249
- ACTUAL_MD5=$(md5sum $FILE_PATH | awk '{print $1}')
250
-
251
- if [ "$EXPECTED_MD5" == "$ACTUAL_MD5" ]; then
252
- echo "${MESSAGES["DOWNLOADED"]}"
253
- else
254
- echo ${MESSAGES["CORRUPTED"]}
255
- download_with_fallback bert_vits2/bert/bert-base-japanese-v3/pytorch_model.bin \
256
- "https://huggingface.co/cl-tohoku/bert-base-japanese-v3/resolve/main/pytorch_model.bin"
257
- fi
258
-
259
- fi
260
-
261
- if [ "$choice_gpu" -eq 2 ]; then
262
- if ! docker run --gpus all artrajz/vits-simple-api:latest-gpu nvidia-smi &>/dev/null; then
263
- echo -e "${RED}Your Docker does not seem to support GPU or NVIDIA Docker is not installed properly.${PLAIN}"
264
- exit 1
265
- fi
266
- fi
267
-
268
- echo -e "\n${MESSAGES["INSTALL_COMPLETE"]}"
269
- echo -e "${MESSAGES["CONFIG_DIR"]} $(realpath $INSTALL_DIR)"
270
- echo -e "${YELLOW}${MESSAGES["IMPORT_NOTICE"]}${PLAIN}"
271
- echo -e "${YELLOW}${MESSAGES["RESTART_NOTICE"]}${PLAIN}"
272
- echo -e "${MESSAGES["ISSUE_NOTICE"]}"
273
- echo -e "${MESSAGES["GITHUB_LINK"]}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.py DELETED
@@ -1,519 +0,0 @@
1
- """
2
- This module uses ctypes to bind a whole bunch of functions and constants from
3
- SecureTransport. The goal here is to provide the low-level API to
4
- SecureTransport. These are essentially the C-level functions and constants, and
5
- they're pretty gross to work with.
6
-
7
- This code is a bastardised version of the code found in Will Bond's oscrypto
8
- library. An enormous debt is owed to him for blazing this trail for us. For
9
- that reason, this code should be considered to be covered both by urllib3's
10
- license and by oscrypto's:
11
-
12
- Copyright (c) 2015-2016 Will Bond <[email protected]>
13
-
14
- Permission is hereby granted, free of charge, to any person obtaining a
15
- copy of this software and associated documentation files (the "Software"),
16
- to deal in the Software without restriction, including without limitation
17
- the rights to use, copy, modify, merge, publish, distribute, sublicense,
18
- and/or sell copies of the Software, and to permit persons to whom the
19
- Software is furnished to do so, subject to the following conditions:
20
-
21
- The above copyright notice and this permission notice shall be included in
22
- all copies or substantial portions of the Software.
23
-
24
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
30
- DEALINGS IN THE SOFTWARE.
31
- """
32
- from __future__ import absolute_import
33
-
34
- import platform
35
- from ctypes import (
36
- CDLL,
37
- CFUNCTYPE,
38
- POINTER,
39
- c_bool,
40
- c_byte,
41
- c_char_p,
42
- c_int32,
43
- c_long,
44
- c_size_t,
45
- c_uint32,
46
- c_ulong,
47
- c_void_p,
48
- )
49
- from ctypes.util import find_library
50
-
51
- from ...packages.six import raise_from
52
-
53
- if platform.system() != "Darwin":
54
- raise ImportError("Only macOS is supported")
55
-
56
- version = platform.mac_ver()[0]
57
- version_info = tuple(map(int, version.split(".")))
58
- if version_info < (10, 8):
59
- raise OSError(
60
- "Only OS X 10.8 and newer are supported, not %s.%s"
61
- % (version_info[0], version_info[1])
62
- )
63
-
64
-
65
- def load_cdll(name, macos10_16_path):
66
- """Loads a CDLL by name, falling back to known path on 10.16+"""
67
- try:
68
- # Big Sur is technically 11 but we use 10.16 due to the Big Sur
69
- # beta being labeled as 10.16.
70
- if version_info >= (10, 16):
71
- path = macos10_16_path
72
- else:
73
- path = find_library(name)
74
- if not path:
75
- raise OSError # Caught and reraised as 'ImportError'
76
- return CDLL(path, use_errno=True)
77
- except OSError:
78
- raise_from(ImportError("The library %s failed to load" % name), None)
79
-
80
-
81
- Security = load_cdll(
82
- "Security", "/System/Library/Frameworks/Security.framework/Security"
83
- )
84
- CoreFoundation = load_cdll(
85
- "CoreFoundation",
86
- "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",
87
- )
88
-
89
-
90
- Boolean = c_bool
91
- CFIndex = c_long
92
- CFStringEncoding = c_uint32
93
- CFData = c_void_p
94
- CFString = c_void_p
95
- CFArray = c_void_p
96
- CFMutableArray = c_void_p
97
- CFDictionary = c_void_p
98
- CFError = c_void_p
99
- CFType = c_void_p
100
- CFTypeID = c_ulong
101
-
102
- CFTypeRef = POINTER(CFType)
103
- CFAllocatorRef = c_void_p
104
-
105
- OSStatus = c_int32
106
-
107
- CFDataRef = POINTER(CFData)
108
- CFStringRef = POINTER(CFString)
109
- CFArrayRef = POINTER(CFArray)
110
- CFMutableArrayRef = POINTER(CFMutableArray)
111
- CFDictionaryRef = POINTER(CFDictionary)
112
- CFArrayCallBacks = c_void_p
113
- CFDictionaryKeyCallBacks = c_void_p
114
- CFDictionaryValueCallBacks = c_void_p
115
-
116
- SecCertificateRef = POINTER(c_void_p)
117
- SecExternalFormat = c_uint32
118
- SecExternalItemType = c_uint32
119
- SecIdentityRef = POINTER(c_void_p)
120
- SecItemImportExportFlags = c_uint32
121
- SecItemImportExportKeyParameters = c_void_p
122
- SecKeychainRef = POINTER(c_void_p)
123
- SSLProtocol = c_uint32
124
- SSLCipherSuite = c_uint32
125
- SSLContextRef = POINTER(c_void_p)
126
- SecTrustRef = POINTER(c_void_p)
127
- SSLConnectionRef = c_uint32
128
- SecTrustResultType = c_uint32
129
- SecTrustOptionFlags = c_uint32
130
- SSLProtocolSide = c_uint32
131
- SSLConnectionType = c_uint32
132
- SSLSessionOption = c_uint32
133
-
134
-
135
- try:
136
- Security.SecItemImport.argtypes = [
137
- CFDataRef,
138
- CFStringRef,
139
- POINTER(SecExternalFormat),
140
- POINTER(SecExternalItemType),
141
- SecItemImportExportFlags,
142
- POINTER(SecItemImportExportKeyParameters),
143
- SecKeychainRef,
144
- POINTER(CFArrayRef),
145
- ]
146
- Security.SecItemImport.restype = OSStatus
147
-
148
- Security.SecCertificateGetTypeID.argtypes = []
149
- Security.SecCertificateGetTypeID.restype = CFTypeID
150
-
151
- Security.SecIdentityGetTypeID.argtypes = []
152
- Security.SecIdentityGetTypeID.restype = CFTypeID
153
-
154
- Security.SecKeyGetTypeID.argtypes = []
155
- Security.SecKeyGetTypeID.restype = CFTypeID
156
-
157
- Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]
158
- Security.SecCertificateCreateWithData.restype = SecCertificateRef
159
-
160
- Security.SecCertificateCopyData.argtypes = [SecCertificateRef]
161
- Security.SecCertificateCopyData.restype = CFDataRef
162
-
163
- Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]
164
- Security.SecCopyErrorMessageString.restype = CFStringRef
165
-
166
- Security.SecIdentityCreateWithCertificate.argtypes = [
167
- CFTypeRef,
168
- SecCertificateRef,
169
- POINTER(SecIdentityRef),
170
- ]
171
- Security.SecIdentityCreateWithCertificate.restype = OSStatus
172
-
173
- Security.SecKeychainCreate.argtypes = [
174
- c_char_p,
175
- c_uint32,
176
- c_void_p,
177
- Boolean,
178
- c_void_p,
179
- POINTER(SecKeychainRef),
180
- ]
181
- Security.SecKeychainCreate.restype = OSStatus
182
-
183
- Security.SecKeychainDelete.argtypes = [SecKeychainRef]
184
- Security.SecKeychainDelete.restype = OSStatus
185
-
186
- Security.SecPKCS12Import.argtypes = [
187
- CFDataRef,
188
- CFDictionaryRef,
189
- POINTER(CFArrayRef),
190
- ]
191
- Security.SecPKCS12Import.restype = OSStatus
192
-
193
- SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t))
194
- SSLWriteFunc = CFUNCTYPE(
195
- OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t)
196
- )
197
-
198
- Security.SSLSetIOFuncs.argtypes = [SSLContextRef, SSLReadFunc, SSLWriteFunc]
199
- Security.SSLSetIOFuncs.restype = OSStatus
200
-
201
- Security.SSLSetPeerID.argtypes = [SSLContextRef, c_char_p, c_size_t]
202
- Security.SSLSetPeerID.restype = OSStatus
203
-
204
- Security.SSLSetCertificate.argtypes = [SSLContextRef, CFArrayRef]
205
- Security.SSLSetCertificate.restype = OSStatus
206
-
207
- Security.SSLSetCertificateAuthorities.argtypes = [SSLContextRef, CFTypeRef, Boolean]
208
- Security.SSLSetCertificateAuthorities.restype = OSStatus
209
-
210
- Security.SSLSetConnection.argtypes = [SSLContextRef, SSLConnectionRef]
211
- Security.SSLSetConnection.restype = OSStatus
212
-
213
- Security.SSLSetPeerDomainName.argtypes = [SSLContextRef, c_char_p, c_size_t]
214
- Security.SSLSetPeerDomainName.restype = OSStatus
215
-
216
- Security.SSLHandshake.argtypes = [SSLContextRef]
217
- Security.SSLHandshake.restype = OSStatus
218
-
219
- Security.SSLRead.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]
220
- Security.SSLRead.restype = OSStatus
221
-
222
- Security.SSLWrite.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]
223
- Security.SSLWrite.restype = OSStatus
224
-
225
- Security.SSLClose.argtypes = [SSLContextRef]
226
- Security.SSLClose.restype = OSStatus
227
-
228
- Security.SSLGetNumberSupportedCiphers.argtypes = [SSLContextRef, POINTER(c_size_t)]
229
- Security.SSLGetNumberSupportedCiphers.restype = OSStatus
230
-
231
- Security.SSLGetSupportedCiphers.argtypes = [
232
- SSLContextRef,
233
- POINTER(SSLCipherSuite),
234
- POINTER(c_size_t),
235
- ]
236
- Security.SSLGetSupportedCiphers.restype = OSStatus
237
-
238
- Security.SSLSetEnabledCiphers.argtypes = [
239
- SSLContextRef,
240
- POINTER(SSLCipherSuite),
241
- c_size_t,
242
- ]
243
- Security.SSLSetEnabledCiphers.restype = OSStatus
244
-
245
- Security.SSLGetNumberEnabledCiphers.argtype = [SSLContextRef, POINTER(c_size_t)]
246
- Security.SSLGetNumberEnabledCiphers.restype = OSStatus
247
-
248
- Security.SSLGetEnabledCiphers.argtypes = [
249
- SSLContextRef,
250
- POINTER(SSLCipherSuite),
251
- POINTER(c_size_t),
252
- ]
253
- Security.SSLGetEnabledCiphers.restype = OSStatus
254
-
255
- Security.SSLGetNegotiatedCipher.argtypes = [SSLContextRef, POINTER(SSLCipherSuite)]
256
- Security.SSLGetNegotiatedCipher.restype = OSStatus
257
-
258
- Security.SSLGetNegotiatedProtocolVersion.argtypes = [
259
- SSLContextRef,
260
- POINTER(SSLProtocol),
261
- ]
262
- Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus
263
-
264
- Security.SSLCopyPeerTrust.argtypes = [SSLContextRef, POINTER(SecTrustRef)]
265
- Security.SSLCopyPeerTrust.restype = OSStatus
266
-
267
- Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]
268
- Security.SecTrustSetAnchorCertificates.restype = OSStatus
269
-
270
- Security.SecTrustSetAnchorCertificatesOnly.argstypes = [SecTrustRef, Boolean]
271
- Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus
272
-
273
- Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)]
274
- Security.SecTrustEvaluate.restype = OSStatus
275
-
276
- Security.SecTrustGetCertificateCount.argtypes = [SecTrustRef]
277
- Security.SecTrustGetCertificateCount.restype = CFIndex
278
-
279
- Security.SecTrustGetCertificateAtIndex.argtypes = [SecTrustRef, CFIndex]
280
- Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef
281
-
282
- Security.SSLCreateContext.argtypes = [
283
- CFAllocatorRef,
284
- SSLProtocolSide,
285
- SSLConnectionType,
286
- ]
287
- Security.SSLCreateContext.restype = SSLContextRef
288
-
289
- Security.SSLSetSessionOption.argtypes = [SSLContextRef, SSLSessionOption, Boolean]
290
- Security.SSLSetSessionOption.restype = OSStatus
291
-
292
- Security.SSLSetProtocolVersionMin.argtypes = [SSLContextRef, SSLProtocol]
293
- Security.SSLSetProtocolVersionMin.restype = OSStatus
294
-
295
- Security.SSLSetProtocolVersionMax.argtypes = [SSLContextRef, SSLProtocol]
296
- Security.SSLSetProtocolVersionMax.restype = OSStatus
297
-
298
- try:
299
- Security.SSLSetALPNProtocols.argtypes = [SSLContextRef, CFArrayRef]
300
- Security.SSLSetALPNProtocols.restype = OSStatus
301
- except AttributeError:
302
- # Supported only in 10.12+
303
- pass
304
-
305
- Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]
306
- Security.SecCopyErrorMessageString.restype = CFStringRef
307
-
308
- Security.SSLReadFunc = SSLReadFunc
309
- Security.SSLWriteFunc = SSLWriteFunc
310
- Security.SSLContextRef = SSLContextRef
311
- Security.SSLProtocol = SSLProtocol
312
- Security.SSLCipherSuite = SSLCipherSuite
313
- Security.SecIdentityRef = SecIdentityRef
314
- Security.SecKeychainRef = SecKeychainRef
315
- Security.SecTrustRef = SecTrustRef
316
- Security.SecTrustResultType = SecTrustResultType
317
- Security.SecExternalFormat = SecExternalFormat
318
- Security.OSStatus = OSStatus
319
-
320
- Security.kSecImportExportPassphrase = CFStringRef.in_dll(
321
- Security, "kSecImportExportPassphrase"
322
- )
323
- Security.kSecImportItemIdentity = CFStringRef.in_dll(
324
- Security, "kSecImportItemIdentity"
325
- )
326
-
327
- # CoreFoundation time!
328
- CoreFoundation.CFRetain.argtypes = [CFTypeRef]
329
- CoreFoundation.CFRetain.restype = CFTypeRef
330
-
331
- CoreFoundation.CFRelease.argtypes = [CFTypeRef]
332
- CoreFoundation.CFRelease.restype = None
333
-
334
- CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]
335
- CoreFoundation.CFGetTypeID.restype = CFTypeID
336
-
337
- CoreFoundation.CFStringCreateWithCString.argtypes = [
338
- CFAllocatorRef,
339
- c_char_p,
340
- CFStringEncoding,
341
- ]
342
- CoreFoundation.CFStringCreateWithCString.restype = CFStringRef
343
-
344
- CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]
345
- CoreFoundation.CFStringGetCStringPtr.restype = c_char_p
346
-
347
- CoreFoundation.CFStringGetCString.argtypes = [
348
- CFStringRef,
349
- c_char_p,
350
- CFIndex,
351
- CFStringEncoding,
352
- ]
353
- CoreFoundation.CFStringGetCString.restype = c_bool
354
-
355
- CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]
356
- CoreFoundation.CFDataCreate.restype = CFDataRef
357
-
358
- CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]
359
- CoreFoundation.CFDataGetLength.restype = CFIndex
360
-
361
- CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]
362
- CoreFoundation.CFDataGetBytePtr.restype = c_void_p
363
-
364
- CoreFoundation.CFDictionaryCreate.argtypes = [
365
- CFAllocatorRef,
366
- POINTER(CFTypeRef),
367
- POINTER(CFTypeRef),
368
- CFIndex,
369
- CFDictionaryKeyCallBacks,
370
- CFDictionaryValueCallBacks,
371
- ]
372
- CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef
373
-
374
- CoreFoundation.CFDictionaryGetValue.argtypes = [CFDictionaryRef, CFTypeRef]
375
- CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef
376
-
377
- CoreFoundation.CFArrayCreate.argtypes = [
378
- CFAllocatorRef,
379
- POINTER(CFTypeRef),
380
- CFIndex,
381
- CFArrayCallBacks,
382
- ]
383
- CoreFoundation.CFArrayCreate.restype = CFArrayRef
384
-
385
- CoreFoundation.CFArrayCreateMutable.argtypes = [
386
- CFAllocatorRef,
387
- CFIndex,
388
- CFArrayCallBacks,
389
- ]
390
- CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef
391
-
392
- CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]
393
- CoreFoundation.CFArrayAppendValue.restype = None
394
-
395
- CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]
396
- CoreFoundation.CFArrayGetCount.restype = CFIndex
397
-
398
- CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]
399
- CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p
400
-
401
- CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll(
402
- CoreFoundation, "kCFAllocatorDefault"
403
- )
404
- CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(
405
- CoreFoundation, "kCFTypeArrayCallBacks"
406
- )
407
- CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll(
408
- CoreFoundation, "kCFTypeDictionaryKeyCallBacks"
409
- )
410
- CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll(
411
- CoreFoundation, "kCFTypeDictionaryValueCallBacks"
412
- )
413
-
414
- CoreFoundation.CFTypeRef = CFTypeRef
415
- CoreFoundation.CFArrayRef = CFArrayRef
416
- CoreFoundation.CFStringRef = CFStringRef
417
- CoreFoundation.CFDictionaryRef = CFDictionaryRef
418
-
419
- except (AttributeError):
420
- raise ImportError("Error initializing ctypes")
421
-
422
-
423
- class CFConst(object):
424
- """
425
- A class object that acts as essentially a namespace for CoreFoundation
426
- constants.
427
- """
428
-
429
- kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)
430
-
431
-
432
- class SecurityConst(object):
433
- """
434
- A class object that acts as essentially a namespace for Security constants.
435
- """
436
-
437
- kSSLSessionOptionBreakOnServerAuth = 0
438
-
439
- kSSLProtocol2 = 1
440
- kSSLProtocol3 = 2
441
- kTLSProtocol1 = 4
442
- kTLSProtocol11 = 7
443
- kTLSProtocol12 = 8
444
- # SecureTransport does not support TLS 1.3 even if there's a constant for it
445
- kTLSProtocol13 = 10
446
- kTLSProtocolMaxSupported = 999
447
-
448
- kSSLClientSide = 1
449
- kSSLStreamType = 0
450
-
451
- kSecFormatPEMSequence = 10
452
-
453
- kSecTrustResultInvalid = 0
454
- kSecTrustResultProceed = 1
455
- # This gap is present on purpose: this was kSecTrustResultConfirm, which
456
- # is deprecated.
457
- kSecTrustResultDeny = 3
458
- kSecTrustResultUnspecified = 4
459
- kSecTrustResultRecoverableTrustFailure = 5
460
- kSecTrustResultFatalTrustFailure = 6
461
- kSecTrustResultOtherError = 7
462
-
463
- errSSLProtocol = -9800
464
- errSSLWouldBlock = -9803
465
- errSSLClosedGraceful = -9805
466
- errSSLClosedNoNotify = -9816
467
- errSSLClosedAbort = -9806
468
-
469
- errSSLXCertChainInvalid = -9807
470
- errSSLCrypto = -9809
471
- errSSLInternal = -9810
472
- errSSLCertExpired = -9814
473
- errSSLCertNotYetValid = -9815
474
- errSSLUnknownRootCert = -9812
475
- errSSLNoRootCert = -9813
476
- errSSLHostNameMismatch = -9843
477
- errSSLPeerHandshakeFail = -9824
478
- errSSLPeerUserCancelled = -9839
479
- errSSLWeakPeerEphemeralDHKey = -9850
480
- errSSLServerAuthCompleted = -9841
481
- errSSLRecordOverflow = -9847
482
-
483
- errSecVerifyFailed = -67808
484
- errSecNoTrustSettings = -25263
485
- errSecItemNotFound = -25300
486
- errSecInvalidTrustSettings = -25262
487
-
488
- # Cipher suites. We only pick the ones our default cipher string allows.
489
- # Source: https://developer.apple.com/documentation/security/1550981-ssl_cipher_suite_values
490
- TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C
491
- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030
492
- TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B
493
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F
494
- TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9
495
- TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8
496
- TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F
497
- TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E
498
- TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024
499
- TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028
500
- TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A
501
- TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014
502
- TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B
503
- TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039
504
- TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023
505
- TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027
506
- TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009
507
- TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013
508
- TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067
509
- TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033
510
- TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D
511
- TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C
512
- TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D
513
- TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C
514
- TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035
515
- TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F
516
- TLS_AES_128_GCM_SHA256 = 0x1301
517
- TLS_AES_256_GCM_SHA384 = 0x1302
518
- TLS_AES_128_CCM_8_SHA256 = 0x1305
519
- TLS_AES_128_CCM_SHA256 = 0x1304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pkg_resources/_vendor/pyparsing/testing.py DELETED
@@ -1,331 +0,0 @@
1
- # testing.py
2
-
3
- from contextlib import contextmanager
4
- import typing
5
-
6
- from .core import (
7
- ParserElement,
8
- ParseException,
9
- Keyword,
10
- __diag__,
11
- __compat__,
12
- )
13
-
14
-
15
- class pyparsing_test:
16
- """
17
- namespace class for classes useful in writing unit tests
18
- """
19
-
20
- class reset_pyparsing_context:
21
- """
22
- Context manager to be used when writing unit tests that modify pyparsing config values:
23
- - packrat parsing
24
- - bounded recursion parsing
25
- - default whitespace characters.
26
- - default keyword characters
27
- - literal string auto-conversion class
28
- - __diag__ settings
29
-
30
- Example::
31
-
32
- with reset_pyparsing_context():
33
- # test that literals used to construct a grammar are automatically suppressed
34
- ParserElement.inlineLiteralsUsing(Suppress)
35
-
36
- term = Word(alphas) | Word(nums)
37
- group = Group('(' + term[...] + ')')
38
-
39
- # assert that the '()' characters are not included in the parsed tokens
40
- self.assertParseAndCheckList(group, "(abc 123 def)", ['abc', '123', 'def'])
41
-
42
- # after exiting context manager, literals are converted to Literal expressions again
43
- """
44
-
45
- def __init__(self):
46
- self._save_context = {}
47
-
48
- def save(self):
49
- self._save_context["default_whitespace"] = ParserElement.DEFAULT_WHITE_CHARS
50
- self._save_context["default_keyword_chars"] = Keyword.DEFAULT_KEYWORD_CHARS
51
-
52
- self._save_context[
53
- "literal_string_class"
54
- ] = ParserElement._literalStringClass
55
-
56
- self._save_context["verbose_stacktrace"] = ParserElement.verbose_stacktrace
57
-
58
- self._save_context["packrat_enabled"] = ParserElement._packratEnabled
59
- if ParserElement._packratEnabled:
60
- self._save_context[
61
- "packrat_cache_size"
62
- ] = ParserElement.packrat_cache.size
63
- else:
64
- self._save_context["packrat_cache_size"] = None
65
- self._save_context["packrat_parse"] = ParserElement._parse
66
- self._save_context[
67
- "recursion_enabled"
68
- ] = ParserElement._left_recursion_enabled
69
-
70
- self._save_context["__diag__"] = {
71
- name: getattr(__diag__, name) for name in __diag__._all_names
72
- }
73
-
74
- self._save_context["__compat__"] = {
75
- "collect_all_And_tokens": __compat__.collect_all_And_tokens
76
- }
77
-
78
- return self
79
-
80
- def restore(self):
81
- # reset pyparsing global state
82
- if (
83
- ParserElement.DEFAULT_WHITE_CHARS
84
- != self._save_context["default_whitespace"]
85
- ):
86
- ParserElement.set_default_whitespace_chars(
87
- self._save_context["default_whitespace"]
88
- )
89
-
90
- ParserElement.verbose_stacktrace = self._save_context["verbose_stacktrace"]
91
-
92
- Keyword.DEFAULT_KEYWORD_CHARS = self._save_context["default_keyword_chars"]
93
- ParserElement.inlineLiteralsUsing(
94
- self._save_context["literal_string_class"]
95
- )
96
-
97
- for name, value in self._save_context["__diag__"].items():
98
- (__diag__.enable if value else __diag__.disable)(name)
99
-
100
- ParserElement._packratEnabled = False
101
- if self._save_context["packrat_enabled"]:
102
- ParserElement.enable_packrat(self._save_context["packrat_cache_size"])
103
- else:
104
- ParserElement._parse = self._save_context["packrat_parse"]
105
- ParserElement._left_recursion_enabled = self._save_context[
106
- "recursion_enabled"
107
- ]
108
-
109
- __compat__.collect_all_And_tokens = self._save_context["__compat__"]
110
-
111
- return self
112
-
113
- def copy(self):
114
- ret = type(self)()
115
- ret._save_context.update(self._save_context)
116
- return ret
117
-
118
- def __enter__(self):
119
- return self.save()
120
-
121
- def __exit__(self, *args):
122
- self.restore()
123
-
124
- class TestParseResultsAsserts:
125
- """
126
- A mixin class to add parse results assertion methods to normal unittest.TestCase classes.
127
- """
128
-
129
- def assertParseResultsEquals(
130
- self, result, expected_list=None, expected_dict=None, msg=None
131
- ):
132
- """
133
- Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,
134
- and compare any defined results names with an optional ``expected_dict``.
135
- """
136
- if expected_list is not None:
137
- self.assertEqual(expected_list, result.as_list(), msg=msg)
138
- if expected_dict is not None:
139
- self.assertEqual(expected_dict, result.as_dict(), msg=msg)
140
-
141
- def assertParseAndCheckList(
142
- self, expr, test_string, expected_list, msg=None, verbose=True
143
- ):
144
- """
145
- Convenience wrapper assert to test a parser element and input string, and assert that
146
- the resulting ``ParseResults.asList()`` is equal to the ``expected_list``.
147
- """
148
- result = expr.parse_string(test_string, parse_all=True)
149
- if verbose:
150
- print(result.dump())
151
- else:
152
- print(result.as_list())
153
- self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)
154
-
155
- def assertParseAndCheckDict(
156
- self, expr, test_string, expected_dict, msg=None, verbose=True
157
- ):
158
- """
159
- Convenience wrapper assert to test a parser element and input string, and assert that
160
- the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``.
161
- """
162
- result = expr.parse_string(test_string, parseAll=True)
163
- if verbose:
164
- print(result.dump())
165
- else:
166
- print(result.as_list())
167
- self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)
168
-
169
- def assertRunTestResults(
170
- self, run_tests_report, expected_parse_results=None, msg=None
171
- ):
172
- """
173
- Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of
174
- list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped
175
- with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.
176
- Finally, asserts that the overall ``runTests()`` success value is ``True``.
177
-
178
- :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests
179
- :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]
180
- """
181
- run_test_success, run_test_results = run_tests_report
182
-
183
- if expected_parse_results is not None:
184
- merged = [
185
- (*rpt, expected)
186
- for rpt, expected in zip(run_test_results, expected_parse_results)
187
- ]
188
- for test_string, result, expected in merged:
189
- # expected should be a tuple containing a list and/or a dict or an exception,
190
- # and optional failure message string
191
- # an empty tuple will skip any result validation
192
- fail_msg = next(
193
- (exp for exp in expected if isinstance(exp, str)), None
194
- )
195
- expected_exception = next(
196
- (
197
- exp
198
- for exp in expected
199
- if isinstance(exp, type) and issubclass(exp, Exception)
200
- ),
201
- None,
202
- )
203
- if expected_exception is not None:
204
- with self.assertRaises(
205
- expected_exception=expected_exception, msg=fail_msg or msg
206
- ):
207
- if isinstance(result, Exception):
208
- raise result
209
- else:
210
- expected_list = next(
211
- (exp for exp in expected if isinstance(exp, list)), None
212
- )
213
- expected_dict = next(
214
- (exp for exp in expected if isinstance(exp, dict)), None
215
- )
216
- if (expected_list, expected_dict) != (None, None):
217
- self.assertParseResultsEquals(
218
- result,
219
- expected_list=expected_list,
220
- expected_dict=expected_dict,
221
- msg=fail_msg or msg,
222
- )
223
- else:
224
- # warning here maybe?
225
- print("no validation for {!r}".format(test_string))
226
-
227
- # do this last, in case some specific test results can be reported instead
228
- self.assertTrue(
229
- run_test_success, msg=msg if msg is not None else "failed runTests"
230
- )
231
-
232
- @contextmanager
233
- def assertRaisesParseException(self, exc_type=ParseException, msg=None):
234
- with self.assertRaises(exc_type, msg=msg):
235
- yield
236
-
237
- @staticmethod
238
- def with_line_numbers(
239
- s: str,
240
- start_line: typing.Optional[int] = None,
241
- end_line: typing.Optional[int] = None,
242
- expand_tabs: bool = True,
243
- eol_mark: str = "|",
244
- mark_spaces: typing.Optional[str] = None,
245
- mark_control: typing.Optional[str] = None,
246
- ) -> str:
247
- """
248
- Helpful method for debugging a parser - prints a string with line and column numbers.
249
- (Line and column numbers are 1-based.)
250
-
251
- :param s: tuple(bool, str - string to be printed with line and column numbers
252
- :param start_line: int - (optional) starting line number in s to print (default=1)
253
- :param end_line: int - (optional) ending line number in s to print (default=len(s))
254
- :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default
255
- :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default="|")
256
- :param mark_spaces: str - (optional) special character to display in place of spaces
257
- :param mark_control: str - (optional) convert non-printing control characters to a placeholding
258
- character; valid values:
259
- - "unicode" - replaces control chars with Unicode symbols, such as "␍" and "␊"
260
- - any single character string - replace control characters with given string
261
- - None (default) - string is displayed as-is
262
-
263
- :return: str - input string with leading line numbers and column number headers
264
- """
265
- if expand_tabs:
266
- s = s.expandtabs()
267
- if mark_control is not None:
268
- if mark_control == "unicode":
269
- tbl = str.maketrans(
270
- {c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))}
271
- | {127: 0x2421}
272
- )
273
- eol_mark = ""
274
- else:
275
- tbl = str.maketrans(
276
- {c: mark_control for c in list(range(0, 32)) + [127]}
277
- )
278
- s = s.translate(tbl)
279
- if mark_spaces is not None and mark_spaces != " ":
280
- if mark_spaces == "unicode":
281
- tbl = str.maketrans({9: 0x2409, 32: 0x2423})
282
- s = s.translate(tbl)
283
- else:
284
- s = s.replace(" ", mark_spaces)
285
- if start_line is None:
286
- start_line = 1
287
- if end_line is None:
288
- end_line = len(s)
289
- end_line = min(end_line, len(s))
290
- start_line = min(max(1, start_line), end_line)
291
-
292
- if mark_control != "unicode":
293
- s_lines = s.splitlines()[start_line - 1 : end_line]
294
- else:
295
- s_lines = [line + "␊" for line in s.split("␊")[start_line - 1 : end_line]]
296
- if not s_lines:
297
- return ""
298
-
299
- lineno_width = len(str(end_line))
300
- max_line_len = max(len(line) for line in s_lines)
301
- lead = " " * (lineno_width + 1)
302
- if max_line_len >= 99:
303
- header0 = (
304
- lead
305
- + "".join(
306
- "{}{}".format(" " * 99, (i + 1) % 100)
307
- for i in range(max(max_line_len // 100, 1))
308
- )
309
- + "\n"
310
- )
311
- else:
312
- header0 = ""
313
- header1 = (
314
- header0
315
- + lead
316
- + "".join(
317
- " {}".format((i + 1) % 10)
318
- for i in range(-(-max_line_len // 10))
319
- )
320
- + "\n"
321
- )
322
- header2 = lead + "1234567890" * (-(-max_line_len // 10)) + "\n"
323
- return (
324
- header1
325
- + header2
326
- + "\n".join(
327
- "{:{}d}:{}{}".format(i, lineno_width, line, eol_mark)
328
- for i, line in enumerate(s_lines, start=start_line)
329
- )
330
- + "\n"
331
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Audio-AGI/AudioSep/models/CLAP/open_clip/utils.py DELETED
@@ -1,361 +0,0 @@
1
- import numpy as np
2
- import torch
3
- from torch import nn as nn
4
- from torchvision.ops.misc import FrozenBatchNorm2d
5
- import logging
6
- import h5py
7
- from tqdm import tqdm
8
- import random
9
- import json
10
- import os
11
- import pathlib
12
-
13
- # TODO: (yusong) this not a good place to store those information and does not scale. Need to be fixed later.
14
- dataset_split = {
15
- "audiocaps": ["train", "valid", "test"],
16
- "audioset": ["balanced_train", "unbalanced_train", "eval"],
17
- "BBCSoundEffects": ["train", "test"],
18
- "Clotho": ["train", "test", "valid"],
19
- "free_to_use_sounds": ["train", "test"],
20
- "paramount_motion": ["train", "test"],
21
- "sonniss_game_effects": ["train", "test"],
22
- "wesoundeffects": ["train", "test"],
23
- "MACS": ["train", "test"],
24
- "freesound": ["train", "test"],
25
- "FSD50K": ["train", "test", "valid"],
26
- "fsd50k_class_label": ["train", "test", "valid"],
27
- "esc50": ["train", "test"],
28
- "audiostock": ["train", "test"],
29
- "freesound_no_overlap_noesc50": ["train", "test"],
30
- "epidemic_sound_effects": ["train", "test"],
31
- "VGGSound": ["train", "test"],
32
- "urbansound8k_class_label": ["train", "test"],
33
- "audioset_t5": ["balanced_train", "unbalanced_train", "eval"],
34
- "epidemic_sound_effects_t5": ["train", "test"],
35
- "WavText5K": ["train", "test"],
36
- "esc50_no_overlap": ["train", "test"],
37
- "usd8k_no_overlap": ["train", "test"],
38
- "fsd50k_200_class_label": ["train", "test", "valid"],
39
- }
40
-
41
-
42
- def freeze_batch_norm_2d(module, module_match={}, name=""):
43
- """
44
- Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
45
- itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and
46
- returned. Otherwise, the module is walked recursively and submodules are converted in place.
47
-
48
- Args:
49
- module (torch.nn.Module): Any PyTorch module.
50
- module_match (dict): Dictionary of full module names to freeze (all if empty)
51
- name (str): Full module name (prefix)
52
-
53
- Returns:
54
- torch.nn.Module: Resulting module
55
-
56
- Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762
57
- """
58
- res = module
59
- is_match = True
60
- if module_match:
61
- is_match = name in module_match
62
- if is_match and isinstance(
63
- module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)
64
- ):
65
- res = FrozenBatchNorm2d(module.num_features)
66
- res.num_features = module.num_features
67
- res.affine = module.affine
68
- if module.affine:
69
- res.weight.data = module.weight.data.clone().detach()
70
- res.bias.data = module.bias.data.clone().detach()
71
- res.running_mean.data = module.running_mean.data
72
- res.running_var.data = module.running_var.data
73
- res.eps = module.eps
74
- else:
75
- for child_name, child in module.named_children():
76
- full_child_name = ".".join([name, child_name]) if name else child_name
77
- new_child = freeze_batch_norm_2d(child, module_match, full_child_name)
78
- if new_child is not child:
79
- res.add_module(child_name, new_child)
80
- return res
81
-
82
-
83
- def exist(dataset_name, dataset_type):
84
- """
85
- Check if dataset exists
86
- """
87
- if dataset_type in dataset_split[dataset_name]:
88
- return True
89
- else:
90
- return False
91
-
92
-
93
- def get_tar_path_from_dataset_name(
94
- dataset_names, dataset_types, islocal, dataset_path, proportion=1, full_dataset=None
95
- ):
96
- """
97
- Get tar path from dataset name and type
98
- """
99
- output = []
100
- for n in dataset_names:
101
- if full_dataset is not None and n in full_dataset:
102
- current_dataset_types = dataset_split[n]
103
- else:
104
- current_dataset_types = dataset_types
105
- for s in current_dataset_types:
106
- tmp = []
107
- if islocal:
108
- sizefilepath_ = f"{dataset_path}/{n}/{s}/sizes.json"
109
- if not os.path.exists(sizefilepath_):
110
- sizefilepath_ = f"./json_files/{n}/{s}/sizes.json"
111
- else:
112
- sizefilepath_ = f"./json_files/{n}/{s}/sizes.json"
113
- if not os.path.exists(sizefilepath_):
114
- continue
115
- sizes = json.load(open(sizefilepath_, "r"))
116
- for k in sizes.keys():
117
- if islocal:
118
- tmp.append(f"{dataset_path}/{n}/{s}/{k}")
119
- else:
120
- tmp.append(
121
- f"pipe:aws s3 --cli-connect-timeout 0 cp s3://s-laion-audio/webdataset_tar/{n}/{s}/{k} -"
122
- )
123
- if proportion != 1:
124
- tmp = random.sample(tmp, int(proportion * len(tmp)))
125
- output.append(tmp)
126
- return sum(output, [])
127
-
128
-
129
- def get_tar_path_from_txts(txt_path, islocal, proportion=1):
130
- """
131
- Get tar path from txt path
132
- """
133
- if isinstance(txt_path, (list, tuple)):
134
- return sum(
135
- [
136
- get_tar_path_from_txts(
137
- txt_path[i], islocal=islocal, proportion=proportion
138
- )
139
- for i in range(len(txt_path))
140
- ],
141
- [],
142
- )
143
- if isinstance(txt_path, str):
144
- with open(txt_path) as f:
145
- lines = f.readlines()
146
- if islocal:
147
- lines = [
148
- lines[i]
149
- .split("\n")[0]
150
- .replace("pipe:aws s3 cp s3://s-laion-audio/", "/mnt/audio_clip/")
151
- for i in range(len(lines))
152
- ]
153
- else:
154
- lines = [
155
- lines[i].split("\n")[0].replace(".tar", ".tar -")
156
- for i in range(len(lines))
157
- ]
158
- if proportion != 1:
159
- print("Sampling tars with proportion of {}".format(proportion))
160
- lines = random.sample(lines, int(proportion * len(lines)))
161
- return lines
162
-
163
-
164
- def get_mix_lambda(mixup_alpha, batch_size):
165
- mixup_lambdas = [
166
- np.random.beta(mixup_alpha, mixup_alpha, 1)[0] for _ in range(batch_size)
167
- ]
168
- return np.array(mixup_lambdas).astype(np.float32)
169
-
170
-
171
- def do_mixup(x, mixup_lambda):
172
- """
173
- Args:
174
- x: (batch_size , ...)
175
- mixup_lambda: (batch_size,)
176
- Returns:
177
- out: (batch_size, ...)
178
- """
179
- out = (
180
- x.transpose(0, -1) * mixup_lambda
181
- + torch.flip(x, dims=[0]).transpose(0, -1) * (1 - mixup_lambda)
182
- ).transpose(0, -1)
183
- return out
184
-
185
-
186
- def interpolate(x, ratio):
187
- """Interpolate data in time domain. This is used to compensate the
188
- resolution reduction in downsampling of a CNN.
189
-
190
- Args:
191
- x: (batch_size, time_steps, classes_num)
192
- ratio: int, ratio to interpolate
193
- Returns:
194
- upsampled: (batch_size, time_steps * ratio, classes_num)
195
- """
196
- (batch_size, time_steps, classes_num) = x.shape
197
- upsampled = x[:, :, None, :].repeat(1, 1, ratio, 1)
198
- upsampled = upsampled.reshape(batch_size, time_steps * ratio, classes_num)
199
- return upsampled
200
-
201
-
202
- def pad_framewise_output(framewise_output, frames_num):
203
- """Pad framewise_output to the same length as input frames. The pad value
204
- is the same as the value of the last frame.
205
- Args:
206
- framewise_output: (batch_size, frames_num, classes_num)
207
- frames_num: int, number of frames to pad
208
- Outputs:
209
- output: (batch_size, frames_num, classes_num)
210
- """
211
- pad = framewise_output[:, -1:, :].repeat(
212
- 1, frames_num - framewise_output.shape[1], 1
213
- )
214
- """tensor for padding"""
215
-
216
- output = torch.cat((framewise_output, pad), dim=1)
217
- """(batch_size, frames_num, classes_num)"""
218
-
219
-
220
- def process_ipc(index_path, classes_num, filename):
221
- # load data
222
- logging.info("Load Data...............")
223
- ipc = [[] for _ in range(classes_num)]
224
- with h5py.File(index_path, "r") as f:
225
- for i in tqdm(range(len(f["target"]))):
226
- t_class = np.where(f["target"][i])[0]
227
- for t in t_class:
228
- ipc[t].append(i)
229
- print(ipc)
230
- np.save(filename, ipc)
231
- logging.info("Load Data Succeed...............")
232
-
233
-
234
- def save_to_dict(s, o_={}):
235
- sp = s.split(": ")
236
- o_.update({sp[0]: float(sp[1])})
237
- return o_
238
-
239
-
240
- def get_data_from_log(txt_path):
241
- """
242
- Output dictionary from out.txt log file
243
- """
244
- with open(txt_path) as f:
245
- lines = f.readlines()
246
- val_data = {}
247
- train_data = {}
248
- train_losses = []
249
- train_losses_epoch = []
250
- for i in range(len(lines)):
251
- if "| INFO |" in lines[i]:
252
- if "Eval Epoch" in lines[i]:
253
- if "val_loss" in lines[i]:
254
- # float(regex.sub("", lines[310].split(" ")[-1]).replace(" ", ""))
255
- line = lines[i].split("Eval Epoch: ")[-1]
256
- num_epoch = int(line.split(" ")[0].split(" ")[0])
257
- d = {
258
- line.split(" ")[0]
259
- .split(" ")[1]
260
- .replace(":", ""): float(line.split(" ")[0].split(" ")[-1])
261
- }
262
- for i in range(1, len(line.split(" "))):
263
- d = save_to_dict(line.split(" ")[i], d)
264
- val_data[num_epoch] = d
265
- elif "Train Epoch" in lines[i]:
266
- num_epoch = int(lines[i].split("Train Epoch: ")[1][0])
267
- loss = float(lines[i].split("Loss: ")[-1].split(" (")[0])
268
- train_losses.append(loss)
269
- train_losses_epoch.append(num_epoch)
270
- for i in range(len(train_losses)):
271
- train_data[i] = {
272
- "num_epoch": train_losses_epoch[i],
273
- "train_loss": train_losses[i],
274
- }
275
- return train_data, val_data
276
-
277
-
278
- def save_p(obj, filename):
279
- import pickle
280
-
281
- try:
282
- from deepdiff import DeepDiff
283
- except:
284
- os.system("pip install deepdiff")
285
- from deepdiff import DeepDiff
286
- with open(filename, "wb") as file:
287
- pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL) # highest protocol
288
- with open(filename, "rb") as file:
289
- z = pickle.load(file)
290
- assert (
291
- DeepDiff(obj, z, ignore_string_case=True) == {}
292
- ), "there is something wrong with the saving process"
293
- return
294
-
295
-
296
- def load_p(filename):
297
- import pickle
298
-
299
- with open(filename, "rb") as file:
300
- z = pickle.load(file)
301
- return z
302
-
303
-
304
- def save_json(data, name="data.json"):
305
- import json
306
-
307
- with open(name, "w") as fp:
308
- json.dump(data, fp)
309
- return
310
-
311
-
312
- def load_json(name):
313
- import json
314
-
315
- with open(name, "r") as fp:
316
- data = json.load(fp)
317
- return data
318
-
319
-
320
- from multiprocessing import Process, Manager
321
- from multiprocessing import Process, Value, Array
322
- from ctypes import c_wchar
323
-
324
-
325
- def load_class_label(path):
326
- # https://stackoverflow.com/questions/48004243/how-to-share-large-read-only-dictionary-list-across-processes-in-multiprocessing
327
- # https://stackoverflow.com/questions/45693949/storing-strings-in-a-multiprocessing-sharedctypes-array
328
- out = None
329
- if path is not None:
330
- if pathlib.Path(path).suffix in [".pkl", ".pickle"]:
331
- out = load_p(path)
332
- elif pathlib.Path(path).suffix in [".json", ".txt"]:
333
- out = load_json(path)
334
- elif pathlib.Path(path).suffix in [".npy", ".npz"]:
335
- out = np.load(path)
336
- elif pathlib.Path(path).suffix in [".csv"]:
337
- import pandas as pd
338
-
339
- out = pd.read_csv(path)
340
- return out
341
- # if out is None:
342
- # return None
343
- # else:
344
- # key = Array(c_wchar, '\n'.join(list(out.keys())), lock=False)
345
- # val = Array('i', out.values(), lock=False)
346
- # return (key, val)
347
-
348
-
349
- from torch import optim
350
-
351
-
352
- def get_optimizer(params, lr, betas, eps, momentum, optimizer_name):
353
- if optimizer_name.lower() == "adamw":
354
- optimizer = optim.AdamW(params, lr=lr, betas=betas, eps=eps)
355
- elif optimizer_name.lower() == "sgd":
356
- optimizer = optim.SGD(params, lr=lr, momentum=momentum)
357
- elif optimizer_name.lower() == "adam":
358
- optimizer = optim.Adam(params, lr=lr, betas=betas, eps=eps)
359
- else:
360
- raise ValueError("optimizer name is not correct")
361
- return optimizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Basit12345/basit123/app.py DELETED
@@ -1,25 +0,0 @@
1
- import openai
2
- import gradio as gr
3
-
4
-
5
-
6
- openai.api_key = "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"
7
-
8
- messages = [{"role": "system", "content": "You are a financial experts that specializes in real estate investment and negotiation"}]
9
-
10
-
11
-
12
-
13
- def CustomChatGPT(user_input):
14
- messages.append({"role": "user", "content": user_input})
15
- response = openai.ChatCompletion.create(
16
- model = "gpt-3.5-turbo",
17
- messages = messages
18
- )
19
- ChatGPT_reply = response["choices"][0]["message"]["content"]
20
- messages.append({"role": "assistant", "content": ChatGPT_reply})
21
- return ChatGPT_reply
22
-
23
- iface = gr.Interface(fn=CustomChatGPT, inputs = "text", outputs = "text", title = "basit cyberwala gpt")
24
- iface.launch()
25
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/pyparsing/diagram/__init__.py DELETED
@@ -1,642 +0,0 @@
1
- import railroad
2
- import pyparsing
3
- import typing
4
- from typing import (
5
- List,
6
- NamedTuple,
7
- Generic,
8
- TypeVar,
9
- Dict,
10
- Callable,
11
- Set,
12
- Iterable,
13
- )
14
- from jinja2 import Template
15
- from io import StringIO
16
- import inspect
17
-
18
-
19
- jinja2_template_source = """\
20
- <!DOCTYPE html>
21
- <html>
22
- <head>
23
- {% if not head %}
24
- <style type="text/css">
25
- .railroad-heading {
26
- font-family: monospace;
27
- }
28
- </style>
29
- {% else %}
30
- {{ head | safe }}
31
- {% endif %}
32
- </head>
33
- <body>
34
- {{ body | safe }}
35
- {% for diagram in diagrams %}
36
- <div class="railroad-group">
37
- <h1 class="railroad-heading">{{ diagram.title }}</h1>
38
- <div class="railroad-description">{{ diagram.text }}</div>
39
- <div class="railroad-svg">
40
- {{ diagram.svg }}
41
- </div>
42
- </div>
43
- {% endfor %}
44
- </body>
45
- </html>
46
- """
47
-
48
- template = Template(jinja2_template_source)
49
-
50
- # Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet
51
- NamedDiagram = NamedTuple(
52
- "NamedDiagram",
53
- [("name", str), ("diagram", typing.Optional[railroad.DiagramItem]), ("index", int)],
54
- )
55
- """
56
- A simple structure for associating a name with a railroad diagram
57
- """
58
-
59
- T = TypeVar("T")
60
-
61
-
62
- class EachItem(railroad.Group):
63
- """
64
- Custom railroad item to compose a:
65
- - Group containing a
66
- - OneOrMore containing a
67
- - Choice of the elements in the Each
68
- with the group label indicating that all must be matched
69
- """
70
-
71
- all_label = "[ALL]"
72
-
73
- def __init__(self, *items):
74
- choice_item = railroad.Choice(len(items) - 1, *items)
75
- one_or_more_item = railroad.OneOrMore(item=choice_item)
76
- super().__init__(one_or_more_item, label=self.all_label)
77
-
78
-
79
- class AnnotatedItem(railroad.Group):
80
- """
81
- Simple subclass of Group that creates an annotation label
82
- """
83
-
84
- def __init__(self, label: str, item):
85
- super().__init__(item=item, label="[{}]".format(label) if label else label)
86
-
87
-
88
- class EditablePartial(Generic[T]):
89
- """
90
- Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been
91
- constructed.
92
- """
93
-
94
- # We need this here because the railroad constructors actually transform the data, so can't be called until the
95
- # entire tree is assembled
96
-
97
- def __init__(self, func: Callable[..., T], args: list, kwargs: dict):
98
- self.func = func
99
- self.args = args
100
- self.kwargs = kwargs
101
-
102
- @classmethod
103
- def from_call(cls, func: Callable[..., T], *args, **kwargs) -> "EditablePartial[T]":
104
- """
105
- If you call this function in the same way that you would call the constructor, it will store the arguments
106
- as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)
107
- """
108
- return EditablePartial(func=func, args=list(args), kwargs=kwargs)
109
-
110
- @property
111
- def name(self):
112
- return self.kwargs["name"]
113
-
114
- def __call__(self) -> T:
115
- """
116
- Evaluate the partial and return the result
117
- """
118
- args = self.args.copy()
119
- kwargs = self.kwargs.copy()
120
-
121
- # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.
122
- # args=['list', 'of', 'things'])
123
- arg_spec = inspect.getfullargspec(self.func)
124
- if arg_spec.varargs in self.kwargs:
125
- args += kwargs.pop(arg_spec.varargs)
126
-
127
- return self.func(*args, **kwargs)
128
-
129
-
130
- def railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str:
131
- """
132
- Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams
133
- :params kwargs: kwargs to be passed in to the template
134
- """
135
- data = []
136
- for diagram in diagrams:
137
- if diagram.diagram is None:
138
- continue
139
- io = StringIO()
140
- diagram.diagram.writeSvg(io.write)
141
- title = diagram.name
142
- if diagram.index == 0:
143
- title += " (root)"
144
- data.append({"title": title, "text": "", "svg": io.getvalue()})
145
-
146
- return template.render(diagrams=data, **kwargs)
147
-
148
-
149
- def resolve_partial(partial: "EditablePartial[T]") -> T:
150
- """
151
- Recursively resolves a collection of Partials into whatever type they are
152
- """
153
- if isinstance(partial, EditablePartial):
154
- partial.args = resolve_partial(partial.args)
155
- partial.kwargs = resolve_partial(partial.kwargs)
156
- return partial()
157
- elif isinstance(partial, list):
158
- return [resolve_partial(x) for x in partial]
159
- elif isinstance(partial, dict):
160
- return {key: resolve_partial(x) for key, x in partial.items()}
161
- else:
162
- return partial
163
-
164
-
165
- def to_railroad(
166
- element: pyparsing.ParserElement,
167
- diagram_kwargs: typing.Optional[dict] = None,
168
- vertical: int = 3,
169
- show_results_names: bool = False,
170
- show_groups: bool = False,
171
- ) -> List[NamedDiagram]:
172
- """
173
- Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram
174
- creation if you want to access the Railroad tree before it is converted to HTML
175
- :param element: base element of the parser being diagrammed
176
- :param diagram_kwargs: kwargs to pass to the Diagram() constructor
177
- :param vertical: (optional) - int - limit at which number of alternatives should be
178
- shown vertically instead of horizontally
179
- :param show_results_names - bool to indicate whether results name annotations should be
180
- included in the diagram
181
- :param show_groups - bool to indicate whether groups should be highlighted with an unlabeled
182
- surrounding box
183
- """
184
- # Convert the whole tree underneath the root
185
- lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})
186
- _to_diagram_element(
187
- element,
188
- lookup=lookup,
189
- parent=None,
190
- vertical=vertical,
191
- show_results_names=show_results_names,
192
- show_groups=show_groups,
193
- )
194
-
195
- root_id = id(element)
196
- # Convert the root if it hasn't been already
197
- if root_id in lookup:
198
- if not element.customName:
199
- lookup[root_id].name = ""
200
- lookup[root_id].mark_for_extraction(root_id, lookup, force=True)
201
-
202
- # Now that we're finished, we can convert from intermediate structures into Railroad elements
203
- diags = list(lookup.diagrams.values())
204
- if len(diags) > 1:
205
- # collapse out duplicate diags with the same name
206
- seen = set()
207
- deduped_diags = []
208
- for d in diags:
209
- # don't extract SkipTo elements, they are uninformative as subdiagrams
210
- if d.name == "...":
211
- continue
212
- if d.name is not None and d.name not in seen:
213
- seen.add(d.name)
214
- deduped_diags.append(d)
215
- resolved = [resolve_partial(partial) for partial in deduped_diags]
216
- else:
217
- # special case - if just one diagram, always display it, even if
218
- # it has no name
219
- resolved = [resolve_partial(partial) for partial in diags]
220
- return sorted(resolved, key=lambda diag: diag.index)
221
-
222
-
223
- def _should_vertical(
224
- specification: int, exprs: Iterable[pyparsing.ParserElement]
225
- ) -> bool:
226
- """
227
- Returns true if we should return a vertical list of elements
228
- """
229
- if specification is None:
230
- return False
231
- else:
232
- return len(_visible_exprs(exprs)) >= specification
233
-
234
-
235
- class ElementState:
236
- """
237
- State recorded for an individual pyparsing Element
238
- """
239
-
240
- # Note: this should be a dataclass, but we have to support Python 3.5
241
- def __init__(
242
- self,
243
- element: pyparsing.ParserElement,
244
- converted: EditablePartial,
245
- parent: EditablePartial,
246
- number: int,
247
- name: str = None,
248
- parent_index: typing.Optional[int] = None,
249
- ):
250
- #: The pyparsing element that this represents
251
- self.element: pyparsing.ParserElement = element
252
- #: The name of the element
253
- self.name: typing.Optional[str] = name
254
- #: The output Railroad element in an unconverted state
255
- self.converted: EditablePartial = converted
256
- #: The parent Railroad element, which we store so that we can extract this if it's duplicated
257
- self.parent: EditablePartial = parent
258
- #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram
259
- self.number: int = number
260
- #: The index of this inside its parent
261
- self.parent_index: typing.Optional[int] = parent_index
262
- #: If true, we should extract this out into a subdiagram
263
- self.extract: bool = False
264
- #: If true, all of this element's children have been filled out
265
- self.complete: bool = False
266
-
267
- def mark_for_extraction(
268
- self, el_id: int, state: "ConverterState", name: str = None, force: bool = False
269
- ):
270
- """
271
- Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram
272
- :param el_id: id of the element
273
- :param state: element/diagram state tracker
274
- :param name: name to use for this element's text
275
- :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the
276
- root element when we know we're finished
277
- """
278
- self.extract = True
279
-
280
- # Set the name
281
- if not self.name:
282
- if name:
283
- # Allow forcing a custom name
284
- self.name = name
285
- elif self.element.customName:
286
- self.name = self.element.customName
287
- else:
288
- self.name = ""
289
-
290
- # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children
291
- # to be added
292
- # Also, if this is just a string literal etc, don't bother extracting it
293
- if force or (self.complete and _worth_extracting(self.element)):
294
- state.extract_into_diagram(el_id)
295
-
296
-
297
- class ConverterState:
298
- """
299
- Stores some state that persists between recursions into the element tree
300
- """
301
-
302
- def __init__(self, diagram_kwargs: typing.Optional[dict] = None):
303
- #: A dictionary mapping ParserElements to state relating to them
304
- self._element_diagram_states: Dict[int, ElementState] = {}
305
- #: A dictionary mapping ParserElement IDs to subdiagrams generated from them
306
- self.diagrams: Dict[int, EditablePartial[NamedDiagram]] = {}
307
- #: The index of the next unnamed element
308
- self.unnamed_index: int = 1
309
- #: The index of the next element. This is used for sorting
310
- self.index: int = 0
311
- #: Shared kwargs that are used to customize the construction of diagrams
312
- self.diagram_kwargs: dict = diagram_kwargs or {}
313
- self.extracted_diagram_names: Set[str] = set()
314
-
315
- def __setitem__(self, key: int, value: ElementState):
316
- self._element_diagram_states[key] = value
317
-
318
- def __getitem__(self, key: int) -> ElementState:
319
- return self._element_diagram_states[key]
320
-
321
- def __delitem__(self, key: int):
322
- del self._element_diagram_states[key]
323
-
324
- def __contains__(self, key: int):
325
- return key in self._element_diagram_states
326
-
327
- def generate_unnamed(self) -> int:
328
- """
329
- Generate a number used in the name of an otherwise unnamed diagram
330
- """
331
- self.unnamed_index += 1
332
- return self.unnamed_index
333
-
334
- def generate_index(self) -> int:
335
- """
336
- Generate a number used to index a diagram
337
- """
338
- self.index += 1
339
- return self.index
340
-
341
- def extract_into_diagram(self, el_id: int):
342
- """
343
- Used when we encounter the same token twice in the same tree. When this
344
- happens, we replace all instances of that token with a terminal, and
345
- create a new subdiagram for the token
346
- """
347
- position = self[el_id]
348
-
349
- # Replace the original definition of this element with a regular block
350
- if position.parent:
351
- ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name)
352
- if "item" in position.parent.kwargs:
353
- position.parent.kwargs["item"] = ret
354
- elif "items" in position.parent.kwargs:
355
- position.parent.kwargs["items"][position.parent_index] = ret
356
-
357
- # If the element we're extracting is a group, skip to its content but keep the title
358
- if position.converted.func == railroad.Group:
359
- content = position.converted.kwargs["item"]
360
- else:
361
- content = position.converted
362
-
363
- self.diagrams[el_id] = EditablePartial.from_call(
364
- NamedDiagram,
365
- name=position.name,
366
- diagram=EditablePartial.from_call(
367
- railroad.Diagram, content, **self.diagram_kwargs
368
- ),
369
- index=position.number,
370
- )
371
-
372
- del self[el_id]
373
-
374
-
375
- def _worth_extracting(element: pyparsing.ParserElement) -> bool:
376
- """
377
- Returns true if this element is worth having its own sub-diagram. Simply, if any of its children
378
- themselves have children, then its complex enough to extract
379
- """
380
- children = element.recurse()
381
- return any(child.recurse() for child in children)
382
-
383
-
384
- def _apply_diagram_item_enhancements(fn):
385
- """
386
- decorator to ensure enhancements to a diagram item (such as results name annotations)
387
- get applied on return from _to_diagram_element (we do this since there are several
388
- returns in _to_diagram_element)
389
- """
390
-
391
- def _inner(
392
- element: pyparsing.ParserElement,
393
- parent: typing.Optional[EditablePartial],
394
- lookup: ConverterState = None,
395
- vertical: int = None,
396
- index: int = 0,
397
- name_hint: str = None,
398
- show_results_names: bool = False,
399
- show_groups: bool = False,
400
- ) -> typing.Optional[EditablePartial]:
401
-
402
- ret = fn(
403
- element,
404
- parent,
405
- lookup,
406
- vertical,
407
- index,
408
- name_hint,
409
- show_results_names,
410
- show_groups,
411
- )
412
-
413
- # apply annotation for results name, if present
414
- if show_results_names and ret is not None:
415
- element_results_name = element.resultsName
416
- if element_results_name:
417
- # add "*" to indicate if this is a "list all results" name
418
- element_results_name += "" if element.modalResults else "*"
419
- ret = EditablePartial.from_call(
420
- railroad.Group, item=ret, label=element_results_name
421
- )
422
-
423
- return ret
424
-
425
- return _inner
426
-
427
-
428
- def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):
429
- non_diagramming_exprs = (
430
- pyparsing.ParseElementEnhance,
431
- pyparsing.PositionToken,
432
- pyparsing.And._ErrorStop,
433
- )
434
- return [
435
- e
436
- for e in exprs
437
- if not (e.customName or e.resultsName or isinstance(e, non_diagramming_exprs))
438
- ]
439
-
440
-
441
- @_apply_diagram_item_enhancements
442
- def _to_diagram_element(
443
- element: pyparsing.ParserElement,
444
- parent: typing.Optional[EditablePartial],
445
- lookup: ConverterState = None,
446
- vertical: int = None,
447
- index: int = 0,
448
- name_hint: str = None,
449
- show_results_names: bool = False,
450
- show_groups: bool = False,
451
- ) -> typing.Optional[EditablePartial]:
452
- """
453
- Recursively converts a PyParsing Element to a railroad Element
454
- :param lookup: The shared converter state that keeps track of useful things
455
- :param index: The index of this element within the parent
456
- :param parent: The parent of this element in the output tree
457
- :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
458
- it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
459
- do so
460
- :param name_hint: If provided, this will override the generated name
461
- :param show_results_names: bool flag indicating whether to add annotations for results names
462
- :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed
463
- :param show_groups: bool flag indicating whether to show groups using bounding box
464
- """
465
- exprs = element.recurse()
466
- name = name_hint or element.customName or element.__class__.__name__
467
-
468
- # Python's id() is used to provide a unique identifier for elements
469
- el_id = id(element)
470
-
471
- element_results_name = element.resultsName
472
-
473
- # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram
474
- if not element.customName:
475
- if isinstance(
476
- element,
477
- (
478
- # pyparsing.TokenConverter,
479
- # pyparsing.Forward,
480
- pyparsing.Located,
481
- ),
482
- ):
483
- # However, if this element has a useful custom name, and its child does not, we can pass it on to the child
484
- if exprs:
485
- if not exprs[0].customName:
486
- propagated_name = name
487
- else:
488
- propagated_name = None
489
-
490
- return _to_diagram_element(
491
- element.expr,
492
- parent=parent,
493
- lookup=lookup,
494
- vertical=vertical,
495
- index=index,
496
- name_hint=propagated_name,
497
- show_results_names=show_results_names,
498
- show_groups=show_groups,
499
- )
500
-
501
- # If the element isn't worth extracting, we always treat it as the first time we say it
502
- if _worth_extracting(element):
503
- if el_id in lookup:
504
- # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,
505
- # so we have to extract it into a new diagram.
506
- looked_up = lookup[el_id]
507
- looked_up.mark_for_extraction(el_id, lookup, name=name_hint)
508
- ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name)
509
- return ret
510
-
511
- elif el_id in lookup.diagrams:
512
- # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we
513
- # just put in a marker element that refers to the sub-diagram
514
- ret = EditablePartial.from_call(
515
- railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
516
- )
517
- return ret
518
-
519
- # Recursively convert child elements
520
- # Here we find the most relevant Railroad element for matching pyparsing Element
521
- # We use ``items=[]`` here to hold the place for where the child elements will go once created
522
- if isinstance(element, pyparsing.And):
523
- # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat
524
- # (all will have the same name, and resultsName)
525
- if not exprs:
526
- return None
527
- if len(set((e.name, e.resultsName) for e in exprs)) == 1:
528
- ret = EditablePartial.from_call(
529
- railroad.OneOrMore, item="", repeat=str(len(exprs))
530
- )
531
- elif _should_vertical(vertical, exprs):
532
- ret = EditablePartial.from_call(railroad.Stack, items=[])
533
- else:
534
- ret = EditablePartial.from_call(railroad.Sequence, items=[])
535
- elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
536
- if not exprs:
537
- return None
538
- if _should_vertical(vertical, exprs):
539
- ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
540
- else:
541
- ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
542
- elif isinstance(element, pyparsing.Each):
543
- if not exprs:
544
- return None
545
- ret = EditablePartial.from_call(EachItem, items=[])
546
- elif isinstance(element, pyparsing.NotAny):
547
- ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="")
548
- elif isinstance(element, pyparsing.FollowedBy):
549
- ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="")
550
- elif isinstance(element, pyparsing.PrecededBy):
551
- ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="")
552
- elif isinstance(element, pyparsing.Group):
553
- if show_groups:
554
- ret = EditablePartial.from_call(AnnotatedItem, label="", item="")
555
- else:
556
- ret = EditablePartial.from_call(railroad.Group, label="", item="")
557
- elif isinstance(element, pyparsing.TokenConverter):
558
- ret = EditablePartial.from_call(
559
- AnnotatedItem, label=type(element).__name__.lower(), item=""
560
- )
561
- elif isinstance(element, pyparsing.Opt):
562
- ret = EditablePartial.from_call(railroad.Optional, item="")
563
- elif isinstance(element, pyparsing.OneOrMore):
564
- ret = EditablePartial.from_call(railroad.OneOrMore, item="")
565
- elif isinstance(element, pyparsing.ZeroOrMore):
566
- ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
567
- elif isinstance(element, pyparsing.Group):
568
- ret = EditablePartial.from_call(
569
- railroad.Group, item=None, label=element_results_name
570
- )
571
- elif isinstance(element, pyparsing.Empty) and not element.customName:
572
- # Skip unnamed "Empty" elements
573
- ret = None
574
- elif len(exprs) > 1:
575
- ret = EditablePartial.from_call(railroad.Sequence, items=[])
576
- elif len(exprs) > 0 and not element_results_name:
577
- ret = EditablePartial.from_call(railroad.Group, item="", label=name)
578
- else:
579
- terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
580
- ret = terminal
581
-
582
- if ret is None:
583
- return
584
-
585
- # Indicate this element's position in the tree so we can extract it if necessary
586
- lookup[el_id] = ElementState(
587
- element=element,
588
- converted=ret,
589
- parent=parent,
590
- parent_index=index,
591
- number=lookup.generate_index(),
592
- )
593
- if element.customName:
594
- lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)
595
-
596
- i = 0
597
- for expr in exprs:
598
- # Add a placeholder index in case we have to extract the child before we even add it to the parent
599
- if "items" in ret.kwargs:
600
- ret.kwargs["items"].insert(i, None)
601
-
602
- item = _to_diagram_element(
603
- expr,
604
- parent=ret,
605
- lookup=lookup,
606
- vertical=vertical,
607
- index=i,
608
- show_results_names=show_results_names,
609
- show_groups=show_groups,
610
- )
611
-
612
- # Some elements don't need to be shown in the diagram
613
- if item is not None:
614
- if "item" in ret.kwargs:
615
- ret.kwargs["item"] = item
616
- elif "items" in ret.kwargs:
617
- # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal
618
- ret.kwargs["items"][i] = item
619
- i += 1
620
- elif "items" in ret.kwargs:
621
- # If we're supposed to skip this element, remove it from the parent
622
- del ret.kwargs["items"][i]
623
-
624
- # If all this items children are none, skip this item
625
- if ret and (
626
- ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0)
627
- or ("item" in ret.kwargs and ret.kwargs["item"] is None)
628
- ):
629
- ret = EditablePartial.from_call(railroad.Terminal, name)
630
-
631
- # Mark this element as "complete", ie it has all of its children
632
- if el_id in lookup:
633
- lookup[el_id].complete = True
634
-
635
- if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:
636
- lookup.extract_into_diagram(el_id)
637
- if ret is not None:
638
- ret = EditablePartial.from_call(
639
- railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
640
- )
641
-
642
- return ret
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Billyosoro/ESRGAN/scripts/generate_meta_info_pairdata.py DELETED
@@ -1,49 +0,0 @@
1
- import argparse
2
- import glob
3
- import os
4
-
5
-
6
- def main(args):
7
- txt_file = open(args.meta_info, 'w')
8
- # sca images
9
- img_paths_gt = sorted(glob.glob(os.path.join(args.input[0], '*')))
10
- img_paths_lq = sorted(glob.glob(os.path.join(args.input[1], '*')))
11
-
12
- assert len(img_paths_gt) == len(img_paths_lq), ('GT folder and LQ folder should have the same length, but got '
13
- f'{len(img_paths_gt)} and {len(img_paths_lq)}.')
14
-
15
- for img_path_gt, img_path_lq in zip(img_paths_gt, img_paths_lq):
16
- # get the relative paths
17
- img_name_gt = os.path.relpath(img_path_gt, args.root[0])
18
- img_name_lq = os.path.relpath(img_path_lq, args.root[1])
19
- print(f'{img_name_gt}, {img_name_lq}')
20
- txt_file.write(f'{img_name_gt}, {img_name_lq}\n')
21
-
22
-
23
- if __name__ == '__main__':
24
- """This script is used to generate meta info (txt file) for paired images.
25
- """
26
- parser = argparse.ArgumentParser()
27
- parser.add_argument(
28
- '--input',
29
- nargs='+',
30
- default=['datasets/DF2K/DIV2K_train_HR_sub', 'datasets/DF2K/DIV2K_train_LR_bicubic_X4_sub'],
31
- help='Input folder, should be [gt_folder, lq_folder]')
32
- parser.add_argument('--root', nargs='+', default=[None, None], help='Folder root, will use the ')
33
- parser.add_argument(
34
- '--meta_info',
35
- type=str,
36
- default='datasets/DF2K/meta_info/meta_info_DIV2K_sub_pair.txt',
37
- help='txt path for meta info')
38
- args = parser.parse_args()
39
-
40
- assert len(args.input) == 2, 'Input folder should have two elements: gt folder and lq folder'
41
- assert len(args.root) == 2, 'Root path should have two elements: root for gt folder and lq folder'
42
- os.makedirs(os.path.dirname(args.meta_info), exist_ok=True)
43
- for i in range(2):
44
- if args.input[i].endswith('/'):
45
- args.input[i] = args.input[i][:-1]
46
- if args.root[i] is None:
47
- args.root[i] = os.path.dirname(args.input[i])
48
-
49
- main(args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Demo-Balanced-MSE/app.py DELETED
@@ -1,300 +0,0 @@
1
- import gradio as gr
2
- import matplotlib.pyplot as plt
3
- import torch
4
- import seaborn as sns
5
- import pandas as pd
6
- import os
7
- import os.path as osp
8
- import ffmpeg
9
- import torch.nn as nn
10
- import torch.nn.functional as F
11
- from torch.nn.modules.loss import _Loss
12
- from torch.utils.data import Dataset, DataLoader
13
-
14
- NUM_PER_BUCKET = 1000
15
- NOISE_SIGMA = 1
16
- Y_UB = 10
17
- Y_LB = 0
18
- K = 1
19
- B = 0
20
- NUM_SEG = 5
21
- NUM_EPOCHS = 100
22
- PRINT_FREQ = NUM_EPOCHS // 20
23
- NUM_TRAIN_SAMPLES = NUM_PER_BUCKET * NUM_SEG
24
- BATCH_SIZE = 256
25
-
26
-
27
- def make_dataframe(x, y, method=None):
28
- x = list(x[:, 0].detach().numpy())
29
- y = list(y[:, 0].detach().numpy())
30
- if method is not None:
31
- method = [method for _ in range(len(x))]
32
- df = pd.DataFrame({'x': x, 'y': y, 'Method': method})
33
- else:
34
- df = pd.DataFrame({'x': x, 'y': y})
35
- return df
36
-
37
-
38
- Y_demo = torch.linspace(Y_LB, Y_UB, 2).unsqueeze(-1)
39
- X_demo = (Y_demo - B) / K
40
-
41
- df_oracle = make_dataframe(X_demo, Y_demo, 'Oracle')
42
-
43
-
44
- def prepare_data(sel_num):
45
- interval = (Y_UB - Y_LB) / NUM_SEG
46
- all_x, all_y = [], []
47
- prob = []
48
- for i in range(NUM_SEG):
49
- uniform_y_distribution = torch.distributions.Uniform(Y_UB - (i + 1) * interval, Y_UB - i * interval)
50
- y_uniform = uniform_y_distribution.sample((NUM_TRAIN_SAMPLES, 1))[:sel_num[i]]
51
-
52
- noise_distribution = torch.distributions.Normal(loc=0, scale=NOISE_SIGMA)
53
- noise = noise_distribution.sample((NUM_TRAIN_SAMPLES, 1))[:sel_num[i]]
54
- y_uniform_oracle = y_uniform - noise
55
-
56
- x_uniform = (y_uniform_oracle - B) / K
57
- all_x += x_uniform
58
- all_y += y_uniform
59
- prob += [torch.tensor(sel_num[i]).float() for _ in range(sel_num[i])]
60
-
61
- all_x = torch.stack(all_x)
62
- all_y = torch.stack(all_y)
63
- prob = torch.stack(prob)
64
- return all_x, all_y, prob
65
-
66
-
67
- def unzip_dataloader(training_loader):
68
- all_x = []
69
- all_y = []
70
- for data, label, _ in training_loader:
71
- all_x.append(data)
72
- all_y.append(label)
73
- all_x = torch.cat(all_x)
74
- all_y = torch.cat(all_y)
75
- return all_x, all_y
76
-
77
-
78
- def train(train_loader, training_df, training_bundle, num_epochs):
79
- visualize_training_process(training_df, training_bundle, -1)
80
- for epoch in range(num_epochs):
81
- for model, optimizer, scheduler, criterion, criterion_name in training_bundle:
82
- model.train()
83
- for data, target, prob in train_loader:
84
- optimizer.zero_grad()
85
- pred = model(data)
86
- if criterion_name == 'Reweight':
87
- loss = criterion(pred, target, prob)
88
- else:
89
- loss = criterion(pred, target)
90
- loss.backward()
91
- optimizer.step()
92
- scheduler.step()
93
- if (epoch + 1) % PRINT_FREQ == 0:
94
- visualize_training_process(training_df, training_bundle, epoch)
95
- visualize_training_process(training_df, training_bundle, num_epochs-1, final=True)
96
-
97
-
98
- def visualize_training_process(training_df, training_bundle, epoch, final=False):
99
- df = df_oracle
100
- for model, optimizer, scheduler, criterion, criterion_name in training_bundle:
101
- model.eval()
102
- y = model(X_demo)
103
- df = df.append(make_dataframe(X_demo, y, criterion_name), ignore_index=True)
104
- visualize(training_df, df, 'train_log/{:05d}.png'.format(epoch + 1), fast=True, epoch=epoch)
105
- if final:
106
- visualize(training_df, df, 'regression_result.png', fast=False)
107
-
108
-
109
- def make_video():
110
- (
111
- ffmpeg
112
- .input('train_log/*.png', pattern_type='glob', framerate=3)
113
- .output('movie.mp4')
114
- .run()
115
- )
116
-
117
-
118
- class ReweightL2(_Loss):
119
- def __init__(self, reweight='inverse'):
120
- super(ReweightL2, self).__init__()
121
- self.reweight = reweight
122
-
123
- def forward(self, pred, target, prob):
124
- reweight = self.reweight
125
- if reweight == 'inverse':
126
- inv_prob = prob.pow(-1)
127
- elif reweight == 'sqrt_inv':
128
- inv_prob = prob.pow(-0.5)
129
- else:
130
- raise NotImplementedError
131
- inv_prob = inv_prob / inv_prob.sum()
132
- loss = F.mse_loss(pred, target, reduction='none').sum(-1) * inv_prob
133
- loss = loss.sum()
134
- return loss
135
-
136
-
137
- class LinearModel(nn.Module):
138
- def __init__(self, input_dim, output_dim):
139
- super(LinearModel, self).__init__()
140
- self.mlp = nn.Sequential(
141
- nn.Linear(input_dim, output_dim),
142
- )
143
-
144
- def forward(self, x):
145
- x = self.mlp(x)
146
- return x
147
-
148
-
149
- def prepare_model():
150
- model = LinearModel(input_dim=1, output_dim=1)
151
- optimizer = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.9)
152
- scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=NUM_EPOCHS)
153
- return model, optimizer, scheduler
154
-
155
-
156
- class BMCLoss(_Loss):
157
- def __init__(self):
158
- super(BMCLoss, self).__init__()
159
- self.noise_sigma = NOISE_SIGMA
160
-
161
- def forward(self, pred, target):
162
- pred = pred.reshape(-1, 1)
163
- target = target.reshape(-1, 1)
164
- noise_var = self.noise_sigma ** 2
165
- loss = bmc_loss(pred, target, noise_var)
166
- return loss
167
-
168
-
169
- def bmc_loss(pred, target, noise_var):
170
- logits = - 0.5 * (pred - target.T).pow(2) / noise_var
171
- loss = F.cross_entropy(logits, torch.arange(pred.shape[0]))
172
-
173
- return loss * (2 * noise_var)
174
-
175
-
176
- def regress(train_loader, training_df):
177
- training_bundle = []
178
- criterions = {
179
- 'MSE': torch.nn.MSELoss(),
180
- 'Reweight': ReweightL2(),
181
- 'Balanced MSE': BMCLoss(),
182
- }
183
- for criterion_name in criterions:
184
- criterion = criterions[criterion_name]
185
- model, optimizer, scheduler = prepare_model()
186
- training_bundle.append((model, optimizer, scheduler, criterion, criterion_name))
187
- train(train_loader, training_df, training_bundle, NUM_EPOCHS)
188
-
189
-
190
- class DummyDataset(Dataset):
191
- def __init__(self, inputs, targets, prob):
192
- self.inputs = inputs
193
- self.targets = targets
194
- self.prob = prob
195
-
196
- def __getitem__(self, index):
197
- return self.inputs[index], self.targets[index], self.prob[index]
198
-
199
- def __len__(self):
200
- return len(self.inputs)
201
-
202
-
203
- def visualize(training_df, df, save_path, fast=False, epoch=None):
204
- if fast:
205
- f = plt.figure(figsize=(3, 3))
206
- g = f.add_subplot(111)
207
- g_line = sns.lineplot(data=df, x='x', y='y', hue='Method', ax=g, estimator=None, ci=None)
208
- plt.xlim((Y_LB - B) / K, (Y_UB - B) / K)
209
- plt.ylim(Y_LB, Y_UB)
210
- else:
211
- g = sns.jointplot(data=training_df, x='x', y='y', color='#003ea1', alpha=0.1, linewidths=0, s=50,
212
- marginal_kws=dict(bins=torch.linspace(Y_LB, Y_UB, steps=NUM_SEG + 1)),
213
- xlim=((Y_LB - B) / K, (Y_UB - B) / K),
214
- ylim=(Y_LB, Y_UB),
215
- space=0.1,
216
- height=5,
217
- ratio=2,
218
- estimator=None, ci=None,
219
- legend=False,
220
- )
221
- g.ax_marg_x.remove()
222
- g_line = sns.lineplot(data=df, x='x', y='y', hue='Method', ax=g.ax_joint, estimator=None, ci=None)
223
- if epoch is not None:
224
- g_line.legend(loc='upper left', title="Epoch {:03d}".format(epoch+1))
225
- else:
226
- g_line.legend(loc='upper left')
227
- plt.gca().axes.set_xlabel(r'$x$')
228
- plt.gca().axes.set_ylabel(r'$y$')
229
-
230
- plt.savefig(save_path, bbox_inches='tight', dpi=200)
231
- plt.close()
232
-
233
-
234
- def clean_up_logs():
235
- if not osp.exists('train_log'):
236
- os.mkdir('train_log')
237
- for f in os.listdir('train_log'):
238
- os.remove(osp.join('train_log', f))
239
- for f in ['regression_result.png', 'training_data.png', 'movie.mp4']:
240
- if osp.isfile(f):
241
- os.remove(f)
242
-
243
-
244
- def run(num1, num2, num3, num4, num5, random_seed, mode):
245
- sel_num = [num1, num2, num3, num4, num5]
246
- sel_num = [int(num / 100 * NUM_PER_BUCKET) for num in sel_num]
247
- torch.manual_seed(int(random_seed))
248
- all_x, all_y, prob = prepare_data(sel_num)
249
- train_loader = DataLoader(DummyDataset(all_x, all_y, prob), BATCH_SIZE, shuffle=True)
250
- training_df = make_dataframe(all_x, all_y)
251
-
252
- clean_up_logs()
253
- if mode == 0:
254
- visualize(training_df, df_oracle, 'training_data.png')
255
- if mode == 1:
256
- regress(train_loader, training_df)
257
- make_video()
258
- if mode == 0:
259
- text = "Press \"Start Regressing\" if your are happy with the training data. Regression takes ~30s."
260
- else:
261
- text = "Press \"Prepare Training Data\" before moving the sliders. You may also change the random seed."
262
- training_data_plot = 'training_data.png' if mode == 0 else None
263
- output = 'regression_result.png'.format(NUM_EPOCHS) if mode == 1 else None
264
- video = "movie.mp4" if mode == 1 else None
265
- return training_data_plot, output, video, text
266
-
267
-
268
- if __name__ == '__main__':
269
- iface = gr.Interface(
270
- fn=run,
271
- inputs=[
272
- gr.inputs.Slider(0, 100, default=20, step=0.1, label='Label percentage in [8, 10)'),
273
- gr.inputs.Slider(0, 100, default=20, step=0.1, label='Label percentage in [6, 8)'),
274
- gr.inputs.Slider(0, 100, default=20, step=0.1, label='Label percentage in [4, 6)'),
275
- gr.inputs.Slider(0, 100, default=20, step=0.1, label='Label percentage in [2, 4)'),
276
- gr.inputs.Slider(0, 100, default=20, step=0.1, label='Label percentage in [0, 2)'),
277
- gr.inputs.Number(default=0, label='Random Seed', optional=False),
278
- gr.inputs.Radio(['Prepare Training Data', 'Start Regressing!'],
279
- type="index", default=None, label='Mode', optional=False),
280
- ],
281
- outputs=[
282
- gr.outputs.Image(type="file", label="Training data"),
283
- gr.outputs.Image(type="file", label="Regression result"),
284
- gr.outputs.Video(type='mp4', label='Training process'),
285
- gr.outputs.Textbox(type="auto", label='What\' s next?')
286
- ],
287
- live=True,
288
- allow_flagging='never',
289
- title="Balanced MSE for Imbalanced Visual Regression [CVPR 2022]",
290
- description="Welcome to the demo of Balanced MSE &#9878;. In this demo, we will work on a simple task: imbalanced <i>linear</i> regression. <br>"
291
- "To get started, move the sliders &#127898; to create your training data "
292
- "or click the examples &#128213; at the bottom of the page &#128071;&#128071;",
293
- examples=[
294
- [0.1, 0.8, 6.4, 51.2, 100, 0, 'Prepare Training Data'],
295
- [1, 10, 100, 10, 1, 0, 'Prepare Training Data'],
296
- ],
297
- css=".output-image, .image-preview {height: 500px !important}",
298
- article="<p style='text-align: center'><a href='https://github.com/jiawei-ren/BalancedMSE' target='_blank'>Balanced MSE @ GitHub</a></p> "
299
- )
300
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/openvqa/openvqa/models/mcan/mca.py DELETED
@@ -1,189 +0,0 @@
1
- # --------------------------------------------------------
2
- # OpenVQA
3
- # Written by Yuhao Cui https://github.com/cuiyuhao1996
4
- # --------------------------------------------------------
5
-
6
- from openvqa.ops.fc import FC, MLP
7
- from openvqa.ops.layer_norm import LayerNorm
8
-
9
- import torch.nn as nn
10
- import torch.nn.functional as F
11
- import torch
12
- import math
13
-
14
-
15
- # ------------------------------
16
- # ---- Multi-Head Attention ----
17
- # ------------------------------
18
-
19
- class MHAtt(nn.Module):
20
- def __init__(self, __C):
21
- super(MHAtt, self).__init__()
22
- self.__C = __C
23
-
24
- self.linear_v = nn.Linear(__C.HIDDEN_SIZE, __C.HIDDEN_SIZE)
25
- self.linear_k = nn.Linear(__C.HIDDEN_SIZE, __C.HIDDEN_SIZE)
26
- self.linear_q = nn.Linear(__C.HIDDEN_SIZE, __C.HIDDEN_SIZE)
27
- self.linear_merge = nn.Linear(__C.HIDDEN_SIZE, __C.HIDDEN_SIZE)
28
-
29
- self.dropout = nn.Dropout(__C.DROPOUT_R)
30
-
31
- def forward(self, v, k, q, mask):
32
- n_batches = q.size(0)
33
-
34
- v = self.linear_v(v).view(
35
- n_batches,
36
- -1,
37
- self.__C.MULTI_HEAD,
38
- int(self.__C.HIDDEN_SIZE / self.__C.MULTI_HEAD)
39
- ).transpose(1, 2)
40
-
41
- k = self.linear_k(k).view(
42
- n_batches,
43
- -1,
44
- self.__C.MULTI_HEAD,
45
- int(self.__C.HIDDEN_SIZE / self.__C.MULTI_HEAD)
46
- ).transpose(1, 2)
47
-
48
- q = self.linear_q(q).view(
49
- n_batches,
50
- -1,
51
- self.__C.MULTI_HEAD,
52
- int(self.__C.HIDDEN_SIZE / self.__C.MULTI_HEAD)
53
- ).transpose(1, 2)
54
-
55
- atted = self.att(v, k, q, mask)
56
- atted = atted.transpose(1, 2).contiguous().view(
57
- n_batches,
58
- -1,
59
- self.__C.HIDDEN_SIZE
60
- )
61
-
62
- atted = self.linear_merge(atted)
63
-
64
- return atted
65
-
66
- def att(self, value, key, query, mask):
67
- d_k = query.size(-1)
68
-
69
- scores = torch.matmul(
70
- query, key.transpose(-2, -1)
71
- ) / math.sqrt(d_k)
72
-
73
- if mask is not None:
74
- scores = scores.masked_fill(mask, -1e9)
75
-
76
- att_map = F.softmax(scores, dim=-1)
77
- att_map = self.dropout(att_map)
78
-
79
- return torch.matmul(att_map, value)
80
-
81
-
82
- # ---------------------------
83
- # ---- Feed Forward Nets ----
84
- # ---------------------------
85
-
86
- class FFN(nn.Module):
87
- def __init__(self, __C):
88
- super(FFN, self).__init__()
89
-
90
- self.mlp = MLP(
91
- in_size=__C.HIDDEN_SIZE,
92
- mid_size=__C.FF_SIZE,
93
- out_size=__C.HIDDEN_SIZE,
94
- dropout_r=__C.DROPOUT_R,
95
- use_relu=True
96
- )
97
-
98
- def forward(self, x):
99
- return self.mlp(x)
100
-
101
-
102
- # ------------------------
103
- # ---- Self Attention ----
104
- # ------------------------
105
-
106
- class SA(nn.Module):
107
- def __init__(self, __C):
108
- super(SA, self).__init__()
109
-
110
- self.mhatt = MHAtt(__C)
111
- self.ffn = FFN(__C)
112
-
113
- self.dropout1 = nn.Dropout(__C.DROPOUT_R)
114
- self.norm1 = LayerNorm(__C.HIDDEN_SIZE)
115
-
116
- self.dropout2 = nn.Dropout(__C.DROPOUT_R)
117
- self.norm2 = LayerNorm(__C.HIDDEN_SIZE)
118
-
119
- def forward(self, y, y_mask):
120
- y = self.norm1(y + self.dropout1(
121
- self.mhatt(y, y, y, y_mask)
122
- ))
123
-
124
- y = self.norm2(y + self.dropout2(
125
- self.ffn(y)
126
- ))
127
-
128
- return y
129
-
130
-
131
- # -------------------------------
132
- # ---- Self Guided Attention ----
133
- # -------------------------------
134
-
135
- class SGA(nn.Module):
136
- def __init__(self, __C):
137
- super(SGA, self).__init__()
138
-
139
- self.mhatt1 = MHAtt(__C)
140
- self.mhatt2 = MHAtt(__C)
141
- self.ffn = FFN(__C)
142
-
143
- self.dropout1 = nn.Dropout(__C.DROPOUT_R)
144
- self.norm1 = LayerNorm(__C.HIDDEN_SIZE)
145
-
146
- self.dropout2 = nn.Dropout(__C.DROPOUT_R)
147
- self.norm2 = LayerNorm(__C.HIDDEN_SIZE)
148
-
149
- self.dropout3 = nn.Dropout(__C.DROPOUT_R)
150
- self.norm3 = LayerNorm(__C.HIDDEN_SIZE)
151
-
152
- def forward(self, x, y, x_mask, y_mask):
153
- x = self.norm1(x + self.dropout1(
154
- self.mhatt1(v=x, k=x, q=x, mask=x_mask)
155
- ))
156
-
157
- x = self.norm2(x + self.dropout2(
158
- self.mhatt2(v=y, k=y, q=x, mask=y_mask)
159
- ))
160
-
161
- x = self.norm3(x + self.dropout3(
162
- self.ffn(x)
163
- ))
164
-
165
- return x
166
-
167
-
168
- # ------------------------------------------------
169
- # ---- MAC Layers Cascaded by Encoder-Decoder ----
170
- # ------------------------------------------------
171
-
172
- class MCA_ED(nn.Module):
173
- def __init__(self, __C):
174
- super(MCA_ED, self).__init__()
175
-
176
- self.enc_list = nn.ModuleList([SA(__C) for _ in range(__C.LAYER)])
177
- self.dec_list = nn.ModuleList([SGA(__C) for _ in range(__C.LAYER)])
178
-
179
- def forward(self, y, x, y_mask, x_mask):
180
- # Get encoder last hidden vector
181
- for enc in self.enc_list:
182
- y = enc(y, y_mask)
183
-
184
- # Input encoder last hidden vector
185
- # And obtain decoder last hidden vectors
186
- for dec in self.dec_list:
187
- x = dec(x, y, x_mask, y_mask)
188
-
189
- return y, x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/pybind11/include/pybind11/stl.h DELETED
@@ -1,388 +0,0 @@
1
- /*
2
- pybind11/stl.h: Transparent conversion for STL data types
3
-
4
- Copyright (c) 2016 Wenzel Jakob <[email protected]>
5
-
6
- All rights reserved. Use of this source code is governed by a
7
- BSD-style license that can be found in the LICENSE file.
8
- */
9
-
10
- #pragma once
11
-
12
- #include "pybind11.h"
13
- #include <set>
14
- #include <unordered_set>
15
- #include <map>
16
- #include <unordered_map>
17
- #include <iostream>
18
- #include <list>
19
- #include <deque>
20
- #include <valarray>
21
-
22
- #if defined(_MSC_VER)
23
- #pragma warning(push)
24
- #pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
25
- #endif
26
-
27
- #ifdef __has_include
28
- // std::optional (but including it in c++14 mode isn't allowed)
29
- # if defined(PYBIND11_CPP17) && __has_include(<optional>)
30
- # include <optional>
31
- # define PYBIND11_HAS_OPTIONAL 1
32
- # endif
33
- // std::experimental::optional (but not allowed in c++11 mode)
34
- # if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
35
- !__has_include(<optional>))
36
- # include <experimental/optional>
37
- # define PYBIND11_HAS_EXP_OPTIONAL 1
38
- # endif
39
- // std::variant
40
- # if defined(PYBIND11_CPP17) && __has_include(<variant>)
41
- # include <variant>
42
- # define PYBIND11_HAS_VARIANT 1
43
- # endif
44
- #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
45
- # include <optional>
46
- # include <variant>
47
- # define PYBIND11_HAS_OPTIONAL 1
48
- # define PYBIND11_HAS_VARIANT 1
49
- #endif
50
-
51
- PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
52
- PYBIND11_NAMESPACE_BEGIN(detail)
53
-
54
- /// Extracts an const lvalue reference or rvalue reference for U based on the type of T (e.g. for
55
- /// forwarding a container element). Typically used indirect via forwarded_type(), below.
56
- template <typename T, typename U>
57
- using forwarded_type = conditional_t<
58
- std::is_lvalue_reference<T>::value, remove_reference_t<U> &, remove_reference_t<U> &&>;
59
-
60
- /// Forwards a value U as rvalue or lvalue according to whether T is rvalue or lvalue; typically
61
- /// used for forwarding a container's elements.
62
- template <typename T, typename U>
63
- forwarded_type<T, U> forward_like(U &&u) {
64
- return std::forward<detail::forwarded_type<T, U>>(std::forward<U>(u));
65
- }
66
-
67
- template <typename Type, typename Key> struct set_caster {
68
- using type = Type;
69
- using key_conv = make_caster<Key>;
70
-
71
- bool load(handle src, bool convert) {
72
- if (!isinstance<pybind11::set>(src))
73
- return false;
74
- auto s = reinterpret_borrow<pybind11::set>(src);
75
- value.clear();
76
- for (auto entry : s) {
77
- key_conv conv;
78
- if (!conv.load(entry, convert))
79
- return false;
80
- value.insert(cast_op<Key &&>(std::move(conv)));
81
- }
82
- return true;
83
- }
84
-
85
- template <typename T>
86
- static handle cast(T &&src, return_value_policy policy, handle parent) {
87
- if (!std::is_lvalue_reference<T>::value)
88
- policy = return_value_policy_override<Key>::policy(policy);
89
- pybind11::set s;
90
- for (auto &&value : src) {
91
- auto value_ = reinterpret_steal<object>(key_conv::cast(forward_like<T>(value), policy, parent));
92
- if (!value_ || !s.add(value_))
93
- return handle();
94
- }
95
- return s.release();
96
- }
97
-
98
- PYBIND11_TYPE_CASTER(type, _("Set[") + key_conv::name + _("]"));
99
- };
100
-
101
- template <typename Type, typename Key, typename Value> struct map_caster {
102
- using key_conv = make_caster<Key>;
103
- using value_conv = make_caster<Value>;
104
-
105
- bool load(handle src, bool convert) {
106
- if (!isinstance<dict>(src))
107
- return false;
108
- auto d = reinterpret_borrow<dict>(src);
109
- value.clear();
110
- for (auto it : d) {
111
- key_conv kconv;
112
- value_conv vconv;
113
- if (!kconv.load(it.first.ptr(), convert) ||
114
- !vconv.load(it.second.ptr(), convert))
115
- return false;
116
- value.emplace(cast_op<Key &&>(std::move(kconv)), cast_op<Value &&>(std::move(vconv)));
117
- }
118
- return true;
119
- }
120
-
121
- template <typename T>
122
- static handle cast(T &&src, return_value_policy policy, handle parent) {
123
- dict d;
124
- return_value_policy policy_key = policy;
125
- return_value_policy policy_value = policy;
126
- if (!std::is_lvalue_reference<T>::value) {
127
- policy_key = return_value_policy_override<Key>::policy(policy_key);
128
- policy_value = return_value_policy_override<Value>::policy(policy_value);
129
- }
130
- for (auto &&kv : src) {
131
- auto key = reinterpret_steal<object>(key_conv::cast(forward_like<T>(kv.first), policy_key, parent));
132
- auto value = reinterpret_steal<object>(value_conv::cast(forward_like<T>(kv.second), policy_value, parent));
133
- if (!key || !value)
134
- return handle();
135
- d[key] = value;
136
- }
137
- return d.release();
138
- }
139
-
140
- PYBIND11_TYPE_CASTER(Type, _("Dict[") + key_conv::name + _(", ") + value_conv::name + _("]"));
141
- };
142
-
143
- template <typename Type, typename Value> struct list_caster {
144
- using value_conv = make_caster<Value>;
145
-
146
- bool load(handle src, bool convert) {
147
- if (!isinstance<sequence>(src) || isinstance<str>(src))
148
- return false;
149
- auto s = reinterpret_borrow<sequence>(src);
150
- value.clear();
151
- reserve_maybe(s, &value);
152
- for (auto it : s) {
153
- value_conv conv;
154
- if (!conv.load(it, convert))
155
- return false;
156
- value.push_back(cast_op<Value &&>(std::move(conv)));
157
- }
158
- return true;
159
- }
160
-
161
- private:
162
- template <typename T = Type,
163
- enable_if_t<std::is_same<decltype(std::declval<T>().reserve(0)), void>::value, int> = 0>
164
- void reserve_maybe(sequence s, Type *) { value.reserve(s.size()); }
165
- void reserve_maybe(sequence, void *) { }
166
-
167
- public:
168
- template <typename T>
169
- static handle cast(T &&src, return_value_policy policy, handle parent) {
170
- if (!std::is_lvalue_reference<T>::value)
171
- policy = return_value_policy_override<Value>::policy(policy);
172
- list l(src.size());
173
- size_t index = 0;
174
- for (auto &&value : src) {
175
- auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
176
- if (!value_)
177
- return handle();
178
- PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference
179
- }
180
- return l.release();
181
- }
182
-
183
- PYBIND11_TYPE_CASTER(Type, _("List[") + value_conv::name + _("]"));
184
- };
185
-
186
- template <typename Type, typename Alloc> struct type_caster<std::vector<Type, Alloc>>
187
- : list_caster<std::vector<Type, Alloc>, Type> { };
188
-
189
- template <typename Type, typename Alloc> struct type_caster<std::deque<Type, Alloc>>
190
- : list_caster<std::deque<Type, Alloc>, Type> { };
191
-
192
- template <typename Type, typename Alloc> struct type_caster<std::list<Type, Alloc>>
193
- : list_caster<std::list<Type, Alloc>, Type> { };
194
-
195
- template <typename ArrayType, typename Value, bool Resizable, size_t Size = 0> struct array_caster {
196
- using value_conv = make_caster<Value>;
197
-
198
- private:
199
- template <bool R = Resizable>
200
- bool require_size(enable_if_t<R, size_t> size) {
201
- if (value.size() != size)
202
- value.resize(size);
203
- return true;
204
- }
205
- template <bool R = Resizable>
206
- bool require_size(enable_if_t<!R, size_t> size) {
207
- return size == Size;
208
- }
209
-
210
- public:
211
- bool load(handle src, bool convert) {
212
- if (!isinstance<sequence>(src))
213
- return false;
214
- auto l = reinterpret_borrow<sequence>(src);
215
- if (!require_size(l.size()))
216
- return false;
217
- size_t ctr = 0;
218
- for (auto it : l) {
219
- value_conv conv;
220
- if (!conv.load(it, convert))
221
- return false;
222
- value[ctr++] = cast_op<Value &&>(std::move(conv));
223
- }
224
- return true;
225
- }
226
-
227
- template <typename T>
228
- static handle cast(T &&src, return_value_policy policy, handle parent) {
229
- list l(src.size());
230
- size_t index = 0;
231
- for (auto &&value : src) {
232
- auto value_ = reinterpret_steal<object>(value_conv::cast(forward_like<T>(value), policy, parent));
233
- if (!value_)
234
- return handle();
235
- PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference
236
- }
237
- return l.release();
238
- }
239
-
240
- PYBIND11_TYPE_CASTER(ArrayType, _("List[") + value_conv::name + _<Resizable>(_(""), _("[") + _<Size>() + _("]")) + _("]"));
241
- };
242
-
243
- template <typename Type, size_t Size> struct type_caster<std::array<Type, Size>>
244
- : array_caster<std::array<Type, Size>, Type, false, Size> { };
245
-
246
- template <typename Type> struct type_caster<std::valarray<Type>>
247
- : array_caster<std::valarray<Type>, Type, true> { };
248
-
249
- template <typename Key, typename Compare, typename Alloc> struct type_caster<std::set<Key, Compare, Alloc>>
250
- : set_caster<std::set<Key, Compare, Alloc>, Key> { };
251
-
252
- template <typename Key, typename Hash, typename Equal, typename Alloc> struct type_caster<std::unordered_set<Key, Hash, Equal, Alloc>>
253
- : set_caster<std::unordered_set<Key, Hash, Equal, Alloc>, Key> { };
254
-
255
- template <typename Key, typename Value, typename Compare, typename Alloc> struct type_caster<std::map<Key, Value, Compare, Alloc>>
256
- : map_caster<std::map<Key, Value, Compare, Alloc>, Key, Value> { };
257
-
258
- template <typename Key, typename Value, typename Hash, typename Equal, typename Alloc> struct type_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>>
259
- : map_caster<std::unordered_map<Key, Value, Hash, Equal, Alloc>, Key, Value> { };
260
-
261
- // This type caster is intended to be used for std::optional and std::experimental::optional
262
- template<typename T> struct optional_caster {
263
- using value_conv = make_caster<typename T::value_type>;
264
-
265
- template <typename T_>
266
- static handle cast(T_ &&src, return_value_policy policy, handle parent) {
267
- if (!src)
268
- return none().inc_ref();
269
- if (!std::is_lvalue_reference<T>::value) {
270
- policy = return_value_policy_override<T>::policy(policy);
271
- }
272
- return value_conv::cast(*std::forward<T_>(src), policy, parent);
273
- }
274
-
275
- bool load(handle src, bool convert) {
276
- if (!src) {
277
- return false;
278
- } else if (src.is_none()) {
279
- return true; // default-constructed value is already empty
280
- }
281
- value_conv inner_caster;
282
- if (!inner_caster.load(src, convert))
283
- return false;
284
-
285
- value.emplace(cast_op<typename T::value_type &&>(std::move(inner_caster)));
286
- return true;
287
- }
288
-
289
- PYBIND11_TYPE_CASTER(T, _("Optional[") + value_conv::name + _("]"));
290
- };
291
-
292
- #if PYBIND11_HAS_OPTIONAL
293
- template<typename T> struct type_caster<std::optional<T>>
294
- : public optional_caster<std::optional<T>> {};
295
-
296
- template<> struct type_caster<std::nullopt_t>
297
- : public void_caster<std::nullopt_t> {};
298
- #endif
299
-
300
- #if PYBIND11_HAS_EXP_OPTIONAL
301
- template<typename T> struct type_caster<std::experimental::optional<T>>
302
- : public optional_caster<std::experimental::optional<T>> {};
303
-
304
- template<> struct type_caster<std::experimental::nullopt_t>
305
- : public void_caster<std::experimental::nullopt_t> {};
306
- #endif
307
-
308
- /// Visit a variant and cast any found type to Python
309
- struct variant_caster_visitor {
310
- return_value_policy policy;
311
- handle parent;
312
-
313
- using result_type = handle; // required by boost::variant in C++11
314
-
315
- template <typename T>
316
- result_type operator()(T &&src) const {
317
- return make_caster<T>::cast(std::forward<T>(src), policy, parent);
318
- }
319
- };
320
-
321
- /// Helper class which abstracts away variant's `visit` function. `std::variant` and similar
322
- /// `namespace::variant` types which provide a `namespace::visit()` function are handled here
323
- /// automatically using argument-dependent lookup. Users can provide specializations for other
324
- /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`.
325
- template <template<typename...> class Variant>
326
- struct visit_helper {
327
- template <typename... Args>
328
- static auto call(Args &&...args) -> decltype(visit(std::forward<Args>(args)...)) {
329
- return visit(std::forward<Args>(args)...);
330
- }
331
- };
332
-
333
- /// Generic variant caster
334
- template <typename Variant> struct variant_caster;
335
-
336
- template <template<typename...> class V, typename... Ts>
337
- struct variant_caster<V<Ts...>> {
338
- static_assert(sizeof...(Ts) > 0, "Variant must consist of at least one alternative.");
339
-
340
- template <typename U, typename... Us>
341
- bool load_alternative(handle src, bool convert, type_list<U, Us...>) {
342
- auto caster = make_caster<U>();
343
- if (caster.load(src, convert)) {
344
- value = cast_op<U>(caster);
345
- return true;
346
- }
347
- return load_alternative(src, convert, type_list<Us...>{});
348
- }
349
-
350
- bool load_alternative(handle, bool, type_list<>) { return false; }
351
-
352
- bool load(handle src, bool convert) {
353
- // Do a first pass without conversions to improve constructor resolution.
354
- // E.g. `py::int_(1).cast<variant<double, int>>()` needs to fill the `int`
355
- // slot of the variant. Without two-pass loading `double` would be filled
356
- // because it appears first and a conversion is possible.
357
- if (convert && load_alternative(src, false, type_list<Ts...>{}))
358
- return true;
359
- return load_alternative(src, convert, type_list<Ts...>{});
360
- }
361
-
362
- template <typename Variant>
363
- static handle cast(Variant &&src, return_value_policy policy, handle parent) {
364
- return visit_helper<V>::call(variant_caster_visitor{policy, parent},
365
- std::forward<Variant>(src));
366
- }
367
-
368
- using Type = V<Ts...>;
369
- PYBIND11_TYPE_CASTER(Type, _("Union[") + detail::concat(make_caster<Ts>::name...) + _("]"));
370
- };
371
-
372
- #if PYBIND11_HAS_VARIANT
373
- template <typename... Ts>
374
- struct type_caster<std::variant<Ts...>> : variant_caster<std::variant<Ts...>> { };
375
- #endif
376
-
377
- PYBIND11_NAMESPACE_END(detail)
378
-
379
- inline std::ostream &operator<<(std::ostream &os, const handle &obj) {
380
- os << (std::string) str(obj);
381
- return os;
382
- }
383
-
384
- PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
385
-
386
- #if defined(_MSC_VER)
387
- #pragma warning(pop)
388
- #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/detail/complex/csinh.h DELETED
@@ -1,205 +0,0 @@
1
- /*
2
- * Copyright 2008-2013 NVIDIA Corporation
3
- * Copyright 2013 Filipe RNC Maia
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
-
18
- /*-
19
- * Copyright (c) 2005 Bruce D. Evans and Steven G. Kargl
20
- * All rights reserved.
21
- *
22
- * Redistribution and use in source and binary forms, with or without
23
- * modification, are permitted provided that the following conditions
24
- * are met:
25
- * 1. Redistributions of source code must retain the above copyright
26
- * notice unmodified, this list of conditions, and the following
27
- * disclaimer.
28
- * 2. Redistributions in binary form must reproduce the above copyright
29
- * notice, this list of conditions and the following disclaimer in the
30
- * documentation and/or other materials provided with the distribution.
31
- *
32
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42
- */
43
-
44
- /* adapted from FreeBSD:
45
- * lib/msun/src/s_csinh.c
46
- */
47
-
48
-
49
- #pragma once
50
-
51
- #include <thrust/complex.h>
52
- #include <thrust/detail/complex/math_private.h>
53
-
54
- namespace thrust{
55
- namespace detail{
56
- namespace complex{
57
-
58
- using thrust::complex;
59
-
60
- __host__ __device__ inline
61
- complex<double> csinh(const complex<double>& z){
62
- double x, y, h;
63
- uint32_t hx, hy, ix, iy, lx, ly;
64
- const double huge = 8.98846567431157953864652595395e+307; // 0x1p1023;
65
-
66
- x = z.real();
67
- y = z.imag();
68
-
69
- extract_words(hx, lx, x);
70
- extract_words(hy, ly, y);
71
-
72
- ix = 0x7fffffff & hx;
73
- iy = 0x7fffffff & hy;
74
-
75
- /* Handle the nearly-non-exceptional cases where x and y are finite. */
76
- if (ix < 0x7ff00000 && iy < 0x7ff00000) {
77
- if ((iy | ly) == 0)
78
- return (complex<double>(sinh(x), y));
79
- if (ix < 0x40360000) /* small x: normal case */
80
- return (complex<double>(sinh(x) * cos(y), cosh(x) * sin(y)));
81
-
82
- /* |x| >= 22, so cosh(x) ~= exp(|x|) */
83
- if (ix < 0x40862e42) {
84
- /* x < 710: exp(|x|) won't overflow */
85
- h = exp(fabs(x)) * 0.5;
86
- return (complex<double>(copysign(h, x) * cos(y), h * sin(y)));
87
- } else if (ix < 0x4096bbaa) {
88
- /* x < 1455: scale to avoid overflow */
89
- complex<double> z_ = ldexp_cexp(complex<double>(fabs(x), y), -1);
90
- return (complex<double>(z_.real() * copysign(1.0, x), z_.imag()));
91
- } else {
92
- /* x >= 1455: the result always overflows */
93
- h = huge * x;
94
- return (complex<double>(h * cos(y), h * h * sin(y)));
95
- }
96
- }
97
-
98
- /*
99
- * sinh(+-0 +- I Inf) = sign(d(+-0, dNaN))0 + I dNaN.
100
- * The sign of 0 in the result is unspecified. Choice = normally
101
- * the same as dNaN. Raise the invalid floating-point exception.
102
- *
103
- * sinh(+-0 +- I NaN) = sign(d(+-0, NaN))0 + I d(NaN).
104
- * The sign of 0 in the result is unspecified. Choice = normally
105
- * the same as d(NaN).
106
- */
107
- if ((ix | lx) == 0 && iy >= 0x7ff00000)
108
- return (complex<double>(copysign(0.0, x * (y - y)), y - y));
109
-
110
- /*
111
- * sinh(+-Inf +- I 0) = +-Inf + I +-0.
112
- *
113
- * sinh(NaN +- I 0) = d(NaN) + I +-0.
114
- */
115
- if ((iy | ly) == 0 && ix >= 0x7ff00000) {
116
- if (((hx & 0xfffff) | lx) == 0)
117
- return (complex<double>(x, y));
118
- return (complex<double>(x, copysign(0.0, y)));
119
- }
120
-
121
- /*
122
- * sinh(x +- I Inf) = dNaN + I dNaN.
123
- * Raise the invalid floating-point exception for finite nonzero x.
124
- *
125
- * sinh(x + I NaN) = d(NaN) + I d(NaN).
126
- * Optionally raises the invalid floating-point exception for finite
127
- * nonzero x. Choice = don't raise (except for signaling NaNs).
128
- */
129
- if (ix < 0x7ff00000 && iy >= 0x7ff00000)
130
- return (complex<double>(y - y, x * (y - y)));
131
-
132
- /*
133
- * sinh(+-Inf + I NaN) = +-Inf + I d(NaN).
134
- * The sign of Inf in the result is unspecified. Choice = normally
135
- * the same as d(NaN).
136
- *
137
- * sinh(+-Inf +- I Inf) = +Inf + I dNaN.
138
- * The sign of Inf in the result is unspecified. Choice = always +.
139
- * Raise the invalid floating-point exception.
140
- *
141
- * sinh(+-Inf + I y) = +-Inf cos(y) + I Inf sin(y)
142
- */
143
- if (ix >= 0x7ff00000 && ((hx & 0xfffff) | lx) == 0) {
144
- if (iy >= 0x7ff00000)
145
- return (complex<double>(x * x, x * (y - y)));
146
- return (complex<double>(x * cos(y), infinity<double>() * sin(y)));
147
- }
148
-
149
- /*
150
- * sinh(NaN + I NaN) = d(NaN) + I d(NaN).
151
- *
152
- * sinh(NaN +- I Inf) = d(NaN) + I d(NaN).
153
- * Optionally raises the invalid floating-point exception.
154
- * Choice = raise.
155
- *
156
- * sinh(NaN + I y) = d(NaN) + I d(NaN).
157
- * Optionally raises the invalid floating-point exception for finite
158
- * nonzero y. Choice = don't raise (except for signaling NaNs).
159
- */
160
- return (complex<double>((x * x) * (y - y), (x + x) * (y - y)));
161
- }
162
-
163
- __host__ __device__ inline
164
- complex<double> csin(complex<double> z){
165
- /* csin(z) = -I * csinh(I * z) */
166
- z = csinh(complex<double>(-z.imag(), z.real()));
167
- return (complex<double>(z.imag(), -z.real()));
168
- }
169
-
170
- } // namespace complex
171
-
172
- } // namespace detail
173
-
174
- template <typename ValueType>
175
- __host__ __device__
176
- inline complex<ValueType> sin(const complex<ValueType>& z){
177
- const ValueType re = z.real();
178
- const ValueType im = z.imag();
179
- return complex<ValueType>(std::sin(re) * std::cosh(im),
180
- std::cos(re) * std::sinh(im));
181
- }
182
-
183
-
184
- template <typename ValueType>
185
- __host__ __device__
186
- inline complex<ValueType> sinh(const complex<ValueType>& z){
187
- const ValueType re = z.real();
188
- const ValueType im = z.imag();
189
- return complex<ValueType>(std::sinh(re) * std::cos(im),
190
- std::cosh(re) * std::sin(im));
191
- }
192
-
193
- template <>
194
- __host__ __device__
195
- inline complex<double> sin(const complex<double>& z){
196
- return detail::complex::csin(z);
197
- }
198
-
199
- template <>
200
- __host__ __device__
201
- inline complex<double> sinh(const complex<double>& z){
202
- return detail::complex::csinh(z);
203
- }
204
-
205
- } // namespace thrust
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/LIVE/thrust/thrust/iterator/detail/discard_iterator_base.h DELETED
@@ -1,65 +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
- #include <thrust/iterator/counting_iterator.h>
21
- #include <thrust/iterator/iterator_adaptor.h>
22
- #include <thrust/iterator/detail/any_assign.h>
23
- #include <cstddef> // for std::ptrdiff_t
24
-
25
- namespace thrust
26
- {
27
-
28
- // forward declaration of discard_iterator
29
- template<typename> class discard_iterator;
30
-
31
- namespace detail
32
- {
33
-
34
-
35
- template<typename System>
36
- struct discard_iterator_base
37
- {
38
- // XXX value_type should actually be void
39
- // but this interferes with zip_iterator<discard_iterator>
40
- typedef any_assign value_type;
41
- typedef any_assign& reference;
42
- typedef std::ptrdiff_t incrementable;
43
-
44
- typedef typename thrust::counting_iterator<
45
- incrementable,
46
- System,
47
- thrust::random_access_traversal_tag
48
- > base_iterator;
49
-
50
- typedef typename thrust::iterator_adaptor<
51
- discard_iterator<System>,
52
- base_iterator,
53
- value_type,
54
- typename thrust::iterator_system<base_iterator>::type,
55
- typename thrust::iterator_traversal<base_iterator>::type,
56
- reference
57
- > type;
58
- }; // end discard_iterator_base
59
-
60
-
61
- } // end detail
62
-
63
- } // end thrust
64
-
65
-