Commit
·
1648a3f
1
Parent(s):
5f6f96e
Update parquet files (step 111 of 121)
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- spaces/101-5/gpt4free/g4f/.v1/unfinished/t3nsor/README.md +0 -44
- spaces/101-5/gpt4free/g4f/Provider/Providers/EasyChat.py +0 -43
- spaces/101-5/gpt4free/g4f/Provider/Providers/Vercel.py +0 -162
- spaces/1acneusushi/gradio-2dmoleculeeditor/data/3DMark Test Free The Best Way to Compare Your PCs Performance.md +0 -26
- spaces/1acneusushi/gradio-2dmoleculeeditor/data/Dll Injector For Mac.md +0 -154
- spaces/1acneusushi/gradio-2dmoleculeeditor/data/HHD Online Player (Full Hd Raja Ki Aayegi Baaraat Movie) Learn More About the Film and Its Cast.md +0 -132
- spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/A to Z Bhojpuri Video Song Download Stream and Download Bhojpuri Songs from Popular Artists and Movies.md +0 -115
- spaces/1phancelerku/anime-remove-background/Bad 2 Bad Apocalypse - The Ultimate Open World Survival RPG Game APK.md +0 -172
- spaces/1phancelerku/anime-remove-background/Download Real Football Soccer 2023 APK and Become a Soccer Champion.md +0 -109
- spaces/1phancelerku/anime-remove-background/Enjoy Football Strike with MOD APK and Unlimited Money on Android 1.md +0 -83
- spaces/2023Liu2023/bingo/src/lib/hooks/use-bing.ts +0 -173
- spaces/4Taps/SadTalker/src/face3d/models/arcface_torch/configs/base.py +0 -56
- spaces/7hao/bingo/src/components/ui/input.tsx +0 -25
- spaces/AAYUSH27/Neuro/installation_steps.md +0 -43
- spaces/AIGC-Audio/Make_An_Audio_inpaint/vocoder/bigvgan/activations.py +0 -120
- spaces/AISuperheroes/08GR-KitchenSink-AIUIUX/demos/kitchen_sink/files/Readme.md +0 -1
- spaces/Ababababababbababa/Ashaar/poetry_diacritizer/util/text_cleaners.py +0 -146
- spaces/Abhilashvj/planogram-compliance/utils/docker/Dockerfile +0 -66
- spaces/AchyuthGamer/OpenGPT-Chat-UI/src/lib/utils/loadClientCerts.ts +0 -50
- spaces/AiMimicry/sovits-models/modules/modules.py +0 -342
- spaces/Aki004/herta-so-vits/README.md +0 -13
- spaces/AkiKagura/Marco-Generation-Img2img/README.md +0 -13
- spaces/AlexWang/lama/saicinpainting/training/trainers/__init__.py +0 -30
- spaces/Amon1/ChatGPTForAcadamic/crazy_functions/test_project/cpp/cppipc/queue.h +0 -216
- spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +0 -661
- spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_pndm.py +0 -462
- spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/utils/logging.py +0 -339
- spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_diffedit.py +0 -399
- spaces/Andy1621/uniformer_image_detection/configs/vfnet/vfnet_r2_101_fpn_mstrain_2x_coco.py +0 -14
- spaces/Andy1621/uniformer_image_detection/mmdet/apis/test.py +0 -190
- spaces/Andy1621/uniformer_image_segmentation/configs/ccnet/ccnet_r50-d8_512x512_80k_ade20k.py +0 -6
- spaces/Aomsin/Lab10_630510654/README.md +0 -13
- spaces/Arnaudding001/OpenAI_whisperLive/vad.py +0 -468
- spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/util/misc.py +0 -717
- spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/__init__.py +0 -19
- spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/pygments/plugin.py +0 -88
- spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/register.py +0 -18
- spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/modeling/meta_arch/build.py +0 -25
- spaces/Benson/text-generation/Examples/Apk3163.md +0 -84
- spaces/BigSalmon/GPTJ/README.md +0 -37
- spaces/CForGETaass/vits-uma-genshin-honkai/text/__init__.py +0 -57
- spaces/CVH-vn1210/make_hair/minigpt4/common/utils.py +0 -424
- spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/data/transforms/transform_gen.py +0 -447
- spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/grid-feats-vqa/grid_feats/roi_heads.py +0 -253
- spaces/CVPR/LIVE/pybind11/include/pybind11/chrono.h +0 -191
- spaces/CVPR/LIVE/thrust/thrust/system/detail/adl/fill.h +0 -44
- spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/default_decomposition.h +0 -45
- spaces/CVPR/SPOTER_Sign_Language_Recognition/spoter_mod/normalization/hand_normalization.py +0 -192
- spaces/CVPR/WALT/mmdet/datasets/wider_face.py +0 -51
- spaces/Chitranshu/Dashboard-Dmart/README.md +0 -10
spaces/101-5/gpt4free/g4f/.v1/unfinished/t3nsor/README.md
DELETED
@@ -1,44 +0,0 @@
|
|
1 |
-
### note: currently patched
|
2 |
-
|
3 |
-
### Example: `t3nsor` (use like openai pypi package) <a name="example-t3nsor"></a>
|
4 |
-
|
5 |
-
```python
|
6 |
-
# Import t3nsor
|
7 |
-
import t3nsor
|
8 |
-
|
9 |
-
# t3nsor.Completion.create
|
10 |
-
# t3nsor.StreamCompletion.create
|
11 |
-
|
12 |
-
[...]
|
13 |
-
|
14 |
-
```
|
15 |
-
|
16 |
-
#### Example Chatbot
|
17 |
-
```python
|
18 |
-
messages = []
|
19 |
-
|
20 |
-
while True:
|
21 |
-
user = input('you: ')
|
22 |
-
|
23 |
-
t3nsor_cmpl = t3nsor.Completion.create(
|
24 |
-
prompt = user,
|
25 |
-
messages = messages
|
26 |
-
)
|
27 |
-
|
28 |
-
print('gpt:', t3nsor_cmpl.completion.choices[0].text)
|
29 |
-
|
30 |
-
messages.extend([
|
31 |
-
{'role': 'user', 'content': user },
|
32 |
-
{'role': 'assistant', 'content': t3nsor_cmpl.completion.choices[0].text}
|
33 |
-
])
|
34 |
-
```
|
35 |
-
|
36 |
-
#### Streaming Response:
|
37 |
-
|
38 |
-
```python
|
39 |
-
for response in t3nsor.StreamCompletion.create(
|
40 |
-
prompt = 'write python code to reverse a string',
|
41 |
-
messages = []):
|
42 |
-
|
43 |
-
print(response.completion.choices[0].text)
|
44 |
-
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/101-5/gpt4free/g4f/Provider/Providers/EasyChat.py
DELETED
@@ -1,43 +0,0 @@
|
|
1 |
-
import os, requests
|
2 |
-
from ...typing import sha256, Dict, get_type_hints
|
3 |
-
import json
|
4 |
-
|
5 |
-
url = "https://free.easychat.work/api/openai/v1/chat/completions"
|
6 |
-
model = ['gpt-3.5-turbo']
|
7 |
-
supports_stream = False
|
8 |
-
needs_auth = False
|
9 |
-
|
10 |
-
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
|
11 |
-
''' limited to 240 messages/hour'''
|
12 |
-
base = ''
|
13 |
-
for message in messages:
|
14 |
-
base += '%s: %s\n' % (message['role'], message['content'])
|
15 |
-
base += 'assistant:'
|
16 |
-
|
17 |
-
headers = {
|
18 |
-
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
|
19 |
-
}
|
20 |
-
|
21 |
-
data = {
|
22 |
-
"messages": [
|
23 |
-
{"role": "system", "content": "You are ChatGPT, a large language model trained by OpenAI."},
|
24 |
-
{"role": "user", "content": base}
|
25 |
-
],
|
26 |
-
"stream": False,
|
27 |
-
"model": "gpt-3.5-turbo",
|
28 |
-
"temperature": 0.5,
|
29 |
-
"presence_penalty": 0,
|
30 |
-
"frequency_penalty": 0,
|
31 |
-
"top_p": 1
|
32 |
-
}
|
33 |
-
|
34 |
-
response = requests.post(url, headers=headers, json=data)
|
35 |
-
if response.status_code == 200:
|
36 |
-
response = response.json()
|
37 |
-
yield response['choices'][0]['message']['content']
|
38 |
-
else:
|
39 |
-
print(f"Error Occurred::{response.status_code}")
|
40 |
-
return None
|
41 |
-
|
42 |
-
params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \
|
43 |
-
'(%s)' % ', '.join([f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/101-5/gpt4free/g4f/Provider/Providers/Vercel.py
DELETED
@@ -1,162 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import json
|
3 |
-
import base64
|
4 |
-
import execjs
|
5 |
-
import queue
|
6 |
-
import threading
|
7 |
-
|
8 |
-
from curl_cffi import requests
|
9 |
-
from ...typing import sha256, Dict, get_type_hints
|
10 |
-
|
11 |
-
url = 'https://play.vercel.ai'
|
12 |
-
supports_stream = True
|
13 |
-
needs_auth = False
|
14 |
-
|
15 |
-
models = {
|
16 |
-
'claude-instant-v1': 'anthropic:claude-instant-v1',
|
17 |
-
'claude-v1': 'anthropic:claude-v1',
|
18 |
-
'alpaca-7b': 'replicate:replicate/alpaca-7b',
|
19 |
-
'stablelm-tuned-alpha-7b': 'replicate:stability-ai/stablelm-tuned-alpha-7b',
|
20 |
-
'bloom': 'huggingface:bigscience/bloom',
|
21 |
-
'bloomz': 'huggingface:bigscience/bloomz',
|
22 |
-
'flan-t5-xxl': 'huggingface:google/flan-t5-xxl',
|
23 |
-
'flan-ul2': 'huggingface:google/flan-ul2',
|
24 |
-
'gpt-neox-20b': 'huggingface:EleutherAI/gpt-neox-20b',
|
25 |
-
'oasst-sft-4-pythia-12b-epoch-3.5': 'huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5',
|
26 |
-
'santacoder': 'huggingface:bigcode/santacoder',
|
27 |
-
'command-medium-nightly': 'cohere:command-medium-nightly',
|
28 |
-
'command-xlarge-nightly': 'cohere:command-xlarge-nightly',
|
29 |
-
'code-cushman-001': 'openai:code-cushman-001',
|
30 |
-
'code-davinci-002': 'openai:code-davinci-002',
|
31 |
-
'gpt-3.5-turbo': 'openai:gpt-3.5-turbo',
|
32 |
-
'text-ada-001': 'openai:text-ada-001',
|
33 |
-
'text-babbage-001': 'openai:text-babbage-001',
|
34 |
-
'text-curie-001': 'openai:text-curie-001',
|
35 |
-
'text-davinci-002': 'openai:text-davinci-002',
|
36 |
-
'text-davinci-003': 'openai:text-davinci-003'
|
37 |
-
}
|
38 |
-
model = models.keys()
|
39 |
-
|
40 |
-
vercel_models = {'anthropic:claude-instant-v1': {'id': 'anthropic:claude-instant-v1', 'provider': 'anthropic', 'providerHumanName': 'Anthropic', 'makerHumanName': 'Anthropic', 'minBillingTier': 'hobby', 'parameters': {'temperature': {'value': 1, 'range': [0, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'topK': {'value': 1, 'range': [1, 500]}, 'presencePenalty': {'value': 1, 'range': [0, 1]}, 'frequencyPenalty': {'value': 1, 'range': [0, 1]}, 'stopSequences': {'value': ['\n\nHuman:'], 'range': []}}, 'name': 'claude-instant-v1'}, 'anthropic:claude-v1': {'id': 'anthropic:claude-v1', 'provider': 'anthropic', 'providerHumanName': 'Anthropic', 'makerHumanName': 'Anthropic', 'minBillingTier': 'hobby', 'parameters': {'temperature': {'value': 1, 'range': [0, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'topK': {'value': 1, 'range': [1, 500]}, 'presencePenalty': {'value': 1, 'range': [0, 1]}, 'frequencyPenalty': {'value': 1, 'range': [0, 1]}, 'stopSequences': {'value': ['\n\nHuman:'], 'range': []}}, 'name': 'claude-v1'}, 'replicate:replicate/alpaca-7b': {'id': 'replicate:replicate/alpaca-7b', 'provider': 'replicate', 'providerHumanName': 'Replicate', 'makerHumanName': 'Stanford', 'parameters': {'temperature': {'value': 0.75, 'range': [0.01, 5]}, 'maximumLength': {'value': 200, 'range': [50, 512]}, 'topP': {'value': 0.95, 'range': [0.01, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'repetitionPenalty': {'value': 1.1765, 'range': [0.01, 5]}, 'stopSequences': {'value': [], 'range': []}}, 'version': '2014ee1247354f2e81c0b3650d71ca715bc1e610189855f134c30ecb841fae21', 'name': 'alpaca-7b'}, 'replicate:stability-ai/stablelm-tuned-alpha-7b': {'id': 'replicate:stability-ai/stablelm-tuned-alpha-7b', 'provider': 'replicate', 'makerHumanName': 'StabilityAI', 'providerHumanName': 'Replicate', 'parameters': {'temperature': {'value': 0.75, 'range': [0.01, 5]}, 'maximumLength': {'value': 200, 'range': [50, 512]}, 'topP': {'value': 0.95, 'range': [0.01, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'repetitionPenalty': {'value': 1.1765, 'range': [0.01, 5]}, 'stopSequences': {'value': [], 'range': []}}, 'version': '4a9a32b4fd86c2d047f1d271fa93972683ec6ef1cf82f402bd021f267330b50b', 'name': 'stablelm-tuned-alpha-7b'}, 'huggingface:bigscience/bloom': {'id': 'huggingface:bigscience/bloom', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'BigScience', 'instructions': "Do NOT talk to Bloom as an entity, it's not a chatbot but a webpage/blog/article completion model. For the best results: mimic a few words of a webpage similar to the content you want to generate. Start a sentence as if YOU were writing a blog, webpage, math post, coding article and Bloom will generate a coherent follow-up.", 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'bloom'}, 'huggingface:bigscience/bloomz': {'id': 'huggingface:bigscience/bloomz', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'BigScience', 'instructions': 'We recommend using the model to perform tasks expressed in natural language. For example, given the prompt "Translate to English: Je t\'aime.", the model will most likely answer "I love you.".', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'bloomz'}, 'huggingface:google/flan-t5-xxl': {'id': 'huggingface:google/flan-t5-xxl', 'provider': 'huggingface', 'makerHumanName': 'Google', 'providerHumanName': 'HuggingFace', 'name': 'flan-t5-xxl', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}}, 'huggingface:google/flan-ul2': {'id': 'huggingface:google/flan-ul2', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'Google', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'flan-ul2'}, 'huggingface:EleutherAI/gpt-neox-20b': {'id': 'huggingface:EleutherAI/gpt-neox-20b', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'EleutherAI', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'gpt-neox-20b'}, 'huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5': {'id': 'huggingface:OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'OpenAssistant', 'parameters': {'maximumLength': {'value': 200, 'range': [50, 1024]}, 'typicalP': {'value': 0.2, 'range': [0.1, 0.99]}, 'repetitionPenalty': {'value': 1, 'range': [0.1, 2]}}, 'name': 'oasst-sft-4-pythia-12b-epoch-3.5'}, 'huggingface:bigcode/santacoder': {
|
41 |
-
'id': 'huggingface:bigcode/santacoder', 'provider': 'huggingface', 'providerHumanName': 'HuggingFace', 'makerHumanName': 'BigCode', 'instructions': 'The model was trained on GitHub code. As such it is not an instruction model and commands like "Write a function that computes the square root." do not work well. You should phrase commands like they occur in source code such as comments (e.g. # the following function computes the sqrt) or write a function signature and docstring and let the model complete the function body.', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 0.95, 'range': [0.01, 0.99]}, 'topK': {'value': 4, 'range': [1, 500]}, 'repetitionPenalty': {'value': 1.03, 'range': [0.1, 2]}}, 'name': 'santacoder'}, 'cohere:command-medium-nightly': {'id': 'cohere:command-medium-nightly', 'provider': 'cohere', 'providerHumanName': 'Cohere', 'makerHumanName': 'Cohere', 'name': 'command-medium-nightly', 'parameters': {'temperature': {'value': 0.9, 'range': [0, 2]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0, 1]}, 'topK': {'value': 0, 'range': [0, 500]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'cohere:command-xlarge-nightly': {'id': 'cohere:command-xlarge-nightly', 'provider': 'cohere', 'providerHumanName': 'Cohere', 'makerHumanName': 'Cohere', 'name': 'command-xlarge-nightly', 'parameters': {'temperature': {'value': 0.9, 'range': [0, 2]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0, 1]}, 'topK': {'value': 0, 'range': [0, 500]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:gpt-4': {'id': 'openai:gpt-4', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'gpt-4', 'minBillingTier': 'pro', 'parameters': {'temperature': {'value': 0.7, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:code-cushman-001': {'id': 'openai:code-cushman-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'code-cushman-001'}, 'openai:code-davinci-002': {'id': 'openai:code-davinci-002', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'code-davinci-002'}, 'openai:gpt-3.5-turbo': {'id': 'openai:gpt-3.5-turbo', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'parameters': {'temperature': {'value': 0.7, 'range': [0, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'topK': {'value': 1, 'range': [1, 500]}, 'presencePenalty': {'value': 1, 'range': [0, 1]}, 'frequencyPenalty': {'value': 1, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}, 'name': 'gpt-3.5-turbo'}, 'openai:text-ada-001': {'id': 'openai:text-ada-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-ada-001', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-babbage-001': {'id': 'openai:text-babbage-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-babbage-001', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-curie-001': {'id': 'openai:text-curie-001', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-curie-001', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-davinci-002': {'id': 'openai:text-davinci-002', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-davinci-002', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}, 'openai:text-davinci-003': {'id': 'openai:text-davinci-003', 'provider': 'openai', 'providerHumanName': 'OpenAI', 'makerHumanName': 'OpenAI', 'name': 'text-davinci-003', 'parameters': {'temperature': {'value': 0.5, 'range': [0.1, 1]}, 'maximumLength': {'value': 200, 'range': [50, 1024]}, 'topP': {'value': 1, 'range': [0.1, 1]}, 'presencePenalty': {'value': 0, 'range': [0, 1]}, 'frequencyPenalty': {'value': 0, 'range': [0, 1]}, 'stopSequences': {'value': [], 'range': []}}}}
|
42 |
-
|
43 |
-
|
44 |
-
# based on https://github.com/ading2210/vercel-llm-api // modified
|
45 |
-
class Client:
|
46 |
-
def __init__(self):
|
47 |
-
self.session = requests.Session()
|
48 |
-
self.headers = {
|
49 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110 Safari/537.36',
|
50 |
-
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
|
51 |
-
'Accept-Encoding': 'gzip, deflate, br',
|
52 |
-
'Accept-Language': 'en-US,en;q=0.5',
|
53 |
-
'Te': 'trailers',
|
54 |
-
'Upgrade-Insecure-Requests': '1'
|
55 |
-
}
|
56 |
-
self.session.headers.update(self.headers)
|
57 |
-
|
58 |
-
def get_token(self):
|
59 |
-
b64 = self.session.get('https://sdk.vercel.ai/openai.jpeg').text
|
60 |
-
data = json.loads(base64.b64decode(b64))
|
61 |
-
|
62 |
-
code = 'const globalThis = {data: `sentinel`}; function token() {return (%s)(%s)}' % (
|
63 |
-
data['c'], data['a'])
|
64 |
-
|
65 |
-
token_string = json.dumps(separators=(',', ':'),
|
66 |
-
obj={'r': execjs.compile(code).call('token'), 't': data['t']})
|
67 |
-
|
68 |
-
return base64.b64encode(token_string.encode()).decode()
|
69 |
-
|
70 |
-
def get_default_params(self, model_id):
|
71 |
-
return {key: param['value'] for key, param in vercel_models[model_id]['parameters'].items()}
|
72 |
-
|
73 |
-
def generate(self, model_id: str, prompt: str, params: dict = {}):
|
74 |
-
if not ':' in model_id:
|
75 |
-
model_id = models[model_id]
|
76 |
-
|
77 |
-
defaults = self.get_default_params(model_id)
|
78 |
-
|
79 |
-
payload = defaults | params | {
|
80 |
-
'prompt': prompt,
|
81 |
-
'model': model_id,
|
82 |
-
}
|
83 |
-
|
84 |
-
headers = self.headers | {
|
85 |
-
'Accept-Encoding': 'gzip, deflate, br',
|
86 |
-
'Custom-Encoding': self.get_token(),
|
87 |
-
'Host': 'sdk.vercel.ai',
|
88 |
-
'Origin': 'https://sdk.vercel.ai',
|
89 |
-
'Referrer': 'https://sdk.vercel.ai',
|
90 |
-
'Sec-Fetch-Dest': 'empty',
|
91 |
-
'Sec-Fetch-Mode': 'cors',
|
92 |
-
'Sec-Fetch-Site': 'same-origin',
|
93 |
-
}
|
94 |
-
|
95 |
-
chunks_queue = queue.Queue()
|
96 |
-
error = None
|
97 |
-
response = None
|
98 |
-
|
99 |
-
def callback(data):
|
100 |
-
chunks_queue.put(data.decode())
|
101 |
-
|
102 |
-
def request_thread():
|
103 |
-
nonlocal response, error
|
104 |
-
for _ in range(3):
|
105 |
-
try:
|
106 |
-
response = self.session.post('https://sdk.vercel.ai/api/generate',
|
107 |
-
json=payload, headers=headers, content_callback=callback)
|
108 |
-
response.raise_for_status()
|
109 |
-
|
110 |
-
except Exception as e:
|
111 |
-
if _ == 2:
|
112 |
-
error = e
|
113 |
-
|
114 |
-
else:
|
115 |
-
continue
|
116 |
-
|
117 |
-
thread = threading.Thread(target=request_thread, daemon=True)
|
118 |
-
thread.start()
|
119 |
-
|
120 |
-
text = ''
|
121 |
-
index = 0
|
122 |
-
while True:
|
123 |
-
try:
|
124 |
-
chunk = chunks_queue.get(block=True, timeout=0.1)
|
125 |
-
|
126 |
-
except queue.Empty:
|
127 |
-
if error:
|
128 |
-
raise error
|
129 |
-
|
130 |
-
elif response:
|
131 |
-
break
|
132 |
-
|
133 |
-
else:
|
134 |
-
continue
|
135 |
-
|
136 |
-
text += chunk
|
137 |
-
lines = text.split('\n')
|
138 |
-
|
139 |
-
if len(lines) - 1 > index:
|
140 |
-
new = lines[index:-1]
|
141 |
-
for word in new:
|
142 |
-
yield json.loads(word)
|
143 |
-
index = len(lines) - 1
|
144 |
-
|
145 |
-
def _create_completion(model: str, messages: list, stream: bool, **kwargs):
|
146 |
-
yield 'Vercel is currently not working.'
|
147 |
-
return
|
148 |
-
|
149 |
-
conversation = 'This is a conversation between a human and a language model, respond to the last message accordingly, referring to the past history of messages if needed.\n'
|
150 |
-
|
151 |
-
for message in messages:
|
152 |
-
conversation += '%s: %s\n' % (message['role'], message['content'])
|
153 |
-
|
154 |
-
conversation += 'assistant: '
|
155 |
-
|
156 |
-
completion = Client().generate(model, conversation)
|
157 |
-
|
158 |
-
for token in completion:
|
159 |
-
yield token
|
160 |
-
|
161 |
-
params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \
|
162 |
-
'(%s)' % ', '.join([f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1acneusushi/gradio-2dmoleculeeditor/data/3DMark Test Free The Best Way to Compare Your PCs Performance.md
DELETED
@@ -1,26 +0,0 @@
|
|
1 |
-
|
2 |
-
<h1>How to Run a 3DMark Test Free on Your PC</h1>
|
3 |
-
<p>If you want to benchmark your PC's performance and compare it with other systems, you might want to try 3DMark, a popular and comprehensive tool for testing graphics and gaming capabilities. But how can you run a 3DMark test free on your PC? Here are some options you can consider.</p>
|
4 |
-
<h2>Download the Free Version of 3DMark</h2>
|
5 |
-
<p>One of the easiest ways to run a 3DMark test free on your PC is to download the free version of 3DMark from Steam or the official website. The free version includes several tests that cover different scenarios, such as Time Spy for DirectX 12, Fire Strike for DirectX 11, Night Raid for integrated graphics, and more. You can also compare your results online with other users and see how your PC ranks among them.</p>
|
6 |
-
<h2>3dmark test free</h2><br /><p><b><b>Download File</b> --->>> <a href="https://byltly.com/2uKv5P">https://byltly.com/2uKv5P</a></b></p><br /><br />
|
7 |
-
<h2>Use the Free Trial of 3DMark Advanced Edition</h2>
|
8 |
-
<p>If you want to access more features and tests that are not available in the free version, you can use the free trial of 3DMark Advanced Edition for 14 days. The Advanced Edition lets you customize your tests, run stress tests, monitor your hardware, and unlock more benchmarks, such as Port Royal for ray tracing, Wild Life for mobile devices, and more. You can also export your results as XML files and use them for further analysis.</p>
|
9 |
-
<h2>Get a Free Key for 3DMark Advanced Edition</h2>
|
10 |
-
<p>Another way to run a 3DMark test free on your PC is to get a free key for 3DMark Advanced Edition from various sources. For example, you might get a free key when you buy a new graphics card or a gaming laptop from certain brands or retailers. You might also find a free key in some giveaways or promotions that are occasionally held by 3DMark or its partners. Just make sure to check the validity and terms of use of the key before you redeem it.</p>
|
11 |
-
<h3>Conclusion</h3>
|
12 |
-
<p>Running a 3DMark test free on your PC is not difficult if you know where to look. You can either download the free version of 3DMark, use the free trial of 3DMark Advanced Edition, or get a free key for 3DMark Advanced Edition from various sources. By doing so, you can benchmark your PC's performance and see how it compares with other systems.</p>
|
13 |
-
<p></p>
|
14 |
-
|
15 |
-
<h3>How to Interpret Your 3DMark Test Results</h3>
|
16 |
-
<p>After running a 3DMark test free on your PC, you might wonder what your results mean and how to use them. Here are some tips on how to interpret your 3DMark test results.</p>
|
17 |
-
<h4>Check Your Score and Compare It with Others</h4>
|
18 |
-
<p>The most obvious thing to look at is your score, which is a numerical value that reflects your PC's performance in the test. The higher the score, the better the performance. You can also compare your score with other users who have similar hardware or run the same test. This can help you see how your PC stacks up against the competition and identify any potential issues or bottlenecks.</p>
|
19 |
-
<h4>Look at Your Frame Rate and Stability</h4>
|
20 |
-
<p>Another thing to look at is your frame rate, which is the number of frames per second (FPS) that your PC can render in the test. The higher the frame rate, the smoother the gameplay. You can also look at your frame rate stability, which is the percentage of frames that meet or exceed a certain threshold. The higher the stability, the more consistent the performance. You can use these metrics to evaluate your PC's gaming experience and see if it meets your expectations or needs.</p>
|
21 |
-
<h4>Analyze Your Hardware Usage and Temperature</h4>
|
22 |
-
<p>A third thing to look at is your hardware usage and temperature, which are the percentage of resources that your CPU and GPU are using in the test and their respective temperatures. The higher the usage, the more workload your hardware is handling. The higher the temperature, the more heat your hardware is generating. You can use these metrics to monitor your PC's health and efficiency and see if it needs any optimization or cooling.</p>
|
23 |
-
<h3>Conclusion</h3>
|
24 |
-
<p>Running a 3DMark test free on your PC can help you benchmark your PC's performance and compare it with other systems. However, you also need to know how to interpret your 3DMark test results and use them for further improvement or analysis. By checking your score, frame rate, stability, hardware usage, and temperature, you can gain more insights into your PC's capabilities and limitations.</p> ddb901b051<br />
|
25 |
-
<br />
|
26 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Dll Injector For Mac.md
DELETED
@@ -1,154 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>DLL Injector for Mac: Everything You Need to Know</h1>
|
3 |
-
<p>If you are a developer, hacker, or gamer, you may have heard of DLL injection. It is a technique that allows you to modify the behavior of a running program by injecting your own code into it. But what exactly is a DLL injector and how does it work? And more importantly, how can you use it on a Mac system?</p>
|
4 |
-
<p>In this article, we will answer these questions and more. We will explain what a DLL injector is, what are its benefits and risks, and how it works on Windows and Mac systems. We will also review some of the best DLL injectors for Mac and show you how to use them. By the end of this article, you will have a clear understanding of DLL injection and how to apply it on your Mac.</p>
|
5 |
-
<h2>Dll Injector For Mac</h2><br /><p><b><b>Download Zip</b> … <a href="https://byltly.com/2uKyhY">https://byltly.com/2uKyhY</a></b></p><br /><br />
|
6 |
-
<h2>What is a DLL injector and why would someone use it?</h2>
|
7 |
-
<p>A DLL injector is a tool that can inject dynamic-link libraries (DLLs) into processes in order to execute arbitrary code in their address space. A DLL is a file that contains executable functions or resources that can be used by other programs. By injecting a DLL into a process, you can modify its functionality or add new features to it.</p>
|
8 |
-
<p>There are many reasons why someone would use a DLL injector. Some of them are:</p>
|
9 |
-
<ul>
|
10 |
-
<li>To enhance the performance or functionality of a program. For example, you can inject a DLL that improves the graphics or adds new features to a game.</li>
|
11 |
-
<li>To debug or test a program. For example, you can inject a DLL that logs or monitors the activity or output of a program.</li>
|
12 |
-
<li>To bypass security or anti-cheat mechanisms. For example, you can inject a DLL that disables or circumvents the protection or detection of a program.</li>
|
13 |
-
<li>To perform malicious actions. For example, you can inject a DLL that steals information or damages the system of a program.</li>
|
14 |
-
</ul>
|
15 |
-
<p>As you can see, DLL injection can be used for both legitimate and illegitimate purposes. It depends on the intention and ethics of the user.</p>
|
16 |
-
<h2>What are the benefits and risks of DLL injection?</h2>
|
17 |
-
<p>DLL injection has both benefits and risks. Some of the benefits are:</p>
|
18 |
-
<ul>
|
19 |
-
<li>It allows you to modify or extend the functionality of a program without modifying its source code or binary file.</li>
|
20 |
-
<li>It allows you to execute code in the context of another process, which may grant you access to its memory, resources, or privileges.</li>
|
21 |
-
<li>It allows you to evade detection or protection from security products or mechanisms, since your code is masked under a legitimate process.</li>
|
22 |
-
</ul>
|
23 |
-
<p>Some of the risks are:</p>
|
24 |
-
<ul>
|
25 |
-
<li>It may cause instability or crashes in the target process or system, especially if the injected code is poorly written or incompatible.</li>
|
26 |
-
<li>It may expose your system to malware or attacks, especially if the injected code is malicious or compromised.</li>
|
27 |
-
<li>It may violate the terms of service or license agreement of the target program or system, especially if the injected code alters its functionality or performance.</li>
|
28 |
-
</ul>
|
29 |
-
<p>Therefore, Therefore, you should use DLL injection with caution and responsibility. You should also respect the rights and privacy of the target program or system and its users. DLL injection can be a powerful and useful technique, but it can also be a dangerous and unethical one.</p>
|
30 |
-
<h2>How does DLL injection work on Windows and Mac systems?</h2>
|
31 |
-
<p>DLL injection works differently on Windows and Mac systems, since they have different operating systems and architectures. Here is a brief overview of how DLL injection works on each system:</p>
|
32 |
-
<p></p>
|
33 |
-
<h3>Windows</h3>
|
34 |
-
<p>On Windows, DLL injection is relatively easy and common, since Windows supports loading DLLs dynamically at runtime. There are several methods of DLL injection on Windows, but the most popular one is the following:</p>
|
35 |
-
<ol>
|
36 |
-
<li>Find the process ID (PID) of the target process using tools like Task Manager or Process Explorer.</li>
|
37 |
-
<li>Open a handle to the target process using the OpenProcess function with the PROCESS_ALL_ACCESS flag.</li>
|
38 |
-
<li>Allocate memory in the target process using the VirtualAllocEx function with the MEM_COMMIT | MEM_RESERVE flags and the PAGE_EXECUTE_READWRITE protection.</li>
|
39 |
-
<li>Write the path of the DLL to be injected into the allocated memory using the WriteProcessMemory function.</li>
|
40 |
-
<li>Create a remote thread in the target process using the CreateRemoteThread function with the address of the LoadLibrary function as the start address and the address of the allocated memory as the parameter.</li>
|
41 |
-
<li>Wait for the remote thread to finish using the WaitForSingleObject function.</li>
|
42 |
-
<li>Close the handle to the target process using the CloseHandle function.</li>
|
43 |
-
</ol>
|
44 |
-
<p>This method essentially loads the DLL into the target process by calling the LoadLibrary function from a remote thread. The LoadLibrary function is a Windows API function that loads a DLL into the calling process and returns its base address. By passing the path of the DLL as a parameter, you can load any DLL you want into the target process.</p>
|
45 |
-
<h3>Mac</h3>
|
46 |
-
<p>On Mac, DLL injection is more difficult and rare, since Mac does not support loading DLLs dynamically at runtime. Mac uses dynamic libraries (dylibs) instead of DLLs, which are similar but not exactly the same. Dylibs are loaded at launch time by a program called dyld, which is responsible for resolving dependencies and linking symbols. There are a few methods of DLL injection on Mac, but one of them is the following:</p>
|
47 |
-
<ol>
|
48 |
-
<li>Find the process ID (PID) of the target process using tools like Activity Monitor or ps.</li>
|
49 |
-
<li>Attach to the target process using the ptrace function with the PT_ATTACH request.</li>
|
50 |
-
<li>Suspend the target process using the kill function with the SIGSTOP signal.</li>
|
51 |
-
<li>Allocate memory in the target process using the mach_vm_allocate function with the VM_FLAGS_ANYWHERE flag.</li>
|
52 |
-
<li>Write a shellcode that calls dlopen into the allocated memory using the mach_vm_write function. dlopen is a POSIX function that loads a dynamic library into memory and returns its handle.</li>
|
53 |
-
<li>Write a pointer to the path of the dylib to be injected after the shellcode using mach_vm_write again.</li>
|
54 |
-
<li>Set a breakpoint at an instruction in the target process using mach_vm_protect with VM_PROT_EXECUTE | VM_PROT_READ | VM_PROT_COPY flags and VM_PROT_ALL protection.</li>
|
55 |
-
<li>Resume Resume the target process using the kill function with the SIGCONT signal.</li>
|
56 |
-
<li>Wait for the breakpoint to be hit using the waitpid function.</li>
|
57 |
-
<li>Read the registers of the target process using the ptrace function with the PT_GETREGS request.</li>
|
58 |
-
<li>Modify the instruction pointer register to point to the shellcode using the ptrace function with the PT_SETREGS request.</li>
|
59 |
-
<li>Resume the target process using the ptrace function with the PT_DETACH request.</li>
|
60 |
-
</ol>
|
61 |
-
<p>This method essentially executes the shellcode in the target process by hijacking its execution flow. The shellcode calls dlopen with the path of the dylib as a parameter, which loads the dylib into memory. By setting a breakpoint at an instruction, you can pause the target process and change its instruction pointer to point to your shellcode.</p>
|
62 |
-
<h2>Best DLL injectors for Mac</h2>
|
63 |
-
<p>Now that you know how DLL injection works on Mac, you may be wondering what are some of the best DLL injectors for Mac. There are not many DLL injectors for Mac, since it is a more challenging and less common technique than on Windows. However, we have found three DLL injectors for Mac that are worth mentioning. They are:</p>
|
64 |
-
<h3>Luject</h3>
|
65 |
-
<p>Luject is a static injector of dynamic library for application (android, iphoneos, macOS, windows, linux) . It is a command-line tool that can inject a dylib into an executable file before launching it. It works by modifying the Mach-O header of the executable file and adding a new load command that points to the dylib. It supports both 32-bit and 64-bit architectures and can inject multiple dylibs at once.</p>
|
66 |
-
<p>Some of the features, pros, and cons of Luject are:</p>
|
67 |
-
<table>
|
68 |
-
<tr><th>Features</th><th>Pros</th><th>Cons</th></tr>
|
69 |
-
<tr><td>- Static injection of dylib into executable file<br>- Support for multiple architectures and platforms<br>- Support for multiple dylibs injection<br>- Easy to use command-line interface</td><td>- Fast and reliable injection<br>- No need to attach to or modify running processes<br>- Compatible with most executable files<br>- Free and open-source</td><td>- Cannot inject into already running processes<br>- Cannot unload or remove injected dylibs<br>- May trigger anti-tampering mechanisms or checksums</td></tr>
|
70 |
-
</table>
|
71 |
-
<h3>Pyinjector</h3>
|
72 |
-
<p>Pyinjector is a Python tool to inject shared libraries into running processes . It is a script that can inject a dylib into a process using the method described in the previous section. It works by attaching to the process, allocating memory, writing shellcode and dylib path, setting a breakpoint, modifying registers, and resuming execution. It supports both 32-bit and 64-bit architectures and can inject multiple dylibs at once.</p>
|
73 |
-
<p>Some of the features, pros, and cons of Pyinjector are:</p>
|
74 |
-
<table>
|
75 |
-
<tr><th>Features</th><th>Pros</th><th>Cons</th></tr>
|
76 |
-
<tr><td>- Dynamic injection of dylib into running process<br>- Support for multiple architectures<br>- Support for multiple dylibs injection<br>- Written in Python and easy to modify or extend</td><td>- Flexible and versatile injection<br>- Can inject into any running process<br>- Can unload or remove injected dylibs<br>- Free and open-source</td><td>- Slow and unstable injection<br>- May cause crashes or errors in target process or system<br>- May be detected or blocked by security products or mechanisms</td></tr>
|
77 |
-
</table>
|
78 |
-
<h3>SocketHook</h3>
|
79 |
-
<p>SocketHook is an injector based on EasyHook (win only) that redirects the traffic to your local server . It is a tool that can inject a dylib into a process that uses network sockets. It works by hooking the socket functions in the target process and redirecting them to your local server. You can then intercept, modify, or spoof the network traffic between the target process and its destination. It supports both 32-bit and 64-bit architectures and can inject multiple dylibs at once.</p>
|
80 |
-
<p>Some of the features, pros, and cons of SocketHook are:</p>
|
81 |
-
<table>
|
82 |
-
<tr><th>Features</th><th>Pros</th><th>Cons</th></tr>
|
83 |
-
<tr><td>- Dynamic injection of dylib into socket-using process<br>- Support for multiple architectures<br>- Support for multiple dylibs injection<br>- Based on EasyHook framework and easy to use</td><td>- Powerful and stealthy injection<br>- Can manipulate network traffic of target process<br>- Can bypass encryption or authentication mechanisms<br>- Free and open-source</td><td>- Limited to socket-using processes - Limited to socket-using processes<br>- May cause network latency or congestion<br>- May be detected or blocked by firewall or antivirus products</td></tr>
|
84 |
-
</table>
|
85 |
-
<h2>How to use DLL injectors for Mac</h2>
|
86 |
-
<p>Now that you know some of the best DLL injectors for Mac, you may be wondering how to use them. In this section, we will show you a step-by-step guide for using Luject, Pyinjector, and SocketHook. We will assume that you have already downloaded and installed the tools on your Mac. We will also assume that you have a target process and a dylib that you want to inject.</p>
|
87 |
-
<h3>Using Luject</h3>
|
88 |
-
<p>To use Luject, follow these steps:</p>
|
89 |
-
<ol>
|
90 |
-
<li>Open a terminal and navigate to the directory where Luject is located.</li>
|
91 |
-
<li>Run the following command to inject a dylib into an executable file:<br><code>./luject -i <dylib_path> -o <output_path> <executable_path></code><br>For example, if you want to inject test.dylib into test.app and save the output as test_injected.app, run:<br><code>./luject -i test.dylib -o test_injected.app test.app</code></li>
|
92 |
-
<li>Run the following command to launch the injected executable file:<br><code>open <output_path></code><br>For example, if you saved the output as test_injected.app, run:<br><code>open test_injected.app</code></li>
|
93 |
-
<li>Enjoy the injected program.</li>
|
94 |
-
</ol>
|
95 |
-
<h3>Using Pyinjector</h3>
|
96 |
-
<p>To use Pyinjector, follow these steps:</p>
|
97 |
-
<ol>
|
98 |
-
<li>Open a terminal and navigate to the directory where Pyinjector is located.</li>
|
99 |
-
<li>Run the following command to inject a dylib into a running process:<br><code>python pyinjector.py -p <pid> -d <dylib_path></code><br>For example, if you want to inject test.dylib into a process with PID 1234, run:<br><code>python pyinjector.py -p 1234 -d test.dylib</code></li>
|
100 |
-
<li>Wait for the injection to complete.</li>
|
101 |
-
<li>Enjoy the injected program.</li>
|
102 |
-
</ol>
|
103 |
-
<h3>Using SocketHook</h3>
|
104 |
-
<p>To use SocketHook, follow these steps:</p>
|
105 |
-
<ol>
|
106 |
-
<li>Open a terminal and navigate to the directory where SocketHook is located.</li>
|
107 |
-
<li>Run the following command to start a local server that listens on port 8080:<br><code>python server.py 8080</code></li>
|
108 |
-
<li>Run the following command to inject a dylib into a running process that uses network sockets:<br><code>./sockethook -p <pid> -d <dylib_path></code><br>For example, if you want to inject test.dylib into a process with PID 1234, run:<br><code>./sockethook -p 1234 -d test.dylib</code></li>
|
109 |
-
<li>Wait for the injection to complete.</li>
|
110 |
-
<li>Enjoy the injected program and its network traffic.</li>
|
111 |
-
</ol>
|
112 |
-
<h2>Tips and tricks for successful DLL injection</h2>
|
113 |
-
<p>DLL injection can be tricky and risky, especially on Mac systems. Here are some tips and tricks that can help you achieve successful DLL injection:</p>
|
114 |
-
<ul>
|
115 |
-
<li>Make sure that your dylib is compatible with the target process and system. For example, if the target process is 64-bit, your dylib should also be 64-bit. If the target system is macOS Big Sur, your dylib should also be compatible with macOS Big Sur.</li>
|
116 |
-
<li>Make sure that your dylib does not interfere with the normal functionality or stability of the target process or system. For example, if your dylib hooks or modifies critical functions or resources, it may cause crashes or errors in the target process or system.</li>
|
117 |
-
<li>Make sure that your dylib does not expose your system to malware or attacks. For example, if your dylib downloads or executes external code or data, it may compromise your system security or privacy.</li>
|
118 |
-
<li>Make sure that your dylib does not violate the terms of service or license agreement of the target process or system. For example, if your dylib alters the functionality or performance of a game, it may result in a ban or legal action from the game developer or publisher.</li>
|
119 |
-
<li>Make sure that you have permission and consent from the target process or system and its users. For example, if you inject a dylib into a process or system that belongs to someone else, you should inform them and obtain their permission and consent before doing so.</li>
|
120 |
-
</ul>
|
121 |
-
<h2>Common errors and troubleshooting</h2>
|
122 |
-
<p>DLL injection can also encounter some errors and problems, especially on Mac systems. Here are some of the common errors and troubleshooting tips that can help you solve them:</p>
|
123 |
-
<ul>
|
124 |
-
<li>If you get an error message that says "Operation not permitted" or "Permission denied", it may mean that you do not have enough privileges or permissions to inject a dylib into the target process or system. You may need to run the DLL injector as root or administrator, or disable some security features or mechanisms that prevent DLL injection.</li>
|
125 |
-
<li>If you get an error message that says "No such file or directory" or "File not found", it may mean that the path of the dylib or the executable file is incorrect or invalid. You may need to check the spelling, case, or location of the files and make sure they exist and are accessible.</li>
|
126 |
-
<li>If you get an error message that says "Bad CPU type in executable" or "Incompatible library version", it may mean that the architecture or version of the dylib or the executable file is mismatched or incompatible. You may need to compile or download the correct version of the files and make sure they match the target process and system.</li>
|
127 |
-
<li>If you get an error message that says "Segmentation fault" or "Bus error", it may mean that the injected code has caused a memory access violation or a hardware error in the target process or system. You may need to debug or test your code and make sure it does not corrupt or overwrite any memory regions or registers.</li>
|
128 |
-
</ul>
|
129 |
-
<h2>Conclusion</h2>
|
130 |
-
<p>DLL injection is a technique that allows you to inject dynamic-link libraries into processes in order to execute arbitrary code in their address space. It can be used for both legitimate and illegitimate purposes, depending on the intention and ethics of the user. It has both benefits and risks, and it works differently on Windows and Mac systems.</p>
|
131 |
-
<p>In this article, we have explained what a DLL injector is, what are its benefits and risks, and how it works on Windows and Mac systems. We have also reviewed some of the best DLL injectors for Mac and showed you how to use them. We have also provided some tips and tricks for successful DLL injection and some common errors and troubleshooting tips.</p>
|
132 |
-
<p>We hope that this article has been informative and helpful for you. If you want to learn more about DLL injection or other related topics, you can check out these resources:</p>
|
133 |
-
<ul>
|
134 |
-
<li>[Luject: A static injector of dynamic library for application (android, iphoneos, macOS, windows, linux) ]</li>
|
135 |
-
<li>[Pyinjector: A Python tool to inject shared libraries into running processes ]</li>
|
136 |
-
<li>[SocketHook: An injector based on EasyHook (win only) that redirects the traffic to your local server ]</li>
|
137 |
-
<li>[DLL Injection - Wikipedia ](https://en.wikipedia.org/wiki/DLL_injection)</li>
|
138 |
-
<li>[Mach-O - Wikipedia ](https://en.wikipedia.org/wiki/Mach-O)</li>
|
139 |
-
<li>[Dynamic loading - Wikipedia ](https://en.wikipedia.org/wiki/Dynamic_loading)</li>
|
140 |
-
</ul>
|
141 |
-
<h2>FAQs</h2>
|
142 |
-
<p>Here are some frequently asked questions about DLL injection:</p>
|
143 |
-
<h3>What is the difference between DLL injection and code injection?</h3>
|
144 |
-
<p>DLL injection is a type of code injection, which is a general term for any technique that injects code into a process. DLL injection specifically injects dynamic-link libraries into processes, while code injection can inject any type of code, such as shellcode, scripts, or bytecode.</p>
|
145 |
-
<h3>How can I detect and prevent DLL injection attacks?</h3>
|
146 |
-
<p>DLL injection attacks can be detected and prevented by using various security products or mechanisms, such as antivirus software, firewall software, anti-debugging techniques, code signing techniques, integrity checking techniques, sandboxing techniques, etc. These products or mechanisms can monitor, block, or alert any suspicious or unauthorized DLL injection attempts.</p>
|
147 |
-
<h3>What are some legitimate uses of DLL injection?</h3>
|
148 |
-
<p>Some legitimate uses of DLL injection are enhancing the performance or functionality of a program, debugging or testing a program, bypassing security or anti-cheat mechanisms for research or educational purposes, etc. However, these uses should be done with permission and consent from the target program or system and its users.</p>
|
149 |
-
<h3>What are some alternatives to DLL injection?</h3>
|
150 |
-
<p>Some alternatives to DLL injection are static linking, dynamic loading, hooking, patching, inter-process communication, etc. These alternatives can achieve similar results as DLL injection without injecting code into processes. However, they may have their own advantages and disadvantages depending on the situation.</p>
|
151 |
-
<h3>Is DLL injection illegal or unethical?</ <h3>Is DLL injection illegal or unethical?</h3>
|
152 |
-
<p>DLL injection is not inherently illegal or unethical, but it depends on the intention and ethics of the user and the target program or system and its users. DLL injection can be illegal or unethical if it violates the law, the terms of service, the license agreement, or the rights and privacy of the target program or system and its users. DLL injection can also be illegal or unethical if it causes harm or damage to the target program or system and its users. Therefore, you should use DLL injection with caution and responsibility and respect the law and the ethics.</p> b2dd77e56b<br />
|
153 |
-
<br />
|
154 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1acneusushi/gradio-2dmoleculeeditor/data/HHD Online Player (Full Hd Raja Ki Aayegi Baaraat Movie) Learn More About the Film and Its Cast.md
DELETED
@@ -1,132 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<br> - Benefits: List the advantages of using HHD Online Player for watching movies online <br> - Features: Highlight the main features of HHD Online Player such as quality, speed, security, and compatibility | | H2: How to watch Raja Ki Aayegi Baaraat movie online with HHD Online Player | - Step 1: Download and install HHD Online Player on your device <br> - Step 2: Search for Raja Ki Aayegi Baaraat movie on HHD Online Player <br> - Step 3: Select the desired quality and language options <br> - Step 4: Enjoy watching Raja Ki Aayegi Baaraat movie online with HHD Online Player | | H3: What is Raja Ki Aayegi Baaraat movie about and why you should watch it | - Plot summary: Give a brief overview of the story and the main characters of Raja Ki Aayegi Baaraat movie <br> - Reviews and ratings: Share some positive feedback and ratings from critics and audiences for Raja Ki Aayegi Baaraat movie <br> - Trivia and facts: Share some interesting facts and trivia about Raja Ki Aayegi Baaraat movie such as awards, box office, and behind-the-scenes | | H4: Conclusion and FAQs | - Conclusion: Summarize the main points of the article and encourage the readers to watch Raja Ki Aayegi Baaraat movie online with HHD Online Player <br> - FAQs: Answer some common questions that the readers might have about HHD Online Player or Raja Ki Aayegi Baaraat movie | **Table 2: Article with HTML formatting** <h1>What is HHD Online Player and why you should use it</h1>
|
3 |
-
<p>If you are a movie lover who likes to watch movies online, you might have heard of HHD Online Player. But what is it exactly and why should you use it? In this article, we will tell you everything you need to know about HHD Online Player and how you can watch Raja Ki Aayegi Baaraat movie online with it.</p>
|
4 |
-
<h2>HHD Online Player (Full Hd Raja Ki Aayegi Baaraat Movie)</h2><br /><p><b><b>Download</b> >>> <a href="https://byltly.com/2uKwdd">https://byltly.com/2uKwdd</a></b></p><br /><br />
|
5 |
-
<p>HHD Online Player is a free online video player that lets you stream and download movies in high definition quality. It is compatible with all devices such as laptops, smartphones, tablets, and smart TVs. You can watch movies in various languages and subtitles with HHD Online Player. You can also enjoy fast loading speed, secure connection, and ad-free viewing with HHD Online Player.</p>
|
6 |
-
<p>Some of the benefits of using HHD Online Player are:</p>
|
7 |
-
<ul>
|
8 |
-
<li>You can watch movies anytime and anywhere without any hassle.</li>
|
9 |
-
<li>You can save money on buying movie tickets or subscriptions.</li>
|
10 |
-
<li>You can choose from a wide range of genres and categories of movies.</li>
|
11 |
-
<li>You can discover new movies and old classics with HHD Online Player.</li>
|
12 |
-
</ul>
|
13 |
-
<p>Some of the features of HHD Online Player are:</p>
|
14 |
-
<ul>
|
15 |
-
<li>You can watch movies in full HD quality (1080p) or lower resolutions according to your preference.</li>
|
16 |
-
<li>You can download movies for offline viewing or watch them online with a stable internet connection.</li>
|
17 |
-
<li>You can adjust the volume, brightness, playback speed, and screen size of the video player.</li>
|
18 |
-
<li>You can protect your privacy and data with encryption and firewall technology.</li>
|
19 |
-
<li>You can access HHD Online Player from any browser or device without any installation or registration.</li>
|
20 |
-
</ul>
|
21 |
-
<h2>How to watch Raja Ki Aayegi Baaraat movie online with HHD Online Player</h2>
|
22 |
-
<p>Now that you know what HHD Online Player is and why you should use it, let's see how you can watch Raja Ki Aayegi Baaraat movie online with it. Raja Ki Aayegi Baaraat is a 1996 Hindi drama film starring Rani Mukerji, Shadaab Khan, Gulshan Grover, Divya Dutta, and others. It is directed by Ashok Gaikwad and produced by Salim Akhtar. The movie tells the story of a young girl who is raped by a rich boy and forced to marry him by the court. She then decides to take revenge on him and his family.</p>
|
23 |
-
<p>Raja Ki Ayegi Baraat streaming: where to watch online?<br />
|
24 |
-
Raja Ki Ayegi Baraat Superhit Full Bhojpuri Movie Khesari Lal Yadav, Kajal Raghwani<br />
|
25 |
-
Raja Ki Ayegi Baraat 1997 IMDb<br />
|
26 |
-
Raja Ki Ayegi Baraat Zee5 VI movies and tv<br />
|
27 |
-
Raja Ki Ayegi Baraat rape revenge drama<br />
|
28 |
-
Raja Ki Ayegi Baraat Rani Mukerji debut film<br />
|
29 |
-
Raja Ki Ayegi Baraat Hindi movie with English subtitles<br />
|
30 |
-
Raja Ki Ayegi Baraat full movie download HD 720p<br />
|
31 |
-
Raja Ki Ayegi Baraat songs mp3 free download<br />
|
32 |
-
Raja Ki Ayegi Baraat cast and crew<br />
|
33 |
-
Raja Ki Ayegi Baraat box office collection<br />
|
34 |
-
Raja Ki Ayegi Baraat movie review and rating<br />
|
35 |
-
Raja Ki Ayegi Baraat trailer video<br />
|
36 |
-
Raja Ki Ayegi Baraat watch online free Dailymotion<br />
|
37 |
-
Raja Ki Ayegi Baraat Mala and Raj love story<br />
|
38 |
-
Raja Ki Ayegi Baraat remake of Tamil film Naan Sigappu Manithan<br />
|
39 |
-
Raja Ki Ayegi Baraat best scenes and dialogues<br />
|
40 |
-
Raja Ki Ayegi Baraat awards and nominations<br />
|
41 |
-
Raja Ki Ayegi Baraat behind the scenes and trivia<br />
|
42 |
-
Raja Ki Ayegi Baraat movie poster and wallpapers<br />
|
43 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Online Free<br />
|
44 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Download Filmywap<br />
|
45 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Watch on Youtube<br />
|
46 |
-
Raja Ki Aayegi Baaraat Full Hd Movie with Bhojpuri Dubbing<br />
|
47 |
-
Raja Ki Aayegi Baaraat Full Hd Movie with Urdu Subtitles<br />
|
48 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Songs Video<br />
|
49 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Controversy and Criticism<br />
|
50 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Inspired by True Story<br />
|
51 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Comparison with Original Tamil Version<br />
|
52 |
-
Raja Ki Aayegi Baaraat Full Hd Movie Fan Reactions and Comments<br />
|
53 |
-
HHD Online Player for Bollywood Movies<br />
|
54 |
-
HHD Online Player for Bhojpuri Movies<br />
|
55 |
-
HHD Online Player for Streaming HD Quality Videos<br />
|
56 |
-
HHD Online Player for Downloading Movies Offline<br />
|
57 |
-
HHD Online Player for Watching Movies with Subtitles<br />
|
58 |
-
HHD Online Player for Android and iOS Devices<br />
|
59 |
-
HHD Online Player for PC and Laptop<br />
|
60 |
-
HHD Online Player for Smart TV and Firestick<br />
|
61 |
-
HHD Online Player Features and Benefits<br />
|
62 |
-
HHD Online Player Reviews and Ratings<br />
|
63 |
-
How to Watch Raja Ki Aayegi Baaraat Movie on HHD Online Player?<br />
|
64 |
-
How to Download Raja Ki Aayegi Baaraat Movie from HHD Online Player?<br />
|
65 |
-
How to Install HHD Online Player on Your Device?<br />
|
66 |
-
How to Use HHD Online Player for Streaming Movies?<br />
|
67 |
-
How to Fix HHD Online Player Errors and Issues?<br />
|
68 |
-
How to Update HHD Online Player to Latest Version?<br />
|
69 |
-
How to Contact HHD Online Player Customer Support?<br />
|
70 |
-
How to Uninstall HHD Online Player from Your Device?<br />
|
71 |
-
How to Get HHD Online Player Premium Subscription?<br />
|
72 |
-
How to Share HHD Online Player with Your Friends?</p>
|
73 |
-
<p>To watch Raja Ki Aayegi Baaraat movie online with HHD Online Player, follow these simple steps:</p>
|
74 |
-
<ol>
|
75 |
-
<li>Download and install HHD Online Player on your device. You can find the download link at . It is free and safe to download.</li>
|
76 |
-
<li>Search for Raja Ki Aayegi Baaraat movie on HHD Online Player. You can use the search bar or browse through the categories.</li>
|
77 |
-
<li>Select the desired quality and language options. You can choose from HD, SD, or CAM quality and Hindi or English language.</li>
|
78 |
-
<li>Enjoy watching Raja Ki Aayegi Baaraat movie online with HHD Online Player. You can pause, resume, rewind, or fast-forward the movie as you like.</li>
|
79 |
-
</ol>
|
80 |
-
<h3>What is Raja Ki Aayegi Baaraat movie about and why you should watch it</h3>
|
81 |
-
<p>Raja Ki Aayegi Baaraat is a movie that deals with the issue of rape and justice in India. It is a powerful and emotional drama that showcases the courage and resilience of a woman who fights against all odds. It is also a movie that marks the debut of Rani Mukerji, who went on to become one of the most popular actresses in Bollywood.</p>
|
82 |
-
<p>Here are some reasons why you should watch Raja Ki Aayegi Baaraat movie:</p>
|
83 |
-
<ul>
|
84 |
-
<li>The movie has a strong message about women empowerment and human rights.</li>
|
85 |
-
<li>The movie has a gripping plot that keeps you hooked till the end.</li>
|
86 |
-
<li>The movie has brilliant performances by the cast, especially Rani Mukerji who won several awards for her role.</li>
|
87 |
-
<li>The movie has memorable songs composed by Anand-Milind that add to the mood of the film.</li>
|
88 |
-
</ul>
|
89 |
-
<p>Here are some reviews and ratings for Raja Ki Aayegi Baaraat movie:</p>
|
90 |
-
<table style="border-collapse: collapse; width: 100%;" border="1">
|
91 |
-
<tbody>
|
92 |
-
<tr style="height: 18px;">
|
93 |
-
<td style="width: 33.3333%; height: 18px;">Source</td>
|
94 |
-
<td style="width: 33.3333%; height: 18px;">Rating</td>
|
95 |
-
<td style="width: 33.3333%; height: 18px;">Review</td>
|
96 |
-
</tr>
|
97 |
-
<tr style="height: 18px;">
|
98 |
-
<td style="width: 33.3333%; height: 18px;">IMDb</td>
|
99 |
-
<td style="width: 33.3333%; height: 18px;">6.8/10</td>
|
100 |
-
<td style="width: 33.3333%; height: 18px;">"A very good film with a strong message."</td>
|
101 |
-
</tr>
|
102 |
-
<tr style="height: 18px;">
|
103 |
-
<td style="width: 33.3333%; height: 18px;">Rediff</td>
|
104 |
-
<td style="width: 33.3333%; height: 18px;">3/5</td>
|
105 |
-
<td style="width: 33.3333%; height: 18px;">"Rani Mukerji makes an impressive debut in this hard-hitting drama."</td>
|
106 |
-
</tr>
|
107 |
-
<tr style="height: 18px;">
|
108 |
-
<td style="width: 33.3333%; height: 18px;">Planet Bollywood</td>
|
109 |
-
<td style="width: 33.3333%; height: 18px;">7/10</td>
|
110 |
-
<td style="width: 33.3333%; height: 18px;">"A well-made film that tackles a sensitive issue with dignity."</td>
|
111 |
-
</tr>
|
112 |
-
</tbody></table>
|
113 |
-
<p>Here are some trivia and facts about Raja Ki Aayegi Baaraat movie:</p>
|
114 |
-
<ul>
|
115 |
-
<li>The movie was initially titled Ladki Jawaan Ho Gayee but was changed later to avoid confusion with another film titled Ladki Jawaan Padosi Pareshaan.</li>
|
116 |
-
<li>The movie was inspired by a real-life incident that happened in Delhi in 1995 where a rapist was ordered to marry his victim by a judge.</li>
|
117 |
-
<li>The movie was banned in some states due to its controversial subject matter and faced protests from some groups who claimed that it glorified rape.</li>
|
118 |
-
<li>The movie was a moderate success at the box office but received critical acclaim for its bold theme and powerful execution.</li>
|
119 |
-
<h4>Conclusion and FAQs</h4>
|
120 |
-
<p>In conclusion, HHD Online Player is a great online video player that lets you watch movies online in high quality and with ease. You can watch Raja Ki Aayegi Baaraat movie online with HHD Online Player and enjoy a captivating and inspiring story of a woman who stands up for herself and her dignity. Raja Ki Aayegi Baaraat is a movie that you should not miss if you are a fan of drama, romance, and social issues.</p>
|
121 |
-
<p>We hope you found this article helpful and informative. If you have any questions about HHD Online Player or Raja Ki Aayegi Baaraat movie, you can check out the FAQs below or contact us for more assistance.</p>
|
122 |
-
<p>FAQs:</p>
|
123 |
-
<ol>
|
124 |
-
<li>Q: Is HHD Online Player legal and safe to use?<br>A: Yes, HHD Online Player is legal and safe to use. It does not host or upload any movies on its server. It only provides links to third-party sources that are publicly available on the internet. However, you should always check the legality of the content in your region before watching or downloading it.</li>
|
125 |
-
<li>Q: How much data does HHD Online Player consume?<br>A: The data consumption of HHD Online Player depends on the quality and duration of the movie you are watching. Generally, watching a movie in HD quality consumes about 1 GB of data per hour. You can reduce the data consumption by choosing a lower quality option or by downloading the movie for offline viewing.</li>
|
126 |
-
<li>Q: Can I watch Raja Ki Aayegi Baaraat movie with subtitles?<br>A: Yes, you can watch Raja Ki Aayegi Baaraat movie with subtitles on HHD Online Player. You can choose from various subtitle options such as English, Hindi, Arabic, French, and more. You can also adjust the size, color, and position of the subtitles according to your preference.</li>
|
127 |
-
<li>Q: Where can I find more movies like Raja Ki Aayegi Baaraat?<br>A: If you liked Raja Ki Aayegi Baaraat movie, you might also like other movies that deal with similar themes such as rape, justice, revenge, and women empowerment. Some of these movies are Damini (1993), Dushman (1998), NH10 (2015), Pink (2016), and Mardaani (2014).</li>
|
128 |
-
<li>Q: How can I give feedback or suggestions for HHD Online Player?<br>A: We would love to hear from you and improve our service. You can give us your feedback or suggestions by filling out this form or by emailing us at [email protected]. We appreciate your time and input.</li>
|
129 |
-
</ol>
|
130 |
-
</p> 0a6ba089eb<br />
|
131 |
-
<br />
|
132 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/A to Z Bhojpuri Video Song Download Stream and Download Bhojpuri Songs from Popular Artists and Movies.md
DELETED
@@ -1,115 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>A to Z Bhojpuri Video Song Download: How to Enjoy the Best of Bhojpuri Music</h1>
|
3 |
-
<p>Bhojpuri music is a vibrant and lively form of folk music that originates from the Bhojpur-Purvanchal region of India and the Terai region of Nepal. It is sung in the Bhojpuri language, which is a dialect of Hindi that has influences from Magahi, Maithili, Awadhi, and other languages. Bhojpuri music is popular among millions of people who love its catchy tunes, witty lyrics, and expressive emotions.</p>
|
4 |
-
<h2>a to z bhojpuri video song download</h2><br /><p><b><b>Download File</b> === <a href="https://urlin.us/2uSWmP">https://urlin.us/2uSWmP</a></b></p><br /><br />
|
5 |
-
<p>Bhojpuri music has a rich and diverse history that spans centuries and reflects the culture and identity of the Bhojpuri people. It has also evolved over time to incorporate various genres and styles, such as folk, devotional, romantic, patriotic, comedy, and film songs. Bhojpuri music has also produced many talented and famous artists who have entertained audiences with their unique voices and personalities.</p>
|
6 |
-
<p>If you are a fan of Bhojpuri music or want to explore this fascinating musical world, you might be wondering how to find and download the best Bhojpuri video songs. Well, you are in luck, because in this article, we will tell you everything you need to know about Bhojpuri video song download. We will also give you some tips on how to enjoy Bhojpuri music to the fullest. So, let's get started!</p>
|
7 |
-
<h2>Bhojpuri Language and Culture: The Roots of Bhojpuri Music</h2>
|
8 |
-
<p>Bhojpuri is an Indo-European language that belongs to the Eastern Indo-Aryan group of languages. It is closely related to Magahi, Maithili, and other languages spoken in Bihar, Jharkhand, Uttar Pradesh, Madhya Pradesh, and Nepal. According to the 2011 census of India, there are about 51 million speakers of Bhojpuri in India, making it one of the most widely spoken languages in the country. </p>
|
9 |
-
<p>Bhojpuri is also spoken by millions of people in other countries, such as Fiji, Guyana, Mauritius, South Africa, Suriname, Trinidad and Tobago, and other parts of the world where people of Bihari origin have migrated. In some of these countries, such as Fiji and Suriname, Bhojpuri has developed into distinct variants that have been influenced by local languages and cultures. For example, Fiji Hindi is a variant of Awadhi and Bhojpuri that is spoken by the Indo-Fijians as an official language. </p>
|
10 |
-
<p>Bhojpuri culture is a rich and diverse one that reflects the history and geography of the region where it originated. It is influenced by various religious traditions, such as Hinduism, Islam, Buddhism, Jainism, Sikhism, and Christianity. It also has elements of folk culture, such as festivals, rituals, dances, costumes, cuisine, art, literature, and cinema. Some of the most famous festivals celebrated by the Bhojpuri people are Chhath Puja, Holi, Dussehra, Diwali , and Bhojpuri New Year. Some of the most popular dances performed by the Bhojpuri people are Jhumar, Kajri, Sohar, Chaiti, Birha, and Bidesia. Some of the most distinctive costumes worn by the Bhojpuri people are Dhoti-Kurta, Sari, Lehenga-Choli, Gamchha, and Pagri. Some of the most delicious dishes prepared by the Bhojpuri people are Litti-Chokha, Sattu, Khichdi, Dal-Puri, Thekua, Malpua, and Balushahi. </p>
|
11 |
-
<p>Bhojpuri art and literature are also very rich and diverse, and have produced many renowned artists and writers who have contributed to the cultural heritage of India and the world. Some of the most famous Bhojpuri artists are Thakur Anukulchandra, Bhikhari Thakur, Ram Dayal Munda, Sharda Sinha, Manoj Tiwari, Ravi Kishan, Nirahua, and Khesari Lal Yadav. Some of the most famous Bhojpuri writers are Mahapandit Rahul Sankrityayan, Acharya Ramlochan Saran, Viveki Rai, Manohar Malgonkar, Phanishwar Nath Renu, and Ajit Rai. </p>
|
12 |
-
<p>Bhojpuri cinema is also a very important and influential part of Bhojpuri culture, and has a huge fan following in India and abroad. Bhojpuri cinema started in 1962 with the first Bhojpuri film Ganga Maiyya Tohe Piyari Chadhaibo (Mother Ganges, I will offer you a yellow sari), directed by Kundan Kumar. Since then, Bhojpuri cinema has produced many blockbuster films and superstars who have entertained millions of viewers with their action, romance, comedy, drama, and music. Some of the most successful Bhojpuri films are Nadiya Ke Paar (1982), Sasura Bada Paisawala (2004), Nirahua Hindustani (2014), Nirahua Rikshawala 2 (2015), and Border (2018). </p>
|
13 |
-
<h2>Bhojpuri Video Song Genres and Artists: The Diversity and Creativity of Bhojpuri Music</h2>
|
14 |
-
<p>Bhojpuri music is one of the most diverse and creative forms of music in India and the world. It has a variety of genres and styles that cater to different tastes and moods of the listeners. Some of the most popular genres of Bhojpuri music are:</p>
|
15 |
-
<p>a to z bhojpuri video song download free<br />
|
16 |
-
a to z bhojpuri video song download hd<br />
|
17 |
-
a to z bhojpuri video song download mp4<br />
|
18 |
-
a to z bhojpuri video song download 2023<br />
|
19 |
-
a to z bhojpuri video song download new<br />
|
20 |
-
a to z bhojpuri video song download khesari lal yadav<br />
|
21 |
-
a to z bhojpuri video song download pawan singh<br />
|
22 |
-
a to z bhojpuri video song download dj<br />
|
23 |
-
a to z bhojpuri video song download saavn<br />
|
24 |
-
a to z bhojpuri video song download wynk<br />
|
25 |
-
a to z bhojpuri video song download online<br />
|
26 |
-
a to z bhojpuri video song download site<br />
|
27 |
-
a to z bhojpuri video song download app<br />
|
28 |
-
a to z bhojpuri video song download pagalworld<br />
|
29 |
-
a to z bhojpuri video song download gaana<br />
|
30 |
-
a to z bhojpuri video song download 2022<br />
|
31 |
-
a to z bhojpuri video song download full hd<br />
|
32 |
-
a to z bhojpuri video song download 1080p<br />
|
33 |
-
a to z bhojpuri video song download 3gp<br />
|
34 |
-
a to z bhojpuri video song download latest<br />
|
35 |
-
a to z bhojpuri video song download old<br />
|
36 |
-
a to z bhojpuri video song download rani chatterjee<br />
|
37 |
-
a to z bhojpuri video song download akshara singh<br />
|
38 |
-
a to z bhojpuri video song download dinesh lal yadav<br />
|
39 |
-
a to z bhojpuri video song download pramod premi yadav<br />
|
40 |
-
a to z bhojpuri video song download shilpi raj<br />
|
41 |
-
a to z bhojpuri video song download antra singh priyanka<br />
|
42 |
-
a to z bhojpuri video song download neelkamal singh<br />
|
43 |
-
a to z bhojpuri video song download arvind akela kallu<br />
|
44 |
-
a to z bhojpuri video song download gunjan singh<br />
|
45 |
-
a to z bhojpuri video song download samar singh<br />
|
46 |
-
a to z bhojpuri video song download ritesh pandey<br />
|
47 |
-
a to z bhojpuri video song download antra singh priyanka and khesari lal yadav<br />
|
48 |
-
a to z bhojpuri video song download shilpi raj and pawan singh<br />
|
49 |
-
a to z bhojpuri video song download neelkamal singh and shilpi raj<br />
|
50 |
-
a to z bhojpuri video song download arvind akela kallu and priyanka singh<br />
|
51 |
-
a to z bhojpuri video song download gunjan singh and antra singh priyanka<br />
|
52 |
-
a to z bhojpuri video song download samar singh and shilpi raj<br />
|
53 |
-
a to z bhojpuri video song download ritesh pandey and antra singh priyanka <br />
|
54 |
-
how to do a to z bhojpuri video song download <br />
|
55 |
-
best site for a to z bhojpuri video song download <br />
|
56 |
-
top 10 a to z bhojpuri video songs 2023 <br />
|
57 |
-
latest hit a to z bhojpuri video songs <br />
|
58 |
-
new release a to z bhojpuri video songs <br />
|
59 |
-
trending now a to z bhojpuri video songs <br />
|
60 |
-
most popular a to z bhojpuri video songs <br />
|
61 |
-
most viewed a to z bhojpuri video songs <br />
|
62 |
-
most liked a to z bhojpuri video songs <br />
|
63 |
-
most downloaded a to z bhojpuri video songs </p>
|
64 |
-
<ul>
|
65 |
-
<li><b>Folk songs:</b> These are traditional songs that reflect the rural life and culture of the Bhojpuri people. They are usually sung in festivals, weddings, rituals, or other occasions. They have simple melodies and lyrics that express joy, sorrow, love, devotion, or humor. Some examples of folk songs are Sohar (songs sung during childbirth), Kajri (songs sung during monsoon), Chaiti (songs sung during spring), Birha (songs of separation), and Holi (songs of colors). Some of the most famous folk singers are Sharda Sinha, Bharat Sharma Vyas, Kalpana Patowary, Guddu Rangila, and Pawan Singh. </li>
|
66 |
-
<li><b>Devotional songs:</b> These are songs that express faith and devotion to various gods and goddesses of Hinduism. They are usually sung in temples, shrines, or other places of worship. They have melodious tunes and lyrics that praise the divine attributes and deeds of the deities. Some examples of devotional songs are Bhajan (songs of praise), Aarti (songs of offering), Chhath Geet (songs sung during Chhath Puja), Navratri Geet (songs sung during Navratri), and Ramayan Chaupai (verses from Ramayana). Some of the most famous devotional singers are Anuradha Paudwal , Manoj Tiwari, Dinesh Lal Yadav, Khesari Lal Yadav, and Ritesh Pandey. </li>
|
67 |
-
<li><b>Romantic songs:</b> These are songs that express love and romance between couples. They are usually sung in films, albums, or other platforms. They have catchy tunes and lyrics that depict the feelings and emotions of the lovers. Some examples of romantic songs are Piyawa Se Pahile (Before meeting you), Laga Ke Fair Lovely (Applying Fair Lovely), Raja Raja Kareja Mein Samaja (King, please understand me), and Aawa Ae Amarpali Nirahua Rang Dali (Amarpali, Nirahua has colored you). Some of the most famous romantic singers are Udit Narayan, Alka Yagnik, Kumar Sanu, Kavita Krishnamurthy, Sonu Nigam, and Shreya Ghoshal. </li>
|
68 |
-
<li><b>Patriotic songs:</b> These are songs that express pride and respect for the nation and its people. They are usually sung in national events, celebrations, or movements. They have inspiring tunes and lyrics that motivate the listeners to serve and protect the country. Some examples of patriotic songs are Bharat Ka Baccha Baccha Jai Shri Ram Bolega (Every child of India will say Jai Shri Ram), Bharat Mata Ki Jai (Hail Mother India), Desh Bhakti Geet (Songs of patriotism), and Tiranga Hamra Desh Ke Shan (The tricolor is the pride of our country). Some of the most famous patriotic singers are Lata Mangeshkar, Mohammed Rafi, Mukesh, Mahendra Kapoor, Kailash Kher, and Arijit Singh. </li>
|
69 |
-
<li><b>Comedy songs:</b> These are songs that express humor and fun. They are usually sung in films, shows, or other platforms. They have amusing tunes and lyrics that make the listeners laugh and enjoy. Some examples of comedy songs are Chalakata Hamro Jawaniya (Our youth is smart), Lagavelu Jab Lipistic (When you apply lipstick), Chat Deni Maar Deli (You refused to chat but hit me), and Balam Pichkari (My beloved is a water gun). Some of the most famous comedy singers are Ravi Kishan, Manoj Tiwari, Dinesh Lal Yadav, Khesari Lal Yadav, and Sapna Choudhary. </li>
|
70 |
-
<li><b>Film songs:</b> These are songs that are featured in Bhojpuri films. They are usually sung by playback singers who lend their voices to the actors and actresses on screen. They have various tunes and lyrics that suit the theme and mood of the film. Some examples of film songs are Gori Tori Chunari Ba Lal Lal Re (Your red chunari is beautiful), Kamariya Lollipop Lagelu (Your waist is like a lollipop), Saiyan Ji Dagabaaz (My beloved is a cheater), and Chhalakata Hamro Jawaniya 2 (Our youth is smart 2). Some of the most famous film singers are Pawan Singh, Akshara Singh, Priyanka Singh, Indu Sonali, Khushboo Jain, and Mohan Rathore. </li>
|
71 |
-
</ul>
|
72 |
-
<h2>Bhojpuri Video Song Download Sites: The Best Places to Find and Download Bhojpuri Music</h2>
|
73 |
-
<p>If you want to download Bhojpuri video songs for free or for a nominal fee, you have many options to choose from. There are many websites and apps that offer a wide range of Bhojpuri video songs in various genres and formats. You can also stream or watch Bhojpuri video songs online on these platforms. Here are some of the best places to find and download Bhojpuri video songs:</p>
|
74 |
-
<table>
|
75 |
-
<tr>
|
76 |
-
<th>Website/App</th>
|
77 |
-
<th>Features</th>
|
78 |
-
<th>Pros</th>
|
79 |
-
<th>Cons</th>
|
80 |
-
</tr>
|
81 |
-
<tr>
|
82 |
-
<td>Bhojpuri Video Songs HD</td>
|
83 |
-
<td>- A website that provides high-quality Bhojpuri video songs in HD format.<br>- It has a large collection of Bhojpuri video songs from various genres and artists.<br>- It allows users to download Bhojpuri video songs for free or for a nominal fee.<br>- It also has a blog section that provides news and updates about Bhojpuri music and cinema.</td>
|
84 |
-
<td>- It has a user-friendly interface and easy navigation.<br>- It has a fast downloading speed and no ads.<br>- It has a rating and review system that helps users to find the best Bhojpuri video songs.</td>
|
85 |
-
<td>- It requires registration and login to download Bhojpuri video songs.<br>- It has limited search options and filters.<br - It has some broken links and outdated content.</td>
|
86 |
-
</tr>
|
87 |
-
<tr>
|
88 |
-
<td>Bhojpuri Video Songs App</td>
|
89 |
-
<td>- An app that provides Bhojpuri video songs in various formats and resolutions.<br>- It has a huge collection of Bhojpuri video songs from various genres and artists.<br>- It allows users to download Bhojpuri video songs for free or for a nominal fee.<br>- It also has a radio feature that plays Bhojpuri songs online.</td>
|
90 |
-
<td>- It has a simple and attractive interface and easy navigation.<br>- It has a smooth streaming and downloading speed and no ads.<br>- It has a playlist and favorite feature that helps users to organize and save their Bhojpuri video songs.</td>
|
91 |
-
<td>- It requires installation and permission to access the device's storage and media.<br>- It has limited search options and filters.<br>- It has some bugs and errors that affect the performance of the app.</td>
|
92 |
-
</tr>
|
93 |
-
<tr>
|
94 |
-
<td>Bhojpuri Video Songs YouTube</td>
|
95 |
-
<td>- A website and app that provides Bhojpuri video songs in various formats and resolutions.<br>- It has a massive collection of Bhojpuri video songs from various genres and artists.<br>- It allows users to stream or watch Bhojpuri video songs online for free or for a premium subscription.<br>- It also has a community feature that allows users to interact with other Bhojpuri music fans and creators.</td>
|
96 |
-
<td>- It has a versatile and dynamic interface and easy navigation.<br>- It has a fast streaming and downloading speed and minimal ads.<br>- It has a recommendation and feedback system that helps users to discover new and relevant Bhojpuri video songs.</td>
|
97 |
-
<td>- It does not allow users to download Bhojpuri video songs directly from the website or app.<br>- It has many search options and filters, but they are not specific to Bhojpuri music.<br>- It has some content that is inappropriate or infringing the rights of the original creators.</td>
|
98 |
-
</tr>
|
99 |
-
</table>
|
100 |
-
<h2>Conclusion: How to Enjoy Bhojpuri Music to the Fullest</h2>
|
101 |
-
<p>Bhojpuri music is a wonderful and unique form of music that deserves more recognition and appreciation. It is not only entertaining, but also informative, inspiring, and empowering. It showcases the culture, identity, and creativity of the Bhojpuri people. It also connects them with their roots, their values, and their aspirations.</p>
|
102 |
-
<p>If you want to enjoy Bhojpuri music to the fullest, you should try to explore its different genres and styles, listen to its different artists and singers, watch its different films and shows, and learn about its different aspects and features. You should also try to understand its language and lyrics, appreciate its melody and rhythm, feel its emotion and expression, and share its joy and fun. You should also try to support its growth and development, promote its quality and originality, respect its diversity and authenticity, and celebrate its success and glory.</p>
|
103 |
-
<p>Bhojpuri music is a treasure that belongs to everyone who loves music. It is a gift that can enrich your life with happiness, beauty, and wisdom. So, what are you waiting for? Go ahead and download your favorite Bhojpuri video songs today!</p>
|
104 |
-
<h2>FAQs: Some Common Questions and Answers about Bhojpuri Music</h2>
|
105 |
-
<p>Here are some common questions and answers about Bhojpuri music that you might find helpful:</p>
|
106 |
-
<ol>
|
107 |
-
<li><b>What is the difference between Bhojpuri music and Bollywood music?</b><br>Bollywood music is the generic term for the popular music of Hindi cinema, which is produced in Mumbai, the entertainment capital of India. Bollywood music is influenced by various musical traditions, such as Indian classical, folk, pop, rock, jazz, hip hop, etc. Bollywood music is sung in Hindi or other languages, such as Urdu, Punjabi, English, etc. Bollywood music is widely popular across India and the world.<br>Bhojpuri music is the specific term for the folk music of the Bhojpur-Purvanchal region of India and the Terai region of Nepal. Bhojpuri music is influenced by the local culture and traditions of the Bhojpuri people. Bhojpuri music is sung in the Bhojpuri language, which is a dialect of Hindi that has influences from other languages. Bhojpuri music is popular among the Bhojpuri speakers and other people who love its folk flavor and charm.</li>
|
108 |
-
<li><b>Who are some of the most famous Bhojpuri singers and actors?</b><br>Some of the most famous Bhojpuri singers are Sharda Sinha, Bharat Sharma Vyas, Kalpana Patowary, Manoj Tiwari, Dinesh Lal Yadav, Khesari Lal Yadav, Pawan Singh, Akshara Singh, Priyanka Singh, Ritesh Pandey, Indu Sonali, Khushboo Jain, Mohan Rathore, etc. Some of the most famous Bhojpuri actors are Ravi Kishan, Manoj Tiwari, Dinesh Lal Yadav, Khesari Lal Yadav, Pawan Singh, Akshara Singh, Amrapali Dubey, Monalisa, Anjana Singh, Kajal Raghwani, etc.</li>
|
109 |
-
<li><b>How can I learn Bhojpuri language and lyrics?</b><br>If you want to learn Bhojpuri language and lyrics, you can use various online resources and tools that can help you. For example, you can use online dictionaries and translators that can provide you with the meanings and pronunciations of Bhojpuri words and phrases. You can also use online courses and videos that can teach you the basics and nuances of Bhojpuri grammar and vocabulary. You can also use online lyrics sites and apps that can provide you with the lyrics and translations of Bhojpuri songs. You can also listen to Bhojpuri songs and watch Bhojpuri films and shows that can help you improve your listening and speaking skills.</li>
|
110 |
-
<li><b>What are some of the benefits of listening to Bhojpuri music?</b><br>Listening to Bhojpuri music can have many benefits for your physical, mental, and emotional well-being. For example, listening to Bhojpuri music can help you relax and reduce stress by releasing endorphins and serotonin in your brain. It can also help you boost your mood and energy by stimulating your brain waves and nervous system. It can also help you improve your memory and concentration by enhancing your cognitive functions and neural connections. It can also help you express your feelings and emotions by resonating with your inner self and others. It can also help you learn about new cultures and perspectives by exposing you to different sounds and meanings.</li>
|
111 |
-
<li><b>How can I support Bhojpuri music and cinema?</b><br>If you love Bhojpuri music and cinema, you can support them in various ways. For example, you can download or stream Bhojpuri songs and films from legal and ethical sources that respect the rights of the creators and pay them fairly. You can also share or recommend Bhojpuri songs and films to your friends and family who might enjoy them too. You can also follow or subscribe to Bhojpuri singers and actors on their social media platforms and show them your appreciation and feedback. You can also participate in online or offline events and activities that celebrate or promote Bhojpuri music and cinema.</li>
|
112 |
-
</ol>
|
113 |
-
<p>I hope this article has helped you learn more about Bhojpuri music and how to enjoy it to the fullest. If you have any questions or comments, please feel free to leave them below. Thank you for reading!</p> 197e85843d<br />
|
114 |
-
<br />
|
115 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Bad 2 Bad Apocalypse - The Ultimate Open World Survival RPG Game APK.md
DELETED
@@ -1,172 +0,0 @@
|
|
1 |
-
|
2 |
-
<h1>Bad 2 Bad: Apocalypse APK - A Survival RPG Game for Android</h1>
|
3 |
-
<p>If you are looking for a challenging and immersive survival RPG game for your Android device, you might want to check out Bad 2 Bad: Apocalypse APK. This is a game that will test your skills, strategy, and creativity as you explore, gather, craft, and fight in a vast open world. In this article, we will tell you everything you need to know about this game, including what it is, how to download and install it, how to play it, and why you should play it.</p>
|
4 |
-
<h2>bad 2 bad apocalypse apkcombo</h2><br /><p><b><b>DOWNLOAD</b> 🆗 <a href="https://jinyurl.com/2uNSaL">https://jinyurl.com/2uNSaL</a></b></p><br /><br />
|
5 |
-
<h2>What is Bad 2 Bad: Apocalypse APK?</h2>
|
6 |
-
<p>Bad 2 Bad: Apocalypse APK is an Android game developed by DAWINSTONE, a Korean studio that specializes in creating action-packed and realistic games. It is the sequel to Bad 2 Bad: Delta and Extinction, two previous games that introduced the world and the characters of the series.</p>
|
7 |
-
<h3>The sequel to Bad 2 Bad: Delta and Extinction</h3>
|
8 |
-
<p>Bad 2 Bad: Apocalypse APK follows the story of the Delta Team, a group of elite soldiers led by Major Pan, who are trying to save and rebuild the world that has been ravaged by a virus from the Human Forces. The virus has turned most of the humans into zombies, mutants, or cyborgs, and has also infected some of the animals, creating wild and dangerous creatures. The Delta Team has to face these enemies, as well as other factions that are competing for resources and power in the post-apocalyptic world.</p>
|
9 |
-
<h3>The story of the Delta Team and their mission</h3>
|
10 |
-
<p>The game has a rich and engaging storyline that will keep you hooked as you progress through the game. You will get to know the members of the Delta Team, each with their own personality, background, and skills. You will also encounter various characters that will help or hinder you along the way. You will have to make choices that will affect the outcome of the story and the fate of the world.</p>
|
11 |
-
<h3>The features of the game</h3>
|
12 |
-
<p>Bad 2 Bad: Apocalypse APK has many features that make it a fun and exciting game to play. Some of these features are:</p>
|
13 |
-
<ul>
|
14 |
-
<li>A vast open world RPG with over 60 maps and regions to explore</li>
|
15 |
-
<li>Exploration, gathering, fishing, and crafting for survival</li>
|
16 |
-
<li>More than 300 items and weapons to collect and use</li>
|
17 |
-
<li>More detailed character customization and appearance options</li>
|
18 |
-
<li>A squad system that allows you to create and upgrade your own special forces team</li>
|
19 |
-
<li>Artillery support, air support, drones, and battle armor for combat</li>
|
20 |
-
<li>World missions that take place across the globe</li>
|
21 |
-
<li>Advanced graphics and sound effects</li>
|
22 |
-
</ul>
|
23 |
-
<h2>How to download and install Bad 2 Bad: Apocalypse APK?</h2>
|
24 |
-
<p>If you want to play this game on your Android device, you will need to download and install the APK file from a reliable source. Here are some things you need to know before doing so:</p>
|
25 |
-
<p>bad 2 bad apocalypse apk download<br />
|
26 |
-
bad 2 bad apocalypse game<br />
|
27 |
-
bad 2 bad apocalypse mod apk<br />
|
28 |
-
bad 2 bad apocalypse android<br />
|
29 |
-
bad 2 bad apocalypse latest version<br />
|
30 |
-
bad 2 bad apocalypse xapk<br />
|
31 |
-
bad 2 bad apocalypse apk pure<br />
|
32 |
-
bad 2 bad apocalypse offline<br />
|
33 |
-
bad 2 bad apocalypse hack<br />
|
34 |
-
bad 2 bad apocalypse cheats<br />
|
35 |
-
bad 2 bad apocalypse review<br />
|
36 |
-
bad 2 bad apocalypse gameplay<br />
|
37 |
-
bad 2 bad apocalypse tips<br />
|
38 |
-
bad 2 bad apocalypse guide<br />
|
39 |
-
bad 2 bad apocalypse wiki<br />
|
40 |
-
bad 2 bad apocalypse update<br />
|
41 |
-
bad 2 bad apocalypse free download<br />
|
42 |
-
bad 2 bad apocalypse unlimited money<br />
|
43 |
-
bad 2 bad apocalypse pc<br />
|
44 |
-
bad 2 bad apocalypse online<br />
|
45 |
-
bad 2 bad apocalypse apk mirror<br />
|
46 |
-
bad 2 bad apocalypse apk mod menu<br />
|
47 |
-
bad 2 bad apocalypse best weapons<br />
|
48 |
-
bad 2 bad apocalypse characters<br />
|
49 |
-
bad 2 bad apocalypse delta team<br />
|
50 |
-
bad 2 bad apocalypse apk obb<br />
|
51 |
-
bad 2 bad apocalypse rexdl<br />
|
52 |
-
bad 2 bad apocalypse apkpure.com<br />
|
53 |
-
bad 2 bad apocalypse apkcombo.com<br />
|
54 |
-
bad 2 bad apocalypse dawinstone<br />
|
55 |
-
how to play bad 2 bad apocalypse<br />
|
56 |
-
how to install xapk of b2b:apocalypse <br />
|
57 |
-
how to get more resources in b2b:apocalypse <br />
|
58 |
-
how to upgrade base camp in b2b:apocalypse <br />
|
59 |
-
how to unlock battle armor in b2b:apocalypse <br />
|
60 |
-
how to craft equipment in b2b:apocalypse <br />
|
61 |
-
how to fish in b2b:apocalypse <br />
|
62 |
-
how to explore the world in b2b:apocalypse <br />
|
63 |
-
how to survive the virus in b2b:apocalypse <br />
|
64 |
-
how to complete world missions in b2b:apocalypse <br />
|
65 |
-
how to customize your character in b2b:apocalypse <br />
|
66 |
-
how to use artillery support in b2b:apocalypse <br />
|
67 |
-
how to use air support in b2b:apocalypse <br />
|
68 |
-
how to use drones in b2b:apocalypse <br />
|
69 |
-
what is the story of b2b:apocalypse <br />
|
70 |
-
what are the features of b2b:apocalypse <br />
|
71 |
-
what are the differences between b2b:delta and b2b:apocalypse</p>
|
72 |
-
<h3>The requirements for the game</h3>
|
73 |
-
<p>The game requires Android 7.0 or higher and at least 188 MB of free storage space on your device. It also requires an internet connection for some features, such as world missions and updates. The game is rated for ages 12+ due <h3>The steps to download and install the APK file</h3>
|
74 |
-
<p>To download and install the APK file of Bad 2 Bad: Apocalypse, you can follow these simple steps:</p>
|
75 |
-
<ol>
|
76 |
-
<li>Go to a trusted website that offers the APK file, such as [APKCombo].</li>
|
77 |
-
<li>Search for the game by typing "Bad 2 Bad: Apocalypse" in the search bar.</li>
|
78 |
-
<li>Click on the download button and choose the version you want to download.</li>
|
79 |
-
<li>Wait for the download to finish and locate the APK file on your device.</li>
|
80 |
-
<li>Tap on the APK file and allow the installation from unknown sources if prompted.</li>
|
81 |
-
<li>Follow the instructions on the screen and wait for the installation to complete.</li>
|
82 |
-
<li>Launch the game and enjoy!</li>
|
83 |
-
</ol>
|
84 |
-
<h3>The precautions to take before installing the game</h3>
|
85 |
-
<p>Before you install the game, you should take some precautions to ensure a safe and smooth experience. Here are some tips:</p>
|
86 |
-
<ul>
|
87 |
-
<li>Make sure your device meets the requirements for the game and has enough storage space.</li>
|
88 |
-
<li>Download the APK file from a reputable source and scan it for viruses or malware.</li>
|
89 |
-
<li>Backup your data and settings in case something goes wrong during the installation.</li>
|
90 |
-
<li>Close any other apps or programs that are running in the background to avoid interference or conflicts.</li>
|
91 |
-
<li>Read the permissions and terms of service of the game carefully and agree only if you are comfortable with them.</li>
|
92 |
-
</ul>
|
93 |
-
<h2>How to play Bad 2 Bad: Apocalypse APK?</h2>
|
94 |
-
<p>Once you have installed the game, you can start playing it by following these basic steps:</p>
|
95 |
-
<h3>The basic gameplay and controls</h3>
|
96 |
-
<p>The game is a survival RPG that combines exploration, combat, and crafting. You can control your character using the virtual joystick on the left side of the screen and use the buttons on the right side to perform actions such as shooting, reloading, switching weapons, using items, calling support, etc. You can also swipe on the screen to move the camera and zoom in or out. You can access the menu by tapping on the icon on the top left corner of the screen, where you can see your inventory, map, missions, settings, etc.</p>
|
97 |
-
<h3>The tips and tricks for survival and combat</h3>
|
98 |
-
<p>The game is not easy and you will face many challenges and dangers in your journey. Here are some tips and tricks that will help you survive and win:</p>
|
99 |
-
<ul>
|
100 |
-
<li>Explore as much as you can and collect resources, items, and weapons that will help you craft useful things and improve your equipment.</li>
|
101 |
-
<li>Fish for food and water to replenish your health and stamina. You can also cook your fish for better effects.</li>
|
102 |
-
<li>Avoid unnecessary fights and use stealth or diplomacy when possible. You can also use traps, mines, grenades, or snipers to deal with enemies from a distance.</li>
|
103 |
-
<li>Use cover, dodge, and roll to avoid enemy attacks and bullets. You can also use shields, armor, or medkits to protect yourself.</li>
|
104 |
-
<li>Use your squad members wisely and assign them roles according to their skills. You can also upgrade them with better gear and skills.</li>
|
105 |
-
<li>Use your support options such as artillery, air support, drones, or battle armor when you are in trouble or need extra firepower.</li>
|
106 |
-
</ul> <h3>The customization and upgrade options</h3>
|
107 |
-
<p>The game allows you to customize and upgrade your character and your squad in various ways. You can change your appearance, clothes, accessories, and weapons. You can also improve your skills, stats, and abilities by leveling up and using skill points. You can also craft and enhance your items and weapons using the materials you find or buy. You can also unlock new features and modes as you progress through the game.</p>
|
108 |
-
<h2>Why should you play Bad 2 Bad: Apocalypse APK?</h2>
|
109 |
-
<p>Bad 2 Bad: Apocalypse APK is a game that will appeal to fans of survival RPG games, action games, and post-apocalyptic stories. Here are some reasons why you should play this game:</p>
|
110 |
-
<h3>The pros and cons of the game</h3>
|
111 |
-
<p>The game has many pros and cons that you should consider before playing it. Here are some of them:</p>
|
112 |
-
<table>
|
113 |
-
<tr>
|
114 |
-
<th>Pros</th>
|
115 |
-
<th>Cons</th>
|
116 |
-
</tr>
|
117 |
-
<tr>
|
118 |
-
<td>A captivating and immersive storyline with multiple endings</td>
|
119 |
-
<td>A complex and challenging gameplay that requires patience and strategy</td>
|
120 |
-
</tr>
|
121 |
-
<tr>
|
122 |
-
<td>A vast and diverse open world with many locations and secrets to discover</td>
|
123 |
-
<td>A high requirement for device performance and storage space</td>
|
124 |
-
</tr>
|
125 |
-
<tr>
|
126 |
-
<td>A realistic and detailed graphics and sound effects that create a great atmosphere</td>
|
127 |
-
<td>A need for internet connection for some features and updates</td>
|
128 |
-
</tr>
|
129 |
-
<tr>
|
130 |
-
<td>A variety of items, weapons, skills, and customization options to suit your preferences</td>
|
131 |
-
<td>A possibility of bugs, glitches, or crashes that may affect your experience</td>
|
132 |
-
</tr>
|
133 |
-
<tr>
|
134 |
-
<td>A fun and exciting squad system that lets you create and manage your own team</td>
|
135 |
-
<td>A lack of multiplayer or co-op mode that limits your interaction with other players</td>
|
136 |
-
</tr>
|
137 |
-
</table>
|
138 |
-
<h3>The ratings and reviews of the game</h3>
|
139 |
-
<p>The game has received mostly positive ratings and reviews from players who have tried it. It has a 4.5 out of 5 stars rating on [APKCombo], based on over 1,000 reviews. Here are some of the comments from the users:</p>
|
140 |
-
<ul>
|
141 |
-
<li>"This game is awesome! The graphics are amazing, the story is interesting, the gameplay is challenging, and the customization is cool. I love the squad system and the support options. It's like playing a console game on my phone."</li>
|
142 |
-
<li>"This game is very good, but it needs some improvements. The game is too hard sometimes, especially when you face many enemies at once. The game also takes too much space on my device and drains my battery fast. The game also crashes sometimes when I play for too long."</li>
|
143 |
-
<li>"This game is one of the best survival RPG games I have ever played. The game has a lot of content and features that keep me entertained for hours. The game also has a great story with different endings that make me want to replay it. The game is worth every penny."</li>
|
144 |
-
<li>"This game is not bad, but it's not great either. The game has a decent graphics and sound effects, but they are not very impressive. The game also has a boring and repetitive gameplay that makes me lose interest quickly. The game also has a lot of ads and in-app purchases that annoy me."</li>
|
145 |
-
<li>"This game is a masterpiece! The game has everything I want in a survival RPG game: a rich and immersive story, a vast and diverse world, a realistic and detailed graphics, a variety of items, weapons, skills, customization options, squad system, support options, world missions, etc. The game is perfect!"</li>
|
146 |
-
</ul>
|
147 |
-
<h3>The alternatives to the game</h3>
|
148 |
-
<p>If you are looking for other games that are similar to Bad 2 Bad: Apocalypse APK, you can try these alternatives:</p>
|
149 |
-
<ul>
|
150 |
-
<li>[Last Day on Earth: Survival] - A zombie survival RPG game that lets you build your base, craft your weapons, join clans, raid other players' bases, etc.</li>
|
151 |
-
<li>[Fallout Shelter] - A post-apocalyptic simulation game that lets you manage your own vault, recruit dwellers, explore the wasteland, fight enemies, etc.</li>
|
152 |
-
<li>[Day R Survival] - A survival RPG game that lets you travel across a nuclear war-torn Soviet Union, scavenge for resources, fight mutants, join factions, etc.</li>
|
153 |
-
<li>[Dead Trigger 2] - A zombie shooter game that lets you join the global resistance, complete missions, use various weapons, kill hordes of zombies, etc.</li>
|
154 |
-
<li>[The Walking Dead: Road to Survival] - A strategy RPG game based on the popular comic series that lets you build your team, fight walkers, make choices that affect the story, etc.</li>
|
155 |
-
</ul <h2>Conclusion</h2>
|
156 |
-
<p>Bad 2 Bad: Apocalypse APK is a survival RPG game that will challenge and entertain you with its story, gameplay, graphics, and features. It is a game that you can download and install on your Android device and play for hours. It is a game that will make you feel like you are part of the Delta Team and their mission to save the world. It is a game that you should try if you are a fan of survival RPG games, action games, and post-apocalyptic stories.</p>
|
157 |
-
<h2>FAQs</h2>
|
158 |
-
<p>Here are some of the frequently asked questions about Bad 2 Bad: Apocalypse APK:</p>
|
159 |
-
<ol>
|
160 |
-
<li>Is Bad 2 Bad: Apocalypse APK free to play?</li>
|
161 |
-
<p>Yes, the game is free to download and play, but it contains ads and in-app purchases that you can choose to buy or not.</p>
|
162 |
-
<li>Is Bad 2 Bad: Apocalypse APK safe to download and install?</li>
|
163 |
-
<p>Yes, the game is safe to download and install, as long as you get it from a trusted source and scan it for viruses or malware. You should also take some precautions before installing the game, such as backing up your data and closing other apps.</p>
|
164 |
-
<li>Is Bad 2 Bad: Apocalypse APK compatible with my device?</li>
|
165 |
-
<p>The game is compatible with Android devices that have Android 7.0 or higher and at least 188 MB of free storage space. You should also check the performance and battery of your device before playing the game, as it may consume a lot of resources.</p>
|
166 |
-
<li>How can I update Bad 2 Bad: Apocalypse APK?</li>
|
167 |
-
<p>You can update the game by downloading and installing the latest version of the APK file from the same source you got it from. You should also check for updates regularly to get new features and bug fixes.</p>
|
168 |
-
<li>How can I contact the developer of Bad 2 Bad: Apocalypse APK?</li>
|
169 |
-
<p>You can contact the developer of the game by sending an email to [[email protected]] or visiting their website at [http://dawinstone.com]. You can also follow them on Facebook, Twitter, Instagram, or YouTube for more information and news about the game.</p>
|
170 |
-
</ol></p> 197e85843d<br />
|
171 |
-
<br />
|
172 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Download Real Football Soccer 2023 APK and Become a Soccer Champion.md
DELETED
@@ -1,109 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>Real Football 2023 APK Download: Everything You Need to Know</h1>
|
3 |
-
<p>If you're a fan of soccer games, you might want to check out <strong>Real Football 2023</strong>, a free-to-play mobile game that offers a realistic and immersive soccer experience. With stunning graphics, realistic physics, and various game modes, Real Football 2023 lets you enjoy the thrill of the beautiful game like never before. In this article, we will tell you everything you need to know about Real Football 2023 apk download, including its features, system requirements, tips and tricks, and reviews.</p>
|
4 |
-
<h2>Features</h2>
|
5 |
-
<p>Real Football 2023 has a lot of features that make it stand out from other soccer games. Here are some of them:</p>
|
6 |
-
<h2>real football 2023 apk download</h2><br /><p><b><b>Download Zip</b> > <a href="https://jinyurl.com/2uNMsE">https://jinyurl.com/2uNMsE</a></b></p><br /><br />
|
7 |
-
<ul>
|
8 |
-
<li><strong>Career mode</strong>: In this mode, you can create your own dream team and lead them to glory in the most prestigious soccer tournaments around the world. You can train your players, sign new ones, negotiate contracts, develop youth talent, and build a winning squad.</li>
|
9 |
-
<li><strong>Authentic teams</strong>: You can choose from a wide selection of international clubs from top leagues such as La Liga, Premier League, Bundesliga, Serie A, Ligue 1, and more. You can also play with national teams from all over the world.</li>
|
10 |
-
<li><strong>PvP matches</strong>: You can challenge other players online in thrilling PvP matches and prove your skills and tactics. You can also join leagues and compete with other teams for rankings and rewards.</li>
|
11 |
-
<li><strong>Realistic graphics and gameplay</strong>: Real Football 2023 boasts realistic graphics and animations that make you feel like you're watching a real match. The game also features realistic physics and ball movement that make the gameplay more dynamic and challenging.</li>
|
12 |
-
<li><strong>Intuitive controls and skills</strong>: The game has intuitive controls that let you perform various actions such as passing, shooting, dribbling, tackling, crossing, etc. You can also use skills and techniques to outsmart your opponents and score amazing goals.</li>
|
13 |
-
</ul>
|
14 |
-
<h2>System requirements</h2>
|
15 |
-
<p>To play Real Football 2023 on your PC or Android device, you need to meet the following system requirements:</p>
|
16 |
-
<table>
|
17 |
-
<tr>
|
18 |
-
<th>Platform</th>
|
19 |
-
<th>Minimum</th>
|
20 |
-
<th>Recommended</th>
|
21 |
-
</tr>
|
22 |
-
<tr>
|
23 |
-
<td>PC (Windows)</td>
|
24 |
-
<td><ul><li>OS: Windows 10 - 64 bit</li><li>CPU: Intel Core i5-2300 / AMD FX-4350</li><li>RAM: 8 GB</li><li>GPU: GeForce GTX 660 Ti / Radeon HD 7790</li><li>Storage: 50 GB</li></ul></td>
|
25 |
-
<td><ul><li>OS: Windows 10 - 64 bit</li><li>CPU: Intel Core i5-7600 / AMD Ryzen 5 1600</li><li>RAM: 8 GB</li><li>GPU: GeForce GTX 1060 / AMD Radeon RX 590</li><li>Storage: 50 GB</li></ul></td>
|
26 |
-
</tr>
|
27 |
-
<tr>
|
28 |
-
<td>Android</td>
|
29 |
-
<td><ul><li>OS: Android 4.4 or higher</li><li>CPU: Quad-core or higher</li><li>RAM: 2 GB or higher</li><li>Storage: 1 GB or higher</li></ul></td>
|
30 |
-
<td>N/A</td>
|
31 |
-
</tr>
|
32 |
-
</table>
|
33 |
-
<h2>Tips and tricks</h2>
|
34 |
-
<p>If you want to improve your performance in Real Football 2023, here are some tips and tricks that might help you:</p>
|
35 |
-
<ul>
|
36 |
-
<li><strong> </strong>Practice your skills</strong>: The game has a training mode where you can practice your skills and techniques. You can also customize your training sessions to focus on specific aspects of the game, such as shooting, passing, dribbling, etc.</li>
|
37 |
-
<li><strong>Use the right formation and strategy</strong>: Depending on your play style and the opponent's team, you might want to use different formations and strategies. You can change your formation and tactics before and during the match. You can also assign different roles and instructions to your players, such as captain, free kick taker, target man, etc.</li>
|
38 |
-
<li><strong>Manage your stamina and morale</strong>: Your players have stamina and morale bars that affect their performance on the pitch. Stamina decreases as the player runs, sprints, or performs actions. Morale increases or decreases depending on the player's performance, team's performance, and match events. You can use substitutions, timeouts, and pep talks to restore your players' stamina and morale.</li>
|
39 |
-
<li><strong>Use the power-ups</strong>: The game has various power-ups that you can use to gain an advantage over your opponent. Some of the power-ups are: speed boost, accuracy boost, shield, freeze, magnet, etc. You can activate them by tapping on the screen or using the buttons on the bottom right corner.</li>
|
40 |
-
<li><strong>Collect and upgrade cards</strong>: The game has a card system that lets you collect and upgrade different types of cards. There are player cards, coach cards, stadium cards, and sponsor cards. Each card has a rarity level and a set of attributes that affect your team's performance. You can upgrade your cards by using coins or gems.</li>
|
41 |
-
</ul>
|
42 |
-
<h2>Reviews</h2>
|
43 |
-
<p>Real Football 2023 has received mostly positive reviews from critics and players alike. Here are some of the reviews from different sources:</p>
|
44 |
-
<ul>
|
45 |
-
<li><em>"Real Football 2023 is a great soccer game that offers a lot of fun and challenge for soccer fans. The graphics are amazing, the gameplay is smooth and realistic, and the game modes are varied and engaging. The game is also free to play, which is a big plus." - Android Authority</em></li>
|
46 |
-
<li><em>"If you're looking for a soccer game that delivers a realistic and immersive experience, Real Football 2023 is the game for you. The game has everything you need to enjoy the beautiful game: authentic teams, realistic physics, intuitive controls, and various game modes. The game is also updated regularly with new content and features." - PC Gamer</em></li>
|
47 |
-
<li><em>"Real Football 2023 is one of the best soccer games I've ever played. The game is very addictive and fun to play. The graphics are stunning, the gameplay is challenging and rewarding, and the game modes are diverse and exciting. The game is also very user-friendly and easy to play." - Google Play user</em></li>
|
48 |
-
</ul>
|
49 |
-
<h2>Conclusion</h2>
|
50 |
-
<p>Real Football 2023 is a game that every soccer fan should try. The game offers a realistic and immersive soccer experience that will keep you hooked for hours. Whether you want to create your own dream team, challenge other players online, or just enjoy a casual match, Real Football 2023 has something for everyone. You can download Real Football 2023 apk for free from the official website or from Google Play Store.</p>
|
51 |
-
<p>real football: soccer 2023 apk free download<br />
|
52 |
-
download real football 2023 android game apk<br />
|
53 |
-
real football 2023 apk latest version download<br />
|
54 |
-
real football 2023 apk mod unlimited money download<br />
|
55 |
-
how to download real football 2023 apk for pc<br />
|
56 |
-
real football 2023 apk offline download<br />
|
57 |
-
real football 2023 apk full game download<br />
|
58 |
-
real football 2023 apk + data download<br />
|
59 |
-
real football 2023 apk hack download<br />
|
60 |
-
real football 2023 apk obb download<br />
|
61 |
-
real football 2023 apk update download<br />
|
62 |
-
real football 2023 apk online download<br />
|
63 |
-
real football 2023 apk cracked download<br />
|
64 |
-
real football 2023 apk premium download<br />
|
65 |
-
real football 2023 apk pro download<br />
|
66 |
-
real football 2023 apk file download<br />
|
67 |
-
real football 2023 apk mirror download<br />
|
68 |
-
real football 2023 apk direct download<br />
|
69 |
-
real football 2023 apk play store download<br />
|
70 |
-
real football 2023 apk old version download<br />
|
71 |
-
real football 2023 apk new version download<br />
|
72 |
-
real football 2023 apk beta download<br />
|
73 |
-
real football 2023 apk original download<br />
|
74 |
-
real football 2023 apk review download<br />
|
75 |
-
real football 2023 apk cheat download<br />
|
76 |
-
real football 2023 apk patch download<br />
|
77 |
-
real football 2023 apk install download<br />
|
78 |
-
real football 2023 apk android tv download<br />
|
79 |
-
real football 2023 apk android tablet download<br />
|
80 |
-
real football 2023 apk android phone download<br />
|
81 |
-
real football 2023 apk android emulator download<br />
|
82 |
-
real football 2023 apk android studio download<br />
|
83 |
-
real football 2023 apk android app download<br />
|
84 |
-
real football 2023 apk android gamepad download<br />
|
85 |
-
real football 2023 apk android device download<br />
|
86 |
-
real football 2023 apk android sdk download<br />
|
87 |
-
real football 2023 apk android oreo download<br />
|
88 |
-
real football 2023 apk android pie download<br />
|
89 |
-
real football 2023 apk android q download<br />
|
90 |
-
real football 2023 apk android r download<br />
|
91 |
-
real football 2023 apk android s download<br />
|
92 |
-
real football 2023 apk gameloft se download<br />
|
93 |
-
real football: soccer game by magic app - free - mobile game for android - latest version:0.5 - updated:23 - com.mt.football.sports.action.soccer.games - free - mobile game for android - latest version:0.5 - updated:23 - com.mt.football.sports.action.soccer.games - free - mobile game for android - latest version:0.5 - updated:23 - com.mt.football.sports.action.soccer.games - free - mobile game for android - latest version:0.5 - updated:23 - com.mt.football.sports.action.soccer.games - free - mobile game for android - latest version:0.5 - updated:23 - com.mt.football.sports.action.soccer.games - free - mobile game for android - latest version:0.5 - updated:23 - com.mt.football.sports.action.soccer.games</p>
|
94 |
-
<h2>FAQs</h2>
|
95 |
-
<p>Here are some of the frequently asked questions about Real Football 2023:</p>
|
96 |
-
<ul>
|
97 |
-
<li><strong>Q: How do I download Real Football 2023 apk?</strong></li>
|
98 |
-
<li>A: You can download Real Football 2023 apk from the official website or from Google Play Store. Just follow the instructions on the screen and install the game on your device.</li>
|
99 |
-
<li><strong>Q: Is Real Football 2023 offline or online?</strong></li>
|
100 |
-
<li>A: Real Football 2023 can be played both offline and online. You can play offline in career mode or training mode. You can play online in PvP matches or leagues.</li>
|
101 |
-
<li><strong>Q: How do I get coins and gems in Real Football 2023?</strong></li>
|
102 |
-
<li>A: You can get coins and gems in Real Football 2023 by playing matches, completing achievements, watching ads, or buying them with real money.</li>
|
103 |
-
<li><strong>Q: How do I unlock new teams and players in Real Football 2023?</strong></li>
|
104 |
-
<li>A: You can unlock new teams and players in Real Football 2023 by collecting and upgrading cards. You can get cards by opening packs, winning matches, or buying them with coins or gems.</li>
|
105 |
-
<li><strong>Q: How do I contact the support team of Real Football 2023?</strong></li <li>A: You can contact the support team of Real Football 2023 by sending an email to [email protected] or by visiting the official website and filling out the contact form.</li>
|
106 |
-
</ul>
|
107 |
-
<p>I hope you enjoyed this article and learned something new about Real Football 2023 apk download. If you have any questions or feedback, feel free to leave a comment below. Thank you for reading and have fun playing Real Football 2023!</p> 197e85843d<br />
|
108 |
-
<br />
|
109 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Enjoy Football Strike with MOD APK and Unlimited Money on Android 1.md
DELETED
@@ -1,83 +0,0 @@
|
|
1 |
-
|
2 |
-
<h1>Football Strike Mod APK Android 1: A Fun and Exciting Soccer Game</h1>
|
3 |
-
<h2>Introduction</h2>
|
4 |
-
<p>If you are a fan of soccer games, you might have heard of Football Strike, a popular free-kick game developed by Miniclip. In this game, you can challenge your friends or other players from around the world in various modes, such as free kick, shooting race, or career. You can also customize your striker and goalkeeper with different outfits, balls, gloves, and shoes.</p>
|
5 |
-
<p>However, if you want to enjoy the game to the fullest, you might need to spend some real money to unlock all the items and features. That's why many players are looking for a modded version of Football Strike that can give them unlimited money and other benefits. In this article, we will introduce you to Football Strike Mod APK Android 1, a modified version of the game that can provide you with unlimited fun and excitement.</p>
|
6 |
-
<h2>football strike mod apk android 1</h2><br /><p><b><b>Download</b> ⚙ <a href="https://jinyurl.com/2uNTLM">https://jinyurl.com/2uNTLM</a></b></p><br /><br />
|
7 |
-
<h2>Why download Football Strike Mod APK Android 1?</h2>
|
8 |
-
<p>Football Strike Mod APK Android 1 is a hacked version of the original game that can give you access to all the premium features without spending a dime. By downloading this modded version, you can enjoy the following benefits:</p>
|
9 |
-
<h2>Features of Football Strike Mod APK Android 1</h2>
|
10 |
-
<h3>Unlimited money</h3>
|
11 |
-
<p>With Football Strike Mod APK Android 1, you can get unlimited money in your account. You can use this money to buy any item or upgrade you want in the game. You can also unlock all the stadiums, leagues, and tournaments without any hassle.</p>
|
12 |
-
<h3>Multiplayer mode</h3>
|
13 |
-
<p>Football Strike Mod APK Android 1 allows you to play online with your friends or other players from around the world. You can choose from different modes, such as free kick, shooting race, or career. You can also chat with your opponents and send them emojis and stickers.</p>
|
14 |
-
<h3>Career mode</h3>
|
15 |
-
<p>If you want to test your skills and become a soccer legend, you can try the career mode in Football Strike Mod APK Android 1. In this mode, you can play against different teams and players in various challenges and tournaments. You can also earn trophies and rewards as you progress.</p>
|
16 |
-
<h3>Customization options</h3>
|
17 |
-
<p>Football Strike Mod APK Android 1 gives you the freedom to customize your striker and goalkeeper with tons of items. You can choose from different outfits, balls, gloves, shoes, hairstyles, tattoos, and more. You can also show off your style or represent your team's colors.</p>
|
18 |
-
<h3>Realistic graphics and sound effects</h3>
|
19 |
-
<p>Football Strike Mod APK Android 1 has stunning graphics and sound effects that make the game more realistic and immersive. You can enjoy the smooth animations and physics of the game, as well as the cheering crowds and commentary. You can also adjust the graphics settings according to your device's performance.</p>
|
20 |
-
<h2>How to download and install Football Strike Mod APK Android 1</h2>
|
21 |
-
<p>If you are interested in downloading and installing Football Strike Mod APK Android 1 on your Android device, you can follow these simple steps:</p>
|
22 |
-
<p>football strike hack apk download for android<br />
|
23 |
-
football strike unlimited money mod apk latest version<br />
|
24 |
-
football strike multiplayer soccer mod apk free<br />
|
25 |
-
football strike miniclip mod apk android 1<br />
|
26 |
-
football strike modded apk online game<br />
|
27 |
-
football strike cheats apk no root<br />
|
28 |
-
football strike premium mod apk unlocked<br />
|
29 |
-
football strike mod apk unlimited cash and coins<br />
|
30 |
-
football strike hack mod apk 2023<br />
|
31 |
-
football strike vip mod apk download<br />
|
32 |
-
football strike pro mod apk revdl<br />
|
33 |
-
football strike mod apk offline mode<br />
|
34 |
-
football strike mod apk android republic<br />
|
35 |
-
football strike mega mod apk unlimited everything<br />
|
36 |
-
football strike mod apk new update<br />
|
37 |
-
football strike hack tool apk without verification<br />
|
38 |
-
football strike cracked mod apk full version<br />
|
39 |
-
football strike mod apk all balls unlocked<br />
|
40 |
-
football strike hack generator apk no survey<br />
|
41 |
-
football strike mod menu apk god mode<br />
|
42 |
-
football strike extreme mod apk unlimited gems<br />
|
43 |
-
football strike super mod apk anti ban<br />
|
44 |
-
football strike mod apk obb data file<br />
|
45 |
-
football strike hack version apk original<br />
|
46 |
-
football strike beta mod apk latest<br />
|
47 |
-
football strike real mod apk no ads<br />
|
48 |
-
football strike ultimate mod apk high damage<br />
|
49 |
-
football strike hack online apk easy<br />
|
50 |
-
football strike mod apk rexdl.com<br />
|
51 |
-
football strike private server mod apk working<br />
|
52 |
-
football strike hack appvn apk safe<br />
|
53 |
-
football strike best mod apk 1.43.2<br />
|
54 |
-
football strike old version mod apk 1.0.0<br />
|
55 |
-
football strike lite mod apk low mb<br />
|
56 |
-
football strike gold mod apk unlimited keys<br />
|
57 |
-
football strike fun mod apk with friends<br />
|
58 |
-
football strike lucky patcher mod apk 2023/06/16<br />
|
59 |
-
football strike xmodgames mod apk ios<br />
|
60 |
-
football strike master mod apk android oyun club<br />
|
61 |
-
football strike royal mod apk android 1.com</p>
|
62 |
-
<h3>Step 1: Enable unknown sources</h3>
|
63 |
-
<p>Before you can install any APK file on your device, you need to enable unknown sources in your security settings. To do this, go to Settings > Security > Unknown Sources and toggle it on.</p>
|
64 |
-
<h3>Step 2: Download the APK file</h3>
|
65 |
-
<p>Next, you need to download the APK file of Football Strike Mod APK Android 1 from a reliable source. <h3>Step 3: Install the APK file</h3>
|
66 |
-
<p>After downloading the APK file, you need to locate it in your file manager and tap on it to start the installation process. You might see a pop-up asking for your permission to install the app. Just tap on Install and wait for a few seconds.</p>
|
67 |
-
<h3>Step 4: Launch the game and enjoy</h3>
|
68 |
-
<p>Once the installation is complete, you can launch the game from your app drawer or home screen. You can now enjoy Football Strike Mod APK Android 1 with unlimited money and other features.</p>
|
69 |
-
<h2>Conclusion</h2>
|
70 |
-
<p>Football Strike Mod APK Android 1 is a great soccer game that can provide you with hours of fun and excitement. You can play online with your friends or other players, customize your striker and goalkeeper, and enjoy realistic graphics and sound effects. You can also get unlimited money and access to all the items and features in the game without spending any real money. If you are looking for a modded version of Football Strike, you should definitely try Football Strike Mod APK Android 1.</p>
|
71 |
-
<h2>FAQs</h2>
|
72 |
-
<h4>Is Football Strike Mod APK Android 1 safe to download and install?</h4>
|
73 |
-
<p>Yes, Football Strike Mod APK Android 1 is safe to download and install on your Android device. It does not contain any viruses or malware that can harm your device or data. However, you should always download it from a trusted source and enable unknown sources in your security settings before installing it.</p>
|
74 |
-
<h4>Does Football Strike Mod APK Android 1 require root access?</h4>
|
75 |
-
<p>No, Football Strike Mod APK Android 1 does not require root access to work on your device. You can install and play it without rooting your device or modifying any system files.</p>
|
76 |
-
<h4>Can I play Football Strike Mod APK Android 1 offline?</h4>
|
77 |
-
<p>No, Football Strike Mod APK Android 1 requires an internet connection to work properly. You need to connect to the internet to play online with other players, access the career mode, and update the game.</p>
|
78 |
-
<h4>Can I update Football Strike Mod APK Android 1 to the latest version?</h4>
|
79 |
-
<p>Yes, you can update Football Strike Mod APK Android 1 to the latest version whenever there is a new update available. However, you might need to uninstall the previous version and download the new version from the same source. You might also lose your progress and data if you update the game.</p>
|
80 |
-
<h4>Can I use my existing account to play Football Strike Mod APK Android 1?</h4>
|
81 |
-
<p>No, you cannot use your existing account to play Football Strike Mod APK Android 1. You need to create a new account or use a guest account to play the modded version of the game. If you use your existing account, you might get banned or suspended by the game developers.</p> 401be4b1e0<br />
|
82 |
-
<br />
|
83 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/2023Liu2023/bingo/src/lib/hooks/use-bing.ts
DELETED
@@ -1,173 +0,0 @@
|
|
1 |
-
'use client'
|
2 |
-
|
3 |
-
import { useState, useCallback, useEffect, useMemo } from 'react'
|
4 |
-
import { useAtom, useAtomValue } from 'jotai'
|
5 |
-
import { chatFamily, bingConversationStyleAtom, GreetMessages, hashAtom, voiceAtom } from '@/state'
|
6 |
-
import { setConversationMessages } from './chat-history'
|
7 |
-
import { ChatMessageModel, BotId, FileItem } from '@/lib/bots/bing/types'
|
8 |
-
import { nanoid } from '../utils'
|
9 |
-
import { TTS } from '../bots/bing/tts'
|
10 |
-
|
11 |
-
export function useBing(botId: BotId = 'bing') {
|
12 |
-
const chatAtom = useMemo(() => chatFamily({ botId, page: 'singleton' }), [botId])
|
13 |
-
const [enableTTS] = useAtom(voiceAtom)
|
14 |
-
const speaker = useMemo(() => new TTS(), [])
|
15 |
-
const [hash, setHash] = useAtom(hashAtom)
|
16 |
-
const bingConversationStyle = useAtomValue(bingConversationStyleAtom)
|
17 |
-
const [chatState, setChatState] = useAtom(chatAtom)
|
18 |
-
const [input, setInput] = useState('')
|
19 |
-
const [attachmentList, setAttachmentList] = useState<FileItem[]>([])
|
20 |
-
|
21 |
-
const updateMessage = useCallback(
|
22 |
-
(messageId: string, updater: (message: ChatMessageModel) => void) => {
|
23 |
-
setChatState((draft) => {
|
24 |
-
const message = draft.messages.find((m) => m.id === messageId)
|
25 |
-
if (message) {
|
26 |
-
updater(message)
|
27 |
-
}
|
28 |
-
})
|
29 |
-
},
|
30 |
-
[setChatState],
|
31 |
-
)
|
32 |
-
|
33 |
-
const sendMessage = useCallback(
|
34 |
-
async (input: string, options = {}) => {
|
35 |
-
const botMessageId = nanoid()
|
36 |
-
const imageUrl = attachmentList?.[0]?.status === 'loaded' ? attachmentList[0].url : undefined
|
37 |
-
setChatState((draft) => {
|
38 |
-
const text = imageUrl ? `${input}\n\n` : input
|
39 |
-
draft.messages.push({ id: nanoid(), text, author: 'user' }, { id: botMessageId, text: '', author: 'bot' })
|
40 |
-
setAttachmentList([])
|
41 |
-
})
|
42 |
-
const abortController = new AbortController()
|
43 |
-
setChatState((draft) => {
|
44 |
-
draft.generatingMessageId = botMessageId
|
45 |
-
draft.abortController = abortController
|
46 |
-
})
|
47 |
-
speaker.reset()
|
48 |
-
await chatState.bot.sendMessage({
|
49 |
-
prompt: input,
|
50 |
-
imageUrl: /\?bcid=([^&]+)/.test(imageUrl ?? '') ? `https://www.bing.com/images/blob?bcid=${RegExp.$1}` : imageUrl,
|
51 |
-
options: {
|
52 |
-
...options,
|
53 |
-
bingConversationStyle,
|
54 |
-
},
|
55 |
-
signal: abortController.signal,
|
56 |
-
onEvent(event) {
|
57 |
-
if (event.type === 'UPDATE_ANSWER') {
|
58 |
-
updateMessage(botMessageId, (message) => {
|
59 |
-
if (event.data.text.length > message.text.length) {
|
60 |
-
message.text = event.data.text
|
61 |
-
}
|
62 |
-
|
63 |
-
if (event.data.spokenText && enableTTS) {
|
64 |
-
speaker.speak(event.data.spokenText)
|
65 |
-
}
|
66 |
-
|
67 |
-
message.throttling = event.data.throttling || message.throttling
|
68 |
-
message.sourceAttributions = event.data.sourceAttributions || message.sourceAttributions
|
69 |
-
message.suggestedResponses = event.data.suggestedResponses || message.suggestedResponses
|
70 |
-
})
|
71 |
-
} else if (event.type === 'ERROR') {
|
72 |
-
updateMessage(botMessageId, (message) => {
|
73 |
-
message.error = event.error
|
74 |
-
})
|
75 |
-
setChatState((draft) => {
|
76 |
-
draft.abortController = undefined
|
77 |
-
draft.generatingMessageId = ''
|
78 |
-
})
|
79 |
-
} else if (event.type === 'DONE') {
|
80 |
-
setChatState((draft) => {
|
81 |
-
draft.abortController = undefined
|
82 |
-
draft.generatingMessageId = ''
|
83 |
-
})
|
84 |
-
}
|
85 |
-
},
|
86 |
-
})
|
87 |
-
},
|
88 |
-
[botId, attachmentList, chatState.bot, setChatState, updateMessage],
|
89 |
-
)
|
90 |
-
|
91 |
-
const uploadImage = useCallback(async (imgUrl: string) => {
|
92 |
-
setAttachmentList([{ url: imgUrl, status: 'loading' }])
|
93 |
-
const response = await chatState.bot.uploadImage(imgUrl, bingConversationStyle)
|
94 |
-
if (response?.blobId) {
|
95 |
-
setAttachmentList([{ url: `/api/blob?bcid=${response.blobId}`, status: 'loaded' }])
|
96 |
-
} else {
|
97 |
-
setAttachmentList([{ url: imgUrl, status: 'error' }])
|
98 |
-
}
|
99 |
-
}, [chatState.bot])
|
100 |
-
|
101 |
-
const resetConversation = useCallback(() => {
|
102 |
-
chatState.bot.resetConversation()
|
103 |
-
speaker.abort()
|
104 |
-
setChatState((draft) => {
|
105 |
-
draft.abortController = undefined
|
106 |
-
draft.generatingMessageId = ''
|
107 |
-
draft.messages = [{ author: 'bot', text: GreetMessages[Math.floor(GreetMessages.length * Math.random())], id: nanoid() }]
|
108 |
-
draft.conversationId = nanoid()
|
109 |
-
})
|
110 |
-
}, [chatState.bot, setChatState])
|
111 |
-
|
112 |
-
const stopGenerating = useCallback(() => {
|
113 |
-
chatState.abortController?.abort()
|
114 |
-
if (chatState.generatingMessageId) {
|
115 |
-
updateMessage(chatState.generatingMessageId, (message) => {
|
116 |
-
if (!message.text && !message.error) {
|
117 |
-
message.text = 'Cancelled'
|
118 |
-
}
|
119 |
-
})
|
120 |
-
}
|
121 |
-
setChatState((draft) => {
|
122 |
-
draft.generatingMessageId = ''
|
123 |
-
})
|
124 |
-
}, [chatState.abortController, chatState.generatingMessageId, setChatState, updateMessage])
|
125 |
-
|
126 |
-
useEffect(() => {
|
127 |
-
if (chatState.messages.length) {
|
128 |
-
setConversationMessages(botId, chatState.conversationId, chatState.messages)
|
129 |
-
}
|
130 |
-
}, [botId, chatState.conversationId, chatState.messages])
|
131 |
-
|
132 |
-
useEffect(() => {
|
133 |
-
if (hash === 'reset') {
|
134 |
-
resetConversation()
|
135 |
-
setHash('')
|
136 |
-
}
|
137 |
-
}, [hash, setHash])
|
138 |
-
|
139 |
-
const chat = useMemo(
|
140 |
-
() => ({
|
141 |
-
botId,
|
142 |
-
bot: chatState.bot,
|
143 |
-
isSpeaking: speaker.isSpeaking,
|
144 |
-
messages: chatState.messages,
|
145 |
-
sendMessage,
|
146 |
-
setInput,
|
147 |
-
input,
|
148 |
-
resetConversation,
|
149 |
-
generating: !!chatState.generatingMessageId,
|
150 |
-
stopGenerating,
|
151 |
-
uploadImage,
|
152 |
-
setAttachmentList,
|
153 |
-
attachmentList,
|
154 |
-
}),
|
155 |
-
[
|
156 |
-
botId,
|
157 |
-
bingConversationStyle,
|
158 |
-
chatState.bot,
|
159 |
-
chatState.generatingMessageId,
|
160 |
-
chatState.messages,
|
161 |
-
speaker.isSpeaking,
|
162 |
-
setInput,
|
163 |
-
input,
|
164 |
-
setAttachmentList,
|
165 |
-
attachmentList,
|
166 |
-
resetConversation,
|
167 |
-
sendMessage,
|
168 |
-
stopGenerating,
|
169 |
-
],
|
170 |
-
)
|
171 |
-
|
172 |
-
return chat
|
173 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/4Taps/SadTalker/src/face3d/models/arcface_torch/configs/base.py
DELETED
@@ -1,56 +0,0 @@
|
|
1 |
-
from easydict import EasyDict as edict
|
2 |
-
|
3 |
-
# make training faster
|
4 |
-
# our RAM is 256G
|
5 |
-
# mount -t tmpfs -o size=140G tmpfs /train_tmp
|
6 |
-
|
7 |
-
config = edict()
|
8 |
-
config.loss = "arcface"
|
9 |
-
config.network = "r50"
|
10 |
-
config.resume = False
|
11 |
-
config.output = "ms1mv3_arcface_r50"
|
12 |
-
|
13 |
-
config.dataset = "ms1m-retinaface-t1"
|
14 |
-
config.embedding_size = 512
|
15 |
-
config.sample_rate = 1
|
16 |
-
config.fp16 = False
|
17 |
-
config.momentum = 0.9
|
18 |
-
config.weight_decay = 5e-4
|
19 |
-
config.batch_size = 128
|
20 |
-
config.lr = 0.1 # batch size is 512
|
21 |
-
|
22 |
-
if config.dataset == "emore":
|
23 |
-
config.rec = "/train_tmp/faces_emore"
|
24 |
-
config.num_classes = 85742
|
25 |
-
config.num_image = 5822653
|
26 |
-
config.num_epoch = 16
|
27 |
-
config.warmup_epoch = -1
|
28 |
-
config.decay_epoch = [8, 14, ]
|
29 |
-
config.val_targets = ["lfw", ]
|
30 |
-
|
31 |
-
elif config.dataset == "ms1m-retinaface-t1":
|
32 |
-
config.rec = "/train_tmp/ms1m-retinaface-t1"
|
33 |
-
config.num_classes = 93431
|
34 |
-
config.num_image = 5179510
|
35 |
-
config.num_epoch = 25
|
36 |
-
config.warmup_epoch = -1
|
37 |
-
config.decay_epoch = [11, 17, 22]
|
38 |
-
config.val_targets = ["lfw", "cfp_fp", "agedb_30"]
|
39 |
-
|
40 |
-
elif config.dataset == "glint360k":
|
41 |
-
config.rec = "/train_tmp/glint360k"
|
42 |
-
config.num_classes = 360232
|
43 |
-
config.num_image = 17091657
|
44 |
-
config.num_epoch = 20
|
45 |
-
config.warmup_epoch = -1
|
46 |
-
config.decay_epoch = [8, 12, 15, 18]
|
47 |
-
config.val_targets = ["lfw", "cfp_fp", "agedb_30"]
|
48 |
-
|
49 |
-
elif config.dataset == "webface":
|
50 |
-
config.rec = "/train_tmp/faces_webface_112x112"
|
51 |
-
config.num_classes = 10572
|
52 |
-
config.num_image = "forget"
|
53 |
-
config.num_epoch = 34
|
54 |
-
config.warmup_epoch = -1
|
55 |
-
config.decay_epoch = [20, 28, 32]
|
56 |
-
config.val_targets = ["lfw", "cfp_fp", "agedb_30"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/7hao/bingo/src/components/ui/input.tsx
DELETED
@@ -1,25 +0,0 @@
|
|
1 |
-
import * as React from 'react'
|
2 |
-
|
3 |
-
import { cn } from '@/lib/utils'
|
4 |
-
|
5 |
-
export interface InputProps
|
6 |
-
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
7 |
-
|
8 |
-
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
9 |
-
({ className, type, ...props }, ref) => {
|
10 |
-
return (
|
11 |
-
<input
|
12 |
-
type={type}
|
13 |
-
className={cn(
|
14 |
-
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
15 |
-
className
|
16 |
-
)}
|
17 |
-
ref={ref}
|
18 |
-
{...props}
|
19 |
-
/>
|
20 |
-
)
|
21 |
-
}
|
22 |
-
)
|
23 |
-
Input.displayName = 'Input'
|
24 |
-
|
25 |
-
export { Input }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AAYUSH27/Neuro/installation_steps.md
DELETED
@@ -1,43 +0,0 @@
|
|
1 |
-
|
2 |
-
## Make sure you have git-lfs installed [Git LFS](https://git-lfs.com) ✅
|
3 |
-
# 🧑🏻💻Steps to download the Code
|
4 |
-
|
5 |
-
**📌 NOTE-1: If the Llama 2 Model is not donwloaded then the code will not work properly.**
|
6 |
-
|
7 |
-
**📌 NOTE-2: If the HuggingFaces API is not in ```.env``` file then generate your own API key from HugginFaces and use it.**
|
8 |
-
|
9 |
-
---
|
10 |
-
|
11 |
-
Step:0
|
12 |
-
- Copy and Paste the below command in terminal.
|
13 |
-
- This command will help to download the code to your local machine.
|
14 |
-
```shell
|
15 |
-
git clone https://huggingface.co/spaces/AAYUSH27/Neuro
|
16 |
-
```
|
17 |
-
- The file is of approx. 5GB
|
18 |
-
- If you want to clone without large files (Llama 2 Model).
|
19 |
-
```shell
|
20 |
-
git clone https://huggingface.co/spaces/AAYUSH27/Neuro
|
21 |
-
GIT_LFS_SKIP_SMUDGE=1
|
22 |
-
```
|
23 |
-
|
24 |
-
Step:1
|
25 |
-
- Copy and Paste the below command in terminal.
|
26 |
-
- This command helps to go into the project directory.
|
27 |
-
```shell
|
28 |
-
cd Neuro
|
29 |
-
```
|
30 |
-
|
31 |
-
Step:2
|
32 |
-
- Copy and Paste the below command in terminal.
|
33 |
-
- This commmand helps to install all the libraries in one take from ```requirements.txt```.
|
34 |
-
```shell
|
35 |
-
pip3 install -r requirements.txt
|
36 |
-
```
|
37 |
-
|
38 |
-
Step:3
|
39 |
-
- Copy and Paste the below command in terminal.
|
40 |
-
- This command helps to run the code into local host via ```streamlit```.
|
41 |
-
```shell
|
42 |
-
streamlit run -app.py
|
43 |
-
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIGC-Audio/Make_An_Audio_inpaint/vocoder/bigvgan/activations.py
DELETED
@@ -1,120 +0,0 @@
|
|
1 |
-
# Implementation adapted from https://github.com/EdwardDixon/snake under the MIT license.
|
2 |
-
# LICENSE is in incl_licenses directory.
|
3 |
-
|
4 |
-
import torch
|
5 |
-
from torch import nn, sin, pow
|
6 |
-
from torch.nn import Parameter
|
7 |
-
|
8 |
-
|
9 |
-
class Snake(nn.Module):
|
10 |
-
'''
|
11 |
-
Implementation of a sine-based periodic activation function
|
12 |
-
Shape:
|
13 |
-
- Input: (B, C, T)
|
14 |
-
- Output: (B, C, T), same shape as the input
|
15 |
-
Parameters:
|
16 |
-
- alpha - trainable parameter
|
17 |
-
References:
|
18 |
-
- This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
19 |
-
https://arxiv.org/abs/2006.08195
|
20 |
-
Examples:
|
21 |
-
>>> a1 = snake(256)
|
22 |
-
>>> x = torch.randn(256)
|
23 |
-
>>> x = a1(x)
|
24 |
-
'''
|
25 |
-
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
|
26 |
-
'''
|
27 |
-
Initialization.
|
28 |
-
INPUT:
|
29 |
-
- in_features: shape of the input
|
30 |
-
- alpha: trainable parameter
|
31 |
-
alpha is initialized to 1 by default, higher values = higher-frequency.
|
32 |
-
alpha will be trained along with the rest of your model.
|
33 |
-
'''
|
34 |
-
super(Snake, self).__init__()
|
35 |
-
self.in_features = in_features
|
36 |
-
|
37 |
-
# initialize alpha
|
38 |
-
self.alpha_logscale = alpha_logscale
|
39 |
-
if self.alpha_logscale: # log scale alphas initialized to zeros
|
40 |
-
self.alpha = Parameter(torch.zeros(in_features) * alpha)
|
41 |
-
else: # linear scale alphas initialized to ones
|
42 |
-
self.alpha = Parameter(torch.ones(in_features) * alpha)
|
43 |
-
|
44 |
-
self.alpha.requires_grad = alpha_trainable
|
45 |
-
|
46 |
-
self.no_div_by_zero = 0.000000001
|
47 |
-
|
48 |
-
def forward(self, x):
|
49 |
-
'''
|
50 |
-
Forward pass of the function.
|
51 |
-
Applies the function to the input elementwise.
|
52 |
-
Snake ∶= x + 1/a * sin^2 (xa)
|
53 |
-
'''
|
54 |
-
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
|
55 |
-
if self.alpha_logscale:
|
56 |
-
alpha = torch.exp(alpha)
|
57 |
-
x = x + (1.0 / (alpha + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
|
58 |
-
|
59 |
-
return x
|
60 |
-
|
61 |
-
|
62 |
-
class SnakeBeta(nn.Module):
|
63 |
-
'''
|
64 |
-
A modified Snake function which uses separate parameters for the magnitude of the periodic components
|
65 |
-
Shape:
|
66 |
-
- Input: (B, C, T)
|
67 |
-
- Output: (B, C, T), same shape as the input
|
68 |
-
Parameters:
|
69 |
-
- alpha - trainable parameter that controls frequency
|
70 |
-
- beta - trainable parameter that controls magnitude
|
71 |
-
References:
|
72 |
-
- This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
|
73 |
-
https://arxiv.org/abs/2006.08195
|
74 |
-
Examples:
|
75 |
-
>>> a1 = snakebeta(256)
|
76 |
-
>>> x = torch.randn(256)
|
77 |
-
>>> x = a1(x)
|
78 |
-
'''
|
79 |
-
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
|
80 |
-
'''
|
81 |
-
Initialization.
|
82 |
-
INPUT:
|
83 |
-
- in_features: shape of the input
|
84 |
-
- alpha - trainable parameter that controls frequency
|
85 |
-
- beta - trainable parameter that controls magnitude
|
86 |
-
alpha is initialized to 1 by default, higher values = higher-frequency.
|
87 |
-
beta is initialized to 1 by default, higher values = higher-magnitude.
|
88 |
-
alpha will be trained along with the rest of your model.
|
89 |
-
'''
|
90 |
-
super(SnakeBeta, self).__init__()
|
91 |
-
self.in_features = in_features
|
92 |
-
|
93 |
-
# initialize alpha
|
94 |
-
self.alpha_logscale = alpha_logscale
|
95 |
-
if self.alpha_logscale: # log scale alphas initialized to zeros
|
96 |
-
self.alpha = Parameter(torch.zeros(in_features) * alpha)
|
97 |
-
self.beta = Parameter(torch.zeros(in_features) * alpha)
|
98 |
-
else: # linear scale alphas initialized to ones
|
99 |
-
self.alpha = Parameter(torch.ones(in_features) * alpha)
|
100 |
-
self.beta = Parameter(torch.ones(in_features) * alpha)
|
101 |
-
|
102 |
-
self.alpha.requires_grad = alpha_trainable
|
103 |
-
self.beta.requires_grad = alpha_trainable
|
104 |
-
|
105 |
-
self.no_div_by_zero = 0.000000001
|
106 |
-
|
107 |
-
def forward(self, x):
|
108 |
-
'''
|
109 |
-
Forward pass of the function.
|
110 |
-
Applies the function to the input elementwise.
|
111 |
-
SnakeBeta ∶= x + 1/b * sin^2 (xa)
|
112 |
-
'''
|
113 |
-
alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
|
114 |
-
beta = self.beta.unsqueeze(0).unsqueeze(-1)
|
115 |
-
if self.alpha_logscale:
|
116 |
-
alpha = torch.exp(alpha)
|
117 |
-
beta = torch.exp(beta)
|
118 |
-
x = x + (1.0 / (beta + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
|
119 |
-
|
120 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AISuperheroes/08GR-KitchenSink-AIUIUX/demos/kitchen_sink/files/Readme.md
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
Creates directory on demos/kitchen_sink/files/ to store programmatic load files
|
|
|
|
spaces/Ababababababbababa/Ashaar/poetry_diacritizer/util/text_cleaners.py
DELETED
@@ -1,146 +0,0 @@
|
|
1 |
-
import re
|
2 |
-
from .constants import VALID_ARABIC
|
3 |
-
from itertools import product, combinations
|
4 |
-
|
5 |
-
_whitespace_re = re.compile(r"\s+")
|
6 |
-
|
7 |
-
|
8 |
-
def collapse_whitespace(text):
|
9 |
-
text = re.sub(_whitespace_re, " ", text)
|
10 |
-
return text
|
11 |
-
|
12 |
-
|
13 |
-
def basic_cleaners(text):
|
14 |
-
text = collapse_whitespace(text)
|
15 |
-
return text.strip()
|
16 |
-
|
17 |
-
|
18 |
-
# def valid_arabic_cleaners(text):
|
19 |
-
# text = filter(lambda char: char in VALID_ARABIC, text)
|
20 |
-
# text = collapse_whitespace(''.join(list(text)))
|
21 |
-
# return text.strip()
|
22 |
-
|
23 |
-
harakat = ["\u0650", "\u064E", "\u064F"] # [kasra, fatha, damma, ]
|
24 |
-
sukun = ["\u0652"] # [sukun]
|
25 |
-
mostly_saken = [
|
26 |
-
"\u0627",
|
27 |
-
"\u0648",
|
28 |
-
"\u0649",
|
29 |
-
"\u064A",
|
30 |
-
] # [alef, waw, alef maqsurah, ya'a]
|
31 |
-
|
32 |
-
always_saken = [
|
33 |
-
"\u0627",
|
34 |
-
"\u0649",
|
35 |
-
]
|
36 |
-
|
37 |
-
tnween_chars = [
|
38 |
-
"\u064c",
|
39 |
-
"\u064d",
|
40 |
-
"\u064b",
|
41 |
-
] # damm tanween, kasra tanween, fatha tanween, maddah
|
42 |
-
shadda_chars = ["\u0651"]
|
43 |
-
all_tashkeel = harakat+tnween_chars+sukun+shadda_chars
|
44 |
-
|
45 |
-
|
46 |
-
all_chars = list("إةابتثجحخدذرزسشصضطظعغفقكلمنهويىأءئؤ ")
|
47 |
-
prem_chars = harakat + sukun + mostly_saken + tnween_chars + shadda_chars + all_chars
|
48 |
-
|
49 |
-
def not_valid_tashkeel_comb(comb):
|
50 |
-
all_comb = list(product(harakat+sukun+tnween_chars, repeat = 2))+list(product(shadda_chars+sukun, repeat = 2))
|
51 |
-
if comb in all_comb or comb[::-1] in all_comb:
|
52 |
-
return True
|
53 |
-
else:
|
54 |
-
return False
|
55 |
-
|
56 |
-
def remove_tanween_on_alef(text):
|
57 |
-
text_copy = ""
|
58 |
-
for i in range(0, len(text)):
|
59 |
-
|
60 |
-
# if there is shaddah or character followed by alef followed by tanween add
|
61 |
-
if i < len(text) - 2 and text[i] in all_chars+shadda_chars and text[i+1] in always_saken and text[i+2] == tnween_chars[2]:
|
62 |
-
text_copy += text[i] + tnween_chars[2]
|
63 |
-
|
64 |
-
#ignore current harakah if there is alef followed by tanween
|
65 |
-
elif i < len(text) - 2 and text[i] in harakat and text[i+1] in always_saken and text[i+2] == tnween_chars[2] :
|
66 |
-
text_copy += tnween_chars[2]
|
67 |
-
|
68 |
-
# if the current char is tanween with alef is the previous character drop tanween
|
69 |
-
elif i > 0 and text[i] == tnween_chars[2] and text[i-1] in always_saken:
|
70 |
-
continue
|
71 |
-
|
72 |
-
else:
|
73 |
-
text_copy += text[i]
|
74 |
-
return text_copy
|
75 |
-
|
76 |
-
def dont_start_by_harakah(text):
|
77 |
-
text_copy = ""
|
78 |
-
for i, char in enumerate(text):
|
79 |
-
if not(char in all_tashkeel):
|
80 |
-
text_copy = text[i:]
|
81 |
-
break
|
82 |
-
return text_copy
|
83 |
-
|
84 |
-
def valid_arabic_cleaners(text):
|
85 |
-
prev_text = text
|
86 |
-
for i in range(5):
|
87 |
-
text = prev_text
|
88 |
-
cleaned_text = ""
|
89 |
-
text = filter(lambda char: char in VALID_ARABIC, text)
|
90 |
-
text = collapse_whitespace(''.join(list(text)))
|
91 |
-
text = dont_start_by_harakah(text)
|
92 |
-
text = text.strip()
|
93 |
-
i = 0
|
94 |
-
cnt = 0
|
95 |
-
len_text = len(text)
|
96 |
-
while( i < len_text):
|
97 |
-
if text[i] in all_tashkeel:
|
98 |
-
cnt += 1
|
99 |
-
else:
|
100 |
-
cnt = 0
|
101 |
-
|
102 |
-
# don't allow three consecutive tashkeel
|
103 |
-
if cnt > 2:
|
104 |
-
i+= 1
|
105 |
-
continue
|
106 |
-
|
107 |
-
# remove second tanween and sukun
|
108 |
-
if i > 1 and text[i] in tnween_chars+sukun and text[i-2] in tnween_chars+sukun:
|
109 |
-
i += 1
|
110 |
-
continue
|
111 |
-
|
112 |
-
# don't allow harakah followed by shaddah or tanween
|
113 |
-
if i < len(text) - 1 and text[i] in harakat and text[i+1] in tnween_chars+sukun+shadda_chars:
|
114 |
-
i += 1
|
115 |
-
continue
|
116 |
-
|
117 |
-
# don't allow harkah on space
|
118 |
-
if i> 0 and text[i] in all_tashkeel and text[i-1] == " " :
|
119 |
-
i += 1
|
120 |
-
continue
|
121 |
-
|
122 |
-
# only allow permissable combinations
|
123 |
-
if not_valid_tashkeel_comb((text[i], text[i-1])):
|
124 |
-
i+=1
|
125 |
-
continue
|
126 |
-
|
127 |
-
# don't allow harkah on alef, alef maqsura, if there is no tashkeel before move it back
|
128 |
-
if i> 1 and text[i] in harakat and text[i-1] in always_saken :
|
129 |
-
if text[i-2] in all_tashkeel: # in case there is a tashkeelah before alef
|
130 |
-
continue
|
131 |
-
else:
|
132 |
-
cleaned_text = text[:i-1]+text[i]+ always_saken[always_saken.index(text[i-1])]
|
133 |
-
i += 1
|
134 |
-
|
135 |
-
if i < len(text):
|
136 |
-
cleaned_text+= text[i]
|
137 |
-
i += 1
|
138 |
-
|
139 |
-
# only allow tanween before alef
|
140 |
-
cleaned_text = remove_tanween_on_alef(cleaned_text)
|
141 |
-
cleaned_text = re.sub(r" +", " ", cleaned_text).strip()
|
142 |
-
if prev_text == cleaned_text:
|
143 |
-
break
|
144 |
-
else:
|
145 |
-
prev_text = cleaned_text
|
146 |
-
return cleaned_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Abhilashvj/planogram-compliance/utils/docker/Dockerfile
DELETED
@@ -1,66 +0,0 @@
|
|
1 |
-
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
2 |
-
# Builds ultralytics/yolov5:latest image on DockerHub https://hub.docker.com/r/ultralytics/yolov5
|
3 |
-
# Image is CUDA-optimized for YOLOv5 single/multi-GPU training and inference
|
4 |
-
|
5 |
-
# Start FROM NVIDIA PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
|
6 |
-
FROM nvcr.io/nvidia/pytorch:22.12-py3
|
7 |
-
RUN rm -rf /opt/pytorch # remove 1.2GB dir
|
8 |
-
|
9 |
-
# Downloads to user config dir
|
10 |
-
ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/
|
11 |
-
|
12 |
-
# Install linux packages
|
13 |
-
RUN apt update && apt install --no-install-recommends -y zip htop screen libgl1-mesa-glx
|
14 |
-
|
15 |
-
# Install pip packages (uninstall torch nightly in favor of stable)
|
16 |
-
COPY requirements.txt .
|
17 |
-
RUN python -m pip install --upgrade pip wheel
|
18 |
-
RUN pip uninstall -y Pillow torchtext torch torchvision
|
19 |
-
RUN pip install --no-cache -U pycocotools # install --upgrade
|
20 |
-
RUN pip install --no-cache -r requirements.txt albumentations comet gsutil notebook 'opencv-python<4.6.0.66' \
|
21 |
-
Pillow>=9.1.0 ultralytics \
|
22 |
-
--extra-index-url https://download.pytorch.org/whl/cu113
|
23 |
-
|
24 |
-
# Create working directory
|
25 |
-
RUN mkdir -p /usr/src/app
|
26 |
-
WORKDIR /usr/src/app
|
27 |
-
|
28 |
-
# Copy contents
|
29 |
-
# COPY . /usr/src/app (issues as not a .git directory)
|
30 |
-
RUN git clone https://github.com/ultralytics/yolov5 /usr/src/app
|
31 |
-
|
32 |
-
# Set environment variables
|
33 |
-
ENV OMP_NUM_THREADS=1
|
34 |
-
|
35 |
-
|
36 |
-
# Usage Examples -------------------------------------------------------------------------------------------------------
|
37 |
-
|
38 |
-
# Build and Push
|
39 |
-
# t=ultralytics/yolov5:latest && sudo docker build -f utils/docker/Dockerfile -t $t . && sudo docker push $t
|
40 |
-
|
41 |
-
# Pull and Run
|
42 |
-
# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t
|
43 |
-
|
44 |
-
# Pull and Run with local directory access
|
45 |
-
# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t
|
46 |
-
|
47 |
-
# Kill all
|
48 |
-
# sudo docker kill $(sudo docker ps -q)
|
49 |
-
|
50 |
-
# Kill all image-based
|
51 |
-
# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest)
|
52 |
-
|
53 |
-
# DockerHub tag update
|
54 |
-
# t=ultralytics/yolov5:latest tnew=ultralytics/yolov5:v6.2 && sudo docker pull $t && sudo docker tag $t $tnew && sudo docker push $tnew
|
55 |
-
|
56 |
-
# Clean up
|
57 |
-
# docker system prune -a --volumes
|
58 |
-
|
59 |
-
# Update Ubuntu drivers
|
60 |
-
# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/
|
61 |
-
|
62 |
-
# DDP test
|
63 |
-
# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3
|
64 |
-
|
65 |
-
# GCP VM from Image
|
66 |
-
# docker.io/ultralytics/yolov5:latest
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AchyuthGamer/OpenGPT-Chat-UI/src/lib/utils/loadClientCerts.ts
DELETED
@@ -1,50 +0,0 @@
|
|
1 |
-
import * as fs from "fs";
|
2 |
-
import { setGlobalDispatcher, Agent } from "undici";
|
3 |
-
|
4 |
-
/**
|
5 |
-
* Load client certificates for mutual TLS authentication. This function must be called before any HTTP requests are made.
|
6 |
-
* This is a global setting that affects all HTTP requests made by the application using the native fetch API.
|
7 |
-
*
|
8 |
-
* @param clientCertPath Path to client certificate
|
9 |
-
* @param clientKeyPath Path to client key
|
10 |
-
* @param caCertPath Path to CA certificate [optional]
|
11 |
-
* @param clientKeyPassword Password for client key [optional]
|
12 |
-
* @param rejectUnauthorized Reject unauthorized certificates.
|
13 |
-
* Only use for testing/development, not recommended in production environments [optional]
|
14 |
-
*
|
15 |
-
* @returns void
|
16 |
-
*
|
17 |
-
* @example
|
18 |
-
* ```typescript
|
19 |
-
* loadClientCertificates("cert.pem", "key.pem", "ca.pem", "password", false);
|
20 |
-
* ```
|
21 |
-
*
|
22 |
-
* @see
|
23 |
-
* [Undici Agent](https://undici.nodejs.org/#/docs/api/Agent)
|
24 |
-
* @see
|
25 |
-
* [Undici Dispatcher](https://undici.nodejs.org/#/docs/api/Dispatcher)
|
26 |
-
* @see
|
27 |
-
* [NodeJS Native Fetch API](https://nodejs.org/docs/latest-v19.x/api/globals.html#fetch)
|
28 |
-
*/
|
29 |
-
export function loadClientCertificates(
|
30 |
-
clientCertPath: string,
|
31 |
-
clientKeyPath: string,
|
32 |
-
caCertPath?: string,
|
33 |
-
clientKeyPassword?: string,
|
34 |
-
rejectUnauthorized?: boolean
|
35 |
-
): void {
|
36 |
-
const clientCert = fs.readFileSync(clientCertPath);
|
37 |
-
const clientKey = fs.readFileSync(clientKeyPath);
|
38 |
-
const caCert = caCertPath ? fs.readFileSync(caCertPath) : undefined;
|
39 |
-
const agent = new Agent({
|
40 |
-
connect: {
|
41 |
-
cert: clientCert,
|
42 |
-
key: clientKey,
|
43 |
-
ca: caCert,
|
44 |
-
passphrase: clientKeyPassword,
|
45 |
-
rejectUnauthorized: rejectUnauthorized,
|
46 |
-
},
|
47 |
-
});
|
48 |
-
|
49 |
-
setGlobalDispatcher(agent);
|
50 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AiMimicry/sovits-models/modules/modules.py
DELETED
@@ -1,342 +0,0 @@
|
|
1 |
-
import copy
|
2 |
-
import math
|
3 |
-
import numpy as np
|
4 |
-
import scipy
|
5 |
-
import torch
|
6 |
-
from torch import nn
|
7 |
-
from torch.nn import functional as F
|
8 |
-
|
9 |
-
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
|
10 |
-
from torch.nn.utils import weight_norm, remove_weight_norm
|
11 |
-
|
12 |
-
import modules.commons as commons
|
13 |
-
from modules.commons import init_weights, get_padding
|
14 |
-
|
15 |
-
|
16 |
-
LRELU_SLOPE = 0.1
|
17 |
-
|
18 |
-
|
19 |
-
class LayerNorm(nn.Module):
|
20 |
-
def __init__(self, channels, eps=1e-5):
|
21 |
-
super().__init__()
|
22 |
-
self.channels = channels
|
23 |
-
self.eps = eps
|
24 |
-
|
25 |
-
self.gamma = nn.Parameter(torch.ones(channels))
|
26 |
-
self.beta = nn.Parameter(torch.zeros(channels))
|
27 |
-
|
28 |
-
def forward(self, x):
|
29 |
-
x = x.transpose(1, -1)
|
30 |
-
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
31 |
-
return x.transpose(1, -1)
|
32 |
-
|
33 |
-
|
34 |
-
class ConvReluNorm(nn.Module):
|
35 |
-
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
|
36 |
-
super().__init__()
|
37 |
-
self.in_channels = in_channels
|
38 |
-
self.hidden_channels = hidden_channels
|
39 |
-
self.out_channels = out_channels
|
40 |
-
self.kernel_size = kernel_size
|
41 |
-
self.n_layers = n_layers
|
42 |
-
self.p_dropout = p_dropout
|
43 |
-
assert n_layers > 1, "Number of layers should be larger than 0."
|
44 |
-
|
45 |
-
self.conv_layers = nn.ModuleList()
|
46 |
-
self.norm_layers = nn.ModuleList()
|
47 |
-
self.conv_layers.append(nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size//2))
|
48 |
-
self.norm_layers.append(LayerNorm(hidden_channels))
|
49 |
-
self.relu_drop = nn.Sequential(
|
50 |
-
nn.ReLU(),
|
51 |
-
nn.Dropout(p_dropout))
|
52 |
-
for _ in range(n_layers-1):
|
53 |
-
self.conv_layers.append(nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size//2))
|
54 |
-
self.norm_layers.append(LayerNorm(hidden_channels))
|
55 |
-
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
|
56 |
-
self.proj.weight.data.zero_()
|
57 |
-
self.proj.bias.data.zero_()
|
58 |
-
|
59 |
-
def forward(self, x, x_mask):
|
60 |
-
x_org = x
|
61 |
-
for i in range(self.n_layers):
|
62 |
-
x = self.conv_layers[i](x * x_mask)
|
63 |
-
x = self.norm_layers[i](x)
|
64 |
-
x = self.relu_drop(x)
|
65 |
-
x = x_org + self.proj(x)
|
66 |
-
return x * x_mask
|
67 |
-
|
68 |
-
|
69 |
-
class DDSConv(nn.Module):
|
70 |
-
"""
|
71 |
-
Dialted and Depth-Separable Convolution
|
72 |
-
"""
|
73 |
-
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.):
|
74 |
-
super().__init__()
|
75 |
-
self.channels = channels
|
76 |
-
self.kernel_size = kernel_size
|
77 |
-
self.n_layers = n_layers
|
78 |
-
self.p_dropout = p_dropout
|
79 |
-
|
80 |
-
self.drop = nn.Dropout(p_dropout)
|
81 |
-
self.convs_sep = nn.ModuleList()
|
82 |
-
self.convs_1x1 = nn.ModuleList()
|
83 |
-
self.norms_1 = nn.ModuleList()
|
84 |
-
self.norms_2 = nn.ModuleList()
|
85 |
-
for i in range(n_layers):
|
86 |
-
dilation = kernel_size ** i
|
87 |
-
padding = (kernel_size * dilation - dilation) // 2
|
88 |
-
self.convs_sep.append(nn.Conv1d(channels, channels, kernel_size,
|
89 |
-
groups=channels, dilation=dilation, padding=padding
|
90 |
-
))
|
91 |
-
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
|
92 |
-
self.norms_1.append(LayerNorm(channels))
|
93 |
-
self.norms_2.append(LayerNorm(channels))
|
94 |
-
|
95 |
-
def forward(self, x, x_mask, g=None):
|
96 |
-
if g is not None:
|
97 |
-
x = x + g
|
98 |
-
for i in range(self.n_layers):
|
99 |
-
y = self.convs_sep[i](x * x_mask)
|
100 |
-
y = self.norms_1[i](y)
|
101 |
-
y = F.gelu(y)
|
102 |
-
y = self.convs_1x1[i](y)
|
103 |
-
y = self.norms_2[i](y)
|
104 |
-
y = F.gelu(y)
|
105 |
-
y = self.drop(y)
|
106 |
-
x = x + y
|
107 |
-
return x * x_mask
|
108 |
-
|
109 |
-
|
110 |
-
class WN(torch.nn.Module):
|
111 |
-
def __init__(self, hidden_channels, kernel_size, dilation_rate, n_layers, gin_channels=0, p_dropout=0):
|
112 |
-
super(WN, self).__init__()
|
113 |
-
assert(kernel_size % 2 == 1)
|
114 |
-
self.hidden_channels =hidden_channels
|
115 |
-
self.kernel_size = kernel_size,
|
116 |
-
self.dilation_rate = dilation_rate
|
117 |
-
self.n_layers = n_layers
|
118 |
-
self.gin_channels = gin_channels
|
119 |
-
self.p_dropout = p_dropout
|
120 |
-
|
121 |
-
self.in_layers = torch.nn.ModuleList()
|
122 |
-
self.res_skip_layers = torch.nn.ModuleList()
|
123 |
-
self.drop = nn.Dropout(p_dropout)
|
124 |
-
|
125 |
-
if gin_channels != 0:
|
126 |
-
cond_layer = torch.nn.Conv1d(gin_channels, 2*hidden_channels*n_layers, 1)
|
127 |
-
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name='weight')
|
128 |
-
|
129 |
-
for i in range(n_layers):
|
130 |
-
dilation = dilation_rate ** i
|
131 |
-
padding = int((kernel_size * dilation - dilation) / 2)
|
132 |
-
in_layer = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, kernel_size,
|
133 |
-
dilation=dilation, padding=padding)
|
134 |
-
in_layer = torch.nn.utils.weight_norm(in_layer, name='weight')
|
135 |
-
self.in_layers.append(in_layer)
|
136 |
-
|
137 |
-
# last one is not necessary
|
138 |
-
if i < n_layers - 1:
|
139 |
-
res_skip_channels = 2 * hidden_channels
|
140 |
-
else:
|
141 |
-
res_skip_channels = hidden_channels
|
142 |
-
|
143 |
-
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
|
144 |
-
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name='weight')
|
145 |
-
self.res_skip_layers.append(res_skip_layer)
|
146 |
-
|
147 |
-
def forward(self, x, x_mask, g=None, **kwargs):
|
148 |
-
output = torch.zeros_like(x)
|
149 |
-
n_channels_tensor = torch.IntTensor([self.hidden_channels])
|
150 |
-
|
151 |
-
if g is not None:
|
152 |
-
g = self.cond_layer(g)
|
153 |
-
|
154 |
-
for i in range(self.n_layers):
|
155 |
-
x_in = self.in_layers[i](x)
|
156 |
-
if g is not None:
|
157 |
-
cond_offset = i * 2 * self.hidden_channels
|
158 |
-
g_l = g[:,cond_offset:cond_offset+2*self.hidden_channels,:]
|
159 |
-
else:
|
160 |
-
g_l = torch.zeros_like(x_in)
|
161 |
-
|
162 |
-
acts = commons.fused_add_tanh_sigmoid_multiply(
|
163 |
-
x_in,
|
164 |
-
g_l,
|
165 |
-
n_channels_tensor)
|
166 |
-
acts = self.drop(acts)
|
167 |
-
|
168 |
-
res_skip_acts = self.res_skip_layers[i](acts)
|
169 |
-
if i < self.n_layers - 1:
|
170 |
-
res_acts = res_skip_acts[:,:self.hidden_channels,:]
|
171 |
-
x = (x + res_acts) * x_mask
|
172 |
-
output = output + res_skip_acts[:,self.hidden_channels:,:]
|
173 |
-
else:
|
174 |
-
output = output + res_skip_acts
|
175 |
-
return output * x_mask
|
176 |
-
|
177 |
-
def remove_weight_norm(self):
|
178 |
-
if self.gin_channels != 0:
|
179 |
-
torch.nn.utils.remove_weight_norm(self.cond_layer)
|
180 |
-
for l in self.in_layers:
|
181 |
-
torch.nn.utils.remove_weight_norm(l)
|
182 |
-
for l in self.res_skip_layers:
|
183 |
-
torch.nn.utils.remove_weight_norm(l)
|
184 |
-
|
185 |
-
|
186 |
-
class ResBlock1(torch.nn.Module):
|
187 |
-
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
|
188 |
-
super(ResBlock1, self).__init__()
|
189 |
-
self.convs1 = nn.ModuleList([
|
190 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
191 |
-
padding=get_padding(kernel_size, dilation[0]))),
|
192 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
193 |
-
padding=get_padding(kernel_size, dilation[1]))),
|
194 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[2],
|
195 |
-
padding=get_padding(kernel_size, dilation[2])))
|
196 |
-
])
|
197 |
-
self.convs1.apply(init_weights)
|
198 |
-
|
199 |
-
self.convs2 = nn.ModuleList([
|
200 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
201 |
-
padding=get_padding(kernel_size, 1))),
|
202 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
203 |
-
padding=get_padding(kernel_size, 1))),
|
204 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=1,
|
205 |
-
padding=get_padding(kernel_size, 1)))
|
206 |
-
])
|
207 |
-
self.convs2.apply(init_weights)
|
208 |
-
|
209 |
-
def forward(self, x, x_mask=None):
|
210 |
-
for c1, c2 in zip(self.convs1, self.convs2):
|
211 |
-
xt = F.leaky_relu(x, LRELU_SLOPE)
|
212 |
-
if x_mask is not None:
|
213 |
-
xt = xt * x_mask
|
214 |
-
xt = c1(xt)
|
215 |
-
xt = F.leaky_relu(xt, LRELU_SLOPE)
|
216 |
-
if x_mask is not None:
|
217 |
-
xt = xt * x_mask
|
218 |
-
xt = c2(xt)
|
219 |
-
x = xt + x
|
220 |
-
if x_mask is not None:
|
221 |
-
x = x * x_mask
|
222 |
-
return x
|
223 |
-
|
224 |
-
def remove_weight_norm(self):
|
225 |
-
for l in self.convs1:
|
226 |
-
remove_weight_norm(l)
|
227 |
-
for l in self.convs2:
|
228 |
-
remove_weight_norm(l)
|
229 |
-
|
230 |
-
|
231 |
-
class ResBlock2(torch.nn.Module):
|
232 |
-
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
|
233 |
-
super(ResBlock2, self).__init__()
|
234 |
-
self.convs = nn.ModuleList([
|
235 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[0],
|
236 |
-
padding=get_padding(kernel_size, dilation[0]))),
|
237 |
-
weight_norm(Conv1d(channels, channels, kernel_size, 1, dilation=dilation[1],
|
238 |
-
padding=get_padding(kernel_size, dilation[1])))
|
239 |
-
])
|
240 |
-
self.convs.apply(init_weights)
|
241 |
-
|
242 |
-
def forward(self, x, x_mask=None):
|
243 |
-
for c in self.convs:
|
244 |
-
xt = F.leaky_relu(x, LRELU_SLOPE)
|
245 |
-
if x_mask is not None:
|
246 |
-
xt = xt * x_mask
|
247 |
-
xt = c(xt)
|
248 |
-
x = xt + x
|
249 |
-
if x_mask is not None:
|
250 |
-
x = x * x_mask
|
251 |
-
return x
|
252 |
-
|
253 |
-
def remove_weight_norm(self):
|
254 |
-
for l in self.convs:
|
255 |
-
remove_weight_norm(l)
|
256 |
-
|
257 |
-
|
258 |
-
class Log(nn.Module):
|
259 |
-
def forward(self, x, x_mask, reverse=False, **kwargs):
|
260 |
-
if not reverse:
|
261 |
-
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
|
262 |
-
logdet = torch.sum(-y, [1, 2])
|
263 |
-
return y, logdet
|
264 |
-
else:
|
265 |
-
x = torch.exp(x) * x_mask
|
266 |
-
return x
|
267 |
-
|
268 |
-
|
269 |
-
class Flip(nn.Module):
|
270 |
-
def forward(self, x, *args, reverse=False, **kwargs):
|
271 |
-
x = torch.flip(x, [1])
|
272 |
-
if not reverse:
|
273 |
-
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
|
274 |
-
return x, logdet
|
275 |
-
else:
|
276 |
-
return x
|
277 |
-
|
278 |
-
|
279 |
-
class ElementwiseAffine(nn.Module):
|
280 |
-
def __init__(self, channels):
|
281 |
-
super().__init__()
|
282 |
-
self.channels = channels
|
283 |
-
self.m = nn.Parameter(torch.zeros(channels,1))
|
284 |
-
self.logs = nn.Parameter(torch.zeros(channels,1))
|
285 |
-
|
286 |
-
def forward(self, x, x_mask, reverse=False, **kwargs):
|
287 |
-
if not reverse:
|
288 |
-
y = self.m + torch.exp(self.logs) * x
|
289 |
-
y = y * x_mask
|
290 |
-
logdet = torch.sum(self.logs * x_mask, [1,2])
|
291 |
-
return y, logdet
|
292 |
-
else:
|
293 |
-
x = (x - self.m) * torch.exp(-self.logs) * x_mask
|
294 |
-
return x
|
295 |
-
|
296 |
-
|
297 |
-
class ResidualCouplingLayer(nn.Module):
|
298 |
-
def __init__(self,
|
299 |
-
channels,
|
300 |
-
hidden_channels,
|
301 |
-
kernel_size,
|
302 |
-
dilation_rate,
|
303 |
-
n_layers,
|
304 |
-
p_dropout=0,
|
305 |
-
gin_channels=0,
|
306 |
-
mean_only=False):
|
307 |
-
assert channels % 2 == 0, "channels should be divisible by 2"
|
308 |
-
super().__init__()
|
309 |
-
self.channels = channels
|
310 |
-
self.hidden_channels = hidden_channels
|
311 |
-
self.kernel_size = kernel_size
|
312 |
-
self.dilation_rate = dilation_rate
|
313 |
-
self.n_layers = n_layers
|
314 |
-
self.half_channels = channels // 2
|
315 |
-
self.mean_only = mean_only
|
316 |
-
|
317 |
-
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
|
318 |
-
self.enc = WN(hidden_channels, kernel_size, dilation_rate, n_layers, p_dropout=p_dropout, gin_channels=gin_channels)
|
319 |
-
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
|
320 |
-
self.post.weight.data.zero_()
|
321 |
-
self.post.bias.data.zero_()
|
322 |
-
|
323 |
-
def forward(self, x, x_mask, g=None, reverse=False):
|
324 |
-
x0, x1 = torch.split(x, [self.half_channels]*2, 1)
|
325 |
-
h = self.pre(x0) * x_mask
|
326 |
-
h = self.enc(h, x_mask, g=g)
|
327 |
-
stats = self.post(h) * x_mask
|
328 |
-
if not self.mean_only:
|
329 |
-
m, logs = torch.split(stats, [self.half_channels]*2, 1)
|
330 |
-
else:
|
331 |
-
m = stats
|
332 |
-
logs = torch.zeros_like(m)
|
333 |
-
|
334 |
-
if not reverse:
|
335 |
-
x1 = m + x1 * torch.exp(logs) * x_mask
|
336 |
-
x = torch.cat([x0, x1], 1)
|
337 |
-
logdet = torch.sum(logs, [1,2])
|
338 |
-
return x, logdet
|
339 |
-
else:
|
340 |
-
x1 = (x1 - m) * torch.exp(-logs) * x_mask
|
341 |
-
x = torch.cat([x0, x1], 1)
|
342 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Aki004/herta-so-vits/README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Herta So Vits
|
3 |
-
emoji: 🦀
|
4 |
-
colorFrom: red
|
5 |
-
colorTo: yellow
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.33.1
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: bsd
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AkiKagura/Marco-Generation-Img2img/README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Marco Generation Img2img
|
3 |
-
emoji: 🦀
|
4 |
-
colorFrom: gray
|
5 |
-
colorTo: green
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.8.1
|
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/AlexWang/lama/saicinpainting/training/trainers/__init__.py
DELETED
@@ -1,30 +0,0 @@
|
|
1 |
-
import logging
|
2 |
-
import torch
|
3 |
-
from saicinpainting.training.trainers.default import DefaultInpaintingTrainingModule
|
4 |
-
|
5 |
-
|
6 |
-
def get_training_model_class(kind):
|
7 |
-
if kind == 'default':
|
8 |
-
return DefaultInpaintingTrainingModule
|
9 |
-
|
10 |
-
raise ValueError(f'Unknown trainer module {kind}')
|
11 |
-
|
12 |
-
|
13 |
-
def make_training_model(config):
|
14 |
-
kind = config.training_model.kind
|
15 |
-
kwargs = dict(config.training_model)
|
16 |
-
kwargs.pop('kind')
|
17 |
-
kwargs['use_ddp'] = config.trainer.kwargs.get('accelerator', None) == 'ddp'
|
18 |
-
|
19 |
-
logging.info(f'Make training model {kind}')
|
20 |
-
|
21 |
-
cls = get_training_model_class(kind)
|
22 |
-
return cls(config, **kwargs)
|
23 |
-
|
24 |
-
|
25 |
-
def load_checkpoint(train_config, path, map_location='cuda', strict=True):
|
26 |
-
model: torch.nn.Module = make_training_model(train_config)
|
27 |
-
state = torch.load(path, map_location=map_location)
|
28 |
-
model.load_state_dict(state['state_dict'], strict=strict)
|
29 |
-
model.on_load_checkpoint(state)
|
30 |
-
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Amon1/ChatGPTForAcadamic/crazy_functions/test_project/cpp/cppipc/queue.h
DELETED
@@ -1,216 +0,0 @@
|
|
1 |
-
#pragma once
|
2 |
-
|
3 |
-
#include <type_traits>
|
4 |
-
#include <new>
|
5 |
-
#include <utility> // [[since C++14]]: std::exchange
|
6 |
-
#include <algorithm>
|
7 |
-
#include <atomic>
|
8 |
-
#include <tuple>
|
9 |
-
#include <thread>
|
10 |
-
#include <chrono>
|
11 |
-
#include <string>
|
12 |
-
#include <cassert> // assert
|
13 |
-
|
14 |
-
#include "libipc/def.h"
|
15 |
-
#include "libipc/shm.h"
|
16 |
-
#include "libipc/rw_lock.h"
|
17 |
-
|
18 |
-
#include "libipc/utility/log.h"
|
19 |
-
#include "libipc/platform/detail.h"
|
20 |
-
#include "libipc/circ/elem_def.h"
|
21 |
-
|
22 |
-
namespace ipc {
|
23 |
-
namespace detail {
|
24 |
-
|
25 |
-
class queue_conn {
|
26 |
-
protected:
|
27 |
-
circ::cc_t connected_ = 0;
|
28 |
-
shm::handle elems_h_;
|
29 |
-
|
30 |
-
template <typename Elems>
|
31 |
-
Elems* open(char const * name) {
|
32 |
-
if (name == nullptr || name[0] == '\0') {
|
33 |
-
ipc::error("fail open waiter: name is empty!\n");
|
34 |
-
return nullptr;
|
35 |
-
}
|
36 |
-
if (!elems_h_.acquire(name, sizeof(Elems))) {
|
37 |
-
return nullptr;
|
38 |
-
}
|
39 |
-
auto elems = static_cast<Elems*>(elems_h_.get());
|
40 |
-
if (elems == nullptr) {
|
41 |
-
ipc::error("fail acquire elems: %s\n", name);
|
42 |
-
return nullptr;
|
43 |
-
}
|
44 |
-
elems->init();
|
45 |
-
return elems;
|
46 |
-
}
|
47 |
-
|
48 |
-
void close() {
|
49 |
-
elems_h_.release();
|
50 |
-
}
|
51 |
-
|
52 |
-
public:
|
53 |
-
queue_conn() = default;
|
54 |
-
queue_conn(const queue_conn&) = delete;
|
55 |
-
queue_conn& operator=(const queue_conn&) = delete;
|
56 |
-
|
57 |
-
bool connected() const noexcept {
|
58 |
-
return connected_ != 0;
|
59 |
-
}
|
60 |
-
|
61 |
-
circ::cc_t connected_id() const noexcept {
|
62 |
-
return connected_;
|
63 |
-
}
|
64 |
-
|
65 |
-
template <typename Elems>
|
66 |
-
auto connect(Elems* elems) noexcept
|
67 |
-
/*needs 'optional' here*/
|
68 |
-
-> std::tuple<bool, bool, decltype(std::declval<Elems>().cursor())> {
|
69 |
-
if (elems == nullptr) return {};
|
70 |
-
// if it's already connected, just return
|
71 |
-
if (connected()) return {connected(), false, 0};
|
72 |
-
connected_ = elems->connect_receiver();
|
73 |
-
return {connected(), true, elems->cursor()};
|
74 |
-
}
|
75 |
-
|
76 |
-
template <typename Elems>
|
77 |
-
bool disconnect(Elems* elems) noexcept {
|
78 |
-
if (elems == nullptr) return false;
|
79 |
-
// if it's already disconnected, just return false
|
80 |
-
if (!connected()) return false;
|
81 |
-
elems->disconnect_receiver(std::exchange(connected_, 0));
|
82 |
-
return true;
|
83 |
-
}
|
84 |
-
};
|
85 |
-
|
86 |
-
template <typename Elems>
|
87 |
-
class queue_base : public queue_conn {
|
88 |
-
using base_t = queue_conn;
|
89 |
-
|
90 |
-
public:
|
91 |
-
using elems_t = Elems;
|
92 |
-
using policy_t = typename elems_t::policy_t;
|
93 |
-
|
94 |
-
protected:
|
95 |
-
elems_t * elems_ = nullptr;
|
96 |
-
decltype(std::declval<elems_t>().cursor()) cursor_ = 0;
|
97 |
-
bool sender_flag_ = false;
|
98 |
-
|
99 |
-
public:
|
100 |
-
using base_t::base_t;
|
101 |
-
|
102 |
-
queue_base() = default;
|
103 |
-
|
104 |
-
explicit queue_base(char const * name)
|
105 |
-
: queue_base{} {
|
106 |
-
elems_ = open<elems_t>(name);
|
107 |
-
}
|
108 |
-
|
109 |
-
explicit queue_base(elems_t * elems) noexcept
|
110 |
-
: queue_base{} {
|
111 |
-
assert(elems != nullptr);
|
112 |
-
elems_ = elems;
|
113 |
-
}
|
114 |
-
|
115 |
-
/* not virtual */ ~queue_base() {
|
116 |
-
base_t::close();
|
117 |
-
}
|
118 |
-
|
119 |
-
elems_t * elems() noexcept { return elems_; }
|
120 |
-
elems_t const * elems() const noexcept { return elems_; }
|
121 |
-
|
122 |
-
bool ready_sending() noexcept {
|
123 |
-
if (elems_ == nullptr) return false;
|
124 |
-
return sender_flag_ || (sender_flag_ = elems_->connect_sender());
|
125 |
-
}
|
126 |
-
|
127 |
-
void shut_sending() noexcept {
|
128 |
-
if (elems_ == nullptr) return;
|
129 |
-
if (!sender_flag_) return;
|
130 |
-
elems_->disconnect_sender();
|
131 |
-
}
|
132 |
-
|
133 |
-
bool connect() noexcept {
|
134 |
-
auto tp = base_t::connect(elems_);
|
135 |
-
if (std::get<0>(tp) && std::get<1>(tp)) {
|
136 |
-
cursor_ = std::get<2>(tp);
|
137 |
-
return true;
|
138 |
-
}
|
139 |
-
return std::get<0>(tp);
|
140 |
-
}
|
141 |
-
|
142 |
-
bool disconnect() noexcept {
|
143 |
-
return base_t::disconnect(elems_);
|
144 |
-
}
|
145 |
-
|
146 |
-
std::size_t conn_count() const noexcept {
|
147 |
-
return (elems_ == nullptr) ? static_cast<std::size_t>(invalid_value) : elems_->conn_count();
|
148 |
-
}
|
149 |
-
|
150 |
-
bool valid() const noexcept {
|
151 |
-
return elems_ != nullptr;
|
152 |
-
}
|
153 |
-
|
154 |
-
bool empty() const noexcept {
|
155 |
-
return !valid() || (cursor_ == elems_->cursor());
|
156 |
-
}
|
157 |
-
|
158 |
-
template <typename T, typename F, typename... P>
|
159 |
-
bool push(F&& prep, P&&... params) {
|
160 |
-
if (elems_ == nullptr) return false;
|
161 |
-
return elems_->push(this, [&](void* p) {
|
162 |
-
if (prep(p)) ::new (p) T(std::forward<P>(params)...);
|
163 |
-
});
|
164 |
-
}
|
165 |
-
|
166 |
-
template <typename T, typename F, typename... P>
|
167 |
-
bool force_push(F&& prep, P&&... params) {
|
168 |
-
if (elems_ == nullptr) return false;
|
169 |
-
return elems_->force_push(this, [&](void* p) {
|
170 |
-
if (prep(p)) ::new (p) T(std::forward<P>(params)...);
|
171 |
-
});
|
172 |
-
}
|
173 |
-
|
174 |
-
template <typename T, typename F>
|
175 |
-
bool pop(T& item, F&& out) {
|
176 |
-
if (elems_ == nullptr) {
|
177 |
-
return false;
|
178 |
-
}
|
179 |
-
return elems_->pop(this, &(this->cursor_), [&item](void* p) {
|
180 |
-
::new (&item) T(std::move(*static_cast<T*>(p)));
|
181 |
-
}, std::forward<F>(out));
|
182 |
-
}
|
183 |
-
};
|
184 |
-
|
185 |
-
} // namespace detail
|
186 |
-
|
187 |
-
template <typename T, typename Policy>
|
188 |
-
class queue final : public detail::queue_base<typename Policy::template elems_t<sizeof(T), alignof(T)>> {
|
189 |
-
using base_t = detail::queue_base<typename Policy::template elems_t<sizeof(T), alignof(T)>>;
|
190 |
-
|
191 |
-
public:
|
192 |
-
using value_t = T;
|
193 |
-
|
194 |
-
using base_t::base_t;
|
195 |
-
|
196 |
-
template <typename... P>
|
197 |
-
bool push(P&&... params) {
|
198 |
-
return base_t::template push<T>(std::forward<P>(params)...);
|
199 |
-
}
|
200 |
-
|
201 |
-
template <typename... P>
|
202 |
-
bool force_push(P&&... params) {
|
203 |
-
return base_t::template force_push<T>(std::forward<P>(params)...);
|
204 |
-
}
|
205 |
-
|
206 |
-
bool pop(T& item) {
|
207 |
-
return base_t::pop(item, [](bool) {});
|
208 |
-
}
|
209 |
-
|
210 |
-
template <typename F>
|
211 |
-
bool pop(T& item, F&& out) {
|
212 |
-
return base_t::pop(item, std::forward<F>(out));
|
213 |
-
}
|
214 |
-
};
|
215 |
-
|
216 |
-
} // namespace ipc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py
DELETED
@@ -1,661 +0,0 @@
|
|
1 |
-
# Copyright 2023 The Intel Labs Team Authors and the HuggingFace Team. All rights reserved.
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
# you may not use this file except in compliance with the License.
|
5 |
-
# You may obtain a copy of the License at
|
6 |
-
#
|
7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
#
|
9 |
-
# Unless required by applicable law or agreed to in writing, software
|
10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
# See the License for the specific language governing permissions and
|
13 |
-
# limitations under the License.
|
14 |
-
|
15 |
-
import inspect
|
16 |
-
from dataclasses import dataclass
|
17 |
-
from typing import Any, Callable, Dict, List, Optional, Union
|
18 |
-
|
19 |
-
import numpy as np
|
20 |
-
import PIL
|
21 |
-
import torch
|
22 |
-
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
23 |
-
|
24 |
-
from ...image_processor import VaeImageProcessorLDM3D
|
25 |
-
from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
26 |
-
from ...models import AutoencoderKL, UNet2DConditionModel
|
27 |
-
from ...schedulers import KarrasDiffusionSchedulers
|
28 |
-
from ...utils import (
|
29 |
-
BaseOutput,
|
30 |
-
is_accelerate_available,
|
31 |
-
is_accelerate_version,
|
32 |
-
logging,
|
33 |
-
randn_tensor,
|
34 |
-
replace_example_docstring,
|
35 |
-
)
|
36 |
-
from ..pipeline_utils import DiffusionPipeline
|
37 |
-
from .safety_checker import StableDiffusionSafetyChecker
|
38 |
-
|
39 |
-
|
40 |
-
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
41 |
-
|
42 |
-
EXAMPLE_DOC_STRING = """
|
43 |
-
Examples:
|
44 |
-
```py
|
45 |
-
>>> import torch
|
46 |
-
>>> from diffusers import StableDiffusionPipeline
|
47 |
-
|
48 |
-
>>> pipe = StableDiffusionLDM3DPipeline.from_pretrained("Intel/ldm3d")
|
49 |
-
>>> pipe = pipe.to("cuda")
|
50 |
-
|
51 |
-
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
52 |
-
>>> output = pipe(prompt)
|
53 |
-
>>> rgb_image, depth_image = output.rgb, output.depth
|
54 |
-
>>> rgb_image[0].save("astronaut_ldm3d_rgb.jpg")
|
55 |
-
>>> depth_image[0].save("astronaut_ldm3d_depth.png")
|
56 |
-
```
|
57 |
-
"""
|
58 |
-
|
59 |
-
|
60 |
-
@dataclass
|
61 |
-
class LDM3DPipelineOutput(BaseOutput):
|
62 |
-
"""
|
63 |
-
Output class for Stable Diffusion pipelines.
|
64 |
-
|
65 |
-
Args:
|
66 |
-
images (`List[PIL.Image.Image]` or `np.ndarray`)
|
67 |
-
List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
|
68 |
-
num_channels)`.
|
69 |
-
nsfw_content_detected (`List[bool]`)
|
70 |
-
List indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content or
|
71 |
-
`None` if safety checking could not be performed.
|
72 |
-
"""
|
73 |
-
|
74 |
-
rgb: Union[List[PIL.Image.Image], np.ndarray]
|
75 |
-
depth: Union[List[PIL.Image.Image], np.ndarray]
|
76 |
-
nsfw_content_detected: Optional[List[bool]]
|
77 |
-
|
78 |
-
|
79 |
-
class StableDiffusionLDM3DPipeline(
|
80 |
-
DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
|
81 |
-
):
|
82 |
-
r"""
|
83 |
-
Pipeline for text-to-image and 3D generation using LDM3D.
|
84 |
-
|
85 |
-
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
86 |
-
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
87 |
-
|
88 |
-
The pipeline also inherits the following loading methods:
|
89 |
-
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
90 |
-
- [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
91 |
-
- [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
92 |
-
- [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
|
93 |
-
|
94 |
-
Args:
|
95 |
-
vae ([`AutoencoderKL`]):
|
96 |
-
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
97 |
-
text_encoder ([`~transformers.CLIPTextModel`]):
|
98 |
-
Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
|
99 |
-
tokenizer ([`~transformers.CLIPTokenizer`]):
|
100 |
-
A `CLIPTokenizer` to tokenize text.
|
101 |
-
unet ([`UNet2DConditionModel`]):
|
102 |
-
A `UNet2DConditionModel` to denoise the encoded image latents.
|
103 |
-
scheduler ([`SchedulerMixin`]):
|
104 |
-
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
105 |
-
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
106 |
-
safety_checker ([`StableDiffusionSafetyChecker`]):
|
107 |
-
Classification module that estimates whether generated images could be considered offensive or harmful.
|
108 |
-
Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
|
109 |
-
about a model's potential harms.
|
110 |
-
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
111 |
-
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
112 |
-
"""
|
113 |
-
_optional_components = ["safety_checker", "feature_extractor"]
|
114 |
-
|
115 |
-
def __init__(
|
116 |
-
self,
|
117 |
-
vae: AutoencoderKL,
|
118 |
-
text_encoder: CLIPTextModel,
|
119 |
-
tokenizer: CLIPTokenizer,
|
120 |
-
unet: UNet2DConditionModel,
|
121 |
-
scheduler: KarrasDiffusionSchedulers,
|
122 |
-
safety_checker: StableDiffusionSafetyChecker,
|
123 |
-
feature_extractor: CLIPImageProcessor,
|
124 |
-
requires_safety_checker: bool = True,
|
125 |
-
):
|
126 |
-
super().__init__()
|
127 |
-
|
128 |
-
if safety_checker is None and requires_safety_checker:
|
129 |
-
logger.warning(
|
130 |
-
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
131 |
-
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
132 |
-
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
133 |
-
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
134 |
-
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
135 |
-
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
136 |
-
)
|
137 |
-
|
138 |
-
if safety_checker is not None and feature_extractor is None:
|
139 |
-
raise ValueError(
|
140 |
-
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
141 |
-
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
142 |
-
)
|
143 |
-
|
144 |
-
self.register_modules(
|
145 |
-
vae=vae,
|
146 |
-
text_encoder=text_encoder,
|
147 |
-
tokenizer=tokenizer,
|
148 |
-
unet=unet,
|
149 |
-
scheduler=scheduler,
|
150 |
-
safety_checker=safety_checker,
|
151 |
-
feature_extractor=feature_extractor,
|
152 |
-
)
|
153 |
-
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
154 |
-
self.image_processor = VaeImageProcessorLDM3D(vae_scale_factor=self.vae_scale_factor)
|
155 |
-
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
156 |
-
|
157 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
|
158 |
-
def enable_vae_slicing(self):
|
159 |
-
r"""
|
160 |
-
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
161 |
-
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
162 |
-
"""
|
163 |
-
self.vae.enable_slicing()
|
164 |
-
|
165 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
|
166 |
-
def disable_vae_slicing(self):
|
167 |
-
r"""
|
168 |
-
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
169 |
-
computing decoding in one step.
|
170 |
-
"""
|
171 |
-
self.vae.disable_slicing()
|
172 |
-
|
173 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
|
174 |
-
def enable_vae_tiling(self):
|
175 |
-
r"""
|
176 |
-
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
177 |
-
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
178 |
-
processing larger images.
|
179 |
-
"""
|
180 |
-
self.vae.enable_tiling()
|
181 |
-
|
182 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
|
183 |
-
def disable_vae_tiling(self):
|
184 |
-
r"""
|
185 |
-
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
186 |
-
computing decoding in one step.
|
187 |
-
"""
|
188 |
-
self.vae.disable_tiling()
|
189 |
-
|
190 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_model_cpu_offload
|
191 |
-
def enable_model_cpu_offload(self, gpu_id=0):
|
192 |
-
r"""
|
193 |
-
Offload all models to CPU to reduce memory usage with a low impact on performance. Moves one whole model at a
|
194 |
-
time to the GPU when its `forward` method is called, and the model remains in GPU until the next model runs.
|
195 |
-
Memory savings are lower than using `enable_sequential_cpu_offload`, but performance is much better due to the
|
196 |
-
iterative execution of the `unet`.
|
197 |
-
"""
|
198 |
-
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
|
199 |
-
from accelerate import cpu_offload_with_hook
|
200 |
-
else:
|
201 |
-
raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
|
202 |
-
|
203 |
-
device = torch.device(f"cuda:{gpu_id}")
|
204 |
-
|
205 |
-
if self.device.type != "cpu":
|
206 |
-
self.to("cpu", silence_dtype_warnings=True)
|
207 |
-
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
|
208 |
-
|
209 |
-
hook = None
|
210 |
-
for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
|
211 |
-
_, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
|
212 |
-
|
213 |
-
if self.safety_checker is not None:
|
214 |
-
_, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
|
215 |
-
|
216 |
-
# We'll offload the last model manually.
|
217 |
-
self.final_offload_hook = hook
|
218 |
-
|
219 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
|
220 |
-
def _encode_prompt(
|
221 |
-
self,
|
222 |
-
prompt,
|
223 |
-
device,
|
224 |
-
num_images_per_prompt,
|
225 |
-
do_classifier_free_guidance,
|
226 |
-
negative_prompt=None,
|
227 |
-
prompt_embeds: Optional[torch.FloatTensor] = None,
|
228 |
-
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
229 |
-
lora_scale: Optional[float] = None,
|
230 |
-
):
|
231 |
-
r"""
|
232 |
-
Encodes the prompt into text encoder hidden states.
|
233 |
-
|
234 |
-
Args:
|
235 |
-
prompt (`str` or `List[str]`, *optional*):
|
236 |
-
prompt to be encoded
|
237 |
-
device: (`torch.device`):
|
238 |
-
torch device
|
239 |
-
num_images_per_prompt (`int`):
|
240 |
-
number of images that should be generated per prompt
|
241 |
-
do_classifier_free_guidance (`bool`):
|
242 |
-
whether to use classifier free guidance or not
|
243 |
-
negative_prompt (`str` or `List[str]`, *optional*):
|
244 |
-
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
245 |
-
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
246 |
-
less than `1`).
|
247 |
-
prompt_embeds (`torch.FloatTensor`, *optional*):
|
248 |
-
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
249 |
-
provided, text embeddings will be generated from `prompt` input argument.
|
250 |
-
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
251 |
-
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
252 |
-
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
253 |
-
argument.
|
254 |
-
lora_scale (`float`, *optional*):
|
255 |
-
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
256 |
-
"""
|
257 |
-
# set lora scale so that monkey patched LoRA
|
258 |
-
# function of text encoder can correctly access it
|
259 |
-
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
260 |
-
self._lora_scale = lora_scale
|
261 |
-
|
262 |
-
if prompt is not None and isinstance(prompt, str):
|
263 |
-
batch_size = 1
|
264 |
-
elif prompt is not None and isinstance(prompt, list):
|
265 |
-
batch_size = len(prompt)
|
266 |
-
else:
|
267 |
-
batch_size = prompt_embeds.shape[0]
|
268 |
-
|
269 |
-
if prompt_embeds is None:
|
270 |
-
# textual inversion: procecss multi-vector tokens if necessary
|
271 |
-
if isinstance(self, TextualInversionLoaderMixin):
|
272 |
-
prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
|
273 |
-
|
274 |
-
text_inputs = self.tokenizer(
|
275 |
-
prompt,
|
276 |
-
padding="max_length",
|
277 |
-
max_length=self.tokenizer.model_max_length,
|
278 |
-
truncation=True,
|
279 |
-
return_tensors="pt",
|
280 |
-
)
|
281 |
-
text_input_ids = text_inputs.input_ids
|
282 |
-
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
|
283 |
-
|
284 |
-
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
|
285 |
-
text_input_ids, untruncated_ids
|
286 |
-
):
|
287 |
-
removed_text = self.tokenizer.batch_decode(
|
288 |
-
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
|
289 |
-
)
|
290 |
-
logger.warning(
|
291 |
-
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
292 |
-
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
293 |
-
)
|
294 |
-
|
295 |
-
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
296 |
-
attention_mask = text_inputs.attention_mask.to(device)
|
297 |
-
else:
|
298 |
-
attention_mask = None
|
299 |
-
|
300 |
-
prompt_embeds = self.text_encoder(
|
301 |
-
text_input_ids.to(device),
|
302 |
-
attention_mask=attention_mask,
|
303 |
-
)
|
304 |
-
prompt_embeds = prompt_embeds[0]
|
305 |
-
|
306 |
-
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
307 |
-
|
308 |
-
bs_embed, seq_len, _ = prompt_embeds.shape
|
309 |
-
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
310 |
-
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
311 |
-
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
312 |
-
|
313 |
-
# get unconditional embeddings for classifier free guidance
|
314 |
-
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
315 |
-
uncond_tokens: List[str]
|
316 |
-
if negative_prompt is None:
|
317 |
-
uncond_tokens = [""] * batch_size
|
318 |
-
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
319 |
-
raise TypeError(
|
320 |
-
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
321 |
-
f" {type(prompt)}."
|
322 |
-
)
|
323 |
-
elif isinstance(negative_prompt, str):
|
324 |
-
uncond_tokens = [negative_prompt]
|
325 |
-
elif batch_size != len(negative_prompt):
|
326 |
-
raise ValueError(
|
327 |
-
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
328 |
-
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
329 |
-
" the batch size of `prompt`."
|
330 |
-
)
|
331 |
-
else:
|
332 |
-
uncond_tokens = negative_prompt
|
333 |
-
|
334 |
-
# textual inversion: procecss multi-vector tokens if necessary
|
335 |
-
if isinstance(self, TextualInversionLoaderMixin):
|
336 |
-
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
|
337 |
-
|
338 |
-
max_length = prompt_embeds.shape[1]
|
339 |
-
uncond_input = self.tokenizer(
|
340 |
-
uncond_tokens,
|
341 |
-
padding="max_length",
|
342 |
-
max_length=max_length,
|
343 |
-
truncation=True,
|
344 |
-
return_tensors="pt",
|
345 |
-
)
|
346 |
-
|
347 |
-
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
|
348 |
-
attention_mask = uncond_input.attention_mask.to(device)
|
349 |
-
else:
|
350 |
-
attention_mask = None
|
351 |
-
|
352 |
-
negative_prompt_embeds = self.text_encoder(
|
353 |
-
uncond_input.input_ids.to(device),
|
354 |
-
attention_mask=attention_mask,
|
355 |
-
)
|
356 |
-
negative_prompt_embeds = negative_prompt_embeds[0]
|
357 |
-
|
358 |
-
if do_classifier_free_guidance:
|
359 |
-
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
360 |
-
seq_len = negative_prompt_embeds.shape[1]
|
361 |
-
|
362 |
-
negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
|
363 |
-
|
364 |
-
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
365 |
-
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
366 |
-
|
367 |
-
# For classifier free guidance, we need to do two forward passes.
|
368 |
-
# Here we concatenate the unconditional and text embeddings into a single batch
|
369 |
-
# to avoid doing two forward passes
|
370 |
-
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
371 |
-
|
372 |
-
return prompt_embeds
|
373 |
-
|
374 |
-
def run_safety_checker(self, image, device, dtype):
|
375 |
-
if self.safety_checker is None:
|
376 |
-
has_nsfw_concept = None
|
377 |
-
else:
|
378 |
-
if torch.is_tensor(image):
|
379 |
-
feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
|
380 |
-
else:
|
381 |
-
feature_extractor_input = self.image_processor.numpy_to_pil(image)
|
382 |
-
rgb_feature_extractor_input = feature_extractor_input[0]
|
383 |
-
safety_checker_input = self.feature_extractor(rgb_feature_extractor_input, return_tensors="pt").to(device)
|
384 |
-
image, has_nsfw_concept = self.safety_checker(
|
385 |
-
images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
|
386 |
-
)
|
387 |
-
return image, has_nsfw_concept
|
388 |
-
|
389 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
390 |
-
def prepare_extra_step_kwargs(self, generator, eta):
|
391 |
-
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
392 |
-
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
393 |
-
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
394 |
-
# and should be between [0, 1]
|
395 |
-
|
396 |
-
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
397 |
-
extra_step_kwargs = {}
|
398 |
-
if accepts_eta:
|
399 |
-
extra_step_kwargs["eta"] = eta
|
400 |
-
|
401 |
-
# check if the scheduler accepts generator
|
402 |
-
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
403 |
-
if accepts_generator:
|
404 |
-
extra_step_kwargs["generator"] = generator
|
405 |
-
return extra_step_kwargs
|
406 |
-
|
407 |
-
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
|
408 |
-
def check_inputs(
|
409 |
-
self,
|
410 |
-
prompt,
|
411 |
-
height,
|
412 |
-
width,
|
413 |
-
callback_steps,
|
414 |
-
negative_prompt=None,
|
415 |
-
prompt_embeds=None,
|
416 |
-
negative_prompt_embeds=None,
|
417 |
-
):
|
418 |
-
if height % 8 != 0 or width % 8 != 0:
|
419 |
-
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
420 |
-
|
421 |
-
if (callback_steps is None) or (
|
422 |
-
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
423 |
-
):
|
424 |
-
raise ValueError(
|
425 |
-
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
426 |
-
f" {type(callback_steps)}."
|
427 |
-
)
|
428 |
-
|
429 |
-
if prompt is not None and prompt_embeds is not None:
|
430 |
-
raise ValueError(
|
431 |
-
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
432 |
-
" only forward one of the two."
|
433 |
-
)
|
434 |
-
elif prompt is None and prompt_embeds is None:
|
435 |
-
raise ValueError(
|
436 |
-
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
437 |
-
)
|
438 |
-
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
439 |
-
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
440 |
-
|
441 |
-
if negative_prompt is not None and negative_prompt_embeds is not None:
|
442 |
-
raise ValueError(
|
443 |
-
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
444 |
-
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
445 |
-
)
|
446 |
-
|
447 |
-
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
448 |
-
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
449 |
-
raise ValueError(
|
450 |
-
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
451 |
-
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
452 |
-
f" {negative_prompt_embeds.shape}."
|
453 |
-
)
|
454 |
-
|
455 |
-
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
456 |
-
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
457 |
-
if isinstance(generator, list) and len(generator) != batch_size:
|
458 |
-
raise ValueError(
|
459 |
-
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
460 |
-
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
461 |
-
)
|
462 |
-
|
463 |
-
if latents is None:
|
464 |
-
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
465 |
-
else:
|
466 |
-
latents = latents.to(device)
|
467 |
-
|
468 |
-
# scale the initial noise by the standard deviation required by the scheduler
|
469 |
-
latents = latents * self.scheduler.init_noise_sigma
|
470 |
-
return latents
|
471 |
-
|
472 |
-
@torch.no_grad()
|
473 |
-
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
474 |
-
def __call__(
|
475 |
-
self,
|
476 |
-
prompt: Union[str, List[str]] = None,
|
477 |
-
height: Optional[int] = None,
|
478 |
-
width: Optional[int] = None,
|
479 |
-
num_inference_steps: int = 49,
|
480 |
-
guidance_scale: float = 5.0,
|
481 |
-
negative_prompt: Optional[Union[str, List[str]]] = None,
|
482 |
-
num_images_per_prompt: Optional[int] = 1,
|
483 |
-
eta: float = 0.0,
|
484 |
-
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
485 |
-
latents: Optional[torch.FloatTensor] = None,
|
486 |
-
prompt_embeds: Optional[torch.FloatTensor] = None,
|
487 |
-
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
488 |
-
output_type: Optional[str] = "pil",
|
489 |
-
return_dict: bool = True,
|
490 |
-
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
491 |
-
callback_steps: int = 1,
|
492 |
-
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
493 |
-
):
|
494 |
-
r"""
|
495 |
-
The call function to the pipeline for generation.
|
496 |
-
|
497 |
-
Args:
|
498 |
-
prompt (`str` or `List[str]`, *optional*):
|
499 |
-
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
500 |
-
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
501 |
-
The height in pixels of the generated image.
|
502 |
-
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
503 |
-
The width in pixels of the generated image.
|
504 |
-
num_inference_steps (`int`, *optional*, defaults to 50):
|
505 |
-
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
506 |
-
expense of slower inference.
|
507 |
-
guidance_scale (`float`, *optional*, defaults to 5.0):
|
508 |
-
A higher guidance scale value encourages the model to generate images closely linked to the text
|
509 |
-
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
510 |
-
negative_prompt (`str` or `List[str]`, *optional*):
|
511 |
-
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
512 |
-
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
513 |
-
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
514 |
-
The number of images to generate per prompt.
|
515 |
-
eta (`float`, *optional*, defaults to 0.0):
|
516 |
-
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
517 |
-
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
518 |
-
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
519 |
-
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
520 |
-
generation deterministic.
|
521 |
-
latents (`torch.FloatTensor`, *optional*):
|
522 |
-
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
523 |
-
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
524 |
-
tensor is generated by sampling using the supplied random `generator`.
|
525 |
-
prompt_embeds (`torch.FloatTensor`, *optional*):
|
526 |
-
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
527 |
-
provided, text embeddings are generated from the `prompt` input argument.
|
528 |
-
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
529 |
-
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
530 |
-
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
531 |
-
output_type (`str`, *optional*, defaults to `"pil"`):
|
532 |
-
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
533 |
-
return_dict (`bool`, *optional*, defaults to `True`):
|
534 |
-
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
535 |
-
plain tuple.
|
536 |
-
callback (`Callable`, *optional*):
|
537 |
-
A function that calls every `callback_steps` steps during inference. The function is called with the
|
538 |
-
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
539 |
-
callback_steps (`int`, *optional*, defaults to 1):
|
540 |
-
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
541 |
-
every step.
|
542 |
-
cross_attention_kwargs (`dict`, *optional*):
|
543 |
-
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
544 |
-
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
|
545 |
-
|
546 |
-
Examples:
|
547 |
-
|
548 |
-
Returns:
|
549 |
-
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
550 |
-
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
551 |
-
otherwise a `tuple` is returned where the first element is a list with the generated images and the
|
552 |
-
second element is a list of `bool`s indicating whether the corresponding generated image contains
|
553 |
-
"not-safe-for-work" (nsfw) content.
|
554 |
-
"""
|
555 |
-
# 0. Default height and width to unet
|
556 |
-
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
557 |
-
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
558 |
-
|
559 |
-
# 1. Check inputs. Raise error if not correct
|
560 |
-
self.check_inputs(
|
561 |
-
prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
|
562 |
-
)
|
563 |
-
|
564 |
-
# 2. Define call parameters
|
565 |
-
if prompt is not None and isinstance(prompt, str):
|
566 |
-
batch_size = 1
|
567 |
-
elif prompt is not None and isinstance(prompt, list):
|
568 |
-
batch_size = len(prompt)
|
569 |
-
else:
|
570 |
-
batch_size = prompt_embeds.shape[0]
|
571 |
-
|
572 |
-
device = self._execution_device
|
573 |
-
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
574 |
-
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
575 |
-
# corresponds to doing no classifier free guidance.
|
576 |
-
do_classifier_free_guidance = guidance_scale > 1.0
|
577 |
-
|
578 |
-
# 3. Encode input prompt
|
579 |
-
prompt_embeds = self._encode_prompt(
|
580 |
-
prompt,
|
581 |
-
device,
|
582 |
-
num_images_per_prompt,
|
583 |
-
do_classifier_free_guidance,
|
584 |
-
negative_prompt,
|
585 |
-
prompt_embeds=prompt_embeds,
|
586 |
-
negative_prompt_embeds=negative_prompt_embeds,
|
587 |
-
)
|
588 |
-
|
589 |
-
# 4. Prepare timesteps
|
590 |
-
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
591 |
-
timesteps = self.scheduler.timesteps
|
592 |
-
|
593 |
-
# 5. Prepare latent variables
|
594 |
-
num_channels_latents = self.unet.config.in_channels
|
595 |
-
latents = self.prepare_latents(
|
596 |
-
batch_size * num_images_per_prompt,
|
597 |
-
num_channels_latents,
|
598 |
-
height,
|
599 |
-
width,
|
600 |
-
prompt_embeds.dtype,
|
601 |
-
device,
|
602 |
-
generator,
|
603 |
-
latents,
|
604 |
-
)
|
605 |
-
|
606 |
-
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
607 |
-
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
608 |
-
|
609 |
-
# 7. Denoising loop
|
610 |
-
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
611 |
-
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
612 |
-
for i, t in enumerate(timesteps):
|
613 |
-
# expand the latents if we are doing classifier free guidance
|
614 |
-
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
615 |
-
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
616 |
-
|
617 |
-
# predict the noise residual
|
618 |
-
noise_pred = self.unet(
|
619 |
-
latent_model_input,
|
620 |
-
t,
|
621 |
-
encoder_hidden_states=prompt_embeds,
|
622 |
-
cross_attention_kwargs=cross_attention_kwargs,
|
623 |
-
return_dict=False,
|
624 |
-
)[0]
|
625 |
-
|
626 |
-
# perform guidance
|
627 |
-
if do_classifier_free_guidance:
|
628 |
-
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
629 |
-
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
630 |
-
|
631 |
-
# compute the previous noisy sample x_t -> x_t-1
|
632 |
-
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
633 |
-
|
634 |
-
# call the callback, if provided
|
635 |
-
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
636 |
-
progress_bar.update()
|
637 |
-
if callback is not None and i % callback_steps == 0:
|
638 |
-
callback(i, t, latents)
|
639 |
-
|
640 |
-
if not output_type == "latent":
|
641 |
-
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
642 |
-
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
|
643 |
-
else:
|
644 |
-
image = latents
|
645 |
-
has_nsfw_concept = None
|
646 |
-
|
647 |
-
if has_nsfw_concept is None:
|
648 |
-
do_denormalize = [True] * image.shape[0]
|
649 |
-
else:
|
650 |
-
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
|
651 |
-
|
652 |
-
rgb, depth = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
|
653 |
-
|
654 |
-
# Offload last model to CPU
|
655 |
-
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
656 |
-
self.final_offload_hook.offload()
|
657 |
-
|
658 |
-
if not return_dict:
|
659 |
-
return ((rgb, depth), has_nsfw_concept)
|
660 |
-
|
661 |
-
return LDM3DPipelineOutput(rgb=rgb, depth=depth, nsfw_content_detected=has_nsfw_concept)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/schedulers/scheduling_pndm.py
DELETED
@@ -1,462 +0,0 @@
|
|
1 |
-
# Copyright 2023 Zhejiang University Team and The HuggingFace Team. All rights reserved.
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
# you may not use this file except in compliance with the License.
|
5 |
-
# You may obtain a copy of the License at
|
6 |
-
#
|
7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
#
|
9 |
-
# Unless required by applicable law or agreed to in writing, software
|
10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
# See the License for the specific language governing permissions and
|
13 |
-
# limitations under the License.
|
14 |
-
|
15 |
-
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
|
16 |
-
|
17 |
-
import math
|
18 |
-
from typing import List, Optional, Tuple, Union
|
19 |
-
|
20 |
-
import numpy as np
|
21 |
-
import torch
|
22 |
-
|
23 |
-
from ..configuration_utils import ConfigMixin, register_to_config
|
24 |
-
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
|
25 |
-
|
26 |
-
|
27 |
-
# Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
|
28 |
-
def betas_for_alpha_bar(
|
29 |
-
num_diffusion_timesteps,
|
30 |
-
max_beta=0.999,
|
31 |
-
alpha_transform_type="cosine",
|
32 |
-
):
|
33 |
-
"""
|
34 |
-
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
|
35 |
-
(1-beta) over time from t = [0,1].
|
36 |
-
|
37 |
-
Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
|
38 |
-
to that part of the diffusion process.
|
39 |
-
|
40 |
-
|
41 |
-
Args:
|
42 |
-
num_diffusion_timesteps (`int`): the number of betas to produce.
|
43 |
-
max_beta (`float`): the maximum beta to use; use values lower than 1 to
|
44 |
-
prevent singularities.
|
45 |
-
alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
|
46 |
-
Choose from `cosine` or `exp`
|
47 |
-
|
48 |
-
Returns:
|
49 |
-
betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
|
50 |
-
"""
|
51 |
-
if alpha_transform_type == "cosine":
|
52 |
-
|
53 |
-
def alpha_bar_fn(t):
|
54 |
-
return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
|
55 |
-
|
56 |
-
elif alpha_transform_type == "exp":
|
57 |
-
|
58 |
-
def alpha_bar_fn(t):
|
59 |
-
return math.exp(t * -12.0)
|
60 |
-
|
61 |
-
else:
|
62 |
-
raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
|
63 |
-
|
64 |
-
betas = []
|
65 |
-
for i in range(num_diffusion_timesteps):
|
66 |
-
t1 = i / num_diffusion_timesteps
|
67 |
-
t2 = (i + 1) / num_diffusion_timesteps
|
68 |
-
betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
|
69 |
-
return torch.tensor(betas, dtype=torch.float32)
|
70 |
-
|
71 |
-
|
72 |
-
class PNDMScheduler(SchedulerMixin, ConfigMixin):
|
73 |
-
"""
|
74 |
-
Pseudo numerical methods for diffusion models (PNDM) proposes using more advanced ODE integration techniques,
|
75 |
-
namely Runge-Kutta method and a linear multi-step method.
|
76 |
-
|
77 |
-
[`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
|
78 |
-
function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
|
79 |
-
[`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
|
80 |
-
[`~SchedulerMixin.from_pretrained`] functions.
|
81 |
-
|
82 |
-
For more details, see the original paper: https://arxiv.org/abs/2202.09778
|
83 |
-
|
84 |
-
Args:
|
85 |
-
num_train_timesteps (`int`): number of diffusion steps used to train the model.
|
86 |
-
beta_start (`float`): the starting `beta` value of inference.
|
87 |
-
beta_end (`float`): the final `beta` value.
|
88 |
-
beta_schedule (`str`):
|
89 |
-
the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
|
90 |
-
`linear`, `scaled_linear`, or `squaredcos_cap_v2`.
|
91 |
-
trained_betas (`np.ndarray`, optional):
|
92 |
-
option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
|
93 |
-
skip_prk_steps (`bool`):
|
94 |
-
allows the scheduler to skip the Runge-Kutta steps that are defined in the original paper as being required
|
95 |
-
before plms steps; defaults to `False`.
|
96 |
-
set_alpha_to_one (`bool`, default `False`):
|
97 |
-
each diffusion step uses the value of alphas product at that step and at the previous one. For the final
|
98 |
-
step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
|
99 |
-
otherwise it uses the value of alpha at step 0.
|
100 |
-
prediction_type (`str`, default `epsilon`, optional):
|
101 |
-
prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion process)
|
102 |
-
or `v_prediction` (see section 2.4 https://imagen.research.google/video/paper.pdf)
|
103 |
-
timestep_spacing (`str`, default `"leading"`):
|
104 |
-
The way the timesteps should be scaled. Refer to Table 2. of [Common Diffusion Noise Schedules and Sample
|
105 |
-
Steps are Flawed](https://arxiv.org/abs/2305.08891) for more information.
|
106 |
-
steps_offset (`int`, default `0`):
|
107 |
-
an offset added to the inference steps. You can use a combination of `offset=1` and
|
108 |
-
`set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in
|
109 |
-
stable diffusion.
|
110 |
-
"""
|
111 |
-
|
112 |
-
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
|
113 |
-
order = 1
|
114 |
-
|
115 |
-
@register_to_config
|
116 |
-
def __init__(
|
117 |
-
self,
|
118 |
-
num_train_timesteps: int = 1000,
|
119 |
-
beta_start: float = 0.0001,
|
120 |
-
beta_end: float = 0.02,
|
121 |
-
beta_schedule: str = "linear",
|
122 |
-
trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
|
123 |
-
skip_prk_steps: bool = False,
|
124 |
-
set_alpha_to_one: bool = False,
|
125 |
-
prediction_type: str = "epsilon",
|
126 |
-
timestep_spacing: str = "leading",
|
127 |
-
steps_offset: int = 0,
|
128 |
-
):
|
129 |
-
if trained_betas is not None:
|
130 |
-
self.betas = torch.tensor(trained_betas, dtype=torch.float32)
|
131 |
-
elif beta_schedule == "linear":
|
132 |
-
self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
|
133 |
-
elif beta_schedule == "scaled_linear":
|
134 |
-
# this schedule is very specific to the latent diffusion model.
|
135 |
-
self.betas = (
|
136 |
-
torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
|
137 |
-
)
|
138 |
-
elif beta_schedule == "squaredcos_cap_v2":
|
139 |
-
# Glide cosine schedule
|
140 |
-
self.betas = betas_for_alpha_bar(num_train_timesteps)
|
141 |
-
else:
|
142 |
-
raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
|
143 |
-
|
144 |
-
self.alphas = 1.0 - self.betas
|
145 |
-
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
|
146 |
-
|
147 |
-
self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
|
148 |
-
|
149 |
-
# standard deviation of the initial noise distribution
|
150 |
-
self.init_noise_sigma = 1.0
|
151 |
-
|
152 |
-
# For now we only support F-PNDM, i.e. the runge-kutta method
|
153 |
-
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
|
154 |
-
# mainly at formula (9), (12), (13) and the Algorithm 2.
|
155 |
-
self.pndm_order = 4
|
156 |
-
|
157 |
-
# running values
|
158 |
-
self.cur_model_output = 0
|
159 |
-
self.counter = 0
|
160 |
-
self.cur_sample = None
|
161 |
-
self.ets = []
|
162 |
-
|
163 |
-
# setable values
|
164 |
-
self.num_inference_steps = None
|
165 |
-
self._timesteps = np.arange(0, num_train_timesteps)[::-1].copy()
|
166 |
-
self.prk_timesteps = None
|
167 |
-
self.plms_timesteps = None
|
168 |
-
self.timesteps = None
|
169 |
-
|
170 |
-
def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
|
171 |
-
"""
|
172 |
-
Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
|
173 |
-
|
174 |
-
Args:
|
175 |
-
num_inference_steps (`int`):
|
176 |
-
the number of diffusion steps used when generating samples with a pre-trained model.
|
177 |
-
"""
|
178 |
-
|
179 |
-
self.num_inference_steps = num_inference_steps
|
180 |
-
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
|
181 |
-
if self.config.timestep_spacing == "linspace":
|
182 |
-
self._timesteps = (
|
183 |
-
np.linspace(0, self.config.num_train_timesteps - 1, num_inference_steps).round().astype(np.int64)
|
184 |
-
)
|
185 |
-
elif self.config.timestep_spacing == "leading":
|
186 |
-
step_ratio = self.config.num_train_timesteps // self.num_inference_steps
|
187 |
-
# creates integer timesteps by multiplying by ratio
|
188 |
-
# casting to int to avoid issues when num_inference_step is power of 3
|
189 |
-
self._timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()
|
190 |
-
self._timesteps += self.config.steps_offset
|
191 |
-
elif self.config.timestep_spacing == "trailing":
|
192 |
-
step_ratio = self.config.num_train_timesteps / self.num_inference_steps
|
193 |
-
# creates integer timesteps by multiplying by ratio
|
194 |
-
# casting to int to avoid issues when num_inference_step is power of 3
|
195 |
-
self._timesteps = np.round(np.arange(self.config.num_train_timesteps, 0, -step_ratio))[::-1].astype(
|
196 |
-
np.int64
|
197 |
-
)
|
198 |
-
self._timesteps -= 1
|
199 |
-
else:
|
200 |
-
raise ValueError(
|
201 |
-
f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
|
202 |
-
)
|
203 |
-
|
204 |
-
if self.config.skip_prk_steps:
|
205 |
-
# for some models like stable diffusion the prk steps can/should be skipped to
|
206 |
-
# produce better results. When using PNDM with `self.config.skip_prk_steps` the implementation
|
207 |
-
# is based on crowsonkb's PLMS sampler implementation: https://github.com/CompVis/latent-diffusion/pull/51
|
208 |
-
self.prk_timesteps = np.array([])
|
209 |
-
self.plms_timesteps = np.concatenate([self._timesteps[:-1], self._timesteps[-2:-1], self._timesteps[-1:]])[
|
210 |
-
::-1
|
211 |
-
].copy()
|
212 |
-
else:
|
213 |
-
prk_timesteps = np.array(self._timesteps[-self.pndm_order :]).repeat(2) + np.tile(
|
214 |
-
np.array([0, self.config.num_train_timesteps // num_inference_steps // 2]), self.pndm_order
|
215 |
-
)
|
216 |
-
self.prk_timesteps = (prk_timesteps[:-1].repeat(2)[1:-1])[::-1].copy()
|
217 |
-
self.plms_timesteps = self._timesteps[:-3][
|
218 |
-
::-1
|
219 |
-
].copy() # we copy to avoid having negative strides which are not supported by torch.from_numpy
|
220 |
-
|
221 |
-
timesteps = np.concatenate([self.prk_timesteps, self.plms_timesteps]).astype(np.int64)
|
222 |
-
self.timesteps = torch.from_numpy(timesteps).to(device)
|
223 |
-
|
224 |
-
self.ets = []
|
225 |
-
self.counter = 0
|
226 |
-
self.cur_model_output = 0
|
227 |
-
|
228 |
-
def step(
|
229 |
-
self,
|
230 |
-
model_output: torch.FloatTensor,
|
231 |
-
timestep: int,
|
232 |
-
sample: torch.FloatTensor,
|
233 |
-
return_dict: bool = True,
|
234 |
-
) -> Union[SchedulerOutput, Tuple]:
|
235 |
-
"""
|
236 |
-
Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
|
237 |
-
process from the learned model outputs (most often the predicted noise).
|
238 |
-
|
239 |
-
This function calls `step_prk()` or `step_plms()` depending on the internal variable `counter`.
|
240 |
-
|
241 |
-
Args:
|
242 |
-
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
243 |
-
timestep (`int`): current discrete timestep in the diffusion chain.
|
244 |
-
sample (`torch.FloatTensor`):
|
245 |
-
current instance of sample being created by diffusion process.
|
246 |
-
return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
|
247 |
-
|
248 |
-
Returns:
|
249 |
-
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
|
250 |
-
[`~schedulers.scheduling_utils.SchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
|
251 |
-
returning a tuple, the first element is the sample tensor.
|
252 |
-
|
253 |
-
"""
|
254 |
-
if self.counter < len(self.prk_timesteps) and not self.config.skip_prk_steps:
|
255 |
-
return self.step_prk(model_output=model_output, timestep=timestep, sample=sample, return_dict=return_dict)
|
256 |
-
else:
|
257 |
-
return self.step_plms(model_output=model_output, timestep=timestep, sample=sample, return_dict=return_dict)
|
258 |
-
|
259 |
-
def step_prk(
|
260 |
-
self,
|
261 |
-
model_output: torch.FloatTensor,
|
262 |
-
timestep: int,
|
263 |
-
sample: torch.FloatTensor,
|
264 |
-
return_dict: bool = True,
|
265 |
-
) -> Union[SchedulerOutput, Tuple]:
|
266 |
-
"""
|
267 |
-
Step function propagating the sample with the Runge-Kutta method. RK takes 4 forward passes to approximate the
|
268 |
-
solution to the differential equation.
|
269 |
-
|
270 |
-
Args:
|
271 |
-
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
272 |
-
timestep (`int`): current discrete timestep in the diffusion chain.
|
273 |
-
sample (`torch.FloatTensor`):
|
274 |
-
current instance of sample being created by diffusion process.
|
275 |
-
return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
|
276 |
-
|
277 |
-
Returns:
|
278 |
-
[`~scheduling_utils.SchedulerOutput`] or `tuple`: [`~scheduling_utils.SchedulerOutput`] if `return_dict` is
|
279 |
-
True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
|
280 |
-
|
281 |
-
"""
|
282 |
-
if self.num_inference_steps is None:
|
283 |
-
raise ValueError(
|
284 |
-
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
285 |
-
)
|
286 |
-
|
287 |
-
diff_to_prev = 0 if self.counter % 2 else self.config.num_train_timesteps // self.num_inference_steps // 2
|
288 |
-
prev_timestep = timestep - diff_to_prev
|
289 |
-
timestep = self.prk_timesteps[self.counter // 4 * 4]
|
290 |
-
|
291 |
-
if self.counter % 4 == 0:
|
292 |
-
self.cur_model_output += 1 / 6 * model_output
|
293 |
-
self.ets.append(model_output)
|
294 |
-
self.cur_sample = sample
|
295 |
-
elif (self.counter - 1) % 4 == 0:
|
296 |
-
self.cur_model_output += 1 / 3 * model_output
|
297 |
-
elif (self.counter - 2) % 4 == 0:
|
298 |
-
self.cur_model_output += 1 / 3 * model_output
|
299 |
-
elif (self.counter - 3) % 4 == 0:
|
300 |
-
model_output = self.cur_model_output + 1 / 6 * model_output
|
301 |
-
self.cur_model_output = 0
|
302 |
-
|
303 |
-
# cur_sample should not be `None`
|
304 |
-
cur_sample = self.cur_sample if self.cur_sample is not None else sample
|
305 |
-
|
306 |
-
prev_sample = self._get_prev_sample(cur_sample, timestep, prev_timestep, model_output)
|
307 |
-
self.counter += 1
|
308 |
-
|
309 |
-
if not return_dict:
|
310 |
-
return (prev_sample,)
|
311 |
-
|
312 |
-
return SchedulerOutput(prev_sample=prev_sample)
|
313 |
-
|
314 |
-
def step_plms(
|
315 |
-
self,
|
316 |
-
model_output: torch.FloatTensor,
|
317 |
-
timestep: int,
|
318 |
-
sample: torch.FloatTensor,
|
319 |
-
return_dict: bool = True,
|
320 |
-
) -> Union[SchedulerOutput, Tuple]:
|
321 |
-
"""
|
322 |
-
Step function propagating the sample with the linear multi-step method. This has one forward pass with multiple
|
323 |
-
times to approximate the solution.
|
324 |
-
|
325 |
-
Args:
|
326 |
-
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
327 |
-
timestep (`int`): current discrete timestep in the diffusion chain.
|
328 |
-
sample (`torch.FloatTensor`):
|
329 |
-
current instance of sample being created by diffusion process.
|
330 |
-
return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
|
331 |
-
|
332 |
-
Returns:
|
333 |
-
[`~scheduling_utils.SchedulerOutput`] or `tuple`: [`~scheduling_utils.SchedulerOutput`] if `return_dict` is
|
334 |
-
True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
|
335 |
-
|
336 |
-
"""
|
337 |
-
if self.num_inference_steps is None:
|
338 |
-
raise ValueError(
|
339 |
-
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
340 |
-
)
|
341 |
-
|
342 |
-
if not self.config.skip_prk_steps and len(self.ets) < 3:
|
343 |
-
raise ValueError(
|
344 |
-
f"{self.__class__} can only be run AFTER scheduler has been run "
|
345 |
-
"in 'prk' mode for at least 12 iterations "
|
346 |
-
"See: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_pndm.py "
|
347 |
-
"for more information."
|
348 |
-
)
|
349 |
-
|
350 |
-
prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
|
351 |
-
|
352 |
-
if self.counter != 1:
|
353 |
-
self.ets = self.ets[-3:]
|
354 |
-
self.ets.append(model_output)
|
355 |
-
else:
|
356 |
-
prev_timestep = timestep
|
357 |
-
timestep = timestep + self.config.num_train_timesteps // self.num_inference_steps
|
358 |
-
|
359 |
-
if len(self.ets) == 1 and self.counter == 0:
|
360 |
-
model_output = model_output
|
361 |
-
self.cur_sample = sample
|
362 |
-
elif len(self.ets) == 1 and self.counter == 1:
|
363 |
-
model_output = (model_output + self.ets[-1]) / 2
|
364 |
-
sample = self.cur_sample
|
365 |
-
self.cur_sample = None
|
366 |
-
elif len(self.ets) == 2:
|
367 |
-
model_output = (3 * self.ets[-1] - self.ets[-2]) / 2
|
368 |
-
elif len(self.ets) == 3:
|
369 |
-
model_output = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
|
370 |
-
else:
|
371 |
-
model_output = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
|
372 |
-
|
373 |
-
prev_sample = self._get_prev_sample(sample, timestep, prev_timestep, model_output)
|
374 |
-
self.counter += 1
|
375 |
-
|
376 |
-
if not return_dict:
|
377 |
-
return (prev_sample,)
|
378 |
-
|
379 |
-
return SchedulerOutput(prev_sample=prev_sample)
|
380 |
-
|
381 |
-
def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
|
382 |
-
"""
|
383 |
-
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
|
384 |
-
current timestep.
|
385 |
-
|
386 |
-
Args:
|
387 |
-
sample (`torch.FloatTensor`): input sample
|
388 |
-
|
389 |
-
Returns:
|
390 |
-
`torch.FloatTensor`: scaled input sample
|
391 |
-
"""
|
392 |
-
return sample
|
393 |
-
|
394 |
-
def _get_prev_sample(self, sample, timestep, prev_timestep, model_output):
|
395 |
-
# See formula (9) of PNDM paper https://arxiv.org/pdf/2202.09778.pdf
|
396 |
-
# this function computes x_(t−δ) using the formula of (9)
|
397 |
-
# Note that x_t needs to be added to both sides of the equation
|
398 |
-
|
399 |
-
# Notation (<variable name> -> <name in paper>
|
400 |
-
# alpha_prod_t -> α_t
|
401 |
-
# alpha_prod_t_prev -> α_(t−δ)
|
402 |
-
# beta_prod_t -> (1 - α_t)
|
403 |
-
# beta_prod_t_prev -> (1 - α_(t−δ))
|
404 |
-
# sample -> x_t
|
405 |
-
# model_output -> e_θ(x_t, t)
|
406 |
-
# prev_sample -> x_(t−δ)
|
407 |
-
alpha_prod_t = self.alphas_cumprod[timestep]
|
408 |
-
alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
|
409 |
-
beta_prod_t = 1 - alpha_prod_t
|
410 |
-
beta_prod_t_prev = 1 - alpha_prod_t_prev
|
411 |
-
|
412 |
-
if self.config.prediction_type == "v_prediction":
|
413 |
-
model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
|
414 |
-
elif self.config.prediction_type != "epsilon":
|
415 |
-
raise ValueError(
|
416 |
-
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `v_prediction`"
|
417 |
-
)
|
418 |
-
|
419 |
-
# corresponds to (α_(t−δ) - α_t) divided by
|
420 |
-
# denominator of x_t in formula (9) and plus 1
|
421 |
-
# Note: (α_(t−δ) - α_t) / (sqrt(α_t) * (sqrt(α_(t−δ)) + sqr(α_t))) =
|
422 |
-
# sqrt(α_(t−δ)) / sqrt(α_t))
|
423 |
-
sample_coeff = (alpha_prod_t_prev / alpha_prod_t) ** (0.5)
|
424 |
-
|
425 |
-
# corresponds to denominator of e_θ(x_t, t) in formula (9)
|
426 |
-
model_output_denom_coeff = alpha_prod_t * beta_prod_t_prev ** (0.5) + (
|
427 |
-
alpha_prod_t * beta_prod_t * alpha_prod_t_prev
|
428 |
-
) ** (0.5)
|
429 |
-
|
430 |
-
# full formula (9)
|
431 |
-
prev_sample = (
|
432 |
-
sample_coeff * sample - (alpha_prod_t_prev - alpha_prod_t) * model_output / model_output_denom_coeff
|
433 |
-
)
|
434 |
-
|
435 |
-
return prev_sample
|
436 |
-
|
437 |
-
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
|
438 |
-
def add_noise(
|
439 |
-
self,
|
440 |
-
original_samples: torch.FloatTensor,
|
441 |
-
noise: torch.FloatTensor,
|
442 |
-
timesteps: torch.IntTensor,
|
443 |
-
) -> torch.FloatTensor:
|
444 |
-
# Make sure alphas_cumprod and timestep have same device and dtype as original_samples
|
445 |
-
alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
|
446 |
-
timesteps = timesteps.to(original_samples.device)
|
447 |
-
|
448 |
-
sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
|
449 |
-
sqrt_alpha_prod = sqrt_alpha_prod.flatten()
|
450 |
-
while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
|
451 |
-
sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
|
452 |
-
|
453 |
-
sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
|
454 |
-
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
|
455 |
-
while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
|
456 |
-
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
|
457 |
-
|
458 |
-
noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
|
459 |
-
return noisy_samples
|
460 |
-
|
461 |
-
def __len__(self):
|
462 |
-
return self.config.num_train_timesteps
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/utils/logging.py
DELETED
@@ -1,339 +0,0 @@
|
|
1 |
-
# coding=utf-8
|
2 |
-
# Copyright 2023 Optuna, Hugging Face
|
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 |
-
""" Logging utilities."""
|
16 |
-
|
17 |
-
import logging
|
18 |
-
import os
|
19 |
-
import sys
|
20 |
-
import threading
|
21 |
-
from logging import (
|
22 |
-
CRITICAL, # NOQA
|
23 |
-
DEBUG, # NOQA
|
24 |
-
ERROR, # NOQA
|
25 |
-
FATAL, # NOQA
|
26 |
-
INFO, # NOQA
|
27 |
-
NOTSET, # NOQA
|
28 |
-
WARN, # NOQA
|
29 |
-
WARNING, # NOQA
|
30 |
-
)
|
31 |
-
from typing import Optional
|
32 |
-
|
33 |
-
from tqdm import auto as tqdm_lib
|
34 |
-
|
35 |
-
|
36 |
-
_lock = threading.Lock()
|
37 |
-
_default_handler: Optional[logging.Handler] = None
|
38 |
-
|
39 |
-
log_levels = {
|
40 |
-
"debug": logging.DEBUG,
|
41 |
-
"info": logging.INFO,
|
42 |
-
"warning": logging.WARNING,
|
43 |
-
"error": logging.ERROR,
|
44 |
-
"critical": logging.CRITICAL,
|
45 |
-
}
|
46 |
-
|
47 |
-
_default_log_level = logging.WARNING
|
48 |
-
|
49 |
-
_tqdm_active = True
|
50 |
-
|
51 |
-
|
52 |
-
def _get_default_logging_level():
|
53 |
-
"""
|
54 |
-
If DIFFUSERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
|
55 |
-
not - fall back to `_default_log_level`
|
56 |
-
"""
|
57 |
-
env_level_str = os.getenv("DIFFUSERS_VERBOSITY", None)
|
58 |
-
if env_level_str:
|
59 |
-
if env_level_str in log_levels:
|
60 |
-
return log_levels[env_level_str]
|
61 |
-
else:
|
62 |
-
logging.getLogger().warning(
|
63 |
-
f"Unknown option DIFFUSERS_VERBOSITY={env_level_str}, "
|
64 |
-
f"has to be one of: { ', '.join(log_levels.keys()) }"
|
65 |
-
)
|
66 |
-
return _default_log_level
|
67 |
-
|
68 |
-
|
69 |
-
def _get_library_name() -> str:
|
70 |
-
return __name__.split(".")[0]
|
71 |
-
|
72 |
-
|
73 |
-
def _get_library_root_logger() -> logging.Logger:
|
74 |
-
return logging.getLogger(_get_library_name())
|
75 |
-
|
76 |
-
|
77 |
-
def _configure_library_root_logger() -> None:
|
78 |
-
global _default_handler
|
79 |
-
|
80 |
-
with _lock:
|
81 |
-
if _default_handler:
|
82 |
-
# This library has already configured the library root logger.
|
83 |
-
return
|
84 |
-
_default_handler = logging.StreamHandler() # Set sys.stderr as stream.
|
85 |
-
_default_handler.flush = sys.stderr.flush
|
86 |
-
|
87 |
-
# Apply our default configuration to the library root logger.
|
88 |
-
library_root_logger = _get_library_root_logger()
|
89 |
-
library_root_logger.addHandler(_default_handler)
|
90 |
-
library_root_logger.setLevel(_get_default_logging_level())
|
91 |
-
library_root_logger.propagate = False
|
92 |
-
|
93 |
-
|
94 |
-
def _reset_library_root_logger() -> None:
|
95 |
-
global _default_handler
|
96 |
-
|
97 |
-
with _lock:
|
98 |
-
if not _default_handler:
|
99 |
-
return
|
100 |
-
|
101 |
-
library_root_logger = _get_library_root_logger()
|
102 |
-
library_root_logger.removeHandler(_default_handler)
|
103 |
-
library_root_logger.setLevel(logging.NOTSET)
|
104 |
-
_default_handler = None
|
105 |
-
|
106 |
-
|
107 |
-
def get_log_levels_dict():
|
108 |
-
return log_levels
|
109 |
-
|
110 |
-
|
111 |
-
def get_logger(name: Optional[str] = None) -> logging.Logger:
|
112 |
-
"""
|
113 |
-
Return a logger with the specified name.
|
114 |
-
|
115 |
-
This function is not supposed to be directly accessed unless you are writing a custom diffusers module.
|
116 |
-
"""
|
117 |
-
|
118 |
-
if name is None:
|
119 |
-
name = _get_library_name()
|
120 |
-
|
121 |
-
_configure_library_root_logger()
|
122 |
-
return logging.getLogger(name)
|
123 |
-
|
124 |
-
|
125 |
-
def get_verbosity() -> int:
|
126 |
-
"""
|
127 |
-
Return the current level for the 🤗 Diffusers' root logger as an `int`.
|
128 |
-
|
129 |
-
Returns:
|
130 |
-
`int`:
|
131 |
-
Logging level integers which can be one of:
|
132 |
-
|
133 |
-
- `50`: `diffusers.logging.CRITICAL` or `diffusers.logging.FATAL`
|
134 |
-
- `40`: `diffusers.logging.ERROR`
|
135 |
-
- `30`: `diffusers.logging.WARNING` or `diffusers.logging.WARN`
|
136 |
-
- `20`: `diffusers.logging.INFO`
|
137 |
-
- `10`: `diffusers.logging.DEBUG`
|
138 |
-
|
139 |
-
"""
|
140 |
-
|
141 |
-
_configure_library_root_logger()
|
142 |
-
return _get_library_root_logger().getEffectiveLevel()
|
143 |
-
|
144 |
-
|
145 |
-
def set_verbosity(verbosity: int) -> None:
|
146 |
-
"""
|
147 |
-
Set the verbosity level for the 🤗 Diffusers' root logger.
|
148 |
-
|
149 |
-
Args:
|
150 |
-
verbosity (`int`):
|
151 |
-
Logging level which can be one of:
|
152 |
-
|
153 |
-
- `diffusers.logging.CRITICAL` or `diffusers.logging.FATAL`
|
154 |
-
- `diffusers.logging.ERROR`
|
155 |
-
- `diffusers.logging.WARNING` or `diffusers.logging.WARN`
|
156 |
-
- `diffusers.logging.INFO`
|
157 |
-
- `diffusers.logging.DEBUG`
|
158 |
-
"""
|
159 |
-
|
160 |
-
_configure_library_root_logger()
|
161 |
-
_get_library_root_logger().setLevel(verbosity)
|
162 |
-
|
163 |
-
|
164 |
-
def set_verbosity_info():
|
165 |
-
"""Set the verbosity to the `INFO` level."""
|
166 |
-
return set_verbosity(INFO)
|
167 |
-
|
168 |
-
|
169 |
-
def set_verbosity_warning():
|
170 |
-
"""Set the verbosity to the `WARNING` level."""
|
171 |
-
return set_verbosity(WARNING)
|
172 |
-
|
173 |
-
|
174 |
-
def set_verbosity_debug():
|
175 |
-
"""Set the verbosity to the `DEBUG` level."""
|
176 |
-
return set_verbosity(DEBUG)
|
177 |
-
|
178 |
-
|
179 |
-
def set_verbosity_error():
|
180 |
-
"""Set the verbosity to the `ERROR` level."""
|
181 |
-
return set_verbosity(ERROR)
|
182 |
-
|
183 |
-
|
184 |
-
def disable_default_handler() -> None:
|
185 |
-
"""Disable the default handler of the 🤗 Diffusers' root logger."""
|
186 |
-
|
187 |
-
_configure_library_root_logger()
|
188 |
-
|
189 |
-
assert _default_handler is not None
|
190 |
-
_get_library_root_logger().removeHandler(_default_handler)
|
191 |
-
|
192 |
-
|
193 |
-
def enable_default_handler() -> None:
|
194 |
-
"""Enable the default handler of the 🤗 Diffusers' root logger."""
|
195 |
-
|
196 |
-
_configure_library_root_logger()
|
197 |
-
|
198 |
-
assert _default_handler is not None
|
199 |
-
_get_library_root_logger().addHandler(_default_handler)
|
200 |
-
|
201 |
-
|
202 |
-
def add_handler(handler: logging.Handler) -> None:
|
203 |
-
"""adds a handler to the HuggingFace Diffusers' root logger."""
|
204 |
-
|
205 |
-
_configure_library_root_logger()
|
206 |
-
|
207 |
-
assert handler is not None
|
208 |
-
_get_library_root_logger().addHandler(handler)
|
209 |
-
|
210 |
-
|
211 |
-
def remove_handler(handler: logging.Handler) -> None:
|
212 |
-
"""removes given handler from the HuggingFace Diffusers' root logger."""
|
213 |
-
|
214 |
-
_configure_library_root_logger()
|
215 |
-
|
216 |
-
assert handler is not None and handler not in _get_library_root_logger().handlers
|
217 |
-
_get_library_root_logger().removeHandler(handler)
|
218 |
-
|
219 |
-
|
220 |
-
def disable_propagation() -> None:
|
221 |
-
"""
|
222 |
-
Disable propagation of the library log outputs. Note that log propagation is disabled by default.
|
223 |
-
"""
|
224 |
-
|
225 |
-
_configure_library_root_logger()
|
226 |
-
_get_library_root_logger().propagate = False
|
227 |
-
|
228 |
-
|
229 |
-
def enable_propagation() -> None:
|
230 |
-
"""
|
231 |
-
Enable propagation of the library log outputs. Please disable the HuggingFace Diffusers' default handler to prevent
|
232 |
-
double logging if the root logger has been configured.
|
233 |
-
"""
|
234 |
-
|
235 |
-
_configure_library_root_logger()
|
236 |
-
_get_library_root_logger().propagate = True
|
237 |
-
|
238 |
-
|
239 |
-
def enable_explicit_format() -> None:
|
240 |
-
"""
|
241 |
-
Enable explicit formatting for every 🤗 Diffusers' logger. The explicit formatter is as follows:
|
242 |
-
```
|
243 |
-
[LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
|
244 |
-
```
|
245 |
-
All handlers currently bound to the root logger are affected by this method.
|
246 |
-
"""
|
247 |
-
handlers = _get_library_root_logger().handlers
|
248 |
-
|
249 |
-
for handler in handlers:
|
250 |
-
formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")
|
251 |
-
handler.setFormatter(formatter)
|
252 |
-
|
253 |
-
|
254 |
-
def reset_format() -> None:
|
255 |
-
"""
|
256 |
-
Resets the formatting for 🤗 Diffusers' loggers.
|
257 |
-
|
258 |
-
All handlers currently bound to the root logger are affected by this method.
|
259 |
-
"""
|
260 |
-
handlers = _get_library_root_logger().handlers
|
261 |
-
|
262 |
-
for handler in handlers:
|
263 |
-
handler.setFormatter(None)
|
264 |
-
|
265 |
-
|
266 |
-
def warning_advice(self, *args, **kwargs):
|
267 |
-
"""
|
268 |
-
This method is identical to `logger.warning()`, but if env var DIFFUSERS_NO_ADVISORY_WARNINGS=1 is set, this
|
269 |
-
warning will not be printed
|
270 |
-
"""
|
271 |
-
no_advisory_warnings = os.getenv("DIFFUSERS_NO_ADVISORY_WARNINGS", False)
|
272 |
-
if no_advisory_warnings:
|
273 |
-
return
|
274 |
-
self.warning(*args, **kwargs)
|
275 |
-
|
276 |
-
|
277 |
-
logging.Logger.warning_advice = warning_advice
|
278 |
-
|
279 |
-
|
280 |
-
class EmptyTqdm:
|
281 |
-
"""Dummy tqdm which doesn't do anything."""
|
282 |
-
|
283 |
-
def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
|
284 |
-
self._iterator = args[0] if args else None
|
285 |
-
|
286 |
-
def __iter__(self):
|
287 |
-
return iter(self._iterator)
|
288 |
-
|
289 |
-
def __getattr__(self, _):
|
290 |
-
"""Return empty function."""
|
291 |
-
|
292 |
-
def empty_fn(*args, **kwargs): # pylint: disable=unused-argument
|
293 |
-
return
|
294 |
-
|
295 |
-
return empty_fn
|
296 |
-
|
297 |
-
def __enter__(self):
|
298 |
-
return self
|
299 |
-
|
300 |
-
def __exit__(self, type_, value, traceback):
|
301 |
-
return
|
302 |
-
|
303 |
-
|
304 |
-
class _tqdm_cls:
|
305 |
-
def __call__(self, *args, **kwargs):
|
306 |
-
if _tqdm_active:
|
307 |
-
return tqdm_lib.tqdm(*args, **kwargs)
|
308 |
-
else:
|
309 |
-
return EmptyTqdm(*args, **kwargs)
|
310 |
-
|
311 |
-
def set_lock(self, *args, **kwargs):
|
312 |
-
self._lock = None
|
313 |
-
if _tqdm_active:
|
314 |
-
return tqdm_lib.tqdm.set_lock(*args, **kwargs)
|
315 |
-
|
316 |
-
def get_lock(self):
|
317 |
-
if _tqdm_active:
|
318 |
-
return tqdm_lib.tqdm.get_lock()
|
319 |
-
|
320 |
-
|
321 |
-
tqdm = _tqdm_cls()
|
322 |
-
|
323 |
-
|
324 |
-
def is_progress_bar_enabled() -> bool:
|
325 |
-
"""Return a boolean indicating whether tqdm progress bars are enabled."""
|
326 |
-
global _tqdm_active
|
327 |
-
return bool(_tqdm_active)
|
328 |
-
|
329 |
-
|
330 |
-
def enable_progress_bar():
|
331 |
-
"""Enable tqdm progress bar."""
|
332 |
-
global _tqdm_active
|
333 |
-
_tqdm_active = True
|
334 |
-
|
335 |
-
|
336 |
-
def disable_progress_bar():
|
337 |
-
"""Disable tqdm progress bar."""
|
338 |
-
global _tqdm_active
|
339 |
-
_tqdm_active = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/pipelines/stable_diffusion_2/test_stable_diffusion_diffedit.py
DELETED
@@ -1,399 +0,0 @@
|
|
1 |
-
# coding=utf-8
|
2 |
-
# Copyright 2023 HuggingFace Inc.
|
3 |
-
#
|
4 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
-
# you may not use this file except in compliance with the License.
|
6 |
-
# You may obtain a copy of the License at
|
7 |
-
#
|
8 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
-
#
|
10 |
-
# Unless required by applicable law or agreed to in writing, software
|
11 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
-
# See the License for the specific language governing permissions and
|
14 |
-
# limitations under the License.
|
15 |
-
|
16 |
-
import gc
|
17 |
-
import random
|
18 |
-
import tempfile
|
19 |
-
import unittest
|
20 |
-
|
21 |
-
import numpy as np
|
22 |
-
import torch
|
23 |
-
from PIL import Image
|
24 |
-
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
|
25 |
-
|
26 |
-
from diffusers import (
|
27 |
-
AutoencoderKL,
|
28 |
-
DDIMInverseScheduler,
|
29 |
-
DDIMScheduler,
|
30 |
-
DPMSolverMultistepInverseScheduler,
|
31 |
-
DPMSolverMultistepScheduler,
|
32 |
-
StableDiffusionDiffEditPipeline,
|
33 |
-
UNet2DConditionModel,
|
34 |
-
)
|
35 |
-
from diffusers.utils import load_image, slow
|
36 |
-
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device
|
37 |
-
|
38 |
-
from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
|
39 |
-
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
|
40 |
-
|
41 |
-
|
42 |
-
enable_full_determinism()
|
43 |
-
|
44 |
-
|
45 |
-
class StableDiffusionDiffEditPipelineFastTests(PipelineLatentTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
46 |
-
pipeline_class = StableDiffusionDiffEditPipeline
|
47 |
-
params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"}
|
48 |
-
batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"}
|
49 |
-
image_params = frozenset(
|
50 |
-
[]
|
51 |
-
) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
|
52 |
-
image_latents_params = frozenset([])
|
53 |
-
|
54 |
-
def get_dummy_components(self):
|
55 |
-
torch.manual_seed(0)
|
56 |
-
unet = UNet2DConditionModel(
|
57 |
-
block_out_channels=(32, 64),
|
58 |
-
layers_per_block=2,
|
59 |
-
sample_size=32,
|
60 |
-
in_channels=4,
|
61 |
-
out_channels=4,
|
62 |
-
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
63 |
-
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
64 |
-
cross_attention_dim=32,
|
65 |
-
# SD2-specific config below
|
66 |
-
attention_head_dim=(2, 4),
|
67 |
-
use_linear_projection=True,
|
68 |
-
)
|
69 |
-
scheduler = DDIMScheduler(
|
70 |
-
beta_start=0.00085,
|
71 |
-
beta_end=0.012,
|
72 |
-
beta_schedule="scaled_linear",
|
73 |
-
clip_sample=False,
|
74 |
-
set_alpha_to_one=False,
|
75 |
-
)
|
76 |
-
inverse_scheduler = DDIMInverseScheduler(
|
77 |
-
beta_start=0.00085,
|
78 |
-
beta_end=0.012,
|
79 |
-
beta_schedule="scaled_linear",
|
80 |
-
clip_sample=False,
|
81 |
-
set_alpha_to_zero=False,
|
82 |
-
)
|
83 |
-
torch.manual_seed(0)
|
84 |
-
vae = AutoencoderKL(
|
85 |
-
block_out_channels=[32, 64],
|
86 |
-
in_channels=3,
|
87 |
-
out_channels=3,
|
88 |
-
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
89 |
-
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
90 |
-
latent_channels=4,
|
91 |
-
sample_size=128,
|
92 |
-
)
|
93 |
-
torch.manual_seed(0)
|
94 |
-
text_encoder_config = CLIPTextConfig(
|
95 |
-
bos_token_id=0,
|
96 |
-
eos_token_id=2,
|
97 |
-
hidden_size=32,
|
98 |
-
intermediate_size=37,
|
99 |
-
layer_norm_eps=1e-05,
|
100 |
-
num_attention_heads=4,
|
101 |
-
num_hidden_layers=5,
|
102 |
-
pad_token_id=1,
|
103 |
-
vocab_size=1000,
|
104 |
-
# SD2-specific config below
|
105 |
-
hidden_act="gelu",
|
106 |
-
projection_dim=512,
|
107 |
-
)
|
108 |
-
text_encoder = CLIPTextModel(text_encoder_config)
|
109 |
-
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
110 |
-
|
111 |
-
components = {
|
112 |
-
"unet": unet,
|
113 |
-
"scheduler": scheduler,
|
114 |
-
"inverse_scheduler": inverse_scheduler,
|
115 |
-
"vae": vae,
|
116 |
-
"text_encoder": text_encoder,
|
117 |
-
"tokenizer": tokenizer,
|
118 |
-
"safety_checker": None,
|
119 |
-
"feature_extractor": None,
|
120 |
-
}
|
121 |
-
|
122 |
-
return components
|
123 |
-
|
124 |
-
def get_dummy_inputs(self, device, seed=0):
|
125 |
-
mask = floats_tensor((1, 16, 16), rng=random.Random(seed)).to(device)
|
126 |
-
latents = floats_tensor((1, 2, 4, 16, 16), rng=random.Random(seed)).to(device)
|
127 |
-
if str(device).startswith("mps"):
|
128 |
-
generator = torch.manual_seed(seed)
|
129 |
-
else:
|
130 |
-
generator = torch.Generator(device=device).manual_seed(seed)
|
131 |
-
inputs = {
|
132 |
-
"prompt": "a dog and a newt",
|
133 |
-
"mask_image": mask,
|
134 |
-
"image_latents": latents,
|
135 |
-
"generator": generator,
|
136 |
-
"num_inference_steps": 2,
|
137 |
-
"inpaint_strength": 1.0,
|
138 |
-
"guidance_scale": 6.0,
|
139 |
-
"output_type": "numpy",
|
140 |
-
}
|
141 |
-
|
142 |
-
return inputs
|
143 |
-
|
144 |
-
def get_dummy_mask_inputs(self, device, seed=0):
|
145 |
-
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
146 |
-
image = image.cpu().permute(0, 2, 3, 1)[0]
|
147 |
-
image = Image.fromarray(np.uint8(image)).convert("RGB")
|
148 |
-
if str(device).startswith("mps"):
|
149 |
-
generator = torch.manual_seed(seed)
|
150 |
-
else:
|
151 |
-
generator = torch.Generator(device=device).manual_seed(seed)
|
152 |
-
inputs = {
|
153 |
-
"image": image,
|
154 |
-
"source_prompt": "a cat and a frog",
|
155 |
-
"target_prompt": "a dog and a newt",
|
156 |
-
"generator": generator,
|
157 |
-
"num_inference_steps": 2,
|
158 |
-
"num_maps_per_mask": 2,
|
159 |
-
"mask_encode_strength": 1.0,
|
160 |
-
"guidance_scale": 6.0,
|
161 |
-
"output_type": "numpy",
|
162 |
-
}
|
163 |
-
|
164 |
-
return inputs
|
165 |
-
|
166 |
-
def get_dummy_inversion_inputs(self, device, seed=0):
|
167 |
-
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
168 |
-
image = image.cpu().permute(0, 2, 3, 1)[0]
|
169 |
-
image = Image.fromarray(np.uint8(image)).convert("RGB")
|
170 |
-
if str(device).startswith("mps"):
|
171 |
-
generator = torch.manual_seed(seed)
|
172 |
-
else:
|
173 |
-
generator = torch.Generator(device=device).manual_seed(seed)
|
174 |
-
inputs = {
|
175 |
-
"image": image,
|
176 |
-
"prompt": "a cat and a frog",
|
177 |
-
"generator": generator,
|
178 |
-
"num_inference_steps": 2,
|
179 |
-
"inpaint_strength": 1.0,
|
180 |
-
"guidance_scale": 6.0,
|
181 |
-
"decode_latents": True,
|
182 |
-
"output_type": "numpy",
|
183 |
-
}
|
184 |
-
return inputs
|
185 |
-
|
186 |
-
def test_save_load_optional_components(self):
|
187 |
-
if not hasattr(self.pipeline_class, "_optional_components"):
|
188 |
-
return
|
189 |
-
|
190 |
-
components = self.get_dummy_components()
|
191 |
-
pipe = self.pipeline_class(**components)
|
192 |
-
pipe.to(torch_device)
|
193 |
-
pipe.set_progress_bar_config(disable=None)
|
194 |
-
|
195 |
-
# set all optional components to None and update pipeline config accordingly
|
196 |
-
for optional_component in pipe._optional_components:
|
197 |
-
setattr(pipe, optional_component, None)
|
198 |
-
pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components})
|
199 |
-
|
200 |
-
inputs = self.get_dummy_inputs(torch_device)
|
201 |
-
output = pipe(**inputs)[0]
|
202 |
-
|
203 |
-
with tempfile.TemporaryDirectory() as tmpdir:
|
204 |
-
pipe.save_pretrained(tmpdir)
|
205 |
-
pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
|
206 |
-
pipe_loaded.to(torch_device)
|
207 |
-
pipe_loaded.set_progress_bar_config(disable=None)
|
208 |
-
|
209 |
-
for optional_component in pipe._optional_components:
|
210 |
-
self.assertTrue(
|
211 |
-
getattr(pipe_loaded, optional_component) is None,
|
212 |
-
f"`{optional_component}` did not stay set to None after loading.",
|
213 |
-
)
|
214 |
-
|
215 |
-
inputs = self.get_dummy_inputs(torch_device)
|
216 |
-
output_loaded = pipe_loaded(**inputs)[0]
|
217 |
-
|
218 |
-
max_diff = np.abs(output - output_loaded).max()
|
219 |
-
self.assertLess(max_diff, 1e-4)
|
220 |
-
|
221 |
-
def test_mask(self):
|
222 |
-
device = "cpu"
|
223 |
-
|
224 |
-
components = self.get_dummy_components()
|
225 |
-
pipe = self.pipeline_class(**components)
|
226 |
-
pipe.to(device)
|
227 |
-
pipe.set_progress_bar_config(disable=None)
|
228 |
-
|
229 |
-
inputs = self.get_dummy_mask_inputs(device)
|
230 |
-
mask = pipe.generate_mask(**inputs)
|
231 |
-
mask_slice = mask[0, -3:, -3:]
|
232 |
-
|
233 |
-
self.assertEqual(mask.shape, (1, 16, 16))
|
234 |
-
expected_slice = np.array([0] * 9)
|
235 |
-
max_diff = np.abs(mask_slice.flatten() - expected_slice).max()
|
236 |
-
self.assertLessEqual(max_diff, 1e-3)
|
237 |
-
self.assertEqual(mask[0, -3, -4], 0)
|
238 |
-
|
239 |
-
def test_inversion(self):
|
240 |
-
device = "cpu"
|
241 |
-
|
242 |
-
components = self.get_dummy_components()
|
243 |
-
pipe = self.pipeline_class(**components)
|
244 |
-
pipe.to(device)
|
245 |
-
pipe.set_progress_bar_config(disable=None)
|
246 |
-
|
247 |
-
inputs = self.get_dummy_inversion_inputs(device)
|
248 |
-
image = pipe.invert(**inputs).images
|
249 |
-
image_slice = image[0, -1, -3:, -3:]
|
250 |
-
|
251 |
-
self.assertEqual(image.shape, (2, 32, 32, 3))
|
252 |
-
expected_slice = np.array(
|
253 |
-
[0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5105, 0.5015, 0.4407, 0.4799],
|
254 |
-
)
|
255 |
-
max_diff = np.abs(image_slice.flatten() - expected_slice).max()
|
256 |
-
self.assertLessEqual(max_diff, 1e-3)
|
257 |
-
|
258 |
-
def test_inference_batch_single_identical(self):
|
259 |
-
super().test_inference_batch_single_identical(expected_max_diff=5e-3)
|
260 |
-
|
261 |
-
def test_inversion_dpm(self):
|
262 |
-
device = "cpu"
|
263 |
-
|
264 |
-
components = self.get_dummy_components()
|
265 |
-
|
266 |
-
scheduler_args = {"beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear"}
|
267 |
-
components["scheduler"] = DPMSolverMultistepScheduler(**scheduler_args)
|
268 |
-
components["inverse_scheduler"] = DPMSolverMultistepInverseScheduler(**scheduler_args)
|
269 |
-
|
270 |
-
pipe = self.pipeline_class(**components)
|
271 |
-
pipe.to(device)
|
272 |
-
pipe.set_progress_bar_config(disable=None)
|
273 |
-
|
274 |
-
inputs = self.get_dummy_inversion_inputs(device)
|
275 |
-
image = pipe.invert(**inputs).images
|
276 |
-
image_slice = image[0, -1, -3:, -3:]
|
277 |
-
|
278 |
-
self.assertEqual(image.shape, (2, 32, 32, 3))
|
279 |
-
expected_slice = np.array(
|
280 |
-
[0.5305, 0.4673, 0.5314, 0.5308, 0.4886, 0.5279, 0.5142, 0.4724, 0.4892],
|
281 |
-
)
|
282 |
-
max_diff = np.abs(image_slice.flatten() - expected_slice).max()
|
283 |
-
self.assertLessEqual(max_diff, 1e-3)
|
284 |
-
|
285 |
-
|
286 |
-
@require_torch_gpu
|
287 |
-
@slow
|
288 |
-
class StableDiffusionDiffEditPipelineIntegrationTests(unittest.TestCase):
|
289 |
-
def tearDown(self):
|
290 |
-
super().tearDown()
|
291 |
-
gc.collect()
|
292 |
-
torch.cuda.empty_cache()
|
293 |
-
|
294 |
-
@classmethod
|
295 |
-
def setUpClass(cls):
|
296 |
-
raw_image = load_image(
|
297 |
-
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"
|
298 |
-
)
|
299 |
-
|
300 |
-
raw_image = raw_image.convert("RGB").resize((768, 768))
|
301 |
-
|
302 |
-
cls.raw_image = raw_image
|
303 |
-
|
304 |
-
def test_stable_diffusion_diffedit_full(self):
|
305 |
-
generator = torch.manual_seed(0)
|
306 |
-
|
307 |
-
pipe = StableDiffusionDiffEditPipeline.from_pretrained(
|
308 |
-
"stabilityai/stable-diffusion-2-1", safety_checker=None, torch_dtype=torch.float16
|
309 |
-
)
|
310 |
-
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
|
311 |
-
pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)
|
312 |
-
pipe.enable_model_cpu_offload()
|
313 |
-
pipe.set_progress_bar_config(disable=None)
|
314 |
-
|
315 |
-
source_prompt = "a bowl of fruit"
|
316 |
-
target_prompt = "a bowl of pears"
|
317 |
-
|
318 |
-
mask_image = pipe.generate_mask(
|
319 |
-
image=self.raw_image,
|
320 |
-
source_prompt=source_prompt,
|
321 |
-
target_prompt=target_prompt,
|
322 |
-
generator=generator,
|
323 |
-
)
|
324 |
-
|
325 |
-
inv_latents = pipe.invert(
|
326 |
-
prompt=source_prompt, image=self.raw_image, inpaint_strength=0.7, generator=generator
|
327 |
-
).latents
|
328 |
-
|
329 |
-
image = pipe(
|
330 |
-
prompt=target_prompt,
|
331 |
-
mask_image=mask_image,
|
332 |
-
image_latents=inv_latents,
|
333 |
-
generator=generator,
|
334 |
-
negative_prompt=source_prompt,
|
335 |
-
inpaint_strength=0.7,
|
336 |
-
output_type="numpy",
|
337 |
-
).images[0]
|
338 |
-
|
339 |
-
expected_image = (
|
340 |
-
np.array(
|
341 |
-
load_image(
|
342 |
-
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
|
343 |
-
"/diffedit/pears.png"
|
344 |
-
).resize((768, 768))
|
345 |
-
)
|
346 |
-
/ 255
|
347 |
-
)
|
348 |
-
assert np.abs((expected_image - image).max()) < 5e-1
|
349 |
-
|
350 |
-
def test_stable_diffusion_diffedit_dpm(self):
|
351 |
-
generator = torch.manual_seed(0)
|
352 |
-
|
353 |
-
pipe = StableDiffusionDiffEditPipeline.from_pretrained(
|
354 |
-
"stabilityai/stable-diffusion-2-1", safety_checker=None, torch_dtype=torch.float16
|
355 |
-
)
|
356 |
-
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
357 |
-
pipe.inverse_scheduler = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config)
|
358 |
-
pipe.enable_model_cpu_offload()
|
359 |
-
pipe.set_progress_bar_config(disable=None)
|
360 |
-
|
361 |
-
source_prompt = "a bowl of fruit"
|
362 |
-
target_prompt = "a bowl of pears"
|
363 |
-
|
364 |
-
mask_image = pipe.generate_mask(
|
365 |
-
image=self.raw_image,
|
366 |
-
source_prompt=source_prompt,
|
367 |
-
target_prompt=target_prompt,
|
368 |
-
generator=generator,
|
369 |
-
)
|
370 |
-
|
371 |
-
inv_latents = pipe.invert(
|
372 |
-
prompt=source_prompt,
|
373 |
-
image=self.raw_image,
|
374 |
-
inpaint_strength=0.7,
|
375 |
-
generator=generator,
|
376 |
-
num_inference_steps=25,
|
377 |
-
).latents
|
378 |
-
|
379 |
-
image = pipe(
|
380 |
-
prompt=target_prompt,
|
381 |
-
mask_image=mask_image,
|
382 |
-
image_latents=inv_latents,
|
383 |
-
generator=generator,
|
384 |
-
negative_prompt=source_prompt,
|
385 |
-
inpaint_strength=0.7,
|
386 |
-
num_inference_steps=25,
|
387 |
-
output_type="numpy",
|
388 |
-
).images[0]
|
389 |
-
|
390 |
-
expected_image = (
|
391 |
-
np.array(
|
392 |
-
load_image(
|
393 |
-
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
|
394 |
-
"/diffedit/pears.png"
|
395 |
-
).resize((768, 768))
|
396 |
-
)
|
397 |
-
/ 255
|
398 |
-
)
|
399 |
-
assert np.abs((expected_image - image).max()) < 5e-1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Andy1621/uniformer_image_detection/configs/vfnet/vfnet_r2_101_fpn_mstrain_2x_coco.py
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
_base_ = './vfnet_r50_fpn_mstrain_2x_coco.py'
|
2 |
-
model = dict(
|
3 |
-
pretrained='open-mmlab://res2net101_v1d_26w_4s',
|
4 |
-
backbone=dict(
|
5 |
-
type='Res2Net',
|
6 |
-
depth=101,
|
7 |
-
scales=4,
|
8 |
-
base_width=26,
|
9 |
-
num_stages=4,
|
10 |
-
out_indices=(0, 1, 2, 3),
|
11 |
-
frozen_stages=1,
|
12 |
-
norm_cfg=dict(type='BN', requires_grad=True),
|
13 |
-
norm_eval=True,
|
14 |
-
style='pytorch'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Andy1621/uniformer_image_detection/mmdet/apis/test.py
DELETED
@@ -1,190 +0,0 @@
|
|
1 |
-
import os.path as osp
|
2 |
-
import pickle
|
3 |
-
import shutil
|
4 |
-
import tempfile
|
5 |
-
import time
|
6 |
-
|
7 |
-
import mmcv
|
8 |
-
import torch
|
9 |
-
import torch.distributed as dist
|
10 |
-
from mmcv.image import tensor2imgs
|
11 |
-
from mmcv.runner import get_dist_info
|
12 |
-
|
13 |
-
from mmdet.core import encode_mask_results
|
14 |
-
|
15 |
-
|
16 |
-
def single_gpu_test(model,
|
17 |
-
data_loader,
|
18 |
-
show=False,
|
19 |
-
out_dir=None,
|
20 |
-
show_score_thr=0.3):
|
21 |
-
model.eval()
|
22 |
-
results = []
|
23 |
-
dataset = data_loader.dataset
|
24 |
-
prog_bar = mmcv.ProgressBar(len(dataset))
|
25 |
-
for i, data in enumerate(data_loader):
|
26 |
-
with torch.no_grad():
|
27 |
-
result = model(return_loss=False, rescale=True, **data)
|
28 |
-
|
29 |
-
batch_size = len(result)
|
30 |
-
if show or out_dir:
|
31 |
-
if batch_size == 1 and isinstance(data['img'][0], torch.Tensor):
|
32 |
-
img_tensor = data['img'][0]
|
33 |
-
else:
|
34 |
-
img_tensor = data['img'][0].data[0]
|
35 |
-
img_metas = data['img_metas'][0].data[0]
|
36 |
-
imgs = tensor2imgs(img_tensor, **img_metas[0]['img_norm_cfg'])
|
37 |
-
assert len(imgs) == len(img_metas)
|
38 |
-
|
39 |
-
for i, (img, img_meta) in enumerate(zip(imgs, img_metas)):
|
40 |
-
h, w, _ = img_meta['img_shape']
|
41 |
-
img_show = img[:h, :w, :]
|
42 |
-
|
43 |
-
ori_h, ori_w = img_meta['ori_shape'][:-1]
|
44 |
-
img_show = mmcv.imresize(img_show, (ori_w, ori_h))
|
45 |
-
|
46 |
-
if out_dir:
|
47 |
-
out_file = osp.join(out_dir, img_meta['ori_filename'])
|
48 |
-
else:
|
49 |
-
out_file = None
|
50 |
-
|
51 |
-
model.module.show_result(
|
52 |
-
img_show,
|
53 |
-
result[i],
|
54 |
-
show=show,
|
55 |
-
out_file=out_file,
|
56 |
-
score_thr=show_score_thr)
|
57 |
-
|
58 |
-
# encode mask results
|
59 |
-
if isinstance(result[0], tuple):
|
60 |
-
result = [(bbox_results, encode_mask_results(mask_results))
|
61 |
-
for bbox_results, mask_results in result]
|
62 |
-
results.extend(result)
|
63 |
-
|
64 |
-
for _ in range(batch_size):
|
65 |
-
prog_bar.update()
|
66 |
-
return results
|
67 |
-
|
68 |
-
|
69 |
-
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False):
|
70 |
-
"""Test model with multiple gpus.
|
71 |
-
|
72 |
-
This method tests model with multiple gpus and collects the results
|
73 |
-
under two different modes: gpu and cpu modes. By setting 'gpu_collect=True'
|
74 |
-
it encodes results to gpu tensors and use gpu communication for results
|
75 |
-
collection. On cpu mode it saves the results on different gpus to 'tmpdir'
|
76 |
-
and collects them by the rank 0 worker.
|
77 |
-
|
78 |
-
Args:
|
79 |
-
model (nn.Module): Model to be tested.
|
80 |
-
data_loader (nn.Dataloader): Pytorch data loader.
|
81 |
-
tmpdir (str): Path of directory to save the temporary results from
|
82 |
-
different gpus under cpu mode.
|
83 |
-
gpu_collect (bool): Option to use either gpu or cpu to collect results.
|
84 |
-
|
85 |
-
Returns:
|
86 |
-
list: The prediction results.
|
87 |
-
"""
|
88 |
-
model.eval()
|
89 |
-
results = []
|
90 |
-
dataset = data_loader.dataset
|
91 |
-
rank, world_size = get_dist_info()
|
92 |
-
if rank == 0:
|
93 |
-
prog_bar = mmcv.ProgressBar(len(dataset))
|
94 |
-
time.sleep(2) # This line can prevent deadlock problem in some cases.
|
95 |
-
for i, data in enumerate(data_loader):
|
96 |
-
with torch.no_grad():
|
97 |
-
result = model(return_loss=False, rescale=True, **data)
|
98 |
-
# encode mask results
|
99 |
-
if isinstance(result[0], tuple):
|
100 |
-
result = [(bbox_results, encode_mask_results(mask_results))
|
101 |
-
for bbox_results, mask_results in result]
|
102 |
-
results.extend(result)
|
103 |
-
|
104 |
-
if rank == 0:
|
105 |
-
batch_size = len(result)
|
106 |
-
for _ in range(batch_size * world_size):
|
107 |
-
prog_bar.update()
|
108 |
-
|
109 |
-
# collect results from all ranks
|
110 |
-
if gpu_collect:
|
111 |
-
results = collect_results_gpu(results, len(dataset))
|
112 |
-
else:
|
113 |
-
results = collect_results_cpu(results, len(dataset), tmpdir)
|
114 |
-
return results
|
115 |
-
|
116 |
-
|
117 |
-
def collect_results_cpu(result_part, size, tmpdir=None):
|
118 |
-
rank, world_size = get_dist_info()
|
119 |
-
# create a tmp dir if it is not specified
|
120 |
-
if tmpdir is None:
|
121 |
-
MAX_LEN = 512
|
122 |
-
# 32 is whitespace
|
123 |
-
dir_tensor = torch.full((MAX_LEN, ),
|
124 |
-
32,
|
125 |
-
dtype=torch.uint8,
|
126 |
-
device='cuda')
|
127 |
-
if rank == 0:
|
128 |
-
mmcv.mkdir_or_exist('.dist_test')
|
129 |
-
tmpdir = tempfile.mkdtemp(dir='.dist_test')
|
130 |
-
tmpdir = torch.tensor(
|
131 |
-
bytearray(tmpdir.encode()), dtype=torch.uint8, device='cuda')
|
132 |
-
dir_tensor[:len(tmpdir)] = tmpdir
|
133 |
-
dist.broadcast(dir_tensor, 0)
|
134 |
-
tmpdir = dir_tensor.cpu().numpy().tobytes().decode().rstrip()
|
135 |
-
else:
|
136 |
-
mmcv.mkdir_or_exist(tmpdir)
|
137 |
-
# dump the part result to the dir
|
138 |
-
mmcv.dump(result_part, osp.join(tmpdir, f'part_{rank}.pkl'))
|
139 |
-
dist.barrier()
|
140 |
-
# collect all parts
|
141 |
-
if rank != 0:
|
142 |
-
return None
|
143 |
-
else:
|
144 |
-
# load results of all parts from tmp dir
|
145 |
-
part_list = []
|
146 |
-
for i in range(world_size):
|
147 |
-
part_file = osp.join(tmpdir, f'part_{i}.pkl')
|
148 |
-
part_list.append(mmcv.load(part_file))
|
149 |
-
# sort the results
|
150 |
-
ordered_results = []
|
151 |
-
for res in zip(*part_list):
|
152 |
-
ordered_results.extend(list(res))
|
153 |
-
# the dataloader may pad some samples
|
154 |
-
ordered_results = ordered_results[:size]
|
155 |
-
# remove tmp dir
|
156 |
-
shutil.rmtree(tmpdir)
|
157 |
-
return ordered_results
|
158 |
-
|
159 |
-
|
160 |
-
def collect_results_gpu(result_part, size):
|
161 |
-
rank, world_size = get_dist_info()
|
162 |
-
# dump result part to tensor with pickle
|
163 |
-
part_tensor = torch.tensor(
|
164 |
-
bytearray(pickle.dumps(result_part)), dtype=torch.uint8, device='cuda')
|
165 |
-
# gather all result part tensor shape
|
166 |
-
shape_tensor = torch.tensor(part_tensor.shape, device='cuda')
|
167 |
-
shape_list = [shape_tensor.clone() for _ in range(world_size)]
|
168 |
-
dist.all_gather(shape_list, shape_tensor)
|
169 |
-
# padding result part tensor to max length
|
170 |
-
shape_max = torch.tensor(shape_list).max()
|
171 |
-
part_send = torch.zeros(shape_max, dtype=torch.uint8, device='cuda')
|
172 |
-
part_send[:shape_tensor[0]] = part_tensor
|
173 |
-
part_recv_list = [
|
174 |
-
part_tensor.new_zeros(shape_max) for _ in range(world_size)
|
175 |
-
]
|
176 |
-
# gather all result part
|
177 |
-
dist.all_gather(part_recv_list, part_send)
|
178 |
-
|
179 |
-
if rank == 0:
|
180 |
-
part_list = []
|
181 |
-
for recv, shape in zip(part_recv_list, shape_list):
|
182 |
-
part_list.append(
|
183 |
-
pickle.loads(recv[:shape[0]].cpu().numpy().tobytes()))
|
184 |
-
# sort the results
|
185 |
-
ordered_results = []
|
186 |
-
for res in zip(*part_list):
|
187 |
-
ordered_results.extend(list(res))
|
188 |
-
# the dataloader may pad some samples
|
189 |
-
ordered_results = ordered_results[:size]
|
190 |
-
return ordered_results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Andy1621/uniformer_image_segmentation/configs/ccnet/ccnet_r50-d8_512x512_80k_ade20k.py
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
_base_ = [
|
2 |
-
'../_base_/models/ccnet_r50-d8.py', '../_base_/datasets/ade20k.py',
|
3 |
-
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
|
4 |
-
]
|
5 |
-
model = dict(
|
6 |
-
decode_head=dict(num_classes=150), auxiliary_head=dict(num_classes=150))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Aomsin/Lab10_630510654/README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Eiei
|
3 |
-
emoji: 👀
|
4 |
-
colorFrom: yellow
|
5 |
-
colorTo: gray
|
6 |
-
sdk: streamlit
|
7 |
-
sdk_version: 1.10.0
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: cc-by-nd-4.0
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Arnaudding001/OpenAI_whisperLive/vad.py
DELETED
@@ -1,468 +0,0 @@
|
|
1 |
-
from abc import ABC, abstractmethod
|
2 |
-
from collections import Counter, deque
|
3 |
-
|
4 |
-
from typing import Any, Deque, Iterator, List, Dict
|
5 |
-
|
6 |
-
from pprint import pprint
|
7 |
-
|
8 |
-
from segments import merge_timestamps
|
9 |
-
|
10 |
-
# Workaround for https://github.com/tensorflow/tensorflow/issues/48797
|
11 |
-
try:
|
12 |
-
import tensorflow as tf
|
13 |
-
except ModuleNotFoundError:
|
14 |
-
# Error handling
|
15 |
-
pass
|
16 |
-
|
17 |
-
import torch
|
18 |
-
|
19 |
-
import ffmpeg
|
20 |
-
import numpy as np
|
21 |
-
|
22 |
-
from utils import format_timestamp
|
23 |
-
from enum import Enum
|
24 |
-
|
25 |
-
class NonSpeechStrategy(Enum):
|
26 |
-
"""
|
27 |
-
Ignore non-speech frames segments.
|
28 |
-
"""
|
29 |
-
SKIP = 1
|
30 |
-
"""
|
31 |
-
Just treat non-speech segments as speech.
|
32 |
-
"""
|
33 |
-
CREATE_SEGMENT = 2
|
34 |
-
"""
|
35 |
-
Expand speech segments into subsequent non-speech segments.
|
36 |
-
"""
|
37 |
-
EXPAND_SEGMENT = 3
|
38 |
-
|
39 |
-
# Defaults for Silero
|
40 |
-
SPEECH_TRESHOLD = 0.3
|
41 |
-
|
42 |
-
# Minimum size of segments to process
|
43 |
-
MIN_SEGMENT_DURATION = 1
|
44 |
-
|
45 |
-
# The maximum time for texts from old segments to be used in the next segment
|
46 |
-
MAX_PROMPT_WINDOW = 0 # seconds (0 = disabled)
|
47 |
-
PROMPT_NO_SPEECH_PROB = 0.1 # Do not pass the text from segments with a no speech probability higher than this
|
48 |
-
|
49 |
-
VAD_MAX_PROCESSING_CHUNK = 60 * 60 # 60 minutes of audio
|
50 |
-
|
51 |
-
class TranscriptionConfig(ABC):
|
52 |
-
def __init__(self, non_speech_strategy: NonSpeechStrategy = NonSpeechStrategy.SKIP,
|
53 |
-
segment_padding_left: float = None, segment_padding_right = None, max_silent_period: float = None,
|
54 |
-
max_merge_size: float = None, max_prompt_window: float = None):
|
55 |
-
self.non_speech_strategy = non_speech_strategy
|
56 |
-
self.segment_padding_left = segment_padding_left
|
57 |
-
self.segment_padding_right = segment_padding_right
|
58 |
-
self.max_silent_period = max_silent_period
|
59 |
-
self.max_merge_size = max_merge_size
|
60 |
-
self.max_prompt_window = max_prompt_window
|
61 |
-
|
62 |
-
class PeriodicTranscriptionConfig(TranscriptionConfig):
|
63 |
-
def __init__(self, periodic_duration: float, non_speech_strategy: NonSpeechStrategy = NonSpeechStrategy.SKIP,
|
64 |
-
segment_padding_left: float = None, segment_padding_right = None, max_silent_period: float = None,
|
65 |
-
max_merge_size: float = None, max_prompt_window: float = None):
|
66 |
-
super().__init__(non_speech_strategy, segment_padding_left, segment_padding_right, max_silent_period, max_merge_size, max_prompt_window)
|
67 |
-
self.periodic_duration = periodic_duration
|
68 |
-
|
69 |
-
class AbstractTranscription(ABC):
|
70 |
-
def __init__(self, sampling_rate: int = 16000):
|
71 |
-
self.sampling_rate = sampling_rate
|
72 |
-
|
73 |
-
def get_audio_segment(self, str, start_time: str = None, duration: str = None):
|
74 |
-
return load_audio(str, self.sampling_rate, start_time, duration)
|
75 |
-
|
76 |
-
@abstractmethod
|
77 |
-
def get_transcribe_timestamps(self, audio: str, config: TranscriptionConfig):
|
78 |
-
"""
|
79 |
-
Get the start and end timestamps of the sections that should be transcribed by this VAD method.
|
80 |
-
Parameters
|
81 |
-
----------
|
82 |
-
audio: str
|
83 |
-
The audio file.
|
84 |
-
config: TranscriptionConfig
|
85 |
-
The transcription configuration.
|
86 |
-
Returns
|
87 |
-
-------
|
88 |
-
A list of start and end timestamps, in fractional seconds.
|
89 |
-
"""
|
90 |
-
return
|
91 |
-
|
92 |
-
def transcribe(self, audio: str, whisperCallable, config: TranscriptionConfig):
|
93 |
-
"""
|
94 |
-
Transcribe the given audo file.
|
95 |
-
Parameters
|
96 |
-
----------
|
97 |
-
audio: str
|
98 |
-
The audio file.
|
99 |
-
whisperCallable: Callable[[Union[str, np.ndarray, torch.Tensor], int, str, str], dict[str, Union[dict, Any]]]
|
100 |
-
The callback that is used to invoke Whisper on an audio file/buffer. The first parameter is the audio file/buffer,
|
101 |
-
the second parameter is an optional text prompt, and the last is the current detected language. The return value is the result of the Whisper call.
|
102 |
-
Returns
|
103 |
-
-------
|
104 |
-
A list of start and end timestamps, in fractional seconds.
|
105 |
-
"""
|
106 |
-
|
107 |
-
# get speech timestamps from full audio file
|
108 |
-
seconds_timestamps = self.get_transcribe_timestamps(audio, config)
|
109 |
-
|
110 |
-
#for seconds_timestamp in seconds_timestamps:
|
111 |
-
# print("VAD timestamp ", format_timestamp(seconds_timestamp['start']), " to ", format_timestamp(seconds_timestamp['end']))
|
112 |
-
|
113 |
-
merged = merge_timestamps(seconds_timestamps, config.max_silent_period, config.max_merge_size, config.segment_padding_left, config.segment_padding_right)
|
114 |
-
|
115 |
-
# A deque of transcribed segments that is passed to the next segment as a prompt
|
116 |
-
prompt_window = deque()
|
117 |
-
|
118 |
-
print("Timestamps:")
|
119 |
-
pprint(merged)
|
120 |
-
|
121 |
-
if config.non_speech_strategy != NonSpeechStrategy.SKIP:
|
122 |
-
max_audio_duration = get_audio_duration(audio)
|
123 |
-
|
124 |
-
# Expand segments to include the gaps between them
|
125 |
-
if (config.non_speech_strategy == NonSpeechStrategy.CREATE_SEGMENT):
|
126 |
-
# When we have a prompt window, we create speech segments betwen each segment if we exceed the merge size
|
127 |
-
merged = self.fill_gaps(merged, total_duration=max_audio_duration, max_expand_size=config.max_merge_size)
|
128 |
-
elif config.non_speech_strategy == NonSpeechStrategy.EXPAND_SEGMENT:
|
129 |
-
# With no prompt window, it is better to just expand the segments (this effectively passes the prompt to the next segment)
|
130 |
-
merged = self.expand_gaps(merged, total_duration=max_audio_duration)
|
131 |
-
else:
|
132 |
-
raise Exception("Unknown non-speech strategy: " + str(config.non_speech_strategy))
|
133 |
-
|
134 |
-
print("Transcribing non-speech:")
|
135 |
-
pprint(merged)
|
136 |
-
|
137 |
-
result = {
|
138 |
-
'text': "",
|
139 |
-
'segments': [],
|
140 |
-
'language': ""
|
141 |
-
}
|
142 |
-
languageCounter = Counter()
|
143 |
-
detected_language = None
|
144 |
-
|
145 |
-
segment_index = -1
|
146 |
-
|
147 |
-
# For each time segment, run whisper
|
148 |
-
for segment in merged:
|
149 |
-
segment_index += 1
|
150 |
-
segment_start = segment['start']
|
151 |
-
segment_end = segment['end']
|
152 |
-
segment_expand_amount = segment.get('expand_amount', 0)
|
153 |
-
segment_gap = segment.get('gap', False)
|
154 |
-
|
155 |
-
segment_duration = segment_end - segment_start
|
156 |
-
|
157 |
-
if segment_duration < MIN_SEGMENT_DURATION:
|
158 |
-
continue;
|
159 |
-
|
160 |
-
# Audio to run on Whisper
|
161 |
-
segment_audio = self.get_audio_segment(audio, start_time = str(segment_start), duration = str(segment_duration))
|
162 |
-
# Previous segments to use as a prompt
|
163 |
-
segment_prompt = ' '.join([segment['text'] for segment in prompt_window]) if len(prompt_window) > 0 else None
|
164 |
-
|
165 |
-
# Detected language
|
166 |
-
detected_language = languageCounter.most_common(1)[0][0] if len(languageCounter) > 0 else None
|
167 |
-
|
168 |
-
print("Running whisper from ", format_timestamp(segment_start), " to ", format_timestamp(segment_end), ", duration: ",
|
169 |
-
segment_duration, "expanded: ", segment_expand_amount, "prompt: ", segment_prompt, "language: ", detected_language)
|
170 |
-
segment_result = whisperCallable(segment_audio, segment_index, segment_prompt, detected_language)
|
171 |
-
|
172 |
-
adjusted_segments = self.adjust_timestamp(segment_result["segments"], adjust_seconds=segment_start, max_source_time=segment_duration)
|
173 |
-
|
174 |
-
# Propagate expand amount to the segments
|
175 |
-
if (segment_expand_amount > 0):
|
176 |
-
segment_without_expansion = segment_duration - segment_expand_amount
|
177 |
-
|
178 |
-
for adjusted_segment in adjusted_segments:
|
179 |
-
adjusted_segment_end = adjusted_segment['end']
|
180 |
-
|
181 |
-
# Add expand amount if the segment got expanded
|
182 |
-
if (adjusted_segment_end > segment_without_expansion):
|
183 |
-
adjusted_segment["expand_amount"] = adjusted_segment_end - segment_without_expansion
|
184 |
-
|
185 |
-
# Append to output
|
186 |
-
result['text'] += segment_result['text']
|
187 |
-
result['segments'].extend(adjusted_segments)
|
188 |
-
|
189 |
-
# Increment detected language
|
190 |
-
if not segment_gap:
|
191 |
-
languageCounter[segment_result['language']] += 1
|
192 |
-
|
193 |
-
# Update prompt window
|
194 |
-
self.__update_prompt_window(prompt_window, adjusted_segments, segment_end, segment_gap, config)
|
195 |
-
|
196 |
-
if detected_language is not None:
|
197 |
-
result['language'] = detected_language
|
198 |
-
|
199 |
-
return result
|
200 |
-
|
201 |
-
def __update_prompt_window(self, prompt_window: Deque, adjusted_segments: List, segment_end: float, segment_gap: bool, config: TranscriptionConfig):
|
202 |
-
if (config.max_prompt_window is not None and config.max_prompt_window > 0):
|
203 |
-
# Add segments to the current prompt window (unless it is a speech gap)
|
204 |
-
if not segment_gap:
|
205 |
-
for segment in adjusted_segments:
|
206 |
-
if segment.get('no_speech_prob', 0) <= PROMPT_NO_SPEECH_PROB:
|
207 |
-
prompt_window.append(segment)
|
208 |
-
|
209 |
-
while (len(prompt_window) > 0):
|
210 |
-
first_end_time = prompt_window[0].get('end', 0)
|
211 |
-
# Time expanded in the segments should be discounted from the prompt window
|
212 |
-
first_expand_time = prompt_window[0].get('expand_amount', 0)
|
213 |
-
|
214 |
-
if (first_end_time - first_expand_time < segment_end - config.max_prompt_window):
|
215 |
-
prompt_window.popleft()
|
216 |
-
else:
|
217 |
-
break
|
218 |
-
|
219 |
-
def include_gaps(self, segments: Iterator[dict], min_gap_length: float, total_duration: float):
|
220 |
-
result = []
|
221 |
-
last_end_time = 0
|
222 |
-
|
223 |
-
for segment in segments:
|
224 |
-
segment_start = float(segment['start'])
|
225 |
-
segment_end = float(segment['end'])
|
226 |
-
|
227 |
-
if (last_end_time != segment_start):
|
228 |
-
delta = segment_start - last_end_time
|
229 |
-
|
230 |
-
if (min_gap_length is None or delta >= min_gap_length):
|
231 |
-
result.append( { 'start': last_end_time, 'end': segment_start, 'gap': True } )
|
232 |
-
|
233 |
-
last_end_time = segment_end
|
234 |
-
result.append(segment)
|
235 |
-
|
236 |
-
# Also include total duration if specified
|
237 |
-
if (total_duration is not None and last_end_time < total_duration):
|
238 |
-
delta = total_duration - segment_start
|
239 |
-
|
240 |
-
if (min_gap_length is None or delta >= min_gap_length):
|
241 |
-
result.append( { 'start': last_end_time, 'end': total_duration, 'gap': True } )
|
242 |
-
|
243 |
-
return result
|
244 |
-
|
245 |
-
# Expand the end time of each segment to the start of the next segment
|
246 |
-
def expand_gaps(self, segments: List[Dict[str, Any]], total_duration: float):
|
247 |
-
result = []
|
248 |
-
|
249 |
-
if len(segments) == 0:
|
250 |
-
return result
|
251 |
-
|
252 |
-
# Add gap at the beginning if needed
|
253 |
-
if (segments[0]['start'] > 0):
|
254 |
-
result.append({ 'start': 0, 'end': segments[0]['start'], 'gap': True } )
|
255 |
-
|
256 |
-
for i in range(len(segments) - 1):
|
257 |
-
current_segment = segments[i]
|
258 |
-
next_segment = segments[i + 1]
|
259 |
-
|
260 |
-
delta = next_segment['start'] - current_segment['end']
|
261 |
-
|
262 |
-
# Expand if the gap actually exists
|
263 |
-
if (delta >= 0):
|
264 |
-
current_segment = current_segment.copy()
|
265 |
-
current_segment['expand_amount'] = delta
|
266 |
-
current_segment['end'] = next_segment['start']
|
267 |
-
|
268 |
-
result.append(current_segment)
|
269 |
-
|
270 |
-
# Add last segment
|
271 |
-
last_segment = segments[-1]
|
272 |
-
result.append(last_segment)
|
273 |
-
|
274 |
-
# Also include total duration if specified
|
275 |
-
if (total_duration is not None):
|
276 |
-
last_segment = result[-1]
|
277 |
-
|
278 |
-
if (last_segment['end'] < total_duration):
|
279 |
-
last_segment = last_segment.copy()
|
280 |
-
last_segment['end'] = total_duration
|
281 |
-
result[-1] = last_segment
|
282 |
-
|
283 |
-
return result
|
284 |
-
|
285 |
-
def fill_gaps(self, segments: List[Dict[str, Any]], total_duration: float, max_expand_size: float = None):
|
286 |
-
result = []
|
287 |
-
|
288 |
-
if len(segments) == 0:
|
289 |
-
return result
|
290 |
-
|
291 |
-
# Add gap at the beginning if needed
|
292 |
-
if (segments[0]['start'] > 0):
|
293 |
-
result.append({ 'start': 0, 'end': segments[0]['start'], 'gap': True } )
|
294 |
-
|
295 |
-
for i in range(len(segments) - 1):
|
296 |
-
expanded = False
|
297 |
-
current_segment = segments[i]
|
298 |
-
next_segment = segments[i + 1]
|
299 |
-
|
300 |
-
delta = next_segment['start'] - current_segment['end']
|
301 |
-
|
302 |
-
if (max_expand_size is not None and delta <= max_expand_size):
|
303 |
-
# Just expand the current segment
|
304 |
-
current_segment = current_segment.copy()
|
305 |
-
current_segment['expand_amount'] = delta
|
306 |
-
current_segment['end'] = next_segment['start']
|
307 |
-
expanded = True
|
308 |
-
|
309 |
-
result.append(current_segment)
|
310 |
-
|
311 |
-
# Add a gap to the next segment if needed
|
312 |
-
if (delta >= 0 and not expanded):
|
313 |
-
result.append({ 'start': current_segment['end'], 'end': next_segment['start'], 'gap': True } )
|
314 |
-
|
315 |
-
# Add last segment
|
316 |
-
last_segment = segments[-1]
|
317 |
-
result.append(last_segment)
|
318 |
-
|
319 |
-
# Also include total duration if specified
|
320 |
-
if (total_duration is not None):
|
321 |
-
last_segment = result[-1]
|
322 |
-
|
323 |
-
delta = total_duration - last_segment['end']
|
324 |
-
|
325 |
-
if (delta > 0):
|
326 |
-
if (max_expand_size is not None and delta <= max_expand_size):
|
327 |
-
# Expand the last segment
|
328 |
-
last_segment = last_segment.copy()
|
329 |
-
last_segment['expand_amount'] = delta
|
330 |
-
last_segment['end'] = total_duration
|
331 |
-
result[-1] = last_segment
|
332 |
-
else:
|
333 |
-
result.append({ 'start': last_segment['end'], 'end': total_duration, 'gap': True } )
|
334 |
-
|
335 |
-
return result
|
336 |
-
|
337 |
-
def adjust_timestamp(self, segments: Iterator[dict], adjust_seconds: float, max_source_time: float = None):
|
338 |
-
result = []
|
339 |
-
|
340 |
-
for segment in segments:
|
341 |
-
segment_start = float(segment['start'])
|
342 |
-
segment_end = float(segment['end'])
|
343 |
-
|
344 |
-
# Filter segments?
|
345 |
-
if (max_source_time is not None):
|
346 |
-
if (segment_start > max_source_time):
|
347 |
-
continue
|
348 |
-
segment_end = min(max_source_time, segment_end)
|
349 |
-
|
350 |
-
new_segment = segment.copy()
|
351 |
-
|
352 |
-
# Add to start and end
|
353 |
-
new_segment['start'] = segment_start + adjust_seconds
|
354 |
-
new_segment['end'] = segment_end + adjust_seconds
|
355 |
-
result.append(new_segment)
|
356 |
-
return result
|
357 |
-
|
358 |
-
def multiply_timestamps(self, timestamps: List[Dict[str, Any]], factor: float):
|
359 |
-
result = []
|
360 |
-
|
361 |
-
for entry in timestamps:
|
362 |
-
start = entry['start']
|
363 |
-
end = entry['end']
|
364 |
-
|
365 |
-
result.append({
|
366 |
-
'start': start * factor,
|
367 |
-
'end': end * factor
|
368 |
-
})
|
369 |
-
return result
|
370 |
-
|
371 |
-
class VadSileroTranscription(AbstractTranscription):
|
372 |
-
def __init__(self, sampling_rate: int = 16000):
|
373 |
-
super().__init__(sampling_rate=sampling_rate)
|
374 |
-
|
375 |
-
self.model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad')
|
376 |
-
(self.get_speech_timestamps, _, _, _, _) = utils
|
377 |
-
|
378 |
-
|
379 |
-
def get_transcribe_timestamps(self, audio: str, config: TranscriptionConfig):
|
380 |
-
audio_duration = get_audio_duration(audio)
|
381 |
-
result = []
|
382 |
-
|
383 |
-
# Divide procesisng of audio into chunks
|
384 |
-
chunk_start = 0.0
|
385 |
-
|
386 |
-
while (chunk_start < audio_duration):
|
387 |
-
chunk_duration = min(audio_duration - chunk_start, VAD_MAX_PROCESSING_CHUNK)
|
388 |
-
|
389 |
-
print("Processing VAD in chunk from {} to {}".format(format_timestamp(chunk_start), format_timestamp(chunk_start + chunk_duration)))
|
390 |
-
wav = self.get_audio_segment(audio, str(chunk_start), str(chunk_duration))
|
391 |
-
|
392 |
-
sample_timestamps = self.get_speech_timestamps(wav, self.model, sampling_rate=self.sampling_rate, threshold=SPEECH_TRESHOLD)
|
393 |
-
seconds_timestamps = self.multiply_timestamps(sample_timestamps, factor=1 / self.sampling_rate)
|
394 |
-
adjusted = self.adjust_timestamp(seconds_timestamps, adjust_seconds=chunk_start, max_source_time=chunk_start + chunk_duration)
|
395 |
-
|
396 |
-
#pprint(adjusted)
|
397 |
-
|
398 |
-
result.extend(adjusted)
|
399 |
-
chunk_start += chunk_duration
|
400 |
-
|
401 |
-
return result
|
402 |
-
|
403 |
-
# A very simple VAD that just marks every N seconds as speech
|
404 |
-
class VadPeriodicTranscription(AbstractTranscription):
|
405 |
-
def __init__(self, sampling_rate: int = 16000):
|
406 |
-
super().__init__(sampling_rate=sampling_rate)
|
407 |
-
|
408 |
-
def get_transcribe_timestamps(self, audio: str, config: PeriodicTranscriptionConfig):
|
409 |
-
# Get duration in seconds
|
410 |
-
audio_duration = get_audio_duration(audio)
|
411 |
-
result = []
|
412 |
-
|
413 |
-
# Generate a timestamp every N seconds
|
414 |
-
start_timestamp = 0
|
415 |
-
|
416 |
-
while (start_timestamp < audio_duration):
|
417 |
-
end_timestamp = min(start_timestamp + config.periodic_duration, audio_duration)
|
418 |
-
segment_duration = end_timestamp - start_timestamp
|
419 |
-
|
420 |
-
# Minimum duration is 1 second
|
421 |
-
if (segment_duration >= 1):
|
422 |
-
result.append( { 'start': start_timestamp, 'end': end_timestamp } )
|
423 |
-
|
424 |
-
start_timestamp = end_timestamp
|
425 |
-
|
426 |
-
return result
|
427 |
-
|
428 |
-
def get_audio_duration(file: str):
|
429 |
-
return float(ffmpeg.probe(file)["format"]["duration"])
|
430 |
-
|
431 |
-
def load_audio(file: str, sample_rate: int = 16000,
|
432 |
-
start_time: str = None, duration: str = None):
|
433 |
-
"""
|
434 |
-
Open an audio file and read as mono waveform, resampling as necessary
|
435 |
-
Parameters
|
436 |
-
----------
|
437 |
-
file: str
|
438 |
-
The audio file to open
|
439 |
-
sr: int
|
440 |
-
The sample rate to resample the audio if necessary
|
441 |
-
start_time: str
|
442 |
-
The start time, using the standard FFMPEG time duration syntax, or None to disable.
|
443 |
-
|
444 |
-
duration: str
|
445 |
-
The duration, using the standard FFMPEG time duration syntax, or None to disable.
|
446 |
-
Returns
|
447 |
-
-------
|
448 |
-
A NumPy array containing the audio waveform, in float32 dtype.
|
449 |
-
"""
|
450 |
-
try:
|
451 |
-
inputArgs = {'threads': 0}
|
452 |
-
|
453 |
-
if (start_time is not None):
|
454 |
-
inputArgs['ss'] = start_time
|
455 |
-
if (duration is not None):
|
456 |
-
inputArgs['t'] = duration
|
457 |
-
|
458 |
-
# This launches a subprocess to decode audio while down-mixing and resampling as necessary.
|
459 |
-
# Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
|
460 |
-
out, _ = (
|
461 |
-
ffmpeg.input(file, **inputArgs)
|
462 |
-
.output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sample_rate)
|
463 |
-
.run(cmd="ffmpeg", capture_stdout=True, capture_stderr=True)
|
464 |
-
)
|
465 |
-
except ffmpeg.Error as e:
|
466 |
-
raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}")
|
467 |
-
|
468 |
-
return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Arulkumar03/GroundingDINO_SOTA_Zero_Shot_Model/groundingdino/util/misc.py
DELETED
@@ -1,717 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
2 |
-
"""
|
3 |
-
Misc functions, including distributed helpers.
|
4 |
-
|
5 |
-
Mostly copy-paste from torchvision references.
|
6 |
-
"""
|
7 |
-
import colorsys
|
8 |
-
import datetime
|
9 |
-
import functools
|
10 |
-
import io
|
11 |
-
import json
|
12 |
-
import os
|
13 |
-
import pickle
|
14 |
-
import subprocess
|
15 |
-
import time
|
16 |
-
from collections import OrderedDict, defaultdict, deque
|
17 |
-
from typing import List, Optional
|
18 |
-
|
19 |
-
import numpy as np
|
20 |
-
import torch
|
21 |
-
import torch.distributed as dist
|
22 |
-
|
23 |
-
# needed due to empty tensor bug in pytorch and torchvision 0.5
|
24 |
-
import torchvision
|
25 |
-
from torch import Tensor
|
26 |
-
|
27 |
-
__torchvision_need_compat_flag = float(torchvision.__version__.split(".")[1]) < 7
|
28 |
-
if __torchvision_need_compat_flag:
|
29 |
-
from torchvision.ops import _new_empty_tensor
|
30 |
-
from torchvision.ops.misc import _output_size
|
31 |
-
|
32 |
-
|
33 |
-
class SmoothedValue(object):
|
34 |
-
"""Track a series of values and provide access to smoothed values over a
|
35 |
-
window or the global series average.
|
36 |
-
"""
|
37 |
-
|
38 |
-
def __init__(self, window_size=20, fmt=None):
|
39 |
-
if fmt is None:
|
40 |
-
fmt = "{median:.4f} ({global_avg:.4f})"
|
41 |
-
self.deque = deque(maxlen=window_size)
|
42 |
-
self.total = 0.0
|
43 |
-
self.count = 0
|
44 |
-
self.fmt = fmt
|
45 |
-
|
46 |
-
def update(self, value, n=1):
|
47 |
-
self.deque.append(value)
|
48 |
-
self.count += n
|
49 |
-
self.total += value * n
|
50 |
-
|
51 |
-
def synchronize_between_processes(self):
|
52 |
-
"""
|
53 |
-
Warning: does not synchronize the deque!
|
54 |
-
"""
|
55 |
-
if not is_dist_avail_and_initialized():
|
56 |
-
return
|
57 |
-
t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
|
58 |
-
dist.barrier()
|
59 |
-
dist.all_reduce(t)
|
60 |
-
t = t.tolist()
|
61 |
-
self.count = int(t[0])
|
62 |
-
self.total = t[1]
|
63 |
-
|
64 |
-
@property
|
65 |
-
def median(self):
|
66 |
-
d = torch.tensor(list(self.deque))
|
67 |
-
if d.shape[0] == 0:
|
68 |
-
return 0
|
69 |
-
return d.median().item()
|
70 |
-
|
71 |
-
@property
|
72 |
-
def avg(self):
|
73 |
-
d = torch.tensor(list(self.deque), dtype=torch.float32)
|
74 |
-
return d.mean().item()
|
75 |
-
|
76 |
-
@property
|
77 |
-
def global_avg(self):
|
78 |
-
if os.environ.get("SHILONG_AMP", None) == "1":
|
79 |
-
eps = 1e-4
|
80 |
-
else:
|
81 |
-
eps = 1e-6
|
82 |
-
return self.total / (self.count + eps)
|
83 |
-
|
84 |
-
@property
|
85 |
-
def max(self):
|
86 |
-
return max(self.deque)
|
87 |
-
|
88 |
-
@property
|
89 |
-
def value(self):
|
90 |
-
return self.deque[-1]
|
91 |
-
|
92 |
-
def __str__(self):
|
93 |
-
return self.fmt.format(
|
94 |
-
median=self.median,
|
95 |
-
avg=self.avg,
|
96 |
-
global_avg=self.global_avg,
|
97 |
-
max=self.max,
|
98 |
-
value=self.value,
|
99 |
-
)
|
100 |
-
|
101 |
-
|
102 |
-
@functools.lru_cache()
|
103 |
-
def _get_global_gloo_group():
|
104 |
-
"""
|
105 |
-
Return a process group based on gloo backend, containing all the ranks
|
106 |
-
The result is cached.
|
107 |
-
"""
|
108 |
-
|
109 |
-
if dist.get_backend() == "nccl":
|
110 |
-
return dist.new_group(backend="gloo")
|
111 |
-
|
112 |
-
return dist.group.WORLD
|
113 |
-
|
114 |
-
|
115 |
-
def all_gather_cpu(data):
|
116 |
-
"""
|
117 |
-
Run all_gather on arbitrary picklable data (not necessarily tensors)
|
118 |
-
Args:
|
119 |
-
data: any picklable object
|
120 |
-
Returns:
|
121 |
-
list[data]: list of data gathered from each rank
|
122 |
-
"""
|
123 |
-
|
124 |
-
world_size = get_world_size()
|
125 |
-
if world_size == 1:
|
126 |
-
return [data]
|
127 |
-
|
128 |
-
cpu_group = _get_global_gloo_group()
|
129 |
-
|
130 |
-
buffer = io.BytesIO()
|
131 |
-
torch.save(data, buffer)
|
132 |
-
data_view = buffer.getbuffer()
|
133 |
-
device = "cuda" if cpu_group is None else "cpu"
|
134 |
-
tensor = torch.ByteTensor(data_view).to(device)
|
135 |
-
|
136 |
-
# obtain Tensor size of each rank
|
137 |
-
local_size = torch.tensor([tensor.numel()], device=device, dtype=torch.long)
|
138 |
-
size_list = [torch.tensor([0], device=device, dtype=torch.long) for _ in range(world_size)]
|
139 |
-
if cpu_group is None:
|
140 |
-
dist.all_gather(size_list, local_size)
|
141 |
-
else:
|
142 |
-
print("gathering on cpu")
|
143 |
-
dist.all_gather(size_list, local_size, group=cpu_group)
|
144 |
-
size_list = [int(size.item()) for size in size_list]
|
145 |
-
max_size = max(size_list)
|
146 |
-
assert isinstance(local_size.item(), int)
|
147 |
-
local_size = int(local_size.item())
|
148 |
-
|
149 |
-
# receiving Tensor from all ranks
|
150 |
-
# we pad the tensor because torch all_gather does not support
|
151 |
-
# gathering tensors of different shapes
|
152 |
-
tensor_list = []
|
153 |
-
for _ in size_list:
|
154 |
-
tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=device))
|
155 |
-
if local_size != max_size:
|
156 |
-
padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device=device)
|
157 |
-
tensor = torch.cat((tensor, padding), dim=0)
|
158 |
-
if cpu_group is None:
|
159 |
-
dist.all_gather(tensor_list, tensor)
|
160 |
-
else:
|
161 |
-
dist.all_gather(tensor_list, tensor, group=cpu_group)
|
162 |
-
|
163 |
-
data_list = []
|
164 |
-
for size, tensor in zip(size_list, tensor_list):
|
165 |
-
tensor = torch.split(tensor, [size, max_size - size], dim=0)[0]
|
166 |
-
buffer = io.BytesIO(tensor.cpu().numpy())
|
167 |
-
obj = torch.load(buffer)
|
168 |
-
data_list.append(obj)
|
169 |
-
|
170 |
-
return data_list
|
171 |
-
|
172 |
-
|
173 |
-
def all_gather(data):
|
174 |
-
"""
|
175 |
-
Run all_gather on arbitrary picklable data (not necessarily tensors)
|
176 |
-
Args:
|
177 |
-
data: any picklable object
|
178 |
-
Returns:
|
179 |
-
list[data]: list of data gathered from each rank
|
180 |
-
"""
|
181 |
-
|
182 |
-
if os.getenv("CPU_REDUCE") == "1":
|
183 |
-
return all_gather_cpu(data)
|
184 |
-
|
185 |
-
world_size = get_world_size()
|
186 |
-
if world_size == 1:
|
187 |
-
return [data]
|
188 |
-
|
189 |
-
# serialized to a Tensor
|
190 |
-
buffer = pickle.dumps(data)
|
191 |
-
storage = torch.ByteStorage.from_buffer(buffer)
|
192 |
-
tensor = torch.ByteTensor(storage).to("cuda")
|
193 |
-
|
194 |
-
# obtain Tensor size of each rank
|
195 |
-
local_size = torch.tensor([tensor.numel()], device="cuda")
|
196 |
-
size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)]
|
197 |
-
dist.all_gather(size_list, local_size)
|
198 |
-
size_list = [int(size.item()) for size in size_list]
|
199 |
-
max_size = max(size_list)
|
200 |
-
|
201 |
-
# receiving Tensor from all ranks
|
202 |
-
# we pad the tensor because torch all_gather does not support
|
203 |
-
# gathering tensors of different shapes
|
204 |
-
tensor_list = []
|
205 |
-
for _ in size_list:
|
206 |
-
tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda"))
|
207 |
-
if local_size != max_size:
|
208 |
-
padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda")
|
209 |
-
tensor = torch.cat((tensor, padding), dim=0)
|
210 |
-
dist.all_gather(tensor_list, tensor)
|
211 |
-
|
212 |
-
data_list = []
|
213 |
-
for size, tensor in zip(size_list, tensor_list):
|
214 |
-
buffer = tensor.cpu().numpy().tobytes()[:size]
|
215 |
-
data_list.append(pickle.loads(buffer))
|
216 |
-
|
217 |
-
return data_list
|
218 |
-
|
219 |
-
|
220 |
-
def reduce_dict(input_dict, average=True):
|
221 |
-
"""
|
222 |
-
Args:
|
223 |
-
input_dict (dict): all the values will be reduced
|
224 |
-
average (bool): whether to do average or sum
|
225 |
-
Reduce the values in the dictionary from all processes so that all processes
|
226 |
-
have the averaged results. Returns a dict with the same fields as
|
227 |
-
input_dict, after reduction.
|
228 |
-
"""
|
229 |
-
world_size = get_world_size()
|
230 |
-
if world_size < 2:
|
231 |
-
return input_dict
|
232 |
-
with torch.no_grad():
|
233 |
-
names = []
|
234 |
-
values = []
|
235 |
-
# sort the keys so that they are consistent across processes
|
236 |
-
for k in sorted(input_dict.keys()):
|
237 |
-
names.append(k)
|
238 |
-
values.append(input_dict[k])
|
239 |
-
values = torch.stack(values, dim=0)
|
240 |
-
dist.all_reduce(values)
|
241 |
-
if average:
|
242 |
-
values /= world_size
|
243 |
-
reduced_dict = {k: v for k, v in zip(names, values)}
|
244 |
-
return reduced_dict
|
245 |
-
|
246 |
-
|
247 |
-
class MetricLogger(object):
|
248 |
-
def __init__(self, delimiter="\t"):
|
249 |
-
self.meters = defaultdict(SmoothedValue)
|
250 |
-
self.delimiter = delimiter
|
251 |
-
|
252 |
-
def update(self, **kwargs):
|
253 |
-
for k, v in kwargs.items():
|
254 |
-
if isinstance(v, torch.Tensor):
|
255 |
-
v = v.item()
|
256 |
-
assert isinstance(v, (float, int))
|
257 |
-
self.meters[k].update(v)
|
258 |
-
|
259 |
-
def __getattr__(self, attr):
|
260 |
-
if attr in self.meters:
|
261 |
-
return self.meters[attr]
|
262 |
-
if attr in self.__dict__:
|
263 |
-
return self.__dict__[attr]
|
264 |
-
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr))
|
265 |
-
|
266 |
-
def __str__(self):
|
267 |
-
loss_str = []
|
268 |
-
for name, meter in self.meters.items():
|
269 |
-
# print(name, str(meter))
|
270 |
-
# import ipdb;ipdb.set_trace()
|
271 |
-
if meter.count > 0:
|
272 |
-
loss_str.append("{}: {}".format(name, str(meter)))
|
273 |
-
return self.delimiter.join(loss_str)
|
274 |
-
|
275 |
-
def synchronize_between_processes(self):
|
276 |
-
for meter in self.meters.values():
|
277 |
-
meter.synchronize_between_processes()
|
278 |
-
|
279 |
-
def add_meter(self, name, meter):
|
280 |
-
self.meters[name] = meter
|
281 |
-
|
282 |
-
def log_every(self, iterable, print_freq, header=None, logger=None):
|
283 |
-
if logger is None:
|
284 |
-
print_func = print
|
285 |
-
else:
|
286 |
-
print_func = logger.info
|
287 |
-
|
288 |
-
i = 0
|
289 |
-
if not header:
|
290 |
-
header = ""
|
291 |
-
start_time = time.time()
|
292 |
-
end = time.time()
|
293 |
-
iter_time = SmoothedValue(fmt="{avg:.4f}")
|
294 |
-
data_time = SmoothedValue(fmt="{avg:.4f}")
|
295 |
-
space_fmt = ":" + str(len(str(len(iterable)))) + "d"
|
296 |
-
if torch.cuda.is_available():
|
297 |
-
log_msg = self.delimiter.join(
|
298 |
-
[
|
299 |
-
header,
|
300 |
-
"[{0" + space_fmt + "}/{1}]",
|
301 |
-
"eta: {eta}",
|
302 |
-
"{meters}",
|
303 |
-
"time: {time}",
|
304 |
-
"data: {data}",
|
305 |
-
"max mem: {memory:.0f}",
|
306 |
-
]
|
307 |
-
)
|
308 |
-
else:
|
309 |
-
log_msg = self.delimiter.join(
|
310 |
-
[
|
311 |
-
header,
|
312 |
-
"[{0" + space_fmt + "}/{1}]",
|
313 |
-
"eta: {eta}",
|
314 |
-
"{meters}",
|
315 |
-
"time: {time}",
|
316 |
-
"data: {data}",
|
317 |
-
]
|
318 |
-
)
|
319 |
-
MB = 1024.0 * 1024.0
|
320 |
-
for obj in iterable:
|
321 |
-
data_time.update(time.time() - end)
|
322 |
-
yield obj
|
323 |
-
# import ipdb; ipdb.set_trace()
|
324 |
-
iter_time.update(time.time() - end)
|
325 |
-
if i % print_freq == 0 or i == len(iterable) - 1:
|
326 |
-
eta_seconds = iter_time.global_avg * (len(iterable) - i)
|
327 |
-
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
328 |
-
if torch.cuda.is_available():
|
329 |
-
print_func(
|
330 |
-
log_msg.format(
|
331 |
-
i,
|
332 |
-
len(iterable),
|
333 |
-
eta=eta_string,
|
334 |
-
meters=str(self),
|
335 |
-
time=str(iter_time),
|
336 |
-
data=str(data_time),
|
337 |
-
memory=torch.cuda.max_memory_allocated() / MB,
|
338 |
-
)
|
339 |
-
)
|
340 |
-
else:
|
341 |
-
print_func(
|
342 |
-
log_msg.format(
|
343 |
-
i,
|
344 |
-
len(iterable),
|
345 |
-
eta=eta_string,
|
346 |
-
meters=str(self),
|
347 |
-
time=str(iter_time),
|
348 |
-
data=str(data_time),
|
349 |
-
)
|
350 |
-
)
|
351 |
-
i += 1
|
352 |
-
end = time.time()
|
353 |
-
total_time = time.time() - start_time
|
354 |
-
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
355 |
-
print_func(
|
356 |
-
"{} Total time: {} ({:.4f} s / it)".format(
|
357 |
-
header, total_time_str, total_time / len(iterable)
|
358 |
-
)
|
359 |
-
)
|
360 |
-
|
361 |
-
|
362 |
-
def get_sha():
|
363 |
-
cwd = os.path.dirname(os.path.abspath(__file__))
|
364 |
-
|
365 |
-
def _run(command):
|
366 |
-
return subprocess.check_output(command, cwd=cwd).decode("ascii").strip()
|
367 |
-
|
368 |
-
sha = "N/A"
|
369 |
-
diff = "clean"
|
370 |
-
branch = "N/A"
|
371 |
-
try:
|
372 |
-
sha = _run(["git", "rev-parse", "HEAD"])
|
373 |
-
subprocess.check_output(["git", "diff"], cwd=cwd)
|
374 |
-
diff = _run(["git", "diff-index", "HEAD"])
|
375 |
-
diff = "has uncommited changes" if diff else "clean"
|
376 |
-
branch = _run(["git", "rev-parse", "--abbrev-ref", "HEAD"])
|
377 |
-
except Exception:
|
378 |
-
pass
|
379 |
-
message = f"sha: {sha}, status: {diff}, branch: {branch}"
|
380 |
-
return message
|
381 |
-
|
382 |
-
|
383 |
-
def collate_fn(batch):
|
384 |
-
# import ipdb; ipdb.set_trace()
|
385 |
-
batch = list(zip(*batch))
|
386 |
-
batch[0] = nested_tensor_from_tensor_list(batch[0])
|
387 |
-
return tuple(batch)
|
388 |
-
|
389 |
-
|
390 |
-
def _max_by_axis(the_list):
|
391 |
-
# type: (List[List[int]]) -> List[int]
|
392 |
-
maxes = the_list[0]
|
393 |
-
for sublist in the_list[1:]:
|
394 |
-
for index, item in enumerate(sublist):
|
395 |
-
maxes[index] = max(maxes[index], item)
|
396 |
-
return maxes
|
397 |
-
|
398 |
-
|
399 |
-
class NestedTensor(object):
|
400 |
-
def __init__(self, tensors, mask: Optional[Tensor]):
|
401 |
-
self.tensors = tensors
|
402 |
-
self.mask = mask
|
403 |
-
if mask == "auto":
|
404 |
-
self.mask = torch.zeros_like(tensors).to(tensors.device)
|
405 |
-
if self.mask.dim() == 3:
|
406 |
-
self.mask = self.mask.sum(0).to(bool)
|
407 |
-
elif self.mask.dim() == 4:
|
408 |
-
self.mask = self.mask.sum(1).to(bool)
|
409 |
-
else:
|
410 |
-
raise ValueError(
|
411 |
-
"tensors dim must be 3 or 4 but {}({})".format(
|
412 |
-
self.tensors.dim(), self.tensors.shape
|
413 |
-
)
|
414 |
-
)
|
415 |
-
|
416 |
-
def imgsize(self):
|
417 |
-
res = []
|
418 |
-
for i in range(self.tensors.shape[0]):
|
419 |
-
mask = self.mask[i]
|
420 |
-
maxH = (~mask).sum(0).max()
|
421 |
-
maxW = (~mask).sum(1).max()
|
422 |
-
res.append(torch.Tensor([maxH, maxW]))
|
423 |
-
return res
|
424 |
-
|
425 |
-
def to(self, device):
|
426 |
-
# type: (Device) -> NestedTensor # noqa
|
427 |
-
cast_tensor = self.tensors.to(device)
|
428 |
-
mask = self.mask
|
429 |
-
if mask is not None:
|
430 |
-
assert mask is not None
|
431 |
-
cast_mask = mask.to(device)
|
432 |
-
else:
|
433 |
-
cast_mask = None
|
434 |
-
return NestedTensor(cast_tensor, cast_mask)
|
435 |
-
|
436 |
-
def to_img_list_single(self, tensor, mask):
|
437 |
-
assert tensor.dim() == 3, "dim of tensor should be 3 but {}".format(tensor.dim())
|
438 |
-
maxH = (~mask).sum(0).max()
|
439 |
-
maxW = (~mask).sum(1).max()
|
440 |
-
img = tensor[:, :maxH, :maxW]
|
441 |
-
return img
|
442 |
-
|
443 |
-
def to_img_list(self):
|
444 |
-
"""remove the padding and convert to img list
|
445 |
-
|
446 |
-
Returns:
|
447 |
-
[type]: [description]
|
448 |
-
"""
|
449 |
-
if self.tensors.dim() == 3:
|
450 |
-
return self.to_img_list_single(self.tensors, self.mask)
|
451 |
-
else:
|
452 |
-
res = []
|
453 |
-
for i in range(self.tensors.shape[0]):
|
454 |
-
tensor_i = self.tensors[i]
|
455 |
-
mask_i = self.mask[i]
|
456 |
-
res.append(self.to_img_list_single(tensor_i, mask_i))
|
457 |
-
return res
|
458 |
-
|
459 |
-
@property
|
460 |
-
def device(self):
|
461 |
-
return self.tensors.device
|
462 |
-
|
463 |
-
def decompose(self):
|
464 |
-
return self.tensors, self.mask
|
465 |
-
|
466 |
-
def __repr__(self):
|
467 |
-
return str(self.tensors)
|
468 |
-
|
469 |
-
@property
|
470 |
-
def shape(self):
|
471 |
-
return {"tensors.shape": self.tensors.shape, "mask.shape": self.mask.shape}
|
472 |
-
|
473 |
-
|
474 |
-
def nested_tensor_from_tensor_list(tensor_list: List[Tensor]):
|
475 |
-
# TODO make this more general
|
476 |
-
if tensor_list[0].ndim == 3:
|
477 |
-
if torchvision._is_tracing():
|
478 |
-
# nested_tensor_from_tensor_list() does not export well to ONNX
|
479 |
-
# call _onnx_nested_tensor_from_tensor_list() instead
|
480 |
-
return _onnx_nested_tensor_from_tensor_list(tensor_list)
|
481 |
-
|
482 |
-
# TODO make it support different-sized images
|
483 |
-
max_size = _max_by_axis([list(img.shape) for img in tensor_list])
|
484 |
-
# min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list]))
|
485 |
-
batch_shape = [len(tensor_list)] + max_size
|
486 |
-
b, c, h, w = batch_shape
|
487 |
-
dtype = tensor_list[0].dtype
|
488 |
-
device = tensor_list[0].device
|
489 |
-
tensor = torch.zeros(batch_shape, dtype=dtype, device=device)
|
490 |
-
mask = torch.ones((b, h, w), dtype=torch.bool, device=device)
|
491 |
-
for img, pad_img, m in zip(tensor_list, tensor, mask):
|
492 |
-
pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
|
493 |
-
m[: img.shape[1], : img.shape[2]] = False
|
494 |
-
else:
|
495 |
-
raise ValueError("not supported")
|
496 |
-
return NestedTensor(tensor, mask)
|
497 |
-
|
498 |
-
|
499 |
-
# _onnx_nested_tensor_from_tensor_list() is an implementation of
|
500 |
-
# nested_tensor_from_tensor_list() that is supported by ONNX tracing.
|
501 |
-
@torch.jit.unused
|
502 |
-
def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor:
|
503 |
-
max_size = []
|
504 |
-
for i in range(tensor_list[0].dim()):
|
505 |
-
max_size_i = torch.max(
|
506 |
-
torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)
|
507 |
-
).to(torch.int64)
|
508 |
-
max_size.append(max_size_i)
|
509 |
-
max_size = tuple(max_size)
|
510 |
-
|
511 |
-
# work around for
|
512 |
-
# pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
|
513 |
-
# m[: img.shape[1], :img.shape[2]] = False
|
514 |
-
# which is not yet supported in onnx
|
515 |
-
padded_imgs = []
|
516 |
-
padded_masks = []
|
517 |
-
for img in tensor_list:
|
518 |
-
padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))]
|
519 |
-
padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0]))
|
520 |
-
padded_imgs.append(padded_img)
|
521 |
-
|
522 |
-
m = torch.zeros_like(img[0], dtype=torch.int, device=img.device)
|
523 |
-
padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1)
|
524 |
-
padded_masks.append(padded_mask.to(torch.bool))
|
525 |
-
|
526 |
-
tensor = torch.stack(padded_imgs)
|
527 |
-
mask = torch.stack(padded_masks)
|
528 |
-
|
529 |
-
return NestedTensor(tensor, mask=mask)
|
530 |
-
|
531 |
-
|
532 |
-
def setup_for_distributed(is_master):
|
533 |
-
"""
|
534 |
-
This function disables printing when not in master process
|
535 |
-
"""
|
536 |
-
import builtins as __builtin__
|
537 |
-
|
538 |
-
builtin_print = __builtin__.print
|
539 |
-
|
540 |
-
def print(*args, **kwargs):
|
541 |
-
force = kwargs.pop("force", False)
|
542 |
-
if is_master or force:
|
543 |
-
builtin_print(*args, **kwargs)
|
544 |
-
|
545 |
-
__builtin__.print = print
|
546 |
-
|
547 |
-
|
548 |
-
def is_dist_avail_and_initialized():
|
549 |
-
if not dist.is_available():
|
550 |
-
return False
|
551 |
-
if not dist.is_initialized():
|
552 |
-
return False
|
553 |
-
return True
|
554 |
-
|
555 |
-
|
556 |
-
def get_world_size():
|
557 |
-
if not is_dist_avail_and_initialized():
|
558 |
-
return 1
|
559 |
-
return dist.get_world_size()
|
560 |
-
|
561 |
-
|
562 |
-
def get_rank():
|
563 |
-
if not is_dist_avail_and_initialized():
|
564 |
-
return 0
|
565 |
-
return dist.get_rank()
|
566 |
-
|
567 |
-
|
568 |
-
def is_main_process():
|
569 |
-
return get_rank() == 0
|
570 |
-
|
571 |
-
|
572 |
-
def save_on_master(*args, **kwargs):
|
573 |
-
if is_main_process():
|
574 |
-
torch.save(*args, **kwargs)
|
575 |
-
|
576 |
-
|
577 |
-
def init_distributed_mode(args):
|
578 |
-
if "WORLD_SIZE" in os.environ and os.environ["WORLD_SIZE"] != "": # 'RANK' in os.environ and
|
579 |
-
args.rank = int(os.environ["RANK"])
|
580 |
-
args.world_size = int(os.environ["WORLD_SIZE"])
|
581 |
-
args.gpu = args.local_rank = int(os.environ["LOCAL_RANK"])
|
582 |
-
|
583 |
-
# launch by torch.distributed.launch
|
584 |
-
# Single node
|
585 |
-
# python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ...
|
586 |
-
# Multi nodes
|
587 |
-
# python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ...
|
588 |
-
# python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ...
|
589 |
-
# args.rank = int(os.environ.get('OMPI_COMM_WORLD_RANK'))
|
590 |
-
# local_world_size = int(os.environ['GPU_PER_NODE_COUNT'])
|
591 |
-
# args.world_size = args.world_size * local_world_size
|
592 |
-
# args.gpu = args.local_rank = int(os.environ['LOCAL_RANK'])
|
593 |
-
# args.rank = args.rank * local_world_size + args.local_rank
|
594 |
-
print(
|
595 |
-
"world size: {}, rank: {}, local rank: {}".format(
|
596 |
-
args.world_size, args.rank, args.local_rank
|
597 |
-
)
|
598 |
-
)
|
599 |
-
print(json.dumps(dict(os.environ), indent=2))
|
600 |
-
elif "SLURM_PROCID" in os.environ:
|
601 |
-
args.rank = int(os.environ["SLURM_PROCID"])
|
602 |
-
args.gpu = args.local_rank = int(os.environ["SLURM_LOCALID"])
|
603 |
-
args.world_size = int(os.environ["SLURM_NPROCS"])
|
604 |
-
|
605 |
-
print(
|
606 |
-
"world size: {}, world rank: {}, local rank: {}, device_count: {}".format(
|
607 |
-
args.world_size, args.rank, args.local_rank, torch.cuda.device_count()
|
608 |
-
)
|
609 |
-
)
|
610 |
-
else:
|
611 |
-
print("Not using distributed mode")
|
612 |
-
args.distributed = False
|
613 |
-
args.world_size = 1
|
614 |
-
args.rank = 0
|
615 |
-
args.local_rank = 0
|
616 |
-
return
|
617 |
-
|
618 |
-
print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank))
|
619 |
-
args.distributed = True
|
620 |
-
torch.cuda.set_device(args.local_rank)
|
621 |
-
args.dist_backend = "nccl"
|
622 |
-
print("| distributed init (rank {}): {}".format(args.rank, args.dist_url), flush=True)
|
623 |
-
|
624 |
-
torch.distributed.init_process_group(
|
625 |
-
backend=args.dist_backend,
|
626 |
-
world_size=args.world_size,
|
627 |
-
rank=args.rank,
|
628 |
-
init_method=args.dist_url,
|
629 |
-
)
|
630 |
-
|
631 |
-
print("Before torch.distributed.barrier()")
|
632 |
-
torch.distributed.barrier()
|
633 |
-
print("End torch.distributed.barrier()")
|
634 |
-
setup_for_distributed(args.rank == 0)
|
635 |
-
|
636 |
-
|
637 |
-
@torch.no_grad()
|
638 |
-
def accuracy(output, target, topk=(1,)):
|
639 |
-
"""Computes the precision@k for the specified values of k"""
|
640 |
-
if target.numel() == 0:
|
641 |
-
return [torch.zeros([], device=output.device)]
|
642 |
-
maxk = max(topk)
|
643 |
-
batch_size = target.size(0)
|
644 |
-
|
645 |
-
_, pred = output.topk(maxk, 1, True, True)
|
646 |
-
pred = pred.t()
|
647 |
-
correct = pred.eq(target.view(1, -1).expand_as(pred))
|
648 |
-
|
649 |
-
res = []
|
650 |
-
for k in topk:
|
651 |
-
correct_k = correct[:k].view(-1).float().sum(0)
|
652 |
-
res.append(correct_k.mul_(100.0 / batch_size))
|
653 |
-
return res
|
654 |
-
|
655 |
-
|
656 |
-
@torch.no_grad()
|
657 |
-
def accuracy_onehot(pred, gt):
|
658 |
-
"""_summary_
|
659 |
-
|
660 |
-
Args:
|
661 |
-
pred (_type_): n, c
|
662 |
-
gt (_type_): n, c
|
663 |
-
"""
|
664 |
-
tp = ((pred - gt).abs().sum(-1) < 1e-4).float().sum()
|
665 |
-
acc = tp / gt.shape[0] * 100
|
666 |
-
return acc
|
667 |
-
|
668 |
-
|
669 |
-
def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
|
670 |
-
# type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor
|
671 |
-
"""
|
672 |
-
Equivalent to nn.functional.interpolate, but with support for empty batch sizes.
|
673 |
-
This will eventually be supported natively by PyTorch, and this
|
674 |
-
class can go away.
|
675 |
-
"""
|
676 |
-
if __torchvision_need_compat_flag < 0.7:
|
677 |
-
if input.numel() > 0:
|
678 |
-
return torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners)
|
679 |
-
|
680 |
-
output_shape = _output_size(2, input, size, scale_factor)
|
681 |
-
output_shape = list(input.shape[:-2]) + list(output_shape)
|
682 |
-
return _new_empty_tensor(input, output_shape)
|
683 |
-
else:
|
684 |
-
return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners)
|
685 |
-
|
686 |
-
|
687 |
-
class color_sys:
|
688 |
-
def __init__(self, num_colors) -> None:
|
689 |
-
self.num_colors = num_colors
|
690 |
-
colors = []
|
691 |
-
for i in np.arange(0.0, 360.0, 360.0 / num_colors):
|
692 |
-
hue = i / 360.0
|
693 |
-
lightness = (50 + np.random.rand() * 10) / 100.0
|
694 |
-
saturation = (90 + np.random.rand() * 10) / 100.0
|
695 |
-
colors.append(
|
696 |
-
tuple([int(j * 255) for j in colorsys.hls_to_rgb(hue, lightness, saturation)])
|
697 |
-
)
|
698 |
-
self.colors = colors
|
699 |
-
|
700 |
-
def __call__(self, idx):
|
701 |
-
return self.colors[idx]
|
702 |
-
|
703 |
-
|
704 |
-
def inverse_sigmoid(x, eps=1e-3):
|
705 |
-
x = x.clamp(min=0, max=1)
|
706 |
-
x1 = x.clamp(min=eps)
|
707 |
-
x2 = (1 - x).clamp(min=eps)
|
708 |
-
return torch.log(x1 / x2)
|
709 |
-
|
710 |
-
|
711 |
-
def clean_state_dict(state_dict):
|
712 |
-
new_state_dict = OrderedDict()
|
713 |
-
for k, v in state_dict.items():
|
714 |
-
if k[:7] == "module.":
|
715 |
-
k = k[7:] # remove `module.`
|
716 |
-
new_state_dict[k] = v
|
717 |
-
return new_state_dict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_internal/__init__.py
DELETED
@@ -1,19 +0,0 @@
|
|
1 |
-
from typing import List, Optional
|
2 |
-
|
3 |
-
import pip._internal.utils.inject_securetransport # noqa
|
4 |
-
from pip._internal.utils import _log
|
5 |
-
|
6 |
-
# init_logging() must be called before any call to logging.getLogger()
|
7 |
-
# which happens at import of most modules.
|
8 |
-
_log.init_logging()
|
9 |
-
|
10 |
-
|
11 |
-
def main(args: (Optional[List[str]]) = None) -> int:
|
12 |
-
"""This is preserved for old console scripts that may still be referencing
|
13 |
-
it.
|
14 |
-
|
15 |
-
For additional details, see https://github.com/pypa/pip/issues/7498.
|
16 |
-
"""
|
17 |
-
from pip._internal.utils.entrypoints import _wrapper
|
18 |
-
|
19 |
-
return _wrapper(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/pygments/plugin.py
DELETED
@@ -1,88 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
pygments.plugin
|
3 |
-
~~~~~~~~~~~~~~~
|
4 |
-
|
5 |
-
Pygments plugin interface. By default, this tries to use
|
6 |
-
``importlib.metadata``, which is in the Python standard
|
7 |
-
library since Python 3.8, or its ``importlib_metadata``
|
8 |
-
backport for earlier versions of Python. It falls back on
|
9 |
-
``pkg_resources`` if not found. Finally, if ``pkg_resources``
|
10 |
-
is not found either, no plugins are loaded at all.
|
11 |
-
|
12 |
-
lexer plugins::
|
13 |
-
|
14 |
-
[pygments.lexers]
|
15 |
-
yourlexer = yourmodule:YourLexer
|
16 |
-
|
17 |
-
formatter plugins::
|
18 |
-
|
19 |
-
[pygments.formatters]
|
20 |
-
yourformatter = yourformatter:YourFormatter
|
21 |
-
/.ext = yourformatter:YourFormatter
|
22 |
-
|
23 |
-
As you can see, you can define extensions for the formatter
|
24 |
-
with a leading slash.
|
25 |
-
|
26 |
-
syntax plugins::
|
27 |
-
|
28 |
-
[pygments.styles]
|
29 |
-
yourstyle = yourstyle:YourStyle
|
30 |
-
|
31 |
-
filter plugin::
|
32 |
-
|
33 |
-
[pygments.filter]
|
34 |
-
yourfilter = yourfilter:YourFilter
|
35 |
-
|
36 |
-
|
37 |
-
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
|
38 |
-
:license: BSD, see LICENSE for details.
|
39 |
-
"""
|
40 |
-
|
41 |
-
LEXER_ENTRY_POINT = 'pygments.lexers'
|
42 |
-
FORMATTER_ENTRY_POINT = 'pygments.formatters'
|
43 |
-
STYLE_ENTRY_POINT = 'pygments.styles'
|
44 |
-
FILTER_ENTRY_POINT = 'pygments.filters'
|
45 |
-
|
46 |
-
|
47 |
-
def iter_entry_points(group_name):
|
48 |
-
try:
|
49 |
-
from importlib.metadata import entry_points
|
50 |
-
except ImportError:
|
51 |
-
try:
|
52 |
-
from importlib_metadata import entry_points
|
53 |
-
except ImportError:
|
54 |
-
try:
|
55 |
-
from pip._vendor.pkg_resources import iter_entry_points
|
56 |
-
except (ImportError, OSError):
|
57 |
-
return []
|
58 |
-
else:
|
59 |
-
return iter_entry_points(group_name)
|
60 |
-
groups = entry_points()
|
61 |
-
if hasattr(groups, 'select'):
|
62 |
-
# New interface in Python 3.10 and newer versions of the
|
63 |
-
# importlib_metadata backport.
|
64 |
-
return groups.select(group=group_name)
|
65 |
-
else:
|
66 |
-
# Older interface, deprecated in Python 3.10 and recent
|
67 |
-
# importlib_metadata, but we need it in Python 3.8 and 3.9.
|
68 |
-
return groups.get(group_name, [])
|
69 |
-
|
70 |
-
|
71 |
-
def find_plugin_lexers():
|
72 |
-
for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):
|
73 |
-
yield entrypoint.load()
|
74 |
-
|
75 |
-
|
76 |
-
def find_plugin_formatters():
|
77 |
-
for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):
|
78 |
-
yield entrypoint.name, entrypoint.load()
|
79 |
-
|
80 |
-
|
81 |
-
def find_plugin_styles():
|
82 |
-
for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):
|
83 |
-
yield entrypoint.name, entrypoint.load()
|
84 |
-
|
85 |
-
|
86 |
-
def find_plugin_filters():
|
87 |
-
for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):
|
88 |
-
yield entrypoint.name, entrypoint.load()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/command/register.py
DELETED
@@ -1,18 +0,0 @@
|
|
1 |
-
from distutils import log
|
2 |
-
import distutils.command.register as orig
|
3 |
-
|
4 |
-
from setuptools.errors import RemovedCommandError
|
5 |
-
|
6 |
-
|
7 |
-
class register(orig.register):
|
8 |
-
"""Formerly used to register packages on PyPI."""
|
9 |
-
|
10 |
-
def run(self):
|
11 |
-
msg = (
|
12 |
-
"The register command has been removed, use twine to upload "
|
13 |
-
+ "instead (https://pypi.org/p/twine)"
|
14 |
-
)
|
15 |
-
|
16 |
-
self.announce("ERROR: " + msg, log.ERROR)
|
17 |
-
|
18 |
-
raise RemovedCommandError(msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/modeling/meta_arch/build.py
DELETED
@@ -1,25 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
-
import torch
|
3 |
-
|
4 |
-
from detectron2.utils.logger import _log_api_usage
|
5 |
-
from detectron2.utils.registry import Registry
|
6 |
-
|
7 |
-
META_ARCH_REGISTRY = Registry("META_ARCH") # noqa F401 isort:skip
|
8 |
-
META_ARCH_REGISTRY.__doc__ = """
|
9 |
-
Registry for meta-architectures, i.e. the whole model.
|
10 |
-
|
11 |
-
The registered object will be called with `obj(cfg)`
|
12 |
-
and expected to return a `nn.Module` object.
|
13 |
-
"""
|
14 |
-
|
15 |
-
|
16 |
-
def build_model(cfg):
|
17 |
-
"""
|
18 |
-
Build the whole model architecture, defined by ``cfg.MODEL.META_ARCHITECTURE``.
|
19 |
-
Note that it does not load any weights from ``cfg``.
|
20 |
-
"""
|
21 |
-
meta_arch = cfg.MODEL.META_ARCHITECTURE
|
22 |
-
model = META_ARCH_REGISTRY.get(meta_arch)(cfg)
|
23 |
-
model.to(torch.device(cfg.MODEL.DEVICE))
|
24 |
-
_log_api_usage("modeling.meta_arch." + meta_arch)
|
25 |
-
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Benson/text-generation/Examples/Apk3163.md
DELETED
@@ -1,84 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>¿Qué es APK3163 y por qué debería tomarlo? </h1>
|
3 |
-
<p>Si usted está interesado en la nutrición deportiva y quiere aprender cómo optimizar su rendimiento y salud a través de la dieta y el ejercicio, entonces APK3163 es el curso para usted. APK3163 significa Fisiología Aplicada y Kinesiología 3163: Nutrición Deportiva. Es un curso en línea de 3 créditos ofrecido por la Universidad de Florida que aborda los aspectos de la nutrición que están relacionados con el rendimiento del ejercicio. </p>
|
4 |
-
<h2>apk3163</h2><br /><p><b><b>Download</b> ✔ <a href="https://bltlly.com/2v6JSu">https://bltlly.com/2v6JSu</a></b></p><br /><br />
|
5 |
-
<h2>Introducción</h2>
|
6 |
-
<p>En este curso, aprenderá sobre los sistemas bioenergéticos, los componentes de la nutrición, las evaluaciones de la composición nutricional y corporal, las ayudas ergogénicas y las modificaciones de la dieta para las personas físicamente activas y los atletas. También aprenderás a aplicar este conocimiento a diferentes escenarios deportivos y de ejercicio. </p>
|
7 |
-
<p>El instructor de este curso es el Dr. Blain Harrison, quien tiene un Ph.D. en Fisiología Aplicada y Kinesiología de UF. También es entrenador deportivo y especialista en fuerza y acondicionamiento. Tiene una amplia experiencia en la enseñanza e investigación de temas de nutrición deportiva. Puede ponerse en contacto con él por correo electrónico a [email protected] o por teléfono al 352-294-1704. También tiene horario de oficina los lunes de 1-2 pm o con cita previa a través de Zoom.</p>
|
8 |
-
<h2>Materiales y formato del curso</h2>
|
9 |
-
<p>Todos los materiales necesarios para el curso se proporcionarán en la página Lienzo de APK3163. Estos materiales incluyen módulos de capítulos semanales escritos por el instructor y varios artículos de investigación de revistas de renombre. También necesitará acceso a una computadora con conexión a Internet y un navegador web que soporte Canvas.</p>
|
10 |
-
<p></p>
|
11 |
-
<p>El curso se imparte en línea a través de Canvas, que es el sistema de gestión de aprendizaje de UF. Accederá a todo el contenido del curso, tareas, exámenes, exámenes, calificaciones y herramientas de comunicación a través de Canvas. También participarás en discusiones en línea con tus compañeros de clase e instructor. </p>
|
12 |
-
|
13 |
-
<h2>Evaluación y calificación del curso</h2>
|
14 |
-
<p>Su calificación final para este curso se basará en su desempeño en exámenes (20%), tareas (30%), exámenes (40%) y discusiones (10%). Usted tendrá que anotar al menos 60% para pasar este curso. </p>
|
15 |
-
<p>Habrá dos exámenes (mitad y final) que pondrán a prueba tu conocimiento del material del curso. Cada examen constará de preguntas de opción múltiple que cubren todos los temas de los módulos. Tendrá dos horas para completar cada examen en línea a través de Canvas. Los exámenes estarán disponibles durante 24 horas el día del examen asignado. </p>
|
16 |
-
<p>Habrá 14 cuestionarios que evaluarán su comprensión de las lecturas y videos de cada módulo. Cada examen tendrá 10 preguntas de opción múltiple y tendrá 15 minutos para completarlo en línea a través de Canvas. Los cuestionarios estarán disponibles durante una semana después del lanzamiento del módulo. </p>
|
17 |
-
<p>Habrá 7 tareas que requerirán que aplique sus conocimientos de nutrición deportiva a situaciones de la vida real. Cada tarea tendrá un formato e instrucciones diferentes, tales como estudios de caso, análisis dietético, planificación de menús, etc. Usted enviará sus tareas en línea a través de Canvas antes de la fecha de vencimiento asignada. </p>
|
18 |
-
<p>Habrá 14 discusiones que te permitirán interactuar con tus compañeros de clase e instructor sobre diversos temas relacionados con la nutrición deportiva. Cada discusión tendrá un aviso que necesita responder en un mínimo de 250 palabras. También es necesario responder a al menos dos de los mensajes de sus compañeros de clase en un mínimo de 100 palabras cada uno. Publicarás tus respuestas en línea a través de Canvas en la fecha de vencimiento asignada. </p>
|
19 |
-
<p>Se espera que usted siga las políticas de UF sobre asistencia, trabajo tardío, honestidad académica y conducta estudiantil. Usted es responsable de revisar Canvas regularmente para actualizaciones de cursos, anuncios y comentarios. También se le anima a comunicarse con su instructor y compañeros de clase a través de Canvas o correo electrónico si tiene alguna pregunta o inquietud. </p>
|
20 |
-
|
21 |
-
<p>Los principales temas tratados en este curso son:</p>
|
22 |
-
<ul>
|
23 |
-
<li>Sistemas bioenergéticos y balance energético</li>
|
24 |
-
<li>Carbohidratos, grasas, proteínas y agua</li>
|
25 |
-
<li>Vitaminas, minerales y antioxidantes</li>
|
26 |
-
<li>Evaluaciones de la composición nutricional y corporal</li>
|
27 |
-
<li>Ayudas y suplementos ergogénicos</li>
|
28 |
-
<li>Modificaciones de la dieta para la resistencia, la fuerza, la potencia y los deportes de equipo</li>
|
29 |
-
<li>Nutrición para poblaciones y condiciones especiales</li>
|
30 |
-
</ul>
|
31 |
-
<p>Los resultados de aprendizaje para cada tema son:</p>
|
32 |
-
<ul>
|
33 |
-
<li>Explicar el papel de los sistemas bioenergéticos y el equilibrio energético en el rendimiento del ejercicio y la salud. </li>
|
34 |
-
<li>Describir las funciones, fuentes, requerimientos, metabolismo y almacenamiento de carbohidratos, grasas, proteínas y agua. </li>
|
35 |
-
<li>Identificar las funciones, fuentes, requerimientos, deficiencias, toxicidades e interacciones de vitaminas, minerales y antioxidantes. </li>
|
36 |
-
<li>Realizar e interpretar evaluaciones nutricionales y de composición corporal utilizando diversos métodos y herramientas. </li>
|
37 |
-
<li>Evaluar la eficacia, seguridad, legalidad y cuestiones éticas de los suplementos y ayudas ergogénicas. </li>
|
38 |
-
<li>Diseñar e implementar modificaciones en la dieta para diferentes tipos de actividades deportivas y de ejercicio. </li>
|
39 |
-
<li>Aplicar principios de nutrición a poblaciones y condiciones especiales como niños, adultos mayores, vegetarianos, embarazo, diabetes, etc.</li>
|
40 |
-
</ul>
|
41 |
-
<p>La programación tentativa del curso se muestra en la siguiente tabla:</p>
|
42 |
-
<borde de la tabla="1">
|
43 |
-
<tr><th>Semana</th><th>Módulo</th><th>Tema</th><th>Lecturas</th><th>Tareas</th></tr>
|
44 |
-
<tr><td>1</td><td>1</td><td><td>Sistemas bioenergéticos y balance energético</td><td>Capítulo 1 & Artículo 1</td><td>Prueba 1 & Discusión 1</td></tr>
|
45 |
-
<tr><td>2</td><td>2</td><td>Carbohidratos</td><td><td>Capítulo 2 & Artículo 2</td><td>Examen 2 & Discusión 2 & Asignación 1</td></tr>
|
46 |
-
<tr><td>3</td><td>3</td><td>Fats</td><td><td>Capítulo 3 & Artículo 3</td><td>Quiz 3 & Discusión 3 & Asignación 2</td></tr>
|
47 |
-
|
48 |
-
<tr><td>5</td><td>5</td><td>Vitaminas</td><td><td>Capítulo 5 & Artículo 5</td><td>Examen 5 & Discusión 5 & Examen de mitad de período</td></tr>
|
49 |
-
<tr><td>6</td><td>6</td><td>Minerales</td><td><td>Capítulo 6 & Artículo 6</td><td>Examen 6 & Discusión 6 & Asignación 4</td></tr>
|
50 |
-
<tr><td>7</td><td>7</td><td>Antioxidantes</td><td><td>Capítulo 7 & Artículo 7 </ [assistant](#message) <tr><td>8</td><td><8</td><Agua</td><td>Capítulo 8 & Artículo<td><><td><>Quiz 8 & Asignación/ 6
|
51 |
-
<tr><td>9</td><td>9</td><td>Evaluaciones de la composición nutricional y corporal</td><td><td>Capítulo 9 & Artículo 9</td><td>Examen 9 & Discusión 9 & Asignación 7</td></tr>
|
52 |
-
<tr><td>10</td><td>10</td><td><td>Ayudas y suplementos ergogénicos</td><td>Capítulo 10 & Artículo 10</td><td>Prueba 10 & Discusión 10</td></tr>
|
53 |
-
<tr><td>11</td><td>11</td><td>Modificaciones de la dieta para deportes de resistencia</td><td>Capítulo 11 & Artículo 11</td><td>Examen 11 & Discusión 11</td></tr>
|
54 |
-
<tr><td>12</td><td>12</td><td>Modificaciones de la dieta para deportes de fuerza y potencia</td><td>Capítulo 12 & Artículo 12</td><td>Prueba 12 & Discusión 12</td></tr>
|
55 |
-
<tr><td>13</td><td>13</td><td>Modificaciones de la dieta para deportes de equipo</td><td>Capítulo 13 & Artículo 13</ [asistente](#message) </tr>
|
56 |
-
<tr><td>14</td><td>14</td><td>Nutrición para poblaciones y condiciones especiales</td><td>Capítulo 14 & Artículo 14</td><td>Prueba 14 & Discusión 14</td></tr>
|
57 |
-
</tabla>
|
58 |
-
<h2>Conclusión</h2>
|
59 |
-
<p>APK3163 es un curso valioso que le enseñará los fundamentos de la nutrición deportiva y cómo aplicarlos a su propio rendimiento de ejercicio y la salud de otros. Aprenderás de un instructor experto que te guiará a través del contenido del curso y las actividades. También interactuará con sus compañeros que comparten su interés en la nutrición deportiva. Al final de este curso, tendrá una sólida comprensión del papel de la nutrición en la fisiología del ejercicio y la kinesiología. </p>
|
60 |
-
|
61 |
-
<p>APK3163 es un curso divertido y atractivo que te hará disfrutar aprendiendo sobre nutrición deportiva. Descubrirá nuevos hechos, conceptos y estrategias que despertarán su curiosidad e interés. También participarás en varias actividades que desafiarán tu pensamiento crítico y tus habilidades para resolver problemas. Usted encontrará APK3163 para ser una experiencia de aprendizaje gratificante y agradable. </p>
|
62 |
-
<h2>Preguntas frecuentes</h2>
|
63 |
-
<p>Aquí hay algunas preguntas frecuentes sobre APK3163:</p>
|
64 |
-
<ol>
|
65 |
-
<li><b>¿Cómo me registro para APK3163? </b></li>
|
66 |
-
<p>Puede registrarse para APK3163 a través del portal ONE.UF de UF. Necesita tener los requisitos previos de APK2100C o APK2105C o PET3322C o equivalente con calificaciones mínimas de C.</p>
|
67 |
-
<li><b>¿Cuánto cuesta APK3163? </b></li>
|
68 |
-
<p>La cuota de matrícula para APK3163 es de $212.71 por hora de crédito para los residentes de la Florida y $955.86 por hora de crédito para los residentes no Florida. Puede haber cargos adicionales para los cursos en línea. </p>
|
69 |
-
<li><b>¿Cómo accedo a APK3163 en línea? </b></li>
|
70 |
-
<p>Puede acceder a APK3163 en línea a través de Canvas, que es el sistema de gestión de aprendizaje de UF. Necesitas tener una cuenta de GatorLink y una contraseña para iniciar sesión en Canvas. También necesitas tener acceso a una computadora con conexión a Internet y un navegador web que soporte Canvas.</p>
|
71 |
-
<li><b>¿Cómo puedo contactar al instructor de APK3163? </b></li>
|
72 |
-
<p>Puede ponerse en contacto con el instructor de APK3163 por correo electrónico a [email protected] o por teléfono al 352-294-1704. También tiene horario de oficina los lunes de 1-2 pm o con cita previa a través de Zoom.</p>
|
73 |
-
<li><b>¿Cómo puedo obtener ayuda con APK3163? </b></li>
|
74 |
-
<p>Puede obtener ayuda con APK3163 utilizando los siguientes recursos:</p>
|
75 |
-
<ul>
|
76 |
-
<li>El instructor: Puede hacer preguntas o buscar aclaraciones del instructor por correo electrónico, teléfono, Zoom o Canvas.</li>
|
77 |
-
<li>Los compañeros de clase: Puede interactuar con sus compañeros de clase a través de discusiones en Canvas o correo electrónico. </li>
|
78 |
-
|
79 |
-
<li>Las bibliotecas UF: Puede acceder a bases de datos, revistas, libros y otros recursos en línea a través del sitio web de las bibliotecas UF. </li>
|
80 |
-
<li>El estudio de escritura UF: Puede obtener comentarios y orientación sobre sus tareas de escritura a través del sitio web del estudio de escritura UF. </li>
|
81 |
-
</ul>
|
82 |
-
</ol></p> 64aa2da5cf<br />
|
83 |
-
<br />
|
84 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/BigSalmon/GPTJ/README.md
DELETED
@@ -1,37 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: GPTJ
|
3 |
-
emoji: 🦀
|
4 |
-
colorFrom: indigo
|
5 |
-
colorTo: pink
|
6 |
-
sdk: gradio
|
7 |
-
app_file: app.py
|
8 |
-
pinned: false
|
9 |
-
---
|
10 |
-
|
11 |
-
# Configuration
|
12 |
-
|
13 |
-
`title`: _string_
|
14 |
-
Display title for the Space
|
15 |
-
|
16 |
-
`emoji`: _string_
|
17 |
-
Space emoji (emoji-only character allowed)
|
18 |
-
|
19 |
-
`colorFrom`: _string_
|
20 |
-
Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
|
21 |
-
|
22 |
-
`colorTo`: _string_
|
23 |
-
Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
|
24 |
-
|
25 |
-
`sdk`: _string_
|
26 |
-
Can be either `gradio` or `streamlit`
|
27 |
-
|
28 |
-
`sdk_version` : _string_
|
29 |
-
Only applicable for `streamlit` SDK.
|
30 |
-
See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
|
31 |
-
|
32 |
-
`app_file`: _string_
|
33 |
-
Path to your main application file (which contains either `gradio` or `streamlit` Python code).
|
34 |
-
Path is relative to the root of the repository.
|
35 |
-
|
36 |
-
`pinned`: _boolean_
|
37 |
-
Whether the Space stays on top of your list.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CForGETaass/vits-uma-genshin-honkai/text/__init__.py
DELETED
@@ -1,57 +0,0 @@
|
|
1 |
-
""" from https://github.com/keithito/tacotron """
|
2 |
-
from text import cleaners
|
3 |
-
from text.symbols import symbols
|
4 |
-
|
5 |
-
|
6 |
-
# Mappings from symbol to numeric ID and vice versa:
|
7 |
-
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
|
8 |
-
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
|
9 |
-
|
10 |
-
|
11 |
-
def text_to_sequence(text, symbols, cleaner_names):
|
12 |
-
'''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
|
13 |
-
Args:
|
14 |
-
text: string to convert to a sequence
|
15 |
-
cleaner_names: names of the cleaner functions to run the text through
|
16 |
-
Returns:
|
17 |
-
List of integers corresponding to the symbols in the text
|
18 |
-
'''
|
19 |
-
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
|
20 |
-
sequence = []
|
21 |
-
|
22 |
-
clean_text = _clean_text(text, cleaner_names)
|
23 |
-
for symbol in clean_text:
|
24 |
-
if symbol not in _symbol_to_id.keys():
|
25 |
-
continue
|
26 |
-
symbol_id = _symbol_to_id[symbol]
|
27 |
-
sequence += [symbol_id]
|
28 |
-
return sequence, clean_text
|
29 |
-
|
30 |
-
|
31 |
-
def cleaned_text_to_sequence(cleaned_text):
|
32 |
-
'''Converts a string of text to a sequence of IDs corresponding to the symbols in the text.
|
33 |
-
Args:
|
34 |
-
text: string to convert to a sequence
|
35 |
-
Returns:
|
36 |
-
List of integers corresponding to the symbols in the text
|
37 |
-
'''
|
38 |
-
sequence = [_symbol_to_id[symbol] for symbol in cleaned_text if symbol in _symbol_to_id.keys()]
|
39 |
-
return sequence
|
40 |
-
|
41 |
-
|
42 |
-
def sequence_to_text(sequence):
|
43 |
-
'''Converts a sequence of IDs back to a string'''
|
44 |
-
result = ''
|
45 |
-
for symbol_id in sequence:
|
46 |
-
s = _id_to_symbol[symbol_id]
|
47 |
-
result += s
|
48 |
-
return result
|
49 |
-
|
50 |
-
|
51 |
-
def _clean_text(text, cleaner_names):
|
52 |
-
for name in cleaner_names:
|
53 |
-
cleaner = getattr(cleaners, name)
|
54 |
-
if not cleaner:
|
55 |
-
raise Exception('Unknown cleaner: %s' % name)
|
56 |
-
text = cleaner(text)
|
57 |
-
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVH-vn1210/make_hair/minigpt4/common/utils.py
DELETED
@@ -1,424 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
Copyright (c) 2022, salesforce.com, inc.
|
3 |
-
All rights reserved.
|
4 |
-
SPDX-License-Identifier: BSD-3-Clause
|
5 |
-
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
|
6 |
-
"""
|
7 |
-
|
8 |
-
import io
|
9 |
-
import json
|
10 |
-
import logging
|
11 |
-
import os
|
12 |
-
import pickle
|
13 |
-
import re
|
14 |
-
import shutil
|
15 |
-
import urllib
|
16 |
-
import urllib.error
|
17 |
-
import urllib.request
|
18 |
-
from typing import Optional
|
19 |
-
from urllib.parse import urlparse
|
20 |
-
|
21 |
-
import numpy as np
|
22 |
-
import pandas as pd
|
23 |
-
import yaml
|
24 |
-
from iopath.common.download import download
|
25 |
-
from iopath.common.file_io import file_lock, g_pathmgr
|
26 |
-
from minigpt4.common.registry import registry
|
27 |
-
from torch.utils.model_zoo import tqdm
|
28 |
-
from torchvision.datasets.utils import (
|
29 |
-
check_integrity,
|
30 |
-
download_file_from_google_drive,
|
31 |
-
extract_archive,
|
32 |
-
)
|
33 |
-
|
34 |
-
|
35 |
-
def now():
|
36 |
-
from datetime import datetime
|
37 |
-
|
38 |
-
return datetime.now().strftime("%Y%m%d%H%M")[:-1]
|
39 |
-
|
40 |
-
|
41 |
-
def is_url(url_or_filename):
|
42 |
-
parsed = urlparse(url_or_filename)
|
43 |
-
return parsed.scheme in ("http", "https")
|
44 |
-
|
45 |
-
|
46 |
-
def get_cache_path(rel_path):
|
47 |
-
return os.path.expanduser(os.path.join(registry.get_path("cache_root"), rel_path))
|
48 |
-
|
49 |
-
|
50 |
-
def get_abs_path(rel_path):
|
51 |
-
return os.path.join(registry.get_path("library_root"), rel_path)
|
52 |
-
|
53 |
-
|
54 |
-
def load_json(filename):
|
55 |
-
with open(filename, "r") as f:
|
56 |
-
return json.load(f)
|
57 |
-
|
58 |
-
|
59 |
-
# The following are adapted from torchvision and vissl
|
60 |
-
# torchvision: https://github.com/pytorch/vision
|
61 |
-
# vissl: https://github.com/facebookresearch/vissl/blob/main/vissl/utils/download.py
|
62 |
-
|
63 |
-
|
64 |
-
def makedir(dir_path):
|
65 |
-
"""
|
66 |
-
Create the directory if it does not exist.
|
67 |
-
"""
|
68 |
-
is_success = False
|
69 |
-
try:
|
70 |
-
if not g_pathmgr.exists(dir_path):
|
71 |
-
g_pathmgr.mkdirs(dir_path)
|
72 |
-
is_success = True
|
73 |
-
except BaseException:
|
74 |
-
print(f"Error creating directory: {dir_path}")
|
75 |
-
return is_success
|
76 |
-
|
77 |
-
|
78 |
-
def get_redirected_url(url: str):
|
79 |
-
"""
|
80 |
-
Given a URL, returns the URL it redirects to or the
|
81 |
-
original URL in case of no indirection
|
82 |
-
"""
|
83 |
-
import requests
|
84 |
-
|
85 |
-
with requests.Session() as session:
|
86 |
-
with session.get(url, stream=True, allow_redirects=True) as response:
|
87 |
-
if response.history:
|
88 |
-
return response.url
|
89 |
-
else:
|
90 |
-
return url
|
91 |
-
|
92 |
-
|
93 |
-
def to_google_drive_download_url(view_url: str) -> str:
|
94 |
-
"""
|
95 |
-
Utility function to transform a view URL of google drive
|
96 |
-
to a download URL for google drive
|
97 |
-
Example input:
|
98 |
-
https://drive.google.com/file/d/137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp/view
|
99 |
-
Example output:
|
100 |
-
https://drive.google.com/uc?export=download&id=137RyRjvTBkBiIfeYBNZBtViDHQ6_Ewsp
|
101 |
-
"""
|
102 |
-
splits = view_url.split("/")
|
103 |
-
assert splits[-1] == "view"
|
104 |
-
file_id = splits[-2]
|
105 |
-
return f"https://drive.google.com/uc?export=download&id={file_id}"
|
106 |
-
|
107 |
-
|
108 |
-
def download_google_drive_url(url: str, output_path: str, output_file_name: str):
|
109 |
-
"""
|
110 |
-
Download a file from google drive
|
111 |
-
Downloading an URL from google drive requires confirmation when
|
112 |
-
the file of the size is too big (google drive notifies that
|
113 |
-
anti-viral checks cannot be performed on such files)
|
114 |
-
"""
|
115 |
-
import requests
|
116 |
-
|
117 |
-
with requests.Session() as session:
|
118 |
-
|
119 |
-
# First get the confirmation token and append it to the URL
|
120 |
-
with session.get(url, stream=True, allow_redirects=True) as response:
|
121 |
-
for k, v in response.cookies.items():
|
122 |
-
if k.startswith("download_warning"):
|
123 |
-
url = url + "&confirm=" + v
|
124 |
-
|
125 |
-
# Then download the content of the file
|
126 |
-
with session.get(url, stream=True, verify=True) as response:
|
127 |
-
makedir(output_path)
|
128 |
-
path = os.path.join(output_path, output_file_name)
|
129 |
-
total_size = int(response.headers.get("Content-length", 0))
|
130 |
-
with open(path, "wb") as file:
|
131 |
-
from tqdm import tqdm
|
132 |
-
|
133 |
-
with tqdm(total=total_size) as progress_bar:
|
134 |
-
for block in response.iter_content(
|
135 |
-
chunk_size=io.DEFAULT_BUFFER_SIZE
|
136 |
-
):
|
137 |
-
file.write(block)
|
138 |
-
progress_bar.update(len(block))
|
139 |
-
|
140 |
-
|
141 |
-
def _get_google_drive_file_id(url: str) -> Optional[str]:
|
142 |
-
parts = urlparse(url)
|
143 |
-
|
144 |
-
if re.match(r"(drive|docs)[.]google[.]com", parts.netloc) is None:
|
145 |
-
return None
|
146 |
-
|
147 |
-
match = re.match(r"/file/d/(?P<id>[^/]*)", parts.path)
|
148 |
-
if match is None:
|
149 |
-
return None
|
150 |
-
|
151 |
-
return match.group("id")
|
152 |
-
|
153 |
-
|
154 |
-
def _urlretrieve(url: str, filename: str, chunk_size: int = 1024) -> None:
|
155 |
-
with open(filename, "wb") as fh:
|
156 |
-
with urllib.request.urlopen(
|
157 |
-
urllib.request.Request(url, headers={"User-Agent": "vissl"})
|
158 |
-
) as response:
|
159 |
-
with tqdm(total=response.length) as pbar:
|
160 |
-
for chunk in iter(lambda: response.read(chunk_size), ""):
|
161 |
-
if not chunk:
|
162 |
-
break
|
163 |
-
pbar.update(chunk_size)
|
164 |
-
fh.write(chunk)
|
165 |
-
|
166 |
-
|
167 |
-
def download_url(
|
168 |
-
url: str,
|
169 |
-
root: str,
|
170 |
-
filename: Optional[str] = None,
|
171 |
-
md5: Optional[str] = None,
|
172 |
-
) -> None:
|
173 |
-
"""Download a file from a url and place it in root.
|
174 |
-
Args:
|
175 |
-
url (str): URL to download file from
|
176 |
-
root (str): Directory to place downloaded file in
|
177 |
-
filename (str, optional): Name to save the file under.
|
178 |
-
If None, use the basename of the URL.
|
179 |
-
md5 (str, optional): MD5 checksum of the download. If None, do not check
|
180 |
-
"""
|
181 |
-
root = os.path.expanduser(root)
|
182 |
-
if not filename:
|
183 |
-
filename = os.path.basename(url)
|
184 |
-
fpath = os.path.join(root, filename)
|
185 |
-
|
186 |
-
makedir(root)
|
187 |
-
|
188 |
-
# check if file is already present locally
|
189 |
-
if check_integrity(fpath, md5):
|
190 |
-
print("Using downloaded and verified file: " + fpath)
|
191 |
-
return
|
192 |
-
|
193 |
-
# expand redirect chain if needed
|
194 |
-
url = get_redirected_url(url)
|
195 |
-
|
196 |
-
# check if file is located on Google Drive
|
197 |
-
file_id = _get_google_drive_file_id(url)
|
198 |
-
if file_id is not None:
|
199 |
-
return download_file_from_google_drive(file_id, root, filename, md5)
|
200 |
-
|
201 |
-
# download the file
|
202 |
-
try:
|
203 |
-
print("Downloading " + url + " to " + fpath)
|
204 |
-
_urlretrieve(url, fpath)
|
205 |
-
except (urllib.error.URLError, IOError) as e: # type: ignore[attr-defined]
|
206 |
-
if url[:5] == "https":
|
207 |
-
url = url.replace("https:", "http:")
|
208 |
-
print(
|
209 |
-
"Failed download. Trying https -> http instead."
|
210 |
-
" Downloading " + url + " to " + fpath
|
211 |
-
)
|
212 |
-
_urlretrieve(url, fpath)
|
213 |
-
else:
|
214 |
-
raise e
|
215 |
-
|
216 |
-
# check integrity of downloaded file
|
217 |
-
if not check_integrity(fpath, md5):
|
218 |
-
raise RuntimeError("File not found or corrupted.")
|
219 |
-
|
220 |
-
|
221 |
-
def download_and_extract_archive(
|
222 |
-
url: str,
|
223 |
-
download_root: str,
|
224 |
-
extract_root: Optional[str] = None,
|
225 |
-
filename: Optional[str] = None,
|
226 |
-
md5: Optional[str] = None,
|
227 |
-
remove_finished: bool = False,
|
228 |
-
) -> None:
|
229 |
-
download_root = os.path.expanduser(download_root)
|
230 |
-
if extract_root is None:
|
231 |
-
extract_root = download_root
|
232 |
-
if not filename:
|
233 |
-
filename = os.path.basename(url)
|
234 |
-
|
235 |
-
download_url(url, download_root, filename, md5)
|
236 |
-
|
237 |
-
archive = os.path.join(download_root, filename)
|
238 |
-
print("Extracting {} to {}".format(archive, extract_root))
|
239 |
-
extract_archive(archive, extract_root, remove_finished)
|
240 |
-
|
241 |
-
|
242 |
-
def cache_url(url: str, cache_dir: str) -> str:
|
243 |
-
"""
|
244 |
-
This implementation downloads the remote resource and caches it locally.
|
245 |
-
The resource will only be downloaded if not previously requested.
|
246 |
-
"""
|
247 |
-
parsed_url = urlparse(url)
|
248 |
-
dirname = os.path.join(cache_dir, os.path.dirname(parsed_url.path.lstrip("/")))
|
249 |
-
makedir(dirname)
|
250 |
-
filename = url.split("/")[-1]
|
251 |
-
cached = os.path.join(dirname, filename)
|
252 |
-
with file_lock(cached):
|
253 |
-
if not os.path.isfile(cached):
|
254 |
-
logging.info(f"Downloading {url} to {cached} ...")
|
255 |
-
cached = download(url, dirname, filename=filename)
|
256 |
-
logging.info(f"URL {url} cached in {cached}")
|
257 |
-
return cached
|
258 |
-
|
259 |
-
|
260 |
-
# TODO (prigoyal): convert this into RAII-style API
|
261 |
-
def create_file_symlink(file1, file2):
|
262 |
-
"""
|
263 |
-
Simply create the symlinks for a given file1 to file2.
|
264 |
-
Useful during model checkpointing to symlinks to the
|
265 |
-
latest successful checkpoint.
|
266 |
-
"""
|
267 |
-
try:
|
268 |
-
if g_pathmgr.exists(file2):
|
269 |
-
g_pathmgr.rm(file2)
|
270 |
-
g_pathmgr.symlink(file1, file2)
|
271 |
-
except Exception as e:
|
272 |
-
logging.info(f"Could NOT create symlink. Error: {e}")
|
273 |
-
|
274 |
-
|
275 |
-
def save_file(data, filename, append_to_json=True, verbose=True):
|
276 |
-
"""
|
277 |
-
Common i/o utility to handle saving data to various file formats.
|
278 |
-
Supported:
|
279 |
-
.pkl, .pickle, .npy, .json
|
280 |
-
Specifically for .json, users have the option to either append (default)
|
281 |
-
or rewrite by passing in Boolean value to append_to_json.
|
282 |
-
"""
|
283 |
-
if verbose:
|
284 |
-
logging.info(f"Saving data to file: {filename}")
|
285 |
-
file_ext = os.path.splitext(filename)[1]
|
286 |
-
if file_ext in [".pkl", ".pickle"]:
|
287 |
-
with g_pathmgr.open(filename, "wb") as fopen:
|
288 |
-
pickle.dump(data, fopen, pickle.HIGHEST_PROTOCOL)
|
289 |
-
elif file_ext == ".npy":
|
290 |
-
with g_pathmgr.open(filename, "wb") as fopen:
|
291 |
-
np.save(fopen, data)
|
292 |
-
elif file_ext == ".json":
|
293 |
-
if append_to_json:
|
294 |
-
with g_pathmgr.open(filename, "a") as fopen:
|
295 |
-
fopen.write(json.dumps(data, sort_keys=True) + "\n")
|
296 |
-
fopen.flush()
|
297 |
-
else:
|
298 |
-
with g_pathmgr.open(filename, "w") as fopen:
|
299 |
-
fopen.write(json.dumps(data, sort_keys=True) + "\n")
|
300 |
-
fopen.flush()
|
301 |
-
elif file_ext == ".yaml":
|
302 |
-
with g_pathmgr.open(filename, "w") as fopen:
|
303 |
-
dump = yaml.dump(data)
|
304 |
-
fopen.write(dump)
|
305 |
-
fopen.flush()
|
306 |
-
else:
|
307 |
-
raise Exception(f"Saving {file_ext} is not supported yet")
|
308 |
-
|
309 |
-
if verbose:
|
310 |
-
logging.info(f"Saved data to file: {filename}")
|
311 |
-
|
312 |
-
|
313 |
-
def load_file(filename, mmap_mode=None, verbose=True, allow_pickle=False):
|
314 |
-
"""
|
315 |
-
Common i/o utility to handle loading data from various file formats.
|
316 |
-
Supported:
|
317 |
-
.pkl, .pickle, .npy, .json
|
318 |
-
For the npy files, we support reading the files in mmap_mode.
|
319 |
-
If the mmap_mode of reading is not successful, we load data without the
|
320 |
-
mmap_mode.
|
321 |
-
"""
|
322 |
-
if verbose:
|
323 |
-
logging.info(f"Loading data from file: {filename}")
|
324 |
-
|
325 |
-
file_ext = os.path.splitext(filename)[1]
|
326 |
-
if file_ext == ".txt":
|
327 |
-
with g_pathmgr.open(filename, "r") as fopen:
|
328 |
-
data = fopen.readlines()
|
329 |
-
elif file_ext in [".pkl", ".pickle"]:
|
330 |
-
with g_pathmgr.open(filename, "rb") as fopen:
|
331 |
-
data = pickle.load(fopen, encoding="latin1")
|
332 |
-
elif file_ext == ".npy":
|
333 |
-
if mmap_mode:
|
334 |
-
try:
|
335 |
-
with g_pathmgr.open(filename, "rb") as fopen:
|
336 |
-
data = np.load(
|
337 |
-
fopen,
|
338 |
-
allow_pickle=allow_pickle,
|
339 |
-
encoding="latin1",
|
340 |
-
mmap_mode=mmap_mode,
|
341 |
-
)
|
342 |
-
except ValueError as e:
|
343 |
-
logging.info(
|
344 |
-
f"Could not mmap {filename}: {e}. Trying without g_pathmgr"
|
345 |
-
)
|
346 |
-
data = np.load(
|
347 |
-
filename,
|
348 |
-
allow_pickle=allow_pickle,
|
349 |
-
encoding="latin1",
|
350 |
-
mmap_mode=mmap_mode,
|
351 |
-
)
|
352 |
-
logging.info("Successfully loaded without g_pathmgr")
|
353 |
-
except Exception:
|
354 |
-
logging.info("Could not mmap without g_pathmgr. Trying without mmap")
|
355 |
-
with g_pathmgr.open(filename, "rb") as fopen:
|
356 |
-
data = np.load(fopen, allow_pickle=allow_pickle, encoding="latin1")
|
357 |
-
else:
|
358 |
-
with g_pathmgr.open(filename, "rb") as fopen:
|
359 |
-
data = np.load(fopen, allow_pickle=allow_pickle, encoding="latin1")
|
360 |
-
elif file_ext == ".json":
|
361 |
-
with g_pathmgr.open(filename, "r") as fopen:
|
362 |
-
data = json.load(fopen)
|
363 |
-
elif file_ext == ".yaml":
|
364 |
-
with g_pathmgr.open(filename, "r") as fopen:
|
365 |
-
data = yaml.load(fopen, Loader=yaml.FullLoader)
|
366 |
-
elif file_ext == ".csv":
|
367 |
-
with g_pathmgr.open(filename, "r") as fopen:
|
368 |
-
data = pd.read_csv(fopen)
|
369 |
-
else:
|
370 |
-
raise Exception(f"Reading from {file_ext} is not supported yet")
|
371 |
-
return data
|
372 |
-
|
373 |
-
|
374 |
-
def abspath(resource_path: str):
|
375 |
-
"""
|
376 |
-
Make a path absolute, but take into account prefixes like
|
377 |
-
"http://" or "manifold://"
|
378 |
-
"""
|
379 |
-
regex = re.compile(r"^\w+://")
|
380 |
-
if regex.match(resource_path) is None:
|
381 |
-
return os.path.abspath(resource_path)
|
382 |
-
else:
|
383 |
-
return resource_path
|
384 |
-
|
385 |
-
|
386 |
-
def makedir(dir_path):
|
387 |
-
"""
|
388 |
-
Create the directory if it does not exist.
|
389 |
-
"""
|
390 |
-
is_success = False
|
391 |
-
try:
|
392 |
-
if not g_pathmgr.exists(dir_path):
|
393 |
-
g_pathmgr.mkdirs(dir_path)
|
394 |
-
is_success = True
|
395 |
-
except BaseException:
|
396 |
-
logging.info(f"Error creating directory: {dir_path}")
|
397 |
-
return is_success
|
398 |
-
|
399 |
-
|
400 |
-
def is_url(input_url):
|
401 |
-
"""
|
402 |
-
Check if an input string is a url. look for http(s):// and ignoring the case
|
403 |
-
"""
|
404 |
-
is_url = re.match(r"^(?:http)s?://", input_url, re.IGNORECASE) is not None
|
405 |
-
return is_url
|
406 |
-
|
407 |
-
|
408 |
-
def cleanup_dir(dir):
|
409 |
-
"""
|
410 |
-
Utility for deleting a directory. Useful for cleaning the storage space
|
411 |
-
that contains various training artifacts like checkpoints, data etc.
|
412 |
-
"""
|
413 |
-
if os.path.exists(dir):
|
414 |
-
logging.info(f"Deleting directory: {dir}")
|
415 |
-
shutil.rmtree(dir)
|
416 |
-
logging.info(f"Deleted contents of directory: {dir}")
|
417 |
-
|
418 |
-
|
419 |
-
def get_file_size(filename):
|
420 |
-
"""
|
421 |
-
Given a file, get the size of file in MB
|
422 |
-
"""
|
423 |
-
size_in_mb = os.path.getsize(filename) / float(1024**2)
|
424 |
-
return size_in_mb
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/detectron2/data/transforms/transform_gen.py
DELETED
@@ -1,447 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
3 |
-
# File: transformer.py
|
4 |
-
|
5 |
-
import inspect
|
6 |
-
import numpy as np
|
7 |
-
import pprint
|
8 |
-
import sys
|
9 |
-
from abc import ABCMeta, abstractmethod
|
10 |
-
from fvcore.transforms.transform import (
|
11 |
-
BlendTransform,
|
12 |
-
CropTransform,
|
13 |
-
HFlipTransform,
|
14 |
-
NoOpTransform,
|
15 |
-
Transform,
|
16 |
-
TransformList,
|
17 |
-
VFlipTransform,
|
18 |
-
)
|
19 |
-
from PIL import Image
|
20 |
-
|
21 |
-
from .transform import ExtentTransform, ResizeTransform
|
22 |
-
|
23 |
-
__all__ = [
|
24 |
-
"RandomBrightness",
|
25 |
-
"RandomContrast",
|
26 |
-
"RandomCrop",
|
27 |
-
"RandomExtent",
|
28 |
-
"RandomFlip",
|
29 |
-
"RandomSaturation",
|
30 |
-
"RandomLighting",
|
31 |
-
"Resize",
|
32 |
-
"ResizeShortestEdge",
|
33 |
-
"TransformGen",
|
34 |
-
"apply_transform_gens",
|
35 |
-
]
|
36 |
-
|
37 |
-
|
38 |
-
def check_dtype(img):
|
39 |
-
assert isinstance(img, np.ndarray), "[TransformGen] Needs an numpy array, but got a {}!".format(
|
40 |
-
type(img)
|
41 |
-
)
|
42 |
-
assert not isinstance(img.dtype, np.integer) or (
|
43 |
-
img.dtype == np.uint8
|
44 |
-
), "[TransformGen] Got image of type {}, use uint8 or floating points instead!".format(
|
45 |
-
img.dtype
|
46 |
-
)
|
47 |
-
assert img.ndim in [2, 3], img.ndim
|
48 |
-
|
49 |
-
|
50 |
-
class TransformGen(metaclass=ABCMeta):
|
51 |
-
"""
|
52 |
-
TransformGen takes an image of type uint8 in range [0, 255], or
|
53 |
-
floating point in range [0, 1] or [0, 255] as input.
|
54 |
-
|
55 |
-
It creates a :class:`Transform` based on the given image, sometimes with randomness.
|
56 |
-
The transform can then be used to transform images
|
57 |
-
or other data (boxes, points, annotations, etc.) associated with it.
|
58 |
-
|
59 |
-
The assumption made in this class
|
60 |
-
is that the image itself is sufficient to instantiate a transform.
|
61 |
-
When this assumption is not true, you need to create the transforms by your own.
|
62 |
-
|
63 |
-
A list of `TransformGen` can be applied with :func:`apply_transform_gens`.
|
64 |
-
"""
|
65 |
-
|
66 |
-
def _init(self, params=None):
|
67 |
-
if params:
|
68 |
-
for k, v in params.items():
|
69 |
-
if k != "self" and not k.startswith("_"):
|
70 |
-
setattr(self, k, v)
|
71 |
-
|
72 |
-
@abstractmethod
|
73 |
-
def get_transform(self, img):
|
74 |
-
pass
|
75 |
-
|
76 |
-
def _rand_range(self, low=1.0, high=None, size=None):
|
77 |
-
"""
|
78 |
-
Uniform float random number between low and high.
|
79 |
-
"""
|
80 |
-
if high is None:
|
81 |
-
low, high = 0, low
|
82 |
-
if size is None:
|
83 |
-
size = []
|
84 |
-
return np.random.uniform(low, high, size)
|
85 |
-
|
86 |
-
def __repr__(self):
|
87 |
-
"""
|
88 |
-
Produce something like:
|
89 |
-
"MyTransformGen(field1={self.field1}, field2={self.field2})"
|
90 |
-
"""
|
91 |
-
try:
|
92 |
-
sig = inspect.signature(self.__init__)
|
93 |
-
classname = type(self).__name__
|
94 |
-
argstr = []
|
95 |
-
for name, param in sig.parameters.items():
|
96 |
-
assert (
|
97 |
-
param.kind != param.VAR_POSITIONAL and param.kind != param.VAR_KEYWORD
|
98 |
-
), "The default __repr__ doesn't support *args or **kwargs"
|
99 |
-
assert hasattr(self, name), (
|
100 |
-
"Attribute {} not found! "
|
101 |
-
"Default __repr__ only works if attributes match the constructor.".format(name)
|
102 |
-
)
|
103 |
-
attr = getattr(self, name)
|
104 |
-
default = param.default
|
105 |
-
if default is attr:
|
106 |
-
continue
|
107 |
-
argstr.append("{}={}".format(name, pprint.pformat(attr)))
|
108 |
-
return "{}({})".format(classname, ", ".join(argstr))
|
109 |
-
except AssertionError:
|
110 |
-
return super().__repr__()
|
111 |
-
|
112 |
-
__str__ = __repr__
|
113 |
-
|
114 |
-
|
115 |
-
class RandomFlip(TransformGen):
|
116 |
-
"""
|
117 |
-
Flip the image horizontally or vertically with the given probability.
|
118 |
-
"""
|
119 |
-
|
120 |
-
def __init__(self, prob=0.5, *, horizontal=True, vertical=False):
|
121 |
-
"""
|
122 |
-
Args:
|
123 |
-
prob (float): probability of flip.
|
124 |
-
horizontal (boolean): whether to apply horizontal flipping
|
125 |
-
vertical (boolean): whether to apply vertical flipping
|
126 |
-
"""
|
127 |
-
super().__init__()
|
128 |
-
|
129 |
-
if horizontal and vertical:
|
130 |
-
raise ValueError("Cannot do both horiz and vert. Please use two Flip instead.")
|
131 |
-
if not horizontal and not vertical:
|
132 |
-
raise ValueError("At least one of horiz or vert has to be True!")
|
133 |
-
self._init(locals())
|
134 |
-
|
135 |
-
def get_transform(self, img):
|
136 |
-
h, w = img.shape[:2]
|
137 |
-
do = self._rand_range() < self.prob
|
138 |
-
if do:
|
139 |
-
if self.horizontal:
|
140 |
-
return HFlipTransform(w)
|
141 |
-
elif self.vertical:
|
142 |
-
return VFlipTransform(h)
|
143 |
-
else:
|
144 |
-
return NoOpTransform()
|
145 |
-
|
146 |
-
|
147 |
-
class Resize(TransformGen):
|
148 |
-
""" Resize image to a target size"""
|
149 |
-
|
150 |
-
def __init__(self, shape, interp=Image.BILINEAR):
|
151 |
-
"""
|
152 |
-
Args:
|
153 |
-
shape: (h, w) tuple or a int
|
154 |
-
interp: PIL interpolation method
|
155 |
-
"""
|
156 |
-
if isinstance(shape, int):
|
157 |
-
shape = (shape, shape)
|
158 |
-
shape = tuple(shape)
|
159 |
-
self._init(locals())
|
160 |
-
|
161 |
-
def get_transform(self, img):
|
162 |
-
return ResizeTransform(
|
163 |
-
img.shape[0], img.shape[1], self.shape[0], self.shape[1], self.interp
|
164 |
-
)
|
165 |
-
|
166 |
-
|
167 |
-
class ResizeShortestEdge(TransformGen):
|
168 |
-
"""
|
169 |
-
Scale the shorter edge to the given size, with a limit of `max_size` on the longer edge.
|
170 |
-
If `max_size` is reached, then downscale so that the longer edge does not exceed max_size.
|
171 |
-
"""
|
172 |
-
|
173 |
-
def __init__(
|
174 |
-
self, short_edge_length, max_size=sys.maxsize, sample_style="range", interp=Image.BILINEAR
|
175 |
-
):
|
176 |
-
"""
|
177 |
-
Args:
|
178 |
-
short_edge_length (list[int]): If ``sample_style=="range"``,
|
179 |
-
a [min, max] interval from which to sample the shortest edge length.
|
180 |
-
If ``sample_style=="choice"``, a list of shortest edge lengths to sample from.
|
181 |
-
max_size (int): maximum allowed longest edge length.
|
182 |
-
sample_style (str): either "range" or "choice".
|
183 |
-
"""
|
184 |
-
super().__init__()
|
185 |
-
assert sample_style in ["range", "choice"], sample_style
|
186 |
-
|
187 |
-
self.is_range = sample_style == "range"
|
188 |
-
if isinstance(short_edge_length, int):
|
189 |
-
short_edge_length = (short_edge_length, short_edge_length)
|
190 |
-
self._init(locals())
|
191 |
-
|
192 |
-
def get_transform(self, img):
|
193 |
-
h, w = img.shape[:2]
|
194 |
-
|
195 |
-
if self.is_range:
|
196 |
-
size = np.random.randint(self.short_edge_length[0], self.short_edge_length[1] + 1)
|
197 |
-
else:
|
198 |
-
size = np.random.choice(self.short_edge_length)
|
199 |
-
if size == 0:
|
200 |
-
return NoOpTransform()
|
201 |
-
|
202 |
-
scale = size * 1.0 / min(h, w)
|
203 |
-
if h < w:
|
204 |
-
newh, neww = size, scale * w
|
205 |
-
else:
|
206 |
-
newh, neww = scale * h, size
|
207 |
-
if max(newh, neww) > self.max_size:
|
208 |
-
scale = self.max_size * 1.0 / max(newh, neww)
|
209 |
-
newh = newh * scale
|
210 |
-
neww = neww * scale
|
211 |
-
neww = int(neww + 0.5)
|
212 |
-
newh = int(newh + 0.5)
|
213 |
-
return ResizeTransform(h, w, newh, neww, self.interp)
|
214 |
-
|
215 |
-
|
216 |
-
class RandomCrop(TransformGen):
|
217 |
-
"""
|
218 |
-
Randomly crop a subimage out of an image.
|
219 |
-
"""
|
220 |
-
|
221 |
-
def __init__(self, crop_type: str, crop_size):
|
222 |
-
"""
|
223 |
-
Args:
|
224 |
-
crop_type (str): one of "relative_range", "relative", "absolute".
|
225 |
-
See `config/defaults.py` for explanation.
|
226 |
-
crop_size (tuple[float]): the relative ratio or absolute pixels of
|
227 |
-
height and width
|
228 |
-
"""
|
229 |
-
super().__init__()
|
230 |
-
assert crop_type in ["relative_range", "relative", "absolute"]
|
231 |
-
self._init(locals())
|
232 |
-
|
233 |
-
def get_transform(self, img):
|
234 |
-
h, w = img.shape[:2]
|
235 |
-
croph, cropw = self.get_crop_size((h, w))
|
236 |
-
assert h >= croph and w >= cropw, "Shape computation in {} has bugs.".format(self)
|
237 |
-
h0 = np.random.randint(h - croph + 1)
|
238 |
-
w0 = np.random.randint(w - cropw + 1)
|
239 |
-
return CropTransform(w0, h0, cropw, croph)
|
240 |
-
|
241 |
-
def get_crop_size(self, image_size):
|
242 |
-
"""
|
243 |
-
Args:
|
244 |
-
image_size (tuple): height, width
|
245 |
-
|
246 |
-
Returns:
|
247 |
-
crop_size (tuple): height, width in absolute pixels
|
248 |
-
"""
|
249 |
-
h, w = image_size
|
250 |
-
if self.crop_type == "relative":
|
251 |
-
ch, cw = self.crop_size
|
252 |
-
return int(h * ch + 0.5), int(w * cw + 0.5)
|
253 |
-
elif self.crop_type == "relative_range":
|
254 |
-
crop_size = np.asarray(self.crop_size, dtype=np.float32)
|
255 |
-
ch, cw = crop_size + np.random.rand(2) * (1 - crop_size)
|
256 |
-
return int(h * ch + 0.5), int(w * cw + 0.5)
|
257 |
-
elif self.crop_type == "absolute":
|
258 |
-
return self.crop_size
|
259 |
-
else:
|
260 |
-
NotImplementedError("Unknown crop type {}".format(self.crop_type))
|
261 |
-
|
262 |
-
|
263 |
-
class RandomExtent(TransformGen):
|
264 |
-
"""
|
265 |
-
Outputs an image by cropping a random "subrect" of the source image.
|
266 |
-
|
267 |
-
The subrect can be parameterized to include pixels outside the source image,
|
268 |
-
in which case they will be set to zeros (i.e. black). The size of the output
|
269 |
-
image will vary with the size of the random subrect.
|
270 |
-
"""
|
271 |
-
|
272 |
-
def __init__(self, scale_range, shift_range):
|
273 |
-
"""
|
274 |
-
Args:
|
275 |
-
output_size (h, w): Dimensions of output image
|
276 |
-
scale_range (l, h): Range of input-to-output size scaling factor
|
277 |
-
shift_range (x, y): Range of shifts of the cropped subrect. The rect
|
278 |
-
is shifted by [w / 2 * Uniform(-x, x), h / 2 * Uniform(-y, y)],
|
279 |
-
where (w, h) is the (width, height) of the input image. Set each
|
280 |
-
component to zero to crop at the image's center.
|
281 |
-
"""
|
282 |
-
super().__init__()
|
283 |
-
self._init(locals())
|
284 |
-
|
285 |
-
def get_transform(self, img):
|
286 |
-
img_h, img_w = img.shape[:2]
|
287 |
-
|
288 |
-
# Initialize src_rect to fit the input image.
|
289 |
-
src_rect = np.array([-0.5 * img_w, -0.5 * img_h, 0.5 * img_w, 0.5 * img_h])
|
290 |
-
|
291 |
-
# Apply a random scaling to the src_rect.
|
292 |
-
src_rect *= np.random.uniform(self.scale_range[0], self.scale_range[1])
|
293 |
-
|
294 |
-
# Apply a random shift to the coordinates origin.
|
295 |
-
src_rect[0::2] += self.shift_range[0] * img_w * (np.random.rand() - 0.5)
|
296 |
-
src_rect[1::2] += self.shift_range[1] * img_h * (np.random.rand() - 0.5)
|
297 |
-
|
298 |
-
# Map src_rect coordinates into image coordinates (center at corner).
|
299 |
-
src_rect[0::2] += 0.5 * img_w
|
300 |
-
src_rect[1::2] += 0.5 * img_h
|
301 |
-
|
302 |
-
return ExtentTransform(
|
303 |
-
src_rect=(src_rect[0], src_rect[1], src_rect[2], src_rect[3]),
|
304 |
-
output_size=(int(src_rect[3] - src_rect[1]), int(src_rect[2] - src_rect[0])),
|
305 |
-
)
|
306 |
-
|
307 |
-
|
308 |
-
class RandomContrast(TransformGen):
|
309 |
-
"""
|
310 |
-
Randomly transforms image contrast.
|
311 |
-
|
312 |
-
Contrast intensity is uniformly sampled in (intensity_min, intensity_max).
|
313 |
-
- intensity < 1 will reduce contrast
|
314 |
-
- intensity = 1 will preserve the input image
|
315 |
-
- intensity > 1 will increase contrast
|
316 |
-
|
317 |
-
See: https://pillow.readthedocs.io/en/3.0.x/reference/ImageEnhance.html
|
318 |
-
"""
|
319 |
-
|
320 |
-
def __init__(self, intensity_min, intensity_max):
|
321 |
-
"""
|
322 |
-
Args:
|
323 |
-
intensity_min (float): Minimum augmentation
|
324 |
-
intensity_max (float): Maximum augmentation
|
325 |
-
"""
|
326 |
-
super().__init__()
|
327 |
-
self._init(locals())
|
328 |
-
|
329 |
-
def get_transform(self, img):
|
330 |
-
w = np.random.uniform(self.intensity_min, self.intensity_max)
|
331 |
-
return BlendTransform(src_image=img.mean(), src_weight=1 - w, dst_weight=w)
|
332 |
-
|
333 |
-
|
334 |
-
class RandomBrightness(TransformGen):
|
335 |
-
"""
|
336 |
-
Randomly transforms image brightness.
|
337 |
-
|
338 |
-
Brightness intensity is uniformly sampled in (intensity_min, intensity_max).
|
339 |
-
- intensity < 1 will reduce brightness
|
340 |
-
- intensity = 1 will preserve the input image
|
341 |
-
- intensity > 1 will increase brightness
|
342 |
-
|
343 |
-
See: https://pillow.readthedocs.io/en/3.0.x/reference/ImageEnhance.html
|
344 |
-
"""
|
345 |
-
|
346 |
-
def __init__(self, intensity_min, intensity_max):
|
347 |
-
"""
|
348 |
-
Args:
|
349 |
-
intensity_min (float): Minimum augmentation
|
350 |
-
intensity_max (float): Maximum augmentation
|
351 |
-
"""
|
352 |
-
super().__init__()
|
353 |
-
self._init(locals())
|
354 |
-
|
355 |
-
def get_transform(self, img):
|
356 |
-
w = np.random.uniform(self.intensity_min, self.intensity_max)
|
357 |
-
return BlendTransform(src_image=0, src_weight=1 - w, dst_weight=w)
|
358 |
-
|
359 |
-
|
360 |
-
class RandomSaturation(TransformGen):
|
361 |
-
"""
|
362 |
-
Randomly transforms image saturation.
|
363 |
-
|
364 |
-
Saturation intensity is uniformly sampled in (intensity_min, intensity_max).
|
365 |
-
- intensity < 1 will reduce saturation (make the image more grayscale)
|
366 |
-
- intensity = 1 will preserve the input image
|
367 |
-
- intensity > 1 will increase saturation
|
368 |
-
|
369 |
-
See: https://pillow.readthedocs.io/en/3.0.x/reference/ImageEnhance.html
|
370 |
-
"""
|
371 |
-
|
372 |
-
def __init__(self, intensity_min, intensity_max):
|
373 |
-
"""
|
374 |
-
Args:
|
375 |
-
intensity_min (float): Minimum augmentation (1 preserves input).
|
376 |
-
intensity_max (float): Maximum augmentation (1 preserves input).
|
377 |
-
"""
|
378 |
-
super().__init__()
|
379 |
-
self._init(locals())
|
380 |
-
|
381 |
-
def get_transform(self, img):
|
382 |
-
assert img.shape[-1] == 3, "Saturation only works on RGB images"
|
383 |
-
w = np.random.uniform(self.intensity_min, self.intensity_max)
|
384 |
-
grayscale = img.dot([0.299, 0.587, 0.114])[:, :, np.newaxis]
|
385 |
-
return BlendTransform(src_image=grayscale, src_weight=1 - w, dst_weight=w)
|
386 |
-
|
387 |
-
|
388 |
-
class RandomLighting(TransformGen):
|
389 |
-
"""
|
390 |
-
Randomly transforms image color using fixed PCA over ImageNet.
|
391 |
-
|
392 |
-
The degree of color jittering is randomly sampled via a normal distribution,
|
393 |
-
with standard deviation given by the scale parameter.
|
394 |
-
"""
|
395 |
-
|
396 |
-
def __init__(self, scale):
|
397 |
-
"""
|
398 |
-
Args:
|
399 |
-
scale (float): Standard deviation of principal component weighting.
|
400 |
-
"""
|
401 |
-
super().__init__()
|
402 |
-
self._init(locals())
|
403 |
-
self.eigen_vecs = np.array(
|
404 |
-
[[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203]]
|
405 |
-
)
|
406 |
-
self.eigen_vals = np.array([0.2175, 0.0188, 0.0045])
|
407 |
-
|
408 |
-
def get_transform(self, img):
|
409 |
-
assert img.shape[-1] == 3, "Saturation only works on RGB images"
|
410 |
-
weights = np.random.normal(scale=self.scale, size=3)
|
411 |
-
return BlendTransform(
|
412 |
-
src_image=self.eigen_vecs.dot(weights * self.eigen_vals), src_weight=1.0, dst_weight=1.0
|
413 |
-
)
|
414 |
-
|
415 |
-
|
416 |
-
def apply_transform_gens(transform_gens, img):
|
417 |
-
"""
|
418 |
-
Apply a list of :class:`TransformGen` on the input image, and
|
419 |
-
returns the transformed image and a list of transforms.
|
420 |
-
|
421 |
-
We cannot simply create and return all transforms without
|
422 |
-
applying it to the image, because a subsequent transform may
|
423 |
-
need the output of the previous one.
|
424 |
-
|
425 |
-
Args:
|
426 |
-
transform_gens (list): list of :class:`TransformGen` instance to
|
427 |
-
be applied.
|
428 |
-
img (ndarray): uint8 or floating point images with 1 or 3 channels.
|
429 |
-
|
430 |
-
Returns:
|
431 |
-
ndarray: the transformed image
|
432 |
-
TransformList: contain the transforms that's used.
|
433 |
-
"""
|
434 |
-
for g in transform_gens:
|
435 |
-
assert isinstance(g, TransformGen), g
|
436 |
-
|
437 |
-
check_dtype(img)
|
438 |
-
|
439 |
-
tfms = []
|
440 |
-
for g in transform_gens:
|
441 |
-
tfm = g.get_transform(img)
|
442 |
-
assert isinstance(
|
443 |
-
tfm, Transform
|
444 |
-
), "TransformGen {} must return an instance of Transform! Got {} instead".format(g, tfm)
|
445 |
-
img = tfm.apply_image(img)
|
446 |
-
tfms.append(tfm)
|
447 |
-
return img, TransformList(tfms)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/grid-feats-vqa/grid_feats/roi_heads.py
DELETED
@@ -1,253 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
2 |
-
import torch
|
3 |
-
from torch import nn
|
4 |
-
from torch.nn import functional as F
|
5 |
-
|
6 |
-
from detectron2.layers import ShapeSpec
|
7 |
-
from detectron2.modeling.roi_heads import (
|
8 |
-
build_box_head,
|
9 |
-
build_mask_head,
|
10 |
-
select_foreground_proposals,
|
11 |
-
ROI_HEADS_REGISTRY,
|
12 |
-
ROIHeads,
|
13 |
-
Res5ROIHeads,
|
14 |
-
StandardROIHeads,
|
15 |
-
)
|
16 |
-
from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers
|
17 |
-
from detectron2.modeling.poolers import ROIPooler
|
18 |
-
|
19 |
-
|
20 |
-
class AttributePredictor(nn.Module):
|
21 |
-
"""
|
22 |
-
Head for attribute prediction, including feature/score computation and
|
23 |
-
loss computation.
|
24 |
-
|
25 |
-
"""
|
26 |
-
|
27 |
-
def __init__(self, cfg, input_dim):
|
28 |
-
super().__init__()
|
29 |
-
|
30 |
-
# fmt: off
|
31 |
-
self.num_objs = cfg.MODEL.ROI_HEADS.NUM_CLASSES
|
32 |
-
self.obj_embed_dim = cfg.MODEL.ROI_ATTRIBUTE_HEAD.OBJ_EMBED_DIM
|
33 |
-
self.fc_dim = cfg.MODEL.ROI_ATTRIBUTE_HEAD.FC_DIM
|
34 |
-
self.num_attributes = cfg.MODEL.ROI_ATTRIBUTE_HEAD.NUM_CLASSES
|
35 |
-
self.max_attr_per_ins = cfg.INPUT.MAX_ATTR_PER_INS
|
36 |
-
self.loss_weight = cfg.MODEL.ROI_ATTRIBUTE_HEAD.LOSS_WEIGHT
|
37 |
-
# fmt: on
|
38 |
-
|
39 |
-
# object class embedding, including the background class
|
40 |
-
self.obj_embed = nn.Embedding(self.num_objs + 1, self.obj_embed_dim)
|
41 |
-
input_dim += self.obj_embed_dim
|
42 |
-
self.fc = nn.Sequential(nn.Linear(input_dim, self.fc_dim), nn.ReLU())
|
43 |
-
self.attr_score = nn.Linear(self.fc_dim, self.num_attributes)
|
44 |
-
nn.init.normal_(self.attr_score.weight, std=0.01)
|
45 |
-
nn.init.constant_(self.attr_score.bias, 0)
|
46 |
-
|
47 |
-
def forward(self, x, obj_labels):
|
48 |
-
attr_feat = torch.cat((x, self.obj_embed(obj_labels)), dim=1)
|
49 |
-
return self.attr_score(self.fc(attr_feat))
|
50 |
-
|
51 |
-
def loss(self, score, label):
|
52 |
-
n = score.shape[0]
|
53 |
-
score = score.unsqueeze(1)
|
54 |
-
score = score.expand(n, self.max_attr_per_ins, self.num_attributes).contiguous()
|
55 |
-
score = score.view(-1, self.num_attributes)
|
56 |
-
inv_weights = (
|
57 |
-
(label >= 0)
|
58 |
-
.sum(dim=1)
|
59 |
-
.repeat(self.max_attr_per_ins, 1)
|
60 |
-
.transpose(0, 1)
|
61 |
-
.flatten()
|
62 |
-
)
|
63 |
-
weights = inv_weights.float().reciprocal()
|
64 |
-
weights[weights > 1] = 0.0
|
65 |
-
n_valid = len((label >= 0).sum(dim=1).nonzero())
|
66 |
-
label = label.view(-1)
|
67 |
-
attr_loss = F.cross_entropy(score, label, reduction="none", ignore_index=-1)
|
68 |
-
attr_loss = (attr_loss * weights).view(n, -1).sum(dim=1)
|
69 |
-
|
70 |
-
if n_valid > 0:
|
71 |
-
attr_loss = attr_loss.sum() * self.loss_weight / n_valid
|
72 |
-
else:
|
73 |
-
attr_loss = attr_loss.sum() * 0.0
|
74 |
-
return {"loss_attr": attr_loss}
|
75 |
-
|
76 |
-
|
77 |
-
class AttributeROIHeads(ROIHeads):
|
78 |
-
"""
|
79 |
-
An extension of ROIHeads to include attribute prediction.
|
80 |
-
"""
|
81 |
-
|
82 |
-
def forward_attribute_loss(self, proposals, box_features):
|
83 |
-
proposals, fg_selection_attributes = select_foreground_proposals(
|
84 |
-
proposals, self.num_classes
|
85 |
-
)
|
86 |
-
attribute_features = box_features[torch.cat(fg_selection_attributes, dim=0)]
|
87 |
-
obj_labels = torch.cat([p.gt_classes for p in proposals])
|
88 |
-
attribute_labels = torch.cat([p.gt_attributes for p in proposals], dim=0)
|
89 |
-
attribute_scores = self.attribute_predictor(attribute_features, obj_labels)
|
90 |
-
return self.attribute_predictor.loss(attribute_scores, attribute_labels)
|
91 |
-
|
92 |
-
|
93 |
-
@ROI_HEADS_REGISTRY.register()
|
94 |
-
class AttributeRes5ROIHeads(AttributeROIHeads, Res5ROIHeads):
|
95 |
-
"""
|
96 |
-
An extension of Res5ROIHeads to include attribute prediction.
|
97 |
-
"""
|
98 |
-
|
99 |
-
def __init__(self, cfg, input_shape):
|
100 |
-
super(Res5ROIHeads, self).__init__(cfg, input_shape)
|
101 |
-
|
102 |
-
assert len(self.in_features) == 1
|
103 |
-
|
104 |
-
# fmt: off
|
105 |
-
pooler_resolution = cfg.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION
|
106 |
-
pooler_type = cfg.MODEL.ROI_BOX_HEAD.POOLER_TYPE
|
107 |
-
pooler_scales = (1.0 / input_shape[self.in_features[0]].stride, )
|
108 |
-
sampling_ratio = cfg.MODEL.ROI_BOX_HEAD.POOLER_SAMPLING_RATIO
|
109 |
-
self.mask_on = cfg.MODEL.MASK_ON
|
110 |
-
self.attribute_on = cfg.MODEL.ATTRIBUTE_ON
|
111 |
-
# fmt: on
|
112 |
-
assert not cfg.MODEL.KEYPOINT_ON
|
113 |
-
|
114 |
-
self.pooler = ROIPooler(
|
115 |
-
output_size=pooler_resolution,
|
116 |
-
scales=pooler_scales,
|
117 |
-
sampling_ratio=sampling_ratio,
|
118 |
-
pooler_type=pooler_type,
|
119 |
-
)
|
120 |
-
|
121 |
-
self.res5, out_channels = self._build_res5_block(cfg)
|
122 |
-
self.box_predictor = FastRCNNOutputLayers(
|
123 |
-
cfg, ShapeSpec(channels=out_channels, height=1, width=1)
|
124 |
-
)
|
125 |
-
|
126 |
-
if self.mask_on:
|
127 |
-
self.mask_head = build_mask_head(
|
128 |
-
cfg,
|
129 |
-
ShapeSpec(
|
130 |
-
channels=out_channels,
|
131 |
-
width=pooler_resolution,
|
132 |
-
height=pooler_resolution,
|
133 |
-
),
|
134 |
-
)
|
135 |
-
|
136 |
-
if self.attribute_on:
|
137 |
-
self.attribute_predictor = AttributePredictor(cfg, out_channels)
|
138 |
-
|
139 |
-
def forward(self, images, features, proposals, targets=None):
|
140 |
-
del images
|
141 |
-
|
142 |
-
if self.training:
|
143 |
-
assert targets
|
144 |
-
proposals = self.label_and_sample_proposals(proposals, targets)
|
145 |
-
del targets
|
146 |
-
|
147 |
-
proposal_boxes = [x.proposal_boxes for x in proposals]
|
148 |
-
box_features = self._shared_roi_transform(
|
149 |
-
[features[f] for f in self.in_features], proposal_boxes
|
150 |
-
)
|
151 |
-
feature_pooled = box_features.mean(dim=[2, 3])
|
152 |
-
predictions = self.box_predictor(feature_pooled)
|
153 |
-
|
154 |
-
if self.training:
|
155 |
-
del features
|
156 |
-
losses = self.box_predictor.losses(predictions, proposals)
|
157 |
-
if self.mask_on:
|
158 |
-
proposals, fg_selection_masks = select_foreground_proposals(
|
159 |
-
proposals, self.num_classes
|
160 |
-
)
|
161 |
-
mask_features = box_features[torch.cat(fg_selection_masks, dim=0)]
|
162 |
-
del box_features
|
163 |
-
losses.update(self.mask_head(mask_features, proposals))
|
164 |
-
if self.attribute_on:
|
165 |
-
losses.update(self.forward_attribute_loss(proposals, feature_pooled))
|
166 |
-
return [], losses
|
167 |
-
else:
|
168 |
-
pred_instances, _ = self.box_predictor.inference(predictions, proposals)
|
169 |
-
pred_instances = self.forward_with_given_boxes(features, pred_instances)
|
170 |
-
return pred_instances, {}
|
171 |
-
|
172 |
-
def get_conv5_features(self, features):
|
173 |
-
features = [features[f] for f in self.in_features]
|
174 |
-
return self.res5(features[0])
|
175 |
-
|
176 |
-
|
177 |
-
@ROI_HEADS_REGISTRY.register()
|
178 |
-
class AttributeStandardROIHeads(AttributeROIHeads, StandardROIHeads):
|
179 |
-
"""
|
180 |
-
An extension of StandardROIHeads to include attribute prediction.
|
181 |
-
"""
|
182 |
-
|
183 |
-
def __init__(self, cfg, input_shape):
|
184 |
-
super(StandardROIHeads, self).__init__(cfg, input_shape)
|
185 |
-
self._init_box_head(cfg, input_shape)
|
186 |
-
self._init_mask_head(cfg, input_shape)
|
187 |
-
self._init_keypoint_head(cfg, input_shape)
|
188 |
-
|
189 |
-
def _init_box_head(self, cfg, input_shape):
|
190 |
-
# fmt: off
|
191 |
-
pooler_resolution = cfg.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION
|
192 |
-
pooler_scales = tuple(1.0 / input_shape[k].stride for k in self.in_features)
|
193 |
-
sampling_ratio = cfg.MODEL.ROI_BOX_HEAD.POOLER_SAMPLING_RATIO
|
194 |
-
pooler_type = cfg.MODEL.ROI_BOX_HEAD.POOLER_TYPE
|
195 |
-
self.train_on_pred_boxes = cfg.MODEL.ROI_BOX_HEAD.TRAIN_ON_PRED_BOXES
|
196 |
-
self.attribute_on = cfg.MODEL.ATTRIBUTE_ON
|
197 |
-
# fmt: on
|
198 |
-
|
199 |
-
in_channels = [input_shape[f].channels for f in self.in_features]
|
200 |
-
assert len(set(in_channels)) == 1, in_channels
|
201 |
-
in_channels = in_channels[0]
|
202 |
-
|
203 |
-
self.box_pooler = ROIPooler(
|
204 |
-
output_size=pooler_resolution,
|
205 |
-
scales=pooler_scales,
|
206 |
-
sampling_ratio=sampling_ratio,
|
207 |
-
pooler_type=pooler_type,
|
208 |
-
)
|
209 |
-
self.box_head = build_box_head(
|
210 |
-
cfg,
|
211 |
-
ShapeSpec(
|
212 |
-
channels=in_channels, height=pooler_resolution, width=pooler_resolution
|
213 |
-
),
|
214 |
-
)
|
215 |
-
self.box_predictor = FastRCNNOutputLayers(cfg, self.box_head.output_shape)
|
216 |
-
|
217 |
-
if self.attribute_on:
|
218 |
-
self.attribute_predictor = AttributePredictor(
|
219 |
-
cfg, self.box_head.output_shape.channels
|
220 |
-
)
|
221 |
-
|
222 |
-
def _forward_box(self, features, proposals):
|
223 |
-
features = [features[f] for f in self.in_features]
|
224 |
-
box_features = self.box_pooler(features, [x.proposal_boxes for x in proposals])
|
225 |
-
box_features = self.box_head(box_features)
|
226 |
-
predictions = self.box_predictor(box_features)
|
227 |
-
|
228 |
-
if self.training:
|
229 |
-
if self.train_on_pred_boxes:
|
230 |
-
with torch.no_grad():
|
231 |
-
pred_boxes = self.box_predictor.predict_boxes_for_gt_classes(
|
232 |
-
predictions, proposals
|
233 |
-
)
|
234 |
-
for proposals_per_image, pred_boxes_per_image in zip(
|
235 |
-
proposals, pred_boxes
|
236 |
-
):
|
237 |
-
proposals_per_image.proposal_boxes = Boxes(pred_boxes_per_image)
|
238 |
-
losses = self.box_predictor.losses(predictions, proposals)
|
239 |
-
if self.attribute_on:
|
240 |
-
losses.update(self.forward_attribute_loss(proposals, box_features))
|
241 |
-
del box_features
|
242 |
-
|
243 |
-
return losses
|
244 |
-
else:
|
245 |
-
pred_instances, keep = self.box_predictor.inference(predictions, proposals)
|
246 |
-
box_features = box_features[keep]
|
247 |
-
return pred_instances, box_features
|
248 |
-
|
249 |
-
def get_conv5_features(self, features):
|
250 |
-
assert len(self.in_features) == 1
|
251 |
-
|
252 |
-
features = [features[f] for f in self.in_features]
|
253 |
-
return features[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/LIVE/pybind11/include/pybind11/chrono.h
DELETED
@@ -1,191 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
|
3 |
-
|
4 |
-
Copyright (c) 2016 Trent Houliston <[email protected]> and
|
5 |
-
Wenzel Jakob <[email protected]>
|
6 |
-
|
7 |
-
All rights reserved. Use of this source code is governed by a
|
8 |
-
BSD-style license that can be found in the LICENSE file.
|
9 |
-
*/
|
10 |
-
|
11 |
-
#pragma once
|
12 |
-
|
13 |
-
#include "pybind11.h"
|
14 |
-
#include <cmath>
|
15 |
-
#include <ctime>
|
16 |
-
#include <chrono>
|
17 |
-
#include <datetime.h>
|
18 |
-
|
19 |
-
// Backport the PyDateTime_DELTA functions from Python3.3 if required
|
20 |
-
#ifndef PyDateTime_DELTA_GET_DAYS
|
21 |
-
#define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days)
|
22 |
-
#endif
|
23 |
-
#ifndef PyDateTime_DELTA_GET_SECONDS
|
24 |
-
#define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds)
|
25 |
-
#endif
|
26 |
-
#ifndef PyDateTime_DELTA_GET_MICROSECONDS
|
27 |
-
#define PyDateTime_DELTA_GET_MICROSECONDS(o) (((PyDateTime_Delta*)o)->microseconds)
|
28 |
-
#endif
|
29 |
-
|
30 |
-
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
31 |
-
PYBIND11_NAMESPACE_BEGIN(detail)
|
32 |
-
|
33 |
-
template <typename type> class duration_caster {
|
34 |
-
public:
|
35 |
-
typedef typename type::rep rep;
|
36 |
-
typedef typename type::period period;
|
37 |
-
|
38 |
-
typedef std::chrono::duration<uint_fast32_t, std::ratio<86400>> days;
|
39 |
-
|
40 |
-
bool load(handle src, bool) {
|
41 |
-
using namespace std::chrono;
|
42 |
-
|
43 |
-
// Lazy initialise the PyDateTime import
|
44 |
-
if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
|
45 |
-
|
46 |
-
if (!src) return false;
|
47 |
-
// If invoked with datetime.delta object
|
48 |
-
if (PyDelta_Check(src.ptr())) {
|
49 |
-
value = type(duration_cast<duration<rep, period>>(
|
50 |
-
days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
|
51 |
-
+ seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
|
52 |
-
+ microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
|
53 |
-
return true;
|
54 |
-
}
|
55 |
-
// If invoked with a float we assume it is seconds and convert
|
56 |
-
else if (PyFloat_Check(src.ptr())) {
|
57 |
-
value = type(duration_cast<duration<rep, period>>(duration<double>(PyFloat_AsDouble(src.ptr()))));
|
58 |
-
return true;
|
59 |
-
}
|
60 |
-
else return false;
|
61 |
-
}
|
62 |
-
|
63 |
-
// If this is a duration just return it back
|
64 |
-
static const std::chrono::duration<rep, period>& get_duration(const std::chrono::duration<rep, period> &src) {
|
65 |
-
return src;
|
66 |
-
}
|
67 |
-
|
68 |
-
// If this is a time_point get the time_since_epoch
|
69 |
-
template <typename Clock> static std::chrono::duration<rep, period> get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
|
70 |
-
return src.time_since_epoch();
|
71 |
-
}
|
72 |
-
|
73 |
-
static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
|
74 |
-
using namespace std::chrono;
|
75 |
-
|
76 |
-
// Use overloaded function to get our duration from our source
|
77 |
-
// Works out if it is a duration or time_point and get the duration
|
78 |
-
auto d = get_duration(src);
|
79 |
-
|
80 |
-
// Lazy initialise the PyDateTime import
|
81 |
-
if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
|
82 |
-
|
83 |
-
// Declare these special duration types so the conversions happen with the correct primitive types (int)
|
84 |
-
using dd_t = duration<int, std::ratio<86400>>;
|
85 |
-
using ss_t = duration<int, std::ratio<1>>;
|
86 |
-
using us_t = duration<int, std::micro>;
|
87 |
-
|
88 |
-
auto dd = duration_cast<dd_t>(d);
|
89 |
-
auto subd = d - dd;
|
90 |
-
auto ss = duration_cast<ss_t>(subd);
|
91 |
-
auto us = duration_cast<us_t>(subd - ss);
|
92 |
-
return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
|
93 |
-
}
|
94 |
-
|
95 |
-
PYBIND11_TYPE_CASTER(type, _("datetime.timedelta"));
|
96 |
-
};
|
97 |
-
|
98 |
-
// This is for casting times on the system clock into datetime.datetime instances
|
99 |
-
template <typename Duration> class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
|
100 |
-
public:
|
101 |
-
typedef std::chrono::time_point<std::chrono::system_clock, Duration> type;
|
102 |
-
bool load(handle src, bool) {
|
103 |
-
using namespace std::chrono;
|
104 |
-
|
105 |
-
// Lazy initialise the PyDateTime import
|
106 |
-
if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
|
107 |
-
|
108 |
-
if (!src) return false;
|
109 |
-
|
110 |
-
std::tm cal;
|
111 |
-
microseconds msecs;
|
112 |
-
|
113 |
-
if (PyDateTime_Check(src.ptr())) {
|
114 |
-
cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
|
115 |
-
cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
|
116 |
-
cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
|
117 |
-
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
118 |
-
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
119 |
-
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
120 |
-
cal.tm_isdst = -1;
|
121 |
-
msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
|
122 |
-
} else if (PyDate_Check(src.ptr())) {
|
123 |
-
cal.tm_sec = 0;
|
124 |
-
cal.tm_min = 0;
|
125 |
-
cal.tm_hour = 0;
|
126 |
-
cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
|
127 |
-
cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
|
128 |
-
cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
|
129 |
-
cal.tm_isdst = -1;
|
130 |
-
msecs = microseconds(0);
|
131 |
-
} else if (PyTime_Check(src.ptr())) {
|
132 |
-
cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
|
133 |
-
cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
|
134 |
-
cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
|
135 |
-
cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
|
136 |
-
cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
|
137 |
-
cal.tm_year = 70; // earliest available date for Python's datetime
|
138 |
-
cal.tm_isdst = -1;
|
139 |
-
msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
|
140 |
-
}
|
141 |
-
else return false;
|
142 |
-
|
143 |
-
value = system_clock::from_time_t(std::mktime(&cal)) + msecs;
|
144 |
-
return true;
|
145 |
-
}
|
146 |
-
|
147 |
-
static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src, return_value_policy /* policy */, handle /* parent */) {
|
148 |
-
using namespace std::chrono;
|
149 |
-
|
150 |
-
// Lazy initialise the PyDateTime import
|
151 |
-
if (!PyDateTimeAPI) { PyDateTime_IMPORT; }
|
152 |
-
|
153 |
-
// Get out microseconds, and make sure they are positive, to avoid bug in eastern hemisphere time zones
|
154 |
-
// (cfr. https://github.com/pybind/pybind11/issues/2417)
|
155 |
-
using us_t = duration<int, std::micro>;
|
156 |
-
auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
|
157 |
-
if (us.count() < 0)
|
158 |
-
us += seconds(1);
|
159 |
-
|
160 |
-
// Subtract microseconds BEFORE `system_clock::to_time_t`, because:
|
161 |
-
// > If std::time_t has lower precision, it is implementation-defined whether the value is rounded or truncated.
|
162 |
-
// (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
|
163 |
-
std::time_t tt = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
|
164 |
-
// this function uses static memory so it's best to copy it out asap just in case
|
165 |
-
// otherwise other code that is using localtime may break this (not just python code)
|
166 |
-
std::tm localtime = *std::localtime(&tt);
|
167 |
-
|
168 |
-
return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
|
169 |
-
localtime.tm_mon + 1,
|
170 |
-
localtime.tm_mday,
|
171 |
-
localtime.tm_hour,
|
172 |
-
localtime.tm_min,
|
173 |
-
localtime.tm_sec,
|
174 |
-
us.count());
|
175 |
-
}
|
176 |
-
PYBIND11_TYPE_CASTER(type, _("datetime.datetime"));
|
177 |
-
};
|
178 |
-
|
179 |
-
// Other clocks that are not the system clock are not measured as datetime.datetime objects
|
180 |
-
// since they are not measured on calendar time. So instead we just make them timedeltas
|
181 |
-
// Or if they have passed us a time as a float we convert that
|
182 |
-
template <typename Clock, typename Duration> class type_caster<std::chrono::time_point<Clock, Duration>>
|
183 |
-
: public duration_caster<std::chrono::time_point<Clock, Duration>> {
|
184 |
-
};
|
185 |
-
|
186 |
-
template <typename Rep, typename Period> class type_caster<std::chrono::duration<Rep, Period>>
|
187 |
-
: public duration_caster<std::chrono::duration<Rep, Period>> {
|
188 |
-
};
|
189 |
-
|
190 |
-
PYBIND11_NAMESPACE_END(detail)
|
191 |
-
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/LIVE/thrust/thrust/system/detail/adl/fill.h
DELETED
@@ -1,44 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
* Copyright 2008-2013 NVIDIA Corporation
|
3 |
-
*
|
4 |
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
-
* you may not use this file except in compliance with the License.
|
6 |
-
* You may obtain a fill of the License at
|
7 |
-
*
|
8 |
-
* http://www.apache.org/licenses/LICENSE-2.0
|
9 |
-
*
|
10 |
-
* Unless required by applicable law or agreed to in writing, software
|
11 |
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
-
* See the License for the specific language governing permissions and
|
14 |
-
* limitations under the License.
|
15 |
-
*/
|
16 |
-
|
17 |
-
#pragma once
|
18 |
-
|
19 |
-
#include <thrust/detail/config.h>
|
20 |
-
|
21 |
-
// the purpose of this header is to #include the fill.h header
|
22 |
-
// of the sequential, host, and device systems. It should be #included in any
|
23 |
-
// code which uses adl to dispatch fill
|
24 |
-
|
25 |
-
#include <thrust/system/detail/sequential/fill.h>
|
26 |
-
|
27 |
-
// SCons can't see through the #defines below to figure out what this header
|
28 |
-
// includes, so we fake it out by specifying all possible files we might end up
|
29 |
-
// including inside an #if 0.
|
30 |
-
#if 0
|
31 |
-
#include <thrust/system/cpp/detail/fill.h>
|
32 |
-
#include <thrust/system/cuda/detail/fill.h>
|
33 |
-
#include <thrust/system/omp/detail/fill.h>
|
34 |
-
#include <thrust/system/tbb/detail/fill.h>
|
35 |
-
#endif
|
36 |
-
|
37 |
-
#define __THRUST_HOST_SYSTEM_FILL_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/fill.h>
|
38 |
-
#include __THRUST_HOST_SYSTEM_FILL_HEADER
|
39 |
-
#undef __THRUST_HOST_SYSTEM_FILL_HEADER
|
40 |
-
|
41 |
-
#define __THRUST_DEVICE_SYSTEM_FILL_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/fill.h>
|
42 |
-
#include __THRUST_DEVICE_SYSTEM_FILL_HEADER
|
43 |
-
#undef __THRUST_DEVICE_SYSTEM_FILL_HEADER
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/LIVE/thrust/thrust/system/omp/detail/default_decomposition.h
DELETED
@@ -1,45 +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 |
-
|
18 |
-
/*! \file default_decomposition.h
|
19 |
-
* \brief Return a decomposition that is appropriate for the OpenMP backend.
|
20 |
-
*/
|
21 |
-
|
22 |
-
#pragma once
|
23 |
-
|
24 |
-
#include <thrust/detail/config.h>
|
25 |
-
#include <thrust/system/detail/internal/decompose.h>
|
26 |
-
|
27 |
-
namespace thrust
|
28 |
-
{
|
29 |
-
namespace system
|
30 |
-
{
|
31 |
-
namespace omp
|
32 |
-
{
|
33 |
-
namespace detail
|
34 |
-
{
|
35 |
-
|
36 |
-
template <typename IndexType>
|
37 |
-
thrust::system::detail::internal::uniform_decomposition<IndexType> default_decomposition(IndexType n);
|
38 |
-
|
39 |
-
} // end namespace detail
|
40 |
-
} // end namespace omp
|
41 |
-
} // end namespace system
|
42 |
-
} // end namespace thrust
|
43 |
-
|
44 |
-
#include <thrust/system/omp/detail/default_decomposition.inl>
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/SPOTER_Sign_Language_Recognition/spoter_mod/normalization/hand_normalization.py
DELETED
@@ -1,192 +0,0 @@
|
|
1 |
-
|
2 |
-
import logging
|
3 |
-
import pandas as pd
|
4 |
-
|
5 |
-
HAND_IDENTIFIERS = [
|
6 |
-
"wrist",
|
7 |
-
"indexTip",
|
8 |
-
"indexDIP",
|
9 |
-
"indexPIP",
|
10 |
-
"indexMCP",
|
11 |
-
"middleTip",
|
12 |
-
"middleDIP",
|
13 |
-
"middlePIP",
|
14 |
-
"middleMCP",
|
15 |
-
"ringTip",
|
16 |
-
"ringDIP",
|
17 |
-
"ringPIP",
|
18 |
-
"ringMCP",
|
19 |
-
"littleTip",
|
20 |
-
"littleDIP",
|
21 |
-
"littlePIP",
|
22 |
-
"littleMCP",
|
23 |
-
"thumbTip",
|
24 |
-
"thumbIP",
|
25 |
-
"thumbMP",
|
26 |
-
"thumbCMC"
|
27 |
-
]
|
28 |
-
|
29 |
-
|
30 |
-
def normalize_hands_full(df: pd.DataFrame) -> pd.DataFrame:
|
31 |
-
"""
|
32 |
-
Normalizes the hands position data using the Bohacek-normalization algorithm.
|
33 |
-
|
34 |
-
:param df: pd.DataFrame to be normalized
|
35 |
-
:return: pd.DataFrame with normalized values for hand pose
|
36 |
-
"""
|
37 |
-
|
38 |
-
# TODO: Fix division by zero
|
39 |
-
df.columns = [item.replace("_left_", "_0_").replace("_right_", "_1_") for item in list(df.columns)]
|
40 |
-
|
41 |
-
normalized_df = pd.DataFrame(columns=df.columns)
|
42 |
-
|
43 |
-
hand_landmarks = {"X": {0: [], 1: []}, "Y": {0: [], 1: []}}
|
44 |
-
|
45 |
-
# Determine how many hands are present in the dataset
|
46 |
-
range_hand_size = 1
|
47 |
-
if "wrist_1_X" in df.columns:
|
48 |
-
range_hand_size = 2
|
49 |
-
|
50 |
-
# Construct the relevant identifiers
|
51 |
-
for identifier in HAND_IDENTIFIERS:
|
52 |
-
for hand_index in range(range_hand_size):
|
53 |
-
hand_landmarks["X"][hand_index].append(identifier + "_" + str(hand_index) + "_X")
|
54 |
-
hand_landmarks["Y"][hand_index].append(identifier + "_" + str(hand_index) + "_Y")
|
55 |
-
|
56 |
-
# Iterate over all of the records in the dataset
|
57 |
-
for index, row in df.iterrows():
|
58 |
-
# Treat each hand individually
|
59 |
-
for hand_index in range(range_hand_size):
|
60 |
-
|
61 |
-
sequence_size = len(row["wrist_" + str(hand_index) + "_X"])
|
62 |
-
|
63 |
-
# Treat each element of the sequence (analyzed frame) individually
|
64 |
-
for sequence_index in range(sequence_size):
|
65 |
-
|
66 |
-
# Retrieve all of the X and Y values of the current frame
|
67 |
-
landmarks_x_values = [row[key][sequence_index] for key in hand_landmarks["X"][hand_index] if row[key][sequence_index] != 0]
|
68 |
-
landmarks_y_values = [row[key][sequence_index] for key in hand_landmarks["Y"][hand_index] if row[key][sequence_index] != 0]
|
69 |
-
|
70 |
-
# Prevent from even starting the analysis if some necessary elements are not present
|
71 |
-
if not landmarks_x_values or not landmarks_y_values:
|
72 |
-
logging.warning(
|
73 |
-
" HAND LANDMARKS: One frame could not be normalized as there is no data present. Record: " + str(index) +
|
74 |
-
", Frame: " + str(sequence_index))
|
75 |
-
continue
|
76 |
-
|
77 |
-
# Calculate the deltas
|
78 |
-
width, height = max(landmarks_x_values) - min(landmarks_x_values), max(landmarks_y_values) - min(
|
79 |
-
landmarks_y_values)
|
80 |
-
if width > height:
|
81 |
-
delta_x = 0.1 * width
|
82 |
-
delta_y = delta_x + ((width - height) / 2)
|
83 |
-
else:
|
84 |
-
delta_y = 0.1 * height
|
85 |
-
delta_x = delta_y + ((height - width) / 2)
|
86 |
-
|
87 |
-
# Set the starting and ending point of the normalization bounding box
|
88 |
-
starting_point = (min(landmarks_x_values) - delta_x, min(landmarks_y_values) - delta_y)
|
89 |
-
ending_point = (max(landmarks_x_values) + delta_x, max(landmarks_y_values) + delta_y)
|
90 |
-
|
91 |
-
# Normalize individual landmarks and save the results
|
92 |
-
for identifier in HAND_IDENTIFIERS:
|
93 |
-
key = identifier + "_" + str(hand_index) + "_"
|
94 |
-
|
95 |
-
# Prevent from trying to normalize incorrectly captured points
|
96 |
-
if row[key + "X"][sequence_index] == 0 or (ending_point[0] - starting_point[0]) == 0 or (starting_point[1] - ending_point[1]) == 0:
|
97 |
-
continue
|
98 |
-
|
99 |
-
normalized_x = (row[key + "X"][sequence_index] - starting_point[0]) / (ending_point[0] -
|
100 |
-
starting_point[0])
|
101 |
-
normalized_y = (row[key + "Y"][sequence_index] - ending_point[1]) / (starting_point[1] -
|
102 |
-
ending_point[1])
|
103 |
-
|
104 |
-
row[key + "X"][sequence_index] = normalized_x
|
105 |
-
row[key + "Y"][sequence_index] = normalized_y
|
106 |
-
|
107 |
-
normalized_df = normalized_df.append(row, ignore_index=True)
|
108 |
-
|
109 |
-
return normalized_df
|
110 |
-
|
111 |
-
|
112 |
-
def normalize_single_dict(row: dict):
|
113 |
-
"""
|
114 |
-
Normalizes the skeletal data for a given sequence of frames with signer's hand pose data. The normalization follows
|
115 |
-
the definition from our paper.
|
116 |
-
|
117 |
-
:param row: Dictionary containing key-value pairs with joint identifiers and corresponding lists (sequences) of
|
118 |
-
that particular joints coordinates
|
119 |
-
:return: Dictionary with normalized skeletal data (following the same schema as input data)
|
120 |
-
"""
|
121 |
-
|
122 |
-
hand_landmarks = {0: [], 1: []}
|
123 |
-
|
124 |
-
# Determine how many hands are present in the dataset
|
125 |
-
range_hand_size = 1
|
126 |
-
if "wrist_1" in row.keys():
|
127 |
-
range_hand_size = 2
|
128 |
-
|
129 |
-
# Construct the relevant identifiers
|
130 |
-
for identifier in HAND_IDENTIFIERS:
|
131 |
-
for hand_index in range(range_hand_size):
|
132 |
-
hand_landmarks[hand_index].append(identifier + "_" + str(hand_index))
|
133 |
-
|
134 |
-
# Treat each hand individually
|
135 |
-
for hand_index in range(range_hand_size):
|
136 |
-
|
137 |
-
sequence_size = len(row["wrist_" + str(hand_index)])
|
138 |
-
|
139 |
-
# Treat each element of the sequence (analyzed frame) individually
|
140 |
-
for sequence_index in range(sequence_size):
|
141 |
-
|
142 |
-
# Retrieve all of the X and Y values of the current frame
|
143 |
-
landmarks_x_values = [row[key][sequence_index][0] for key in hand_landmarks[hand_index] if
|
144 |
-
row[key][sequence_index][0] != 0]
|
145 |
-
landmarks_y_values = [row[key][sequence_index][1] for key in hand_landmarks[hand_index] if
|
146 |
-
row[key][sequence_index][1] != 0]
|
147 |
-
|
148 |
-
# Prevent from even starting the analysis if some necessary elements are not present
|
149 |
-
if not landmarks_x_values or not landmarks_y_values:
|
150 |
-
continue
|
151 |
-
|
152 |
-
# Calculate the deltas
|
153 |
-
width, height = max(landmarks_x_values) - min(landmarks_x_values), max(landmarks_y_values) - min(
|
154 |
-
landmarks_y_values)
|
155 |
-
if width > height:
|
156 |
-
delta_x = 0.1 * width
|
157 |
-
delta_y = delta_x + ((width - height) / 2)
|
158 |
-
else:
|
159 |
-
delta_y = 0.1 * height
|
160 |
-
delta_x = delta_y + ((height - width) / 2)
|
161 |
-
|
162 |
-
# Set the starting and ending point of the normalization bounding box
|
163 |
-
starting_point = [min(landmarks_x_values) - delta_x, min(landmarks_y_values) - delta_y]
|
164 |
-
ending_point = [max(landmarks_x_values) + delta_x, max(landmarks_y_values) + delta_y]
|
165 |
-
# Ensure that all of the bounding-box-defining coordinates are not out of the picture
|
166 |
-
if starting_point[0] < 0: starting_point[0] = 0
|
167 |
-
if starting_point[1] > 1: starting_point[1] = 1
|
168 |
-
if ending_point[0] < 0: ending_point[0] = 0
|
169 |
-
if ending_point[1] > 1: ending_point[1] = 1
|
170 |
-
|
171 |
-
# Normalize individual landmarks and save the results
|
172 |
-
for identifier in HAND_IDENTIFIERS:
|
173 |
-
key = identifier + "_" + str(hand_index)
|
174 |
-
|
175 |
-
# Prevent from trying to normalize incorrectly captured points
|
176 |
-
if row[key][sequence_index][0] == 0 or (ending_point[0] - starting_point[0]) == 0 or (
|
177 |
-
starting_point[1] - ending_point[1]) == 0:
|
178 |
-
continue
|
179 |
-
|
180 |
-
normalized_x = (row[key][sequence_index][0] - starting_point[0]) / (ending_point[0] - starting_point[0])
|
181 |
-
normalized_y = (row[key][sequence_index][1] - starting_point[1]) / (ending_point[1] - starting_point[1])
|
182 |
-
|
183 |
-
row[key][sequence_index] = list(row[key][sequence_index])
|
184 |
-
|
185 |
-
row[key][sequence_index][0] = normalized_x
|
186 |
-
row[key][sequence_index][1] = normalized_y
|
187 |
-
|
188 |
-
return row
|
189 |
-
|
190 |
-
|
191 |
-
if __name__ == "__main__":
|
192 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/WALT/mmdet/datasets/wider_face.py
DELETED
@@ -1,51 +0,0 @@
|
|
1 |
-
import os.path as osp
|
2 |
-
import xml.etree.ElementTree as ET
|
3 |
-
|
4 |
-
import mmcv
|
5 |
-
|
6 |
-
from .builder import DATASETS
|
7 |
-
from .xml_style import XMLDataset
|
8 |
-
|
9 |
-
|
10 |
-
@DATASETS.register_module()
|
11 |
-
class WIDERFaceDataset(XMLDataset):
|
12 |
-
"""Reader for the WIDER Face dataset in PASCAL VOC format.
|
13 |
-
|
14 |
-
Conversion scripts can be found in
|
15 |
-
https://github.com/sovrasov/wider-face-pascal-voc-annotations
|
16 |
-
"""
|
17 |
-
CLASSES = ('face', )
|
18 |
-
|
19 |
-
def __init__(self, **kwargs):
|
20 |
-
super(WIDERFaceDataset, self).__init__(**kwargs)
|
21 |
-
|
22 |
-
def load_annotations(self, ann_file):
|
23 |
-
"""Load annotation from WIDERFace XML style annotation file.
|
24 |
-
|
25 |
-
Args:
|
26 |
-
ann_file (str): Path of XML file.
|
27 |
-
|
28 |
-
Returns:
|
29 |
-
list[dict]: Annotation info from XML file.
|
30 |
-
"""
|
31 |
-
|
32 |
-
data_infos = []
|
33 |
-
img_ids = mmcv.list_from_file(ann_file)
|
34 |
-
for img_id in img_ids:
|
35 |
-
filename = f'{img_id}.jpg'
|
36 |
-
xml_path = osp.join(self.img_prefix, 'Annotations',
|
37 |
-
f'{img_id}.xml')
|
38 |
-
tree = ET.parse(xml_path)
|
39 |
-
root = tree.getroot()
|
40 |
-
size = root.find('size')
|
41 |
-
width = int(size.find('width').text)
|
42 |
-
height = int(size.find('height').text)
|
43 |
-
folder = root.find('folder').text
|
44 |
-
data_infos.append(
|
45 |
-
dict(
|
46 |
-
id=img_id,
|
47 |
-
filename=osp.join(folder, filename),
|
48 |
-
width=width,
|
49 |
-
height=height))
|
50 |
-
|
51 |
-
return data_infos
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Chitranshu/Dashboard-Dmart/README.md
DELETED
@@ -1,10 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Dmart-Dashboard
|
3 |
-
emoji: 📊
|
4 |
-
colorFrom: green
|
5 |
-
colorTo: green
|
6 |
-
sdk: docker
|
7 |
-
pinned: false
|
8 |
-
---
|
9 |
-
|
10 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|