Commit
·
895ddf0
1
Parent(s):
5d68446
Update parquet files (step 15 of 296)
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- spaces/101-5/gpt4free/g4f/.v1/gpt4free/hpgptai/__init__.py +0 -103
- spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/ 3utools iOS.md +0 -141
- spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Animal Kingdom MOD APK Unlock All Islands and Bridges in this Adventure Game.md +0 -84
- spaces/1phancelerku/anime-remove-background/Bowmasters MOD APK 4.0.1 Unlimited Coins and Fun for Android.md +0 -113
- spaces/1phancelerku/anime-remove-background/Download Avara Avara Nuvvu Song for Free - Listen to Fikos Latest Hit.md +0 -137
- spaces/1phancelerku/anime-remove-background/Download Hog Rider Sound Effects for Free - Clash of Clans and Clash Royale.md +0 -107
- spaces/1phancelerku/anime-remove-background/Download Plague Inc Evolved APK Premium and Unleash Your Inner Evil Genius.md +0 -114
- spaces/2023Liu2023/bingo/src/components/welcome-screen.tsx +0 -34
- spaces/232labs/VToonify/vtoonify/model/raft/core/update.py +0 -139
- spaces/44ov41za8i/FreeVC/speaker_encoder/model.py +0 -135
- spaces/4Taps/SadTalker/src/face3d/models/arcface_torch/docs/modelzoo.md +0 -0
- spaces/52Hz/CMFNet_deblurring/app.py +0 -37
- spaces/AB-TW/team-ai/documents/bussiness_context/NOTION_DB/Engineering Wiki 2402f5396a3244fdb3f1d135bdb0f3d6/Engineering Guidelines 4208cbd4733d4f6f94982f3fb24f6379.md +0 -39
- spaces/AIFILMS/StyleGANEX/models/mtcnn/mtcnn_pytorch/src/first_stage.py +0 -101
- spaces/AIFILMS/generate_human_motion/pyrender/pyrender/utils.py +0 -115
- spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/audio/vad.py +0 -78
- spaces/AIZero2Hero4Health/7-ClinicalTerminologyUIUX-GR/files/Readme.md +0 -1
- spaces/AUBADA-ALARABI/poetry1/README.md +0 -13
- spaces/AchyuthGamer/OpenGPT/client/css/global.css +0 -70
- spaces/Adr740/SmartHadithFR/README.md +0 -12
- spaces/AgentVerse/agentVerse/agentverse/llms/base.py +0 -45
- spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/shakeposition-plugin.d.ts +0 -9
- spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/grid/Factory.d.ts +0 -6
- spaces/Aityz/Aityz-3B/README.md +0 -13
- spaces/AkitoP/umamusume_bert_vits2/text/tone_sandhi.py +0 -769
- spaces/AlgoveraAI/web3-wallet/README.md +0 -37
- spaces/Alycer/VITS-Umamusume-voice-synthesizer/text/english.py +0 -188
- spaces/Amrrs/DragGan-Inversion/PTI/models/e4e/stylegan2/op/upfirdn2d.py +0 -60
- spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/optimization/mps.md +0 -67
- spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/schedulers/test_scheduler_heun.py +0 -160
- spaces/Andy1621/uniformer_image_detection/mmdet/models/losses/__init__.py +0 -29
- spaces/AnimalEquality/chatbot/lv_recipe_chatbot/app.py +0 -170
- spaces/Anonymous-sub/Rerender/src/img_util.py +0 -25
- spaces/Arnx/MusicGenXvAKN/README.md +0 -141
- spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/cells.py +0 -154
- spaces/AutoLLM/ArxivDigest/README.md +0 -13
- spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/Detectron1-Comparisons/README.md +0 -84
- spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/modeling/backbone/regnet.py +0 -452
- spaces/BatuhanYilmaz/Whisper-Auto-Subtitled-Video-Generator/languages.py +0 -101
- spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/req/req_uninstall.py +0 -650
- spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/packaging/utils.py +0 -136
- spaces/Big-Web/MMSD/env/Lib/site-packages/s3transfer/manager.py +0 -731
- spaces/Big-Web/MMSD/env/Lib/site-packages/urllib3/contrib/pyopenssl.py +0 -518
- spaces/CC123123/blip2_t/app.py +0 -282
- spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/tests/test_box2box_transform.py +0 -64
- spaces/CVPR/WALT/mmdet/models/roi_heads/scnet_roi_head.py +0 -582
- spaces/CVPR/lama-example/models/ade20k/segm_lib/nn/modules/tests/test_sync_batchnorm.py +0 -111
- spaces/CVPR/lama-example/models/ade20k/segm_lib/utils/__init__.py +0 -1
- spaces/CikeyQI/Yunzai/Yunzai/lib/renderer/loader.js +0 -56
- spaces/CjangCjengh/Shanghainese-TTS/attentions.py +0 -300
spaces/101-5/gpt4free/g4f/.v1/gpt4free/hpgptai/__init__.py
DELETED
@@ -1,103 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
"""
|
3 |
-
@Time : 2023/5/22 14:04
|
4 |
-
@Auth : Hp_mzx
|
5 |
-
@File :__init__.py.py
|
6 |
-
@IDE :PyCharm
|
7 |
-
"""
|
8 |
-
import re
|
9 |
-
import json
|
10 |
-
import base64
|
11 |
-
import random
|
12 |
-
import string
|
13 |
-
import requests
|
14 |
-
from fake_useragent import UserAgent
|
15 |
-
|
16 |
-
|
17 |
-
class ChatCompletion:
|
18 |
-
@staticmethod
|
19 |
-
def create(
|
20 |
-
messages: list,
|
21 |
-
context: str = "Converse as if you were an AI assistant. Be friendly, creative.",
|
22 |
-
restNonce: str = None,
|
23 |
-
proxy: str = None
|
24 |
-
):
|
25 |
-
url = "https://chatgptlogin.ac/wp-json/ai-chatbot/v1/chat"
|
26 |
-
if not restNonce:
|
27 |
-
restNonce = ChatCompletion.get_restNonce(proxy)
|
28 |
-
headers = {
|
29 |
-
"Content-Type": "application/json",
|
30 |
-
"X-Wp-Nonce": restNonce
|
31 |
-
}
|
32 |
-
proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy} if proxy else None
|
33 |
-
data = {
|
34 |
-
"env": "chatbot",
|
35 |
-
"session": "N/A",
|
36 |
-
"prompt": ChatCompletion.__build_prompt(context, messages),
|
37 |
-
"context": context,
|
38 |
-
"messages": messages,
|
39 |
-
"newMessage": messages[-1]["content"],
|
40 |
-
"userName": "<div class=\"mwai-name-text\">User:</div>",
|
41 |
-
"aiName": "<div class=\"mwai-name-text\">AI:</div>",
|
42 |
-
"model": "gpt-3.5-turbo",
|
43 |
-
"temperature": 0.8,
|
44 |
-
"maxTokens": 1024,
|
45 |
-
"maxResults": 1,
|
46 |
-
"apiKey": "",
|
47 |
-
"service": "openai",
|
48 |
-
"embeddingsIndex": "",
|
49 |
-
"stop": "",
|
50 |
-
"clientId": ChatCompletion.randomStr(),
|
51 |
-
}
|
52 |
-
res = requests.post(url=url, data=json.dumps(data), headers=headers, proxies=proxies)
|
53 |
-
if res.status_code == 200:
|
54 |
-
return res.json()
|
55 |
-
return res.text
|
56 |
-
|
57 |
-
@staticmethod
|
58 |
-
def randomStr():
|
59 |
-
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=34))[:11]
|
60 |
-
|
61 |
-
@classmethod
|
62 |
-
def __build_prompt(cls, context: str, message: list, isCasuallyFineTuned=False, last=15):
|
63 |
-
prompt = context + '\n\n' if context else ''
|
64 |
-
message = message[-last:]
|
65 |
-
if isCasuallyFineTuned:
|
66 |
-
lastLine = message[-1]
|
67 |
-
prompt = lastLine.content + ""
|
68 |
-
return prompt
|
69 |
-
conversation = [x["who"] + x["content"] for x in message]
|
70 |
-
prompt += '\n'.join(conversation)
|
71 |
-
prompt += '\n' + "AI: "
|
72 |
-
return prompt
|
73 |
-
|
74 |
-
@classmethod
|
75 |
-
def get_restNonce(cls, proxy: str = None):
|
76 |
-
url = "https://chatgptlogin.ac/"
|
77 |
-
headers = {
|
78 |
-
"Referer": "https://chatgptlogin.ac/",
|
79 |
-
"User-Agent": UserAgent().random
|
80 |
-
}
|
81 |
-
proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy} if proxy else None
|
82 |
-
res = requests.get(url, headers=headers, proxies=proxies)
|
83 |
-
src = re.search(
|
84 |
-
'class="mwai-chat mwai-chatgpt">.*<span>Send</span></button></div></div></div> <script defer src="(.*?)">',
|
85 |
-
res.text).group(1)
|
86 |
-
decoded_string = base64.b64decode(src.split(",")[-1]).decode('utf-8')
|
87 |
-
restNonce = re.search(r"let restNonce = '(.*?)';", decoded_string).group(1)
|
88 |
-
return restNonce
|
89 |
-
|
90 |
-
|
91 |
-
class Completion:
|
92 |
-
@staticmethod
|
93 |
-
def create(prompt: str, proxy: str):
|
94 |
-
messages = [
|
95 |
-
{
|
96 |
-
"content": prompt,
|
97 |
-
"html": prompt,
|
98 |
-
"id": ChatCompletion.randomStr(),
|
99 |
-
"role": "user",
|
100 |
-
"who": "User: ",
|
101 |
-
},
|
102 |
-
]
|
103 |
-
return ChatCompletion.create(messages=messages, proxy=proxy)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/ 3utools iOS.md
DELETED
@@ -1,141 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>Скачать 3utools: Лучший инструмент для пользователей iOS</h1>
|
3 |
-
<p>Если вы являетесь владельцем iPhone, iPad или iPod, то вы наверняка знаете, как важно иметь хороший инструмент для работы с вашими iOS устройствами. С помощью такого инструмента вы можете легко управлять файлами и данными на вашем устройстве, загружать приложения, рингтоны и обои, прошивать и делать джейлбрейк вашего устройства, а также использовать множество других полезных и интересных функций.</p>
|
4 |
-
<p>Одним из таких инструментов является <strong>3utools</strong>, который представляет собой бесплатное приложение для Windows, которое позволяет вам делать все вышеперечисленное и многое другое. В этой статье мы расскажем вам, что такое 3utools, зачем его скачивать, как его установить и использовать для работы с вашими iOS устройствами.</p>
|
5 |
-
<h2>скачать 3utools</h2><br /><p><b><b>Download</b> ☑ <a href="https://urlin.us/2uT0Zg">https://urlin.us/2uT0Zg</a></b></p><br /><br />
|
6 |
-
<h2>Что такое 3utools и зачем его скачивать?</h2>
|
7 |
-
<p><strong>3utools</strong> - это все-в-одном инструмент для пользователей iOS, который предлагает множество функций для управления, настройки и оптимизации вашего iOS устройства. С помощью 3utools вы можете:</p>
|
8 |
-
<ul>
|
9 |
-
<li>Управлять файлами, данными, приложениями, фотографиями, музыкой, рингтонами, видео и другими мультимедийными файлами на вашем устройстве.</li>
|
10 |
-
<li>Загружать различные приложения, рингтоны и обои из огромной библиотеки бесплатного контента.</li>
|
11 |
-
<li>Прошивать и делать джейлбрейк вашего устройства в разных режимах (нормальный, DFU, восстановление) с автоматическим подбором подходящих прошивок.</li>
|
12 |
-
<li>Использовать дополнительные возможности, такие как резер соответствуют следующим системным требованиям и совместимости:</p>
|
13 |
-
<h3>Системные требования и совместимость</h3>
|
14 |
-
<table>
|
15 |
-
<tr>
|
16 |
-
<th>Компьютер</th>
|
17 |
-
<th>iOS устройство</th>
|
18 |
-
</tr>
|
19 |
-
<tr>
|
20 |
-
<td>Операционная система: Windows 7/8/10 (32 или 64 бит)</td>
|
21 |
-
<td>Версия iOS: от iOS 4 до iOS 15</td>
|
22 |
-
</tr>
|
23 |
-
<tr>
|
24 |
-
<td>Процессор: Intel или AMD с частотой не менее 1 ГГц</td>
|
25 |
-
<td>Модель устройства: iPhone, iPad или iPod touch любого поколения</td>
|
26 |
-
</tr>
|
27 |
-
<tr>
|
28 |
-
<td>Оперативная память: не менее 512 МБ</td>
|
29 |
-
<td>Свободное место на устройстве: не менее 1 ГБ</td>
|
30 |
-
</tr>
|
31 |
-
<tr>
|
32 |
-
<td>Свободное место на диске: не менее 100 МБ</td>
|
33 |
-
<td>Кабель для подключения к компьютеру: USB или Lightning</td>
|
34 |
-
</tr>
|
35 |
-
<tr>
|
36 |
-
<td>Интернет-соединение: для загрузки приложений, рингтонов, обоев и прошивок</td>
|
37 |
-
<td>Режим разработчика: для джейлбрейка устройства (необязательно)</td>
|
38 |
-
</tr>
|
39 |
-
</table>
|
40 |
-
<h3>Источники для скачивания 3utools</h3>
|
41 |
-
<p>Существует несколько источников, с которых вы можете скачать 3utools на свой компьютер. Однако мы рекомендуем вам использовать только официальный сайт 3utools или проверенные сторонние сайты, чтобы избежать вирусов, вредоносных программ или поддельных версий. Вот некоторые из них:</p>
|
42 |
-
<ul>
|
43 |
-
<li><a href="">Официальный сайт 3utools</a>: это самый надежный и безопасный источник для скачивания 3utools. Вы можете найти последнюю версию приложения, а также полезную информацию, руководства и поддержку на этом сайте.</li>
|
44 |
-
<li><a href="">Softonic</a>: это популярный сайт для скачивания различных программного обеспечения для Windows, Mac и мобильных устройств. Вы можете скачать 3utools с этого сайта, но убедитесь, что вы выбираете правильную версию для вашей операционной системы.</li>
|
45 |
-
<li><a href="">Uptodown</a>: это еще один известный сайт для скачивания приложений для разных платформ. Вы можете найти 3utools на этом сайте, а также прочитать отзывы пользователей и редакторов о приложении.</li>
|
46 |
-
</ul>
|
47 |
-
<h3>Шаги по установке 3utools</h3>
|
48 |
-
<p>После того, как вы скачали файл установки 3utools (обычно имеет расширение .exe), вы можете приступить к установке приложения на свой компьютер. Для этого вам нужно выполнить следующие шаги:</p>
|
49 |
-
<ol>
|
50 |
-
<li>Запустите файл установки 3utools и следуйте инструкциям на экране. Вы можете выбрать язык интерфейса, папку для установки и ярлыки для приложения.</li>
|
51 |
-
<li>Дождитесь окончания установки и нажмите кнопку "Завершить". Приложение 3utools будет автоматически запущено на вашем компьютере.</li>
|
52 |
-
<li>Проверьте настройки при ложения 3utools, такие как путь к iTunes, язык, тема, обновления и т.д. Вы можете изменить их в любое время в меню "Настройки".</li>
|
53 |
-
</ol>
|
54 |
-
<p>Поздравляем, вы успешно установили 3utools на свой компьютер! Теперь вы можете использовать его для работы с вашими iOS устройствами.</p>
|
55 |
-
<h2>Как использовать 3utools для работы с iOS устройствами?</h2>
|
56 |
-
<p>Чтобы использовать 3utools для работы с вашими iOS устройствами, вам нужно сделать следующее:</p>
|
57 |
-
<p>скачать 3utools для windows 10<br />
|
58 |
-
скачать 3utools для iphone<br />
|
59 |
-
скачать 3utools на русском языке<br />
|
60 |
-
скачать 3utools последнюю версию<br />
|
61 |
-
скачать 3utools бесплатно<br />
|
62 |
-
скачать 3utools для ios 14<br />
|
63 |
-
скачать 3utools для ipad<br />
|
64 |
-
скачать 3utools для windows 7<br />
|
65 |
-
скачать 3utools для mac<br />
|
66 |
-
скачать 3utools для ipod<br />
|
67 |
-
скачать 3utools для прошивки iphone<br />
|
68 |
-
скачать 3utools для jailbreak<br />
|
69 |
-
скачать 3utools для windows xp<br />
|
70 |
-
скачать 3utools для windows 8<br />
|
71 |
-
скачать 3utools для windows vista<br />
|
72 |
-
скачать 3utools для активации iphone<br />
|
73 |
-
скачать 3utools для восстановления iphone<br />
|
74 |
-
скачать 3utools для рингтонов iphone<br />
|
75 |
-
скачать 3utools для видео iphone<br />
|
76 |
-
скачать 3utools для музыки iphone<br />
|
77 |
-
скачать 3utools для фото iphone<br />
|
78 |
-
скачать 3utools для данных iphone<br />
|
79 |
-
скачать 3utools для приложений iphone<br />
|
80 |
-
скачать 3utools для обоев iphone<br />
|
81 |
-
скачать 3utools для аудио iphone<br />
|
82 |
-
скачать 3utools для конвертации iphone<br />
|
83 |
-
скачать 3utools для резервного копирования iphone<br />
|
84 |
-
скачать 3utools для очистки iphone<br />
|
85 |
-
скачать 3utools для ssh iphone<br />
|
86 |
-
скачать 3utools для экрана iphone<br />
|
87 |
-
скачать 3utools для лога iphone<br />
|
88 |
-
скачать 3utools для иконок iphone<br />
|
89 |
-
скачать 3utools для миграции данных iphone<br />
|
90 |
-
скачать 3utools для компрессии фото iphone<br />
|
91 |
-
скачать 3utools для управления файлами iphone<br />
|
92 |
-
скачать 3utools отзывы<br />
|
93 |
-
скачать 3utools инструкция<br />
|
94 |
-
скачать 3utools официальный сайт<br />
|
95 |
-
скачать 3utools альтернатива<br />
|
96 |
-
скачать 3utools безопасно ли<br />
|
97 |
-
как скачать и установить 3utools<br />
|
98 |
-
как пользоваться программой 3utools<br />
|
99 |
-
как обновить программу 3utools<br />
|
100 |
-
как удалить программу 3utools<br />
|
101 |
-
как восстановить пароль на iphone через программу 3uTools</p>
|
102 |
-
<h3>Подключение iOS устройства к компьютеру</h3>
|
103 |
-
<p>Первым шагом является подключение вашего iOS устройства к вашему компьютеру с помощью USB или Lightning кабеля. Убедитесь, что на вашем устройстве разрешен доступ к данным и доверие к компьютеру. Вы можете проверить это в настройках вашего устройства.</p>
|
104 |
-
<p>После подключения вашего устройства к компьютеру, вы должны увидеть его имя и информацию на главном экране 3utools. Вы также можете видеть различные параметры и статусы вашего устройства, такие как заряд батареи, свободное место, версия iOS, серийный номер и т.д.</p>
|
105 |
-
<h3>Выбор режима работы с 3utools</h3>
|
106 |
-
<p>В зависимости от того, что вы хотите сделать с вашим устройством, вы можете выбрать один из трех режимов работы с 3utools:</p>
|
107 |
-
<ul>
|
108 |
-
<li><strong>Easy mode</strong>: это самый простой и быстрый режим, который позволяет вам выполнить основные операции, такие как прошивка, джейлбрейк, очистка мусора, резервное копирование и восстановление данных. В этом режиме 3utools автоматически определяет подходящие прошивки и инструменты для вашего устройства и выполняет операции за вас.</li>
|
109 |
-
<li><strong>Professional mode</strong>: это более продвинутый и настраиваемый режим, который позволяет вам контролировать все аспекты работы с вашим устройством. В этом режиме вы можете выбирать разные прошивки и инструменты для джейлбрейка, а также изменять различные параметры и опции для каждой операции.</li>
|
110 |
-
<li><strong>Multiple mode</strong>: это специальный режим, который позволяет вам работать с несколькими iOS устройствами одновременно. В этом режиме вы можете подключать до 10 устройств к одному компьютеру и выполнять одинаковые или разные операции для каждого из них.</li>
|
111 |
-
</ul>
|
112 |
-
<p>Вы можете переключаться между разными режимами работы с 3utools в верхнем правом углу главного экрана приложения.</p>
|
113 |
-
<h3>Использование различных функций 3utools</h3>
|
114 |
-
<p>После того, как вы выбрали режим работы с 3utools, вы можете начать использовать различные функции приложения для работы с вашими iOS устройствами. Некоторые из этих функций включают:</p>
|
115 |
-
<ul>
|
116 |
-
<li><strong>Управление файлами и данными iOS</strong>: вы можете просматривать, копировать, перемещать, удалять и редактировать файлы и данные на вашем устройстве с помощью файлового менеджера 3utools. Вы также можете импортировать или эк спортировать файлы и данные с вашего компьютера на ваше устройство. Вы также можете создавать резервные копии и восстанавливать данные с помощью функции "Backup/Restore".</li>
|
117 |
-
<li><strong>Загрузка приложений, рингтонов и обоев</strong>: вы можете загружать различные приложения, рингтоны и обои из огромной библиотеки бесплатного контента, которую предлагает 3utools. Вы можете просматривать разные категории, темы, жанры и рейтинги контента, а также искать по ключевым словам. Вы также можете устанавливать, удалять и обновлять приложения на вашем устройстве с помощью функции "Apps".</li>
|
118 |
-
<li><strong>Прошивка и джейлбрейк iOS</strong>: в�� можете прошивать и делать джейлбрейк вашего устройства в разных режимах (нормальный, DFU, восстановление) с помощью функции "Flash & JB". 3utools автоматически определяет подходящие прошивки и инструменты для джейлбрейка для вашего устройства и показывает вам доступные опции. Вы также можете настраивать различные параметры и опции для каждой операции, такие как сохранение данных, активация, откат базовой станции и т.д.</li>
|
119 |
-
<li><strong>Дополнительные возможности 3utools</strong>: вы можете использовать множество других полезных и интересных функций, которые предлагает 3utools, такие как очистка мусора, проверка состояния батареи, восстановление удаленных данных, проверка сертификатов SHSH, конвертация видео и аудио, создание рингтонов и обоев и многое другое. Вы можете найти эти функции в меню "Toolbox".</li>
|
120 |
-
</ul>
|
121 |
-
<p>Вы можете узнать больше о каждой функции 3utools, прочитав подробные руководства и советы на официальном сайте 3utools или в разделе "Help" приложения.</p>
|
122 |
-
<h2>Заключение и часто задаваемые вопросы</h2>
|
123 |
-
<p>В этой статье мы рассказали вам о 3utools - лучшем инструменте для пользователей iOS, который позволяет вам управлять, настраивать и оптимизировать ваше iOS устройство. Мы показали вам, что такое 3utools, зачем его скачивать, как его установить и использовать для работы с вашими iOS устройствами. Мы надеемся, что эта информация была полезна для вас и помогла вам лучше понять и использовать 3utools.</p>
|
124 |
-
<p>Если у вас есть какие-либо вопросы или проблемы с 3utools, вы можете обратиться к следующим часто задаваемым вопросам или связаться с поддержкой 3utools через официальный сайт или форум.</p>
|
125 |
-
<h4>Часто задаваемые вопросы</h4>
|
126 |
-
<ul>
|
127 |
-
<li><strong>Q: Является ли 3utools безопасным для использования?</strong></li>
|
128 |
-
<li>A: Да, 3utools является безопасным для использования, если вы скачиваете его из официального или проверенного источника. 3utools не содержит вирусов, вредоносных программ или поддельных версий. Однак о, вы должны быть осторожны при использовании некоторых функций 3utools, таких как джейлбрейк, прошивка или восстановление данных, так как они могут повлиять на гарантию, стабильность или безопасность вашего устройства. Вы должны всегда делать резервные копии ваших данных перед выполнением этих операций и следовать инструкциям 3utools.</li>
|
129 |
-
<li><strong>Q: Как обновить 3utools до последней версии?</strong></li>
|
130 |
-
<li>A: Вы можете обновить 3utools до последней версии с помощью функции "Check for updates" в меню "Настройки" приложения. Вы также можете скачать и установить последнюю версию 3utools с официального сайта или другого проверенного источника. Мы рекомендуем вам всегда использовать последнюю версию 3utools, чтобы получать новые функции, исправления ошибок и улучшения производительности.</li>
|
131 |
-
<li><strong>Q: Как связаться с поддержкой 3utools?</strong></li>
|
132 |
-
<li>A: Вы можете связаться с поддержкой 3utools через официальный сайт или форум 3utools. Вы можете отправить свой вопрос, проблему или отзыв чере�� форму обратной связи на сайте или создать тему на форуме. Вы также можете просмотреть часто задаваемые вопросы, руководства и советы на сайте или форуме, чтобы найти ответы на свои вопросы.</li>
|
133 |
-
<li><strong>Q: Как удалить 3utools с компьютера?</strong></li>
|
134 |
-
<li>A: Вы можете удалить 3utools с вашего компьютера с помощью стандартной функции "Удаление программ" в панели управления Windows. Вы также можете использовать специальную программу для удаления 3utools, которую вы можете скачать с официального сайта 3utools. После удаления 3utools вы можете удалить все оставшиеся файлы и папки, связанные с приложением, с вашего диска.</li>
|
135 |
-
<li><strong>Q: Где найти больше информации о 3utools?</strong></li>
|
136 |
-
<li>A: Вы можете найти больше информации о 3utools на официальном сайте 3utools или на различных сайтах и блогах, посвященных iOS и технологиям. Вы также можете подписаться на каналы 3utools в социальных сетях, таких как Facebook, Twitter или YouTube, чтобы получать новости, обновления и видео о 3utools.</li>
|
137 |
-
</ul>
|
138 |
-
<p>Спасибо за чтение этой статьи! Надеемся, что вы нашли ее полезной и интересной. Если вы хотите скачать 3utools и попробовать его сами, вы можете перейти по ссылке ниже. Удачи!</p>
|
139 |
-
<p><a href="">Скачать 3utools</a></p> 197e85843d<br />
|
140 |
-
<br />
|
141 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Animal Kingdom MOD APK Unlock All Islands and Bridges in this Adventure Game.md
DELETED
@@ -1,84 +0,0 @@
|
|
1 |
-
|
2 |
-
<h1>Animal Kingdom Mod APK: A Fun and Addictive Animal Adventure Game</h1>
|
3 |
-
<p>Do you love animals and adventure games? If yes, then you will surely enjoy Animal Kingdom Mod APK, a game that lets you play with millions of players around the globe in this addictive animal adventure game. Build islands and bridges, raid lands, and collect treasure island coins! Explore the animal island, steal coins, and build your kingdom to become the ultimate raid master!</p>
|
4 |
-
<h2>animal kingdom mod apk</h2><br /><p><b><b>Download Zip</b> > <a href="https://urlin.us/2uSTbX">https://urlin.us/2uSTbX</a></b></p><br /><br />
|
5 |
-
<p>In this article, we will tell you everything you need to know about Animal Kingdom Mod APK, including its features, how to download and install it, how to play it, and some tips and tricks to make the most out of it. So, without further ado, let's get started!</p>
|
6 |
-
<h2>What is Animal Kingdom Mod APK?</h2>
|
7 |
-
<p>Animal Kingdom Mod APK is a modified version of the original Animal Kingdom game, which is available on Google Play Store. The original game is a casual adventure game that lets you create your own animal kingdom by building islands and bridges, collecting coins, and raiding other players' lands. You can also explore different animal islands, such as panda island, lion island, elephant island, and more.</p>
|
8 |
-
<p>However, the original game has some limitations that may affect your gaming experience. For example, you need to spend real money to buy coins and gems, which are the main currencies in the game. You also need to watch ads to get some extra rewards or spin the wheel of fortune. Moreover, you need to unlock new animals and islands by completing certain tasks or reaching certain levels.</p>
|
9 |
-
<p>That's why many players prefer to use Animal Kingdom Mod APK, which is a hacked version of the game that gives you access to unlimited coins and gems, all animals and islands unlocked, no ads, and no root required. With these features, you can enjoy the game without any restrictions or interruptions.</p>
|
10 |
-
<h2>How to download and install Animal Kingdom Mod APK?</h2>
|
11 |
-
<p>Downloading and installing Animal Kingdom Mod APK is very easy and simple. Just follow these steps:</p>
|
12 |
-
<h3>Step 1: Download the APK file from a trusted source</h3>
|
13 |
-
<p>The first thing you need to do is to download the APK file of Animal Kingdom Mod APK from a reliable source. You can use this link to download the latest version of the modded game. Make sure you have enough storage space on your device before downloading the file.</p>
|
14 |
-
<p>animal kingdom mod apk download free<br />
|
15 |
-
animal kingdom mod apk unlimited coins<br />
|
16 |
-
animal kingdom mod apk latest version<br />
|
17 |
-
animal kingdom mod apk android 1<br />
|
18 |
-
animal kingdom mod apk offline<br />
|
19 |
-
animal kingdom mod apk no ads<br />
|
20 |
-
animal kingdom mod apk hack<br />
|
21 |
-
animal kingdom mod apk revdl<br />
|
22 |
-
animal kingdom mod apk rexdl<br />
|
23 |
-
animal kingdom mod apk happymod<br />
|
24 |
-
animal kingdom mod apk 12.8.3<br />
|
25 |
-
animal kingdom mod apk 2023<br />
|
26 |
-
animal kingdom mod apk for pc<br />
|
27 |
-
animal kingdom mod apk for ios<br />
|
28 |
-
animal kingdom mod apk online<br />
|
29 |
-
animal kingdom mod apk obb<br />
|
30 |
-
animal kingdom mod apk data<br />
|
31 |
-
animal kingdom mod apk pure<br />
|
32 |
-
animal kingdom mod apk vip<br />
|
33 |
-
animal kingdom mod apk pro<br />
|
34 |
-
animal kingdom adventure game mod apk<br />
|
35 |
-
animal kingdom battle simulator 3d mod apk<br />
|
36 |
-
animal kingdom craft: build, explore & survive mod apk<br />
|
37 |
-
disney magic kingdoms: build your own magical park - animal kingdom update mod apk<br />
|
38 |
-
jurassic world alive - dinosaur game in the real world - animal kingdom update mod apk<br />
|
39 |
-
zoo 2: animal park - your wonderful zoo and animal game - unlimited money and gems mod apk<br />
|
40 |
-
wildcraft: animal sim online 3d - explore nature as a wild animal - all animals unlocked and free shopping mod apk<br />
|
41 |
-
zoo island: exotic garden - create your own zoo with cute animals - unlimited coins and gems mod apk<br />
|
42 |
-
zoo tycoon: ultimate animal collection - build and manage your dream zoo - full version and crack mod apk<br />
|
43 |
-
planet zoo - the ultimate zoo simulation game - deluxe edition and all dlcs mod apk</p>
|
44 |
-
<h3>Step 2: Enable unknown sources on your device</h3>
|
45 |
-
<p>The next thing you need to do is to enable unknown sources on your device. This is necessary because Android devices do not allow installing apps from sources other than Google Play Store by default. To enable unknown sources, go to Settings > Security > Unknown Sources and toggle it on.</p>
|
46 |
-
<h3>Step 3: Install the APK file and launch the game</h3>
|
47 |
-
<p>The final thing you need to do is to install the APK file on your device. To do this, locate the downloaded file in your file manager and tap on it. Follow the instructions on the screen to complete the installation process. Once done, launch the game from your app drawer and enjoy!</p>
|
48 |
-
<h2>How to play Animal Kingdom Mod APK?</h2>
|
49 |
-
<p>Playing Animal Kingdom Mod APK is very fun and easy. Here are some of the things you can do in the game:</p>
|
50 |
-
<h3>Build your own animal kingdom</h3>
|
51 |
-
<p>One of the main goals of the game is to build your own animal kingdom by creating islands and bridges. You can use coins and gems to buy different animals and islands, such as pandas, lions, elephants, and more. Each animal and island has its own unique features and benefits. For example, pandas can produce more coins, lions can protect your island from raids, and elephants can help you build bridges faster. You can also upgrade your animals and islands to make them more powerful and attractive.</p>
|
52 |
-
<h3>Raid other players' islands</h3>
|
53 |
-
<p>Another fun aspect of the game is to raid other players' islands and steal their coins. You can use a map to find other players' islands and choose which one you want to attack. You can also use a spyglass to see their defenses and plan your strategy. To raid an island, you need to spin a wheel that determines how many moves you have. You can use these moves to break their shields, destroy their buildings, or steal their coins. You can also use special items, such as bombs, hammers, or rockets, to help you in your raids.</p>
|
54 |
-
<h3>Collect treasure island coins</h3>
|
55 |
-
<p>Besides raiding other players' islands, you can also collect treasure island coins by visiting different animal islands. These coins are hidden in chests that you need to open by solving puzzles or playing mini-games. You can use these coins to buy more animals and islands, or to upgrade your existing ones. You can also exchange these coins for gems, which are more valuable and rare.</p>
|
56 |
-
<h3>Explore different animal islands</h3>
|
57 |
-
<p>The game also lets you explore different animal islands that have their own themes and challenges. For example, you can visit panda island, where you can see cute pandas and bamboo forests; lion island, where you can see majestic lions and savannas; elephant island, where you can see giant elephants and waterfalls; and more. Each island has its own quests and rewards that you can complete and claim. You can also interact with other players on these islands and chat with them.</p>
|
58 |
-
<h2>Tips and tricks for Animal Kingdom Mod APK</h2>
|
59 |
-
<p>To make the most out of Animal Kingdom Mod APK, here are some tips and tricks that you should know:</p>
|
60 |
-
<h3>Upgrade your animals and islands regularly</h3>
|
61 |
-
<p>One of the best ways to improve your animal kingdom is to upgrade your animals and islands as often as possible. Upgrading your animals will increase their coin production, defense, and attack power. Upgrading your islands will increase their capacity, beauty, and bonus effects. To upgrade your animals and islands, you need to spend coins or gems, which you can easily get from Animal Kingdom Mod APK.</p>
|
62 |
-
<h3>Spin the wheel of fortune for extra rewards</h3>
|
63 |
-
<p>Another way to get more rewards in the game is to spin the wheel of fortune every day. The wheel of fortune is a feature that gives you a chance to win various prizes, such as coins, gems, items, or even a jackpot. You can spin the wheel once for free every day, or you can use gems to spin it more times. You can also watch ads to get extra spins.</p>
|
64 |
-
<h3>Join a clan and cooperate with other players</h3>
|
65 |
-
<p>A great way to enhance your gaming experience is to join a clan and cooperate with other players. A clan is a group of players who share the same interests and goals in the game. By joining a clan, you can chat with other members, exchange gifts, request help, or participate in clan wars. Clan wars are events where clans compete against each other for glory and rewards.</p>
|
66 |
-
<h3>Use the shield to protect your island from raids</h3>
|
67 |
-
<p>A smart way to protect your island from raids is to use the shield feature. The shield is a feature that prevents other players from attacking your island for a certain period of time. You can get a shield by buying it with gems or by getting it as a reward from the wheel of fortune or clan wars. You can also activate a shield automatically by logging out of the game for more than three hours.</p>
|
68 |
-
<h2>Conclusion</h2>
|
69 |
-
<p>Animal Kingdom Mod APK is a fun and addictive animal adventure game that lets you build your own animal kingdom by creating islands and bridges, collecting coins, and raiding other players' lands. You can also explore different animal islands, such as panda island, lion island, elephant island, and more.</p>
|
70 |
-
<p>With Animal Kingdom Mod APK, you can enjoy the game without any limitations or interruptions. You can get unlimited coins and gems, all animals and islands unlocked, no ads, and no root required. You can use these features to upgrade your animals and islands, spin the wheel of fortune, join a clan, or use the shield.</p <p>If you are looking for a game that combines animals and adventure, then you should definitely try Animal Kingdom Mod APK. It is a game that will keep you entertained and hooked for hours. Download it now and start your animal adventure!</p>
|
71 |
-
<h2>FAQs</h2>
|
72 |
-
<p>Here are some of the frequently asked questions about Animal Kingdom Mod APK:</p>
|
73 |
-
<h3>Q: Is Animal Kingdom Mod APK safe to use?</h3>
|
74 |
-
<p>A: Yes, Animal Kingdom Mod APK is safe to use as long as you download it from a trusted source. However, you should always be careful when installing apps from unknown sources and scan them for viruses or malware before installing them.</p>
|
75 |
-
<h3>Q: Can I play Animal Kingdom Mod APK offline?</h3>
|
76 |
-
<p>A: No, Animal Kingdom Mod APK requires an internet connection to play. You need to connect to the internet to access the game features, such as raiding other players' islands, joining a clan, or spinning the wheel of fortune.</p>
|
77 |
-
<h3>Q: Can I play Animal Kingdom Mod APK with my friends?</h3>
|
78 |
-
<p>A: Yes, you can play Animal Kingdom Mod APK with your friends by joining a clan or inviting them to your island. You can also chat with them, exchange gifts, or cooperate with them in clan wars.</p>
|
79 |
-
<h3>Q: How can I get more coins and gems in Animal Kingdom Mod APK?</h3>
|
80 |
-
<p>A: With Animal Kingdom Mod APK, you can get unlimited coins and gems without spending any real money. You can also get more coins and gems by raiding other players' islands, collecting treasure island coins, spinning the wheel of fortune, or completing quests and rewards.</p>
|
81 |
-
<h3>Q: How can I unlock new animals and islands in Animal Kingdom Mod APK?</h3>
|
82 |
-
<p>A: With Animal Kingdom Mod APK, you can unlock all animals and islands without completing any tasks or reaching any levels. You can also buy new animals and islands with coins or gems, or get them as rewards from the wheel of fortune or clan wars.</p> 197e85843d<br />
|
83 |
-
<br />
|
84 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Bowmasters MOD APK 4.0.1 Unlimited Coins and Fun for Android.md
DELETED
@@ -1,113 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>What is Bowmasters?</h1>
|
3 |
-
<p>Bowmasters is a popular multiplayer game with bowmen that lets you aim and shoot at your enemies in various modes and scenarios. You can choose from over 60 insane characters, each with their own unique weapons and skills, and compete with your friends or other players online. You can also shoot birds or fruits, defeat bosses, earn coins and gems, and unlock new content. The game has stunning graphics, hilarious animations, rag-doll physics, and epic fatalities.</p>
|
4 |
-
<h2>mod apk of bowmasters</h2><br /><p><b><b>DOWNLOAD</b> ✅ <a href="https://jinyurl.com/2uNSJa">https://jinyurl.com/2uNSJa</a></b></p><br /><br />
|
5 |
-
<h2>Why do you need mod apk of Bowmasters?</h2>
|
6 |
-
<p>Mod apk of Bowmasters is a modified version of the original game that gives you access to unlimited resources, features, and options that are not available in the official app. With mod apk of Bowmasters, you can enjoy the game without any restrictions or limitations. Here are some of the reasons why you need mod apk of Bowmasters:</p>
|
7 |
-
<ul>
|
8 |
-
<li>You can get unlimited coins and gems to buy or upgrade anything you want in the game.</li>
|
9 |
-
<li>You can unlock all the characters and weapons without spending real money or watching ads.</li>
|
10 |
-
<li>You can remove all the ads that interrupt your gameplay and annoy you.</li>
|
11 |
-
<li>You can customize your settings and preferences according to your liking.</li>
|
12 |
-
<li>You can have more fun and challenge with the game by using different cheats and hacks.</li>
|
13 |
-
</ul>
|
14 |
-
<h3>How to download and install mod apk of Bowmasters?</h3>
|
15 |
-
<p>Downloading and installing mod apk of Bowmasters is very easy and simple. Just follow these steps:</p>
|
16 |
-
<ol>
|
17 |
-
<li>Go to [text](^4^) and search for "Bowmasters mod apk".</li>
|
18 |
-
<li>Select the latest version of the mod apk file and click on the download button.</li>
|
19 |
-
<li>Wait for the download to finish and then open the file manager on your device.</li>
|
20 |
-
<li>Locate the downloaded file and tap on it to install it.</li>
|
21 |
-
<li>If you see a warning message that says "Install blocked", go to your device settings and enable "Unknown sources".</li>
|
22 |
-
<li>Once the installation is complete, launch the game and enjoy!</li>
|
23 |
-
</ol>
|
24 |
-
<h4>What are the features of mod apk of Bowmasters?</h4>
|
25 |
-
<p>Mod apk of Bowmasters has many features that make it better than the original game. Here is a table that compares the two versions:</p>
|
26 |
-
<table>
|
27 |
-
<tr><th>Feature</th><th>Original</th><th>Modded</th></tr>
|
28 |
-
<tr><td>Coins</td><td>Limited</td><td>Unlimited</td></tr>
|
29 |
-
<tr><td>Gems</td><td>Limited</td><td>Unlimited</td></tr>
|
30 |
-
<tr><td>Characters</td><td>Locked</td><td>Unlocked</td></tr>
|
31 |
-
<tr><td>Weapons</td><td>Locked</td><td>Unlocked</td></tr>
|
32 |
-
<tr><td>Ads</td><td>Yes</td><td>No</td></tr>
|
33 |
-
<tr><td>Cheats</td><td>No</td><td>Yes</td></tr>
|
34 |
-
<tr><td>Hacks</td><td>No</td><td>Yes</td></tr>
|
35 |
-
<tr><td>Customization</td><td>No</td><td>Yes</td></tr>
|
36 |
-
<h2>Tips and tricks for playing Bowmasters with mod apk</h2>
|
37 |
-
<p>Playing Bowmasters with mod apk can be a lot of fun and challenge, but it can also be frustrating if you don't know how to play it well. Here are some tips and tricks that can help you improve your skills and enjoy the game more:</p>
|
38 |
-
<p>bowmasters mod apk unlimited money and gems<br />
|
39 |
-
bowmasters mod apk all characters unlocked<br />
|
40 |
-
bowmasters mod apk latest version download<br />
|
41 |
-
bowmasters mod apk android 1<br />
|
42 |
-
bowmasters mod apk revdl<br />
|
43 |
-
bowmasters mod apk hack<br />
|
44 |
-
bowmasters mod apk no ads<br />
|
45 |
-
bowmasters mod apk offline<br />
|
46 |
-
bowmasters mod apk an1<br />
|
47 |
-
bowmasters mod apk free shopping<br />
|
48 |
-
bowmasters mod apk unlimited everything<br />
|
49 |
-
bowmasters mod apk all weapons unlocked<br />
|
50 |
-
bowmasters mod apk rexdl<br />
|
51 |
-
bowmasters mod apk happymod<br />
|
52 |
-
bowmasters mod apk 4.0.1<br />
|
53 |
-
bowmasters mod apk 2023<br />
|
54 |
-
bowmasters mod apk online<br />
|
55 |
-
bowmasters mod apk unlimited coins and diamonds<br />
|
56 |
-
bowmasters mod apk unlocked premium characters<br />
|
57 |
-
bowmasters mod apk unlimited health<br />
|
58 |
-
bowmasters mod apk 2.14.8<br />
|
59 |
-
bowmasters mod apk ios<br />
|
60 |
-
bowmasters mod apk download for android<br />
|
61 |
-
bowmasters mod apk pure<br />
|
62 |
-
bowmasters mod apk vip unlocked<br />
|
63 |
-
bowmasters mod apk unlimited arrows<br />
|
64 |
-
bowmasters mod apk 3.0.0<br />
|
65 |
-
bowmasters mod apk new version<br />
|
66 |
-
bowmasters mod apk old version<br />
|
67 |
-
bowmasters mod apk unlimited coins and gems download<br />
|
68 |
-
bowmasters mod apk 2.12.7<br />
|
69 |
-
bowmasters mod apk apkpure<br />
|
70 |
-
bowmasters mod apk unlimited money and gems download for android<br />
|
71 |
-
bowmasters mod apk all characters and weapons unlocked<br />
|
72 |
-
bowmasters mod apk mediafıre<br />
|
73 |
-
bowmasters mod apk no root<br />
|
74 |
-
bowmasters mod apk 2.14.7<br />
|
75 |
-
bowmasters mod apk for pc<br />
|
76 |
-
bowmasters mod apk unlimited money and gems 2023 download for android free shopping latest version offline hack no ads all characters unlocked weapons revdl rexdl happymod an1 android 1 vip premium health coins diamonds arrows online ios pure apkpure mediafıre old new 4.0.1 3.0.0 2.14.8 2.14.7 2.12.7 no root for pc</p>
|
77 |
-
<ul>
|
78 |
-
<li>Practice your aim and timing. The key to winning in Bowmasters is to hit your target accurately and quickly. You can practice your aim and timing in the training mode or the single-player mode before you challenge other players online.</li>
|
79 |
-
<li>Learn the strengths and weaknesses of each character and weapon. Each character and weapon in Bowmasters has its own advantages and disadvantages. For example, some characters have more health or damage, while some weapons have more range or speed. You should learn the characteristics of each character and weapon and choose the ones that suit your play style and strategy.</li>
|
80 |
-
<li>Use the environment to your advantage. The game has various maps and scenarios that can affect your gameplay. For example, some maps have obstacles or hazards that can block or damage your shots, while some scenarios have wind or gravity that can alter your trajectory. You should use the environment to your advantage by adjusting your aim and power accordingly.</li>
|
81 |
-
<li>Use cheats and hacks wisely. Mod apk of Bowmasters gives you access to various cheats and hacks that can make the game easier or harder for you. For example, you can use the god mode cheat to make yourself invincible, or the one-hit kill hack to kill your enemies instantly. However, you should use these cheats and hacks wisely, as they can also ruin the fun and challenge of the game. You should also avoid using them in online multiplayer mode, as they can get you banned or reported by other players.</li>
|
82 |
-
</ul>
|
83 |
-
<h3>How to play online multiplayer mode with mod apk?</h3>
|
84 |
-
<p>One of the most exciting features of Bowmasters is the online multiplayer mode, where you can compete with other players from around the world in real-time matches. However, playing online multiplayer mode with mod apk can be tricky, as you might encounter some problems or issues. Here is how to play online multiplayer mode with mod apk:</p>
|
85 |
-
<ol>
|
86 |
-
<li>Make sure you have a stable internet connection. Online multiplayer mode requires a good internet connection to work properly. If you have a slow or unstable internet connection, you might experience lag, disconnects, or errors while playing online multiplayer mode.</li>
|
87 |
-
<li>Make sure you have the latest version of the mod apk. Online multiplayer mode requires that you have the same version of the game as other players. If you have an outdated version of the mod apk, you might not be able to join or create online matches with other players.</li>
|
88 |
-
<li>Make sure you have a compatible device. Online multiplayer mode requires that you have a device that can run the game smoothly and without glitches. If you have a low-end device, you might experience crashes, freezes, or bugs while playing online multiplayer mode.</li>
|
89 |
-
<li>Join or create an online match. To play online multiplayer mode with mod apk, you need to join or create an online match with other players. You can do this by tapping on the "Online" button on the main menu and choosing one of the options: "Quick Match", "Friends", or "Custom". Quick Match will match you with a random player, Friends will let you invite or join your friends who are online, and Custom will let you create or join a custom match with your own settings.</li>
|
90 |
-
<li>Enjoy the game! Once you join or create an online match, you can enjoy the game with other players. You can chat with them, send them emojis, or challenge them to a rematch. You can also earn coins and gems for winning online matches.</li>
|
91 |
-
</ol>
|
92 |
-
<h4>How to avoid bans and errors with mod apk?</h4>
|
93 |
-
<p>Mod apk of Bowmasters is not an official app from the developers of the game. It is a modified app that violates the terms and conditions of the game. Therefore, using mod apk of Bowmasters can cause some bans and errors that can affect your gameplay. Here are some ways to avoid bans and errors with mod apk:</p>
|
94 |
-
<ul>
|
95 |
-
<li>Do not use cheats and hacks in online multiplayer mode. Cheats and hacks are not allowed in online multiplayer mode, as they give you an unfair advantage over other players. If you use cheats and hacks in online multiplayer mode, you might get banned or reported by other players.</li>
|
96 |
-
<li>Do not update the game from the Play Store or App Store. Updating the game from the Play Store or App Store will overwrite the mod apk file and remove all its features and options. If you update the game from the Play Store or App Store, you might get errors or lose your progress.</li>
|
97 |
-
<li>Do not log in with your Google or Facebook account. Logging in with your Google or Facebook account will link your mod apk file to your official account and expose your activity to the developers of the game. If you log in with your Google or Facebook account, you might get banned or lose your data.</li>
|
98 |
-
<li>Do not share your mod apk file with others. Sharing your mod apk file with others will increase the risk of detection and spread of viruses or malware. If you share your mod apk file with others, you might get hacked or infected.</li>
|
99 |
-
</ul>
|
100 |
-
<h2>Conclusion</h2>
|
101 |
-
<p>Bowmasters is a fun and addictive game that you can play with your friends or other players online. However, if you want to have more freedom and fun with the game, you can use mod apk of Bowmasters. Mod apk of Bowmasters is a modified version of the original game that gives you unlimited resources, features, and options that are not available in the official app. With mod apk of Bowmasters, you can unlock all the characters and weapons, remove all the ads, customize your settings, and use cheats and hacks. However, you should also be careful and responsible when using mod apk of Bowmasters, as it can cause some bans and errors that can affect your gameplay. You should follow the steps and tips in this article to download, install, and play mod apk of Bowmasters safely and smoothly.</p>
|
102 |
-
<p>If you are interested in mod apk of Bowmasters, you can download it from [text] and enjoy the game!</p>
|
103 |
-
<h3>FAQs</h3>
|
104 |
-
<p>Here are some frequently asked questions and answers about mod apk of Bowmasters:</p>
|
105 |
-
<ol>
|
106 |
-
<li>Q: Is mod apk of Bowmasters safe to use?<br>A: Mod apk of Bowmasters is safe to use as long as you download it from a trusted source and follow the instructions and precautions in this article. However, you should also be aware that mod apk of Bowmasters is not an official app from the developers of the game and it violates their terms and conditions. Therefore, using mod apk of Bowmasters is at your own risk and discretion.</li>
|
107 |
-
<li>Q: Is mod apk of Bowmasters free to use?<br>A: Mod apk of Bowmasters is free to use and does not require any payment or subscription. However, you might need to watch some ads or complete some surveys to download or access some features of mod apk of Bowmasters.</li>
|
108 |
-
<li>Q: Can I play online multiplayer mode with mod apk of Bowmasters?<br>A: Yes, you can play online multiplayer mode with mod apk of Bowmasters. However, you should avoid using cheats and hacks in online multiplayer mode, as they can get you banned or reported by other players. You should also make sure that you have a stable internet connection, the latest version of the mod apk file, and a compatible device.</li>
|
109 |
-
<li>Q: Can I update mod apk of Bowmasters?<br>A: No, you cannot update mod apk of Bowmasters from the Play Store or App Store. Updating the game from the Play Store or App Store will overwrite the mod apk file and remove all its features and options. If you want to update mod apk of Bowmasters, you need to download the latest version of the mod apk file from [text] and install it again.</li>
|
110 |
-
<li>Q: Can I log in with my Google or Facebook account with mod apk of Bowmasters?<br>A: No, you cannot log in with your Google or Facebook account with mod apk of Bowmasters. Logging in with your Google or Facebook account will link your mod apk file to your official account and expose your activity to the developers of the game. If you want to log in with your Google or Facebook account, you need to use the original game app.</li>
|
111 |
-
</ol></p> 197e85843d<br />
|
112 |
-
<br />
|
113 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Download Avara Avara Nuvvu Song for Free - Listen to Fikos Latest Hit.md
DELETED
@@ -1,137 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>Avara Avara Nuvvu Song Download: How to Enjoy This Romantic Telugu Song</h1>
|
3 |
-
<p>If you are a fan of Telugu songs, you might have heard of <strong>Avara Avara Nuvvu</strong>, a romantic song that has been trending on social media and YouTube. This song is a beautiful expression of love and longing, and it will surely touch your heart. But how can you download this song for free and enjoy it offline? In this article, we will tell you everything you need to know about this song, including its meaning, lyrics, singer, movie, popularity, and how to download it from the best free music download sites.</p>
|
4 |
-
<h2>What is Avara Avara Nuvvu Song?</h2>
|
5 |
-
<p>Avara Avara Nuvvu is a Telugu song that was released in 2021. It is a remake of the Tamil song <em>Evare Nuvvu</em>, which was originally composed by Yuvan Shankar Raja and sung by Harish Raghavendra for the movie <em>Rajubhai</em> in 2007. The Telugu version of the song was sung by Vaagdevi, a young and talented singer who rose to fame with her live performance of the song on YouTube. The song was also featured in the movie <em>777 Charlie</em>, a Kannada-language adventure comedy-drama film starring Rakshit Shetty, Sangeetha Sringeri, and Raj B Shetty.</p>
|
6 |
-
<h2>avara avara nuvvu song download</h2><br /><p><b><b>Download File</b> 🆓 <a href="https://jinyurl.com/2uNRLL">https://jinyurl.com/2uNRLL</a></b></p><br /><br />
|
7 |
-
<h3>The meaning and lyrics of the song</h3>
|
8 |
-
<p>The title of the song <strong>Avara Avara Nuvvu</strong> means <em>Who are you? You are who?</em> in Telugu. It is a rhetorical question that expresses the curiosity and admiration of the singer for their lover. The song is a sweet and poetic declaration of love, where the singer praises their lover's beauty, charm, smile, eyes, and soul. The singer also expresses their desire to be with their lover forever, and how their life has changed after meeting them. The song has a catchy chorus that goes like this:</p>
|
9 |
-
<pre><code>
|
10 |
-
Evare nuvvu nannu kadipavu Nee lokamloki laagavu Kannulu moosi tericheloga Na praanam nuvvayipoyavu </code></pre>
|
11 |
-
<p>This roughly translates to:</p>
|
12 |
-
<p>avara avara nuvvu mp3 song download<br />
|
13 |
-
avara avara nuvvu song lyrics<br />
|
14 |
-
avara avara nuvvu song free download<br />
|
15 |
-
avara avara nuvvu song online streaming<br />
|
16 |
-
avara avara nuvvu song by fiko<br />
|
17 |
-
avara avara nuvvu song wynk music<br />
|
18 |
-
avara avara nuvvu song video<br />
|
19 |
-
avara avara nuvvu song ringtone<br />
|
20 |
-
avara avara nuvvu song status<br />
|
21 |
-
avara avara nuvvu song whatsapp status<br />
|
22 |
-
avara avara nuvvu song meaning<br />
|
23 |
-
avara avara nuvvu song translation<br />
|
24 |
-
avara avara nuvvu song review<br />
|
25 |
-
avara avara nuvvu song reaction<br />
|
26 |
-
avara avara nuvvu song cover<br />
|
27 |
-
avara avara nuvvu song remix<br />
|
28 |
-
avara avara nuvvu song karaoke<br />
|
29 |
-
avara avara nuvvu song instrumental<br />
|
30 |
-
avara avara nuvvu song 320kbps download<br />
|
31 |
-
avara avara nuvvu song 128kbps download<br />
|
32 |
-
how to download avara avara nuvvu song<br />
|
33 |
-
where to download avara avara nuvvu song<br />
|
34 |
-
best site to download avara avara nuvvu song<br />
|
35 |
-
best app to download avara avara nuvvu song<br />
|
36 |
-
best quality to download avara avara nuvvu song<br />
|
37 |
-
listen to avara avara nuvvu song online<br />
|
38 |
-
watch avara avara nuvvu song video online<br />
|
39 |
-
share avara avara nuvvu song with friends<br />
|
40 |
-
enjoy avara avara nuvvu song offline<br />
|
41 |
-
play and download all songs of Avara Avara album<br />
|
42 |
-
Avara Avara album mp3 songs download<br />
|
43 |
-
Avara Avara album songs lyrics<br />
|
44 |
-
Avara Avara album songs free download<br />
|
45 |
-
Avara Avara album songs online streaming<br />
|
46 |
-
Avara Avara album songs by Fiko<br />
|
47 |
-
Avara Avar</p>
|
48 |
-
<pre><code>
|
49 |
-
Who are you? You are who? You took me into your world You closed your eyes and showed me light You became my life </code></pre>
|
50 |
-
<p>You can find the full lyrics of the song in Telugu and English on various websites, such as [JioSaavn](^4^) or [Gaana](^5^).</p>
|
51 |
-
<h3>The singer and movie of the song</h3>
|
52 |
-
<p>The singer of <strong>Avara Avara Nuvvu</strong> is Vaagdevi, a 12-year-old girl from Hyderabad who has a passion for singing. She started singing at the age of four, and has participated in several singing competitions and shows. She became famous after her live performance of <strong>Avara Avara Nuvvu</strong> on YouTube went viral, garnering millions of views and likes. She also received appreciation from celebrities like Rana Daggubati, Rakshit Shetty, Ram Gopal Varma, and others. You can watch her amazing singing on her YouTube channel [Singer Vaagdevi](^8^) or [Sankharavam](^9^).</p>
|
53 |
-
<p>The movie that featured <strong>Avara Avara Nuvvu</strong> is <em>777 Charlie</em>, an upcoming Indian Kannada-language adventure comedy-drama film directed by Kiranraj K. <p>The movie <em>777 Charlie</em> is an upcoming Indian Kannada-language adventure comedy-drama film directed by Kiranraj K. and produced by Paramvah Studios. It stars Charlie, a labrador dog in the titular role, and Rakshit Shetty alongside Sangeetha Sringeri, Raj B. Shetty, Danish Sait, Bobby Simha and Aniruddh Roy. The film follows the journey and bonding between a lonely factory worker and a stray labrador dog. <em>777 Charlie</em> was announced in September 2017. Principal photography took place from June 2018 to October 2021, with delays due to COVID-19 pandemic. The film was shot in various locations across Karnataka, Goa, Gujarat, Rajasthan, Punjab, Himachal Pradesh and Kashmir. <em>777 Charlie</em> had a limited theatrical release on 2 June 2022, and released in cinemas worldwide on 10 June 2022. The film received critical acclaim for its cast performances (particularly Rakshit Shetty and Charlie), writing, emotional weight and direction .</p>
|
54 |
-
<h2>Why is Avara Avara Nuvvu Song Popular?</h2>
|
55 |
-
<p><strong>Avara Avara Nuvvu</strong> song has become one of the most popular songs of 2021, thanks to its catchy tune and melody, and its emotional appeal and message. Here are some of the reasons why this song has won the hearts of millions of listeners:</p>
|
56 |
-
<h3>The catchy tune and melody of the song</h3>
|
57 |
-
<p>The song has a soothing and melodious tune that is easy to hum and sing along. The song is composed by Yuvan Shankar Raja, one of the most renowned music directors in South India, who has given many hit songs in Tamil, Telugu, Kannada, Malayalam and Hindi languages. The song has a blend of classical and modern elements, with the use of instruments like flute, guitar, tabla, keyboard and drums. The song also has a variation in tempo and pitch, which makes it more interesting and dynamic.</p>
|
58 |
-
<h3>The emotional appeal and message of the song</h3>
|
59 |
-
<p>The song has a deep and heartfelt message that resonates with many people who are in love or looking for love. The song expresses the feelings of curiosity, admiration, attraction, affection, devotion and commitment that one feels for their lover. The song also conveys the sense of joy and happiness that one experiences when they find their soulmate. The song also touches upon the themes of destiny, fate and serendipity, as the singer wonders how they met their lover and how their life changed after that.</p>
|
60 |
-
<h2>How to Download Avara Avara Nuvvu Song for Free?</h2>
|
61 |
-
<p>If you want to download <strong>Avara Avara Nuvvu</strong> song for free and enjoy it offline, you have many options to choose from. There are many free music download sites that offer this song in various formats and qualities. However, you should be careful while downloading songs from these sites, as some of them may contain viruses or malware that can harm your device or data. Here are some of the best free music download sites that you can use to download this song safely and legally:</p>
|
62 |
-
<h3>The best free music download sites</h3>
|
63 |
-
<table>
|
64 |
-
<tr>
|
65 |
-
<th>Site Name</th>
|
66 |
-
<th>Features</th>
|
67 |
-
<th>Link</th>
|
68 |
-
</tr>
|
69 |
-
<tr>
|
70 |
-
<td>Naa Songs</td>
|
71 |
-
<td>- Offers Telugu songs in MP3 format<br>- Has a large collection of old and new songs<br>- Allows direct download without registration or subscription<br>- Provides high-quality audio files<br>- Has a user-friendly interface and search function</td>
|
72 |
-
<td>[Naa Songs]</td>
|
73 |
-
</tr>
|
74 |
-
<tr>
|
75 |
-
<td>Sensongsmp3</td>
|
76 |
-
<td>- Offers Telugu songs in MP3 format<br>- Has a wide range of songs from different genres and eras<br>- Allows direct download without registration or subscription<br>- Provides high-quality audio files<br>- Has a simple and easy-to-use interface</td>
|
77 |
-
<td>[Sensongsmp3]</td>
|
78 |
-
</tr>
|
79 |
-
<tr>
|
80 |
-
<td>JioSaavn</td>
|
81 |
-
<td>- Offers Telugu songs in MP3 format<br>- Has a huge library of songs from various languages and regions<br>- Allows direct download without registration or subscription<br>- Provides high-quality audio files<br>- Has a sleek and modern interface with advanced features like playlists, recommendations, lyrics, etc.</td>
|
82 |
-
<td>[JioSaavn]</td>
|
83 |
-
</tr>
|
84 |
-
<tr>
|
85 |
-
<td>Gaana</td>
|
86 |
-
<td>- Offers Telugu songs in MP3 format<br>- Has a massive collection of songs from different artists and albums<br>- Allows direct download without registration or subscription<br>- Provides high-quality audio files<br>- Has a stylish and attractive interface with features like radio, podcasts, videos, etc.</td>
|
87 |
-
<td>[Gaana]</td>
|
88 |
-
</tr>
|
89 |
-
</table>
|
90 |
-
<h3>The steps to download the song from each site</h3>
|
91 |
-
<p>Here are the steps to download <strong>Avara Avara Nuvvu</strong> song from each of the above-mentioned sites:</p>
|
92 |
-
<ol>
|
93 |
-
<li>Naa Songs <ul>
|
94 |
-
<li>Go to [Naa Songs] website and search for <strong>Avara Avara Nuvvu</strong> song in the search box.</li>
|
95 |
-
<li>Select the song from the search results and click on the download button.</li>
|
96 |
-
<li>Choose the quality and format of the song and click on the download link.</li>
|
97 |
-
<li>Save the song to your device and enjoy it offline.</li>
|
98 |
-
</ul>
|
99 |
-
</li>
|
100 |
-
<li>Sensongsmp3 <ul>
|
101 |
-
<li>Go to [Sensongsmp3] website and search for <strong>Avara Avara Nuvvu</strong> song in the search box.</li>
|
102 |
-
<li>Select the song from the search results and click on the download button.</li>
|
103 |
-
<li>Choose the quality and format of the song and click on the download link.</li>
|
104 |
-
<li>Save the song to your device and enjoy it offline.</li>
|
105 |
-
</ul>
|
106 |
-
</li>
|
107 |
-
<li>JioSaavn <ul>
|
108 |
-
<li>Go to [JioSaavn] website and search for <strong>Avara Avara Nuvvu</strong> song in the search box.</li>
|
109 |
-
<li>Select the song from the search results and click on the play button.</li>
|
110 |
-
<li>Click on the three dots icon on the bottom right corner of the player and select download option.</li>
|
111 |
-
<li>Choose the quality and format of the song and click on the download button.</li>
|
112 |
-
<li>Save the song to your device and enjoy it offline.</li>
|
113 |
-
</ul>
|
114 |
-
</li>
|
115 |
-
<li>Gaana <ul>
|
116 |
-
<li>Go to [Gaana] website and search for <strong>Avara Avara Nuvvu</strong> song in the search box.</li>
|
117 |
-
<li>Select the song from the search results and click on the play button.</li>
|
118 |
-
<li>Click on the download icon on the bottom left corner of the player and select download option.</li>
|
119 |
-
<li>Choose the quality and format of the song and click on the download button.</li>
|
120 |
-
<li>Save the song to your device and enjoy it offline.</li>
|
121 |
-
</ul>
|
122 |
-
</li>
|
123 |
-
</ol>
|
124 |
-
<h2>Conclusion</h2>
|
125 |
-
<p><strong>Avara Avara Nuvvu</strong> is a romantic Telugu song that has captivated millions of listeners with its catchy tune, melody, lyrics, and message. It is a remake of a Tamil song sung by Vaagdevi, a young and talented singer who became famous with her live performance of this song on YouTube. The song was also featured in a Kannada movie called <em>777 Charlie</em>, an adventure comedy-drama film starring Rakshit Shetty and a labrador dog. If you want to download this song for free and enjoy it offline, you can use any of the free music download sites mentioned above, such as Naa Songs, Sensongsmp3, JioSaavn, or Gaana. Just follow the simple steps given above and you will be able to listen to this beautiful song anytime, anywhere.</p>
|
126 |
-
<h2>FAQs</h2>
|
127 |
-
<p>Here are some of the frequently asked questions about <strong>Avara Avara Nuvvu</strong> song:</p>
|
128 |
-
<ol>
|
129 |
-
<li><strong>Who wrote Avara Avara Nuvvu song?</strong></br>The original Tamil version of this song was written by Na. Muthukumar, a famous lyricist who passed away in 2016. The Telugu version was written by Ramajogayya Sastry, a popular lyricist who has penned many hit songs in Telugu cinema.</br></br></li>
|
130 |
-
<li><strong>Who composed Avara Avara Nuvvu song?</strong></br>The original Tamil version of this song was composed by Yuvan Shankar Raja, one of the most renowned music directors in South India, who has given many hit songs in Tamil, Telugu, Kannada, Malayalam and Hindi languages. The Telugu version was also composed by him, with some minor changes to suit the Telugu audience.</br></br></li>
|
131 |
-
<li><strong>Who sang Avara Avara Nuvvu song?</strong></br>The original Tamil version of this song was sung by Harish Raghavendra, a well-known playback singer who has sung many songs in Tamil, Telugu, Kannada and Malayalam languages. The Telugu version was sung by Vaagdevi, a 12-year-old girl from Hyderabad who became famous with her live performance of this song on YouTube. She also received appreciation from celebrities like Rana Daggubati, Rakshit Shetty, Ram Gopal Varma, and others.</br></br></li>
|
132 |
-
<li><strong>Which movie featured Avara Avara Nuvvu song?</strong></br>The original Tamil version of this song was featured in the movie <em>Rajubhai</em>, a 2007 Tamil-language action film starring Madhavan and Bhavana. The Telugu version of this song was featured in the movie <em>777 Charlie</em>, a 2022 Kannada-language adventure comedy-drama film starring Rakshit Shetty, Sangeetha Sringeri, Raj B. Shetty, Danish Sait, Bobby Simha and Aniruddh Roy. The film follows the journey and bonding between a lonely factory worker and a stray labrador dog.</br></br></li>
|
133 |
-
<li><strong>How to watch 777 Charlie movie online?</strong></br>If you want to watch <em>777 Charlie</em> movie online, you can use any of the online streaming platforms that offer this movie, such as [Amazon Prime Video], [Netflix], [Hotstar], or [Zee5]. You may need to subscribe or register to these platforms to access the movie. Alternatively, you can also watch the movie on YouTube, where it is available for rent or purchase.</br></br></li>
|
134 |
-
<li><strong>How to get the ringtone of Avara Avara Nuvvu song?</strong></br>If you want to get the ringtone of <strong>Avara Avara Nuvvu</strong> song, you can use any of the free ringtone download sites that offer this song, such as [Zedge], [Prokerala], [Mobcup], or [Ringtone123]. You can also use any of the free ringtone maker apps that allow you to create your own ringtones from any song, such as [Ringdroid], [MP3 Cutter and Ringtone Maker], [Ringtone Maker], or [Audiko]. Just follow the simple steps given on these sites or apps and you will be able to set this song as your ringtone.</li>
|
135 |
-
</ol></p> 401be4b1e0<br />
|
136 |
-
<br />
|
137 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Download Hog Rider Sound Effects for Free - Clash of Clans and Clash Royale.md
DELETED
@@ -1,107 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>How to Download Hog Rider Sound from Clash of Clans</h1>
|
3 |
-
<p>If you are a fan of Clash of Clans, you probably know the iconic sound of the hog rider, the mustachioed barbarian who rides a hog into battle. The hog rider sound is a loud and enthusiastic yell that can be heard whenever you deploy this troop or when you watch a replay of a clan war. But did you know that you can download the hog rider sound and use it for your own purposes? In this article, we will show you how to do that in a few simple steps.</p>
|
4 |
-
<h2>download hog rider sound</h2><br /><p><b><b>DOWNLOAD</b> →→→ <a href="https://jinyurl.com/2uNQmf">https://jinyurl.com/2uNQmf</a></b></p><br /><br />
|
5 |
-
<h2>What is Hog Rider Sound?</h2>
|
6 |
-
<p>Hog rider sound is the name given to the sound effect that plays when the hog rider troop is used in Clash of Clans. It is a voice clip of a man shouting "Hog Riderrrrr!" with a lot of enthusiasm and energy. The voice actor who recorded this sound is unknown, but he has become famous among Clash of Clans players for his memorable performance.</p>
|
7 |
-
<p>Hog rider sound is one of the many sound effects that are part of the game's audio design. Clash of Clans has a rich and diverse soundtrack that includes music, ambient sounds, and sound effects for different troops, buildings, spells, and events. The game's audio design helps create an immersive and engaging experience for the players.</p>
|
8 |
-
<h2>Why would you want to download it?</h2>
|
9 |
-
<p>There are many reasons why you might want to download the hog rider sound from Clash of Clans. Here are some of them:</p>
|
10 |
-
<ul>
|
11 |
-
<li>You love the hog rider and want to show your appreciation for this troop.</li>
|
12 |
-
<li>You want to have some fun and prank your friends or family with the hog rider sound.</li>
|
13 |
-
<li>You want to customize your phone or computer with the hog rider sound as a ringtone, notification sound, or alarm sound.</li>
|
14 |
-
<li>You want to create your own remixes, mashups, or parodies with the hog rider sound.</li>
|
15 |
-
<li>You want to learn more about the game's audio design and how it was created.</li>
|
16 |
-
</ul>
|
17 |
-
<p>Whatever your reason is, downloading the hog rider sound from Clash of Clans is not difficult. You just need to follow some simple steps that we will explain below.</p>
|
18 |
-
<h2>How to find the sound files in the game directory</h2>
|
19 |
-
<p>The first step to download the hog rider sound from Clash of Clans is to find the sound files in the game directory. The game directory is the folder where the game's data and files are stored on your device. Depending on what device you are using, the game directory may be located in different places.</p>
|
20 |
-
<p>download hog rider sound effect<br />
|
21 |
-
download hog rider sound mp3<br />
|
22 |
-
download hog rider sound clip<br />
|
23 |
-
download hog rider sound free<br />
|
24 |
-
download hog rider sound meme<br />
|
25 |
-
download hog rider sound voicy<br />
|
26 |
-
download hog rider sound youtube<br />
|
27 |
-
download hog rider sound tuna<br />
|
28 |
-
download hog rider sound earrape<br />
|
29 |
-
download hog rider sound clash of clans<br />
|
30 |
-
download hog rider sound button<br />
|
31 |
-
download hog rider sound board<br />
|
32 |
-
download hog rider sound ringtone<br />
|
33 |
-
download hog rider sound remix<br />
|
34 |
-
download hog rider sound online<br />
|
35 |
-
download hog rider sound wav<br />
|
36 |
-
download hog rider sound file<br />
|
37 |
-
download hog rider sound generator<br />
|
38 |
-
download hog rider sound app<br />
|
39 |
-
download hog rider sound android<br />
|
40 |
-
download hog rider sound ios<br />
|
41 |
-
download hog rider sound iphone<br />
|
42 |
-
download hog rider sound video<br />
|
43 |
-
download hog rider sound tiktok<br />
|
44 |
-
download hog rider sound reddit<br />
|
45 |
-
download hog rider sound discord<br />
|
46 |
-
download hog rider sound voicemod<br />
|
47 |
-
download hog rider sound prank<br />
|
48 |
-
download hog rider sound funny<br />
|
49 |
-
download hog rider sound loud<br />
|
50 |
-
download hog rider sound original<br />
|
51 |
-
download hog rider sound best<br />
|
52 |
-
download hog rider sound quality<br />
|
53 |
-
download hog rider sound high definition<br />
|
54 |
-
download hog rider sound hd<br />
|
55 |
-
download hog rider sound 4k<br />
|
56 |
-
download hog rider sound 1080p<br />
|
57 |
-
download hog rider sound 720p<br />
|
58 |
-
download hog rider sound 480p<br />
|
59 |
-
download hog rider sound 360p<br />
|
60 |
-
download hog rider sound 240p<br />
|
61 |
-
download hog rider sound 144p<br />
|
62 |
-
download hog rider sound zip<br />
|
63 |
-
download hog rider sound rar<br />
|
64 |
-
download hog rider sound torrent<br />
|
65 |
-
download hog rider sound magnet link<br />
|
66 |
-
download hog rider sound mediafire</p>
|
67 |
-
<p>If you are playing Clash of Clans on an Android device, you can use a file manager app to browse through your device's storage and find the game directory. The game directory is usually located in: <code>/storage/emulated/0/Android/data/com.supercell.clashofclans/files</code>. In this folder, you will see several subfolders with names like <code>assets</code>, <code>cache</code>, <code>res</code>, and <code>update</code>. The sound files are stored in the <code>assets</code> folder.</p>
|
68 |
-
<p>If you are playing Clash of Clans on an iOS device, you will need to use a computer and a software tool like iFunBox or iExplorer to access your device's file system and find the game directory. The game directory is usually located in: <code>/var/mobile/Containers/Data/Application/[random string]/Documents</code>. In this folder, you will see several subfolders with names like <code >assets</code>, <code>cache</code>, <code>res</code>, and <code>update</code>. The sound files are stored in the <code>assets</code> folder.</p>
|
69 |
-
<h2>How to extract the sound files from .pck or .bnk archives</h2>
|
70 |
-
<p>The next step to download the hog rider sound from Clash of Clans is to extract the sound files from the .pck or .bnk archives. These are compressed files that contain the game's sound effects, music, and voice clips. You will need a software tool like Wwise Unpacker or Ravioli Game Tools to open these files and extract the sound files inside them.</p>
|
71 |
-
<p>The .pck or .bnk files are located in the <code>assets/sounds</code> subfolder of the game directory. You will see several files with names like <code>game_sfx.pck</code>, <code>game_music.bnk</code>, <code>game_voices_en.bnk</code>, and so on. The hog rider sound is part of the <code>game_voices_en.bnk</code> file, which contains all the English voice clips for the game.</p>
|
72 |
-
<p>To extract the sound files from the .pck or .bnk files, you will need to follow these steps:</p>
|
73 |
-
<ol>
|
74 |
-
<li>Download and install Wwise Unpacker or Ravioli Game Tools on your computer.</li>
|
75 |
-
<li>Copy the .pck or .bnk files from your device to your computer.</li>
|
76 |
-
<li>Run Wwise Unpacker or Ravioli Game Tools and select the .pck or .bnk file you want to open.</li>
|
77 |
-
<li>Choose a destination folder where you want to save the extracted sound files.</li>
|
78 |
-
<li>Click on Extract or Unpack and wait for the process to finish.</li>
|
79 |
-
<li>Browse through the extracted sound files and look for the hog rider sound. It is usually named something like <code>sfx_vo_hog_rider_01.wav</code>.</li>
|
80 |
-
</ol>
|
81 |
-
<p>Congratulations, you have successfully extracted the hog rider sound from Clash of Clans!</p>
|
82 |
-
<h2>How to convert the sound files to .mp3 or .wav format</h2>
|
83 |
-
<p>The final step to download the hog rider sound from Clash of Clans is to convert the sound files to .mp3 or .wav format. This is because the extracted sound files are usually in a format that is not compatible with most media players or devices. You will need a software tool like Audacity or VLC Media Player to convert the sound files to a more common format.</p>
|
84 |
-
<p>To convert the sound files to .mp3 or .wav format, you will need to follow these steps:</p>
|
85 |
-
<ol>
|
86 |
-
<li>Download and install Audacity or VLC Media Player on your computer.</li>
|
87 |
-
<li>Open Audacity or VLC Media Player and drag and drop the hog rider sound file into it.</li>
|
88 |
-
<li>Select File > Export > Export as MP3 or Export as WAV and choose a destination folder where you want to save the converted file.</li>
|
89 |
-
<li>Click on Save and wait for the process to finish.</li>
|
90 |
-
</ol>
|
91 |
-
<p>Congratulations, you have successfully converted the hog rider sound from Clash of Clans!</p>
|
92 |
-
<h2>Tips and tricks for using hog rider sound</h2>
|
93 |
-
<p>Now that you have downloaded and converted the hog rider sound from Clash of Clans, you can use it for various purposes. Here are some tips and tricks for using hog rider sound:</p>
|
94 |
-
<h3>How to use hog rider sound as a ringtone or notification sound</h3>
|
95 |
-
<p>If you want to use hog rider sound as a ringtone or notification sound for your phone, you will need to copy the converted file to your device's storage and set it as your default sound. Depending on what device you are using, this may vary slightly, but here are some general steps:</p>
|
96 |
-
<ol>
|
97 |
-
<li>Connect your device to your computer via USB cable or Bluetooth.</li>
|
98 |
-
<li>Browse through your device's storage and find a folder named <code>Ringtones</code> or <code>Notifications</code>.</li>
|
99 |
-
<li>Copy and paste the hog rider sound file into this folder.</li>
|
100 |
-
<li>Disconnect your device from your computer.</li>
|
101 |
-
<li>Go to your device's settings and select Sound > Ringtone or Notification Sound.</li>
|
102 |
-
<li>Browse through the list of available sounds and select hog rider sound as your default sound.</li>
|
103 |
-
</ol>
|
104 |
-
<p>Congratulations, you have successfully set hog rider sound as your ringtone or notification sound!</p>
|
105 |
-
<h3></h3></p> 197e85843d<br />
|
106 |
-
<br />
|
107 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/1phancelerku/anime-remove-background/Download Plague Inc Evolved APK Premium and Unleash Your Inner Evil Genius.md
DELETED
@@ -1,114 +0,0 @@
|
|
1 |
-
<br />
|
2 |
-
<h1>Plague Inc Evolved APK Premium: A Strategy Game That Challenges You to Infect the World</h1>
|
3 |
-
<p>If you are looking for a strategy game that is both fun and educational, you might want to check out Plague Inc Evolved APK Premium. This is a game that lets you create and evolve a deadly disease that can wipe out humanity. Sounds grim, right? But don't worry, it's all in good fun. 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 some FAQs.</p>
|
4 |
-
<h2>plague inc evolved apk premium</h2><br /><p><b><b>DOWNLOAD</b> · <a href="https://jinyurl.com/2uNJSc">https://jinyurl.com/2uNJSc</a></b></p><br /><br />
|
5 |
-
<h2>What is Plague Inc Evolved APK Premium?</h2>
|
6 |
-
<p>Plague Inc Evolved APK Premium is a modified version of Plague Inc Evolved, which is a remake of the widely acclaimed mobile game Plague Inc. The game was developed by Ndemic Creations, a UK-based independent studio. The game was released for PC and consoles in 2016, and has received many positive reviews from critics and players alike.</p>
|
7 |
-
<h3>A remake of the popular mobile game Plague Inc</h3>
|
8 |
-
<p>The original Plague Inc was launched in 2012 for iOS and Android devices. It was a unique mix of high strategy and realistic simulation that challenged players to infect the world with a pathogen. The game was praised for its innovative gameplay, its use of real-world data and events, and its educational value. The game was so realistic that the developer was invited to speak at the CDC about the infection models in the game.</p>
|
9 |
-
<h3>A game that simulates a global pandemic with realistic scenarios and data</h3>
|
10 |
-
<p>Plague Inc Evolved takes the original gameplay to the next level by adding new features and improvements. The game uses an epidemic model with a complex and realistic set of variables to simulate the spread and severity of the plague. The game also incorporates real-world data and events, such as climate change, population density, health care systems, political stability, etc. The game also features 23 unique scenarios that create further challenges for your pandemic, such as a new strain of swine flu, a world in ice age, or a zombie apocalypse.</p>
|
11 |
-
<h3>A game that offers various features and modes for different challenges and experiences</h3>
|
12 |
-
<p>Plague Inc Evolved also offers more variety and replayability than the original game. The game has 10 different disease types that require different strategies to master, such as bacteria, virus, fungus, parasite, prion, nano-virus, bio-weapon, neurax worm, necroa virus, and simian flu. The game also has three different game modes that offer different objectives and gameplay styles, such as the main mode, the speed run mode, and the co-op mode. The game also supports custom scenarios that are created by other players or yourself, and can be shared online. The game also has a competitive multiplayer mode that allows you to play against other players online, and see who can infect the world faster or better.</p>
|
13 |
-
<h2>How to download and install Plague Inc Evolved APK Premium?</h2>
|
14 |
-
<p>Plague Inc Evolved APK Premium is a modified version of the game that offers some extra features and benefits, such as unlimited DNA points, unlocked genes and cheats, and no ads. However, this version is not available on the official Google Play Store or the developer's website. Therefore, you will need to download and install it from a third-party source, which may involve some risks and challenges. Here are the steps and tips to download and install Plague Inc Evolved APK Premium on your Android device.</p>
|
15 |
-
<h3>The requirements and steps to download and install the game on your Android device</h3>
|
16 |
-
<p>To download and install Plague Inc Evolved APK Premium, you will need an Android device that runs on Android 4.1 or higher, and has at least 1 GB of RAM and 500 MB of free storage space. You will also need a stable internet connection to download the game files. Here are the steps to follow:</p>
|
17 |
-
<ol>
|
18 |
-
<li>Go to a reliable website that offers the Plague Inc Evolved APK Premium file, such as [APKPure] or [APKMody].</li>
|
19 |
-
<li>Download the APK file and the OBB file (if required) to your device.</li>
|
20 |
-
<li>Go to your device's settings and enable the installation of apps from unknown sources.</li>
|
21 |
-
<li>Locate the downloaded files in your device's file manager and tap on them to install them.</li>
|
22 |
-
<li>If you downloaded the OBB file, you will need to copy it to the Android/OBB folder in your device's internal storage.</li>
|
23 |
-
<li>Launch the game and enjoy!</li>
|
24 |
-
</ol>
|
25 |
-
<h3>The benefits and risks of downloading and installing the game from unofficial sources</h3>
|
26 |
-
<p>Downloading and installing Plague Inc Evolved APK Premium from unofficial sources may have some benefits, such as getting access to premium features for free, saving money, and avoiding ads. However, it may also have some risks, such as getting infected with malware, violating the developer's terms of service, losing your progress or data, or facing legal issues. Therefore, you should be careful and cautious when downloading and installing the game from unofficial sources, and do it at your own risk.</p>
|
27 |
-
<h3>The alternatives and precautions to enjoy the game safely and legally</h3>
|
28 |
-
<p>If you want to enjoy Plague Inc Evolved without risking your device or breaking any rules, you have some alternatives and precautions that you can take. For example, you can:</p>
|
29 |
-
<p>plague inc evolved mod apk all unlocked<br />
|
30 |
-
plague inc evolved apk download latest version<br />
|
31 |
-
plague inc evolved android full version free<br />
|
32 |
-
plague inc evolved premium features unlocked<br />
|
33 |
-
plague inc evolved apk no ads<br />
|
34 |
-
plague inc evolved simulation game mod apk<br />
|
35 |
-
plague inc evolved strategy game apk<br />
|
36 |
-
plague inc evolved realistic simulation mod apk<br />
|
37 |
-
plague inc evolved apk unlimited dna<br />
|
38 |
-
plague inc evolved full game unlocked apk<br />
|
39 |
-
plague inc evolved free download for android<br />
|
40 |
-
plague inc evolved mod apk everything unlocked<br />
|
41 |
-
plague inc evolved apk latest update<br />
|
42 |
-
plague inc evolved premium apk 2023<br />
|
43 |
-
plague inc evolved hack mod apk download<br />
|
44 |
-
plague inc evolved best simulation game apk<br />
|
45 |
-
plague inc evolved apk offline mode<br />
|
46 |
-
plague inc evolved mod apk all scenarios unlocked<br />
|
47 |
-
plague inc evolved apk no root required<br />
|
48 |
-
plague inc evolved premium version download<br />
|
49 |
-
plague inc evolved mod apk free shopping<br />
|
50 |
-
plague inc evolved apk high graphics<br />
|
51 |
-
plague inc evolved realistic game mod apk<br />
|
52 |
-
plague inc evolved strategy game mod apk<br />
|
53 |
-
plague inc evolved apk no virus<br />
|
54 |
-
plague inc evolved mod apk all cheats unlocked<br />
|
55 |
-
plague inc evolved apk easy installation<br />
|
56 |
-
plague inc evolved premium game mod apk<br />
|
57 |
-
plague inc evolved hack apk unlimited everything<br />
|
58 |
-
plague inc evolved full version free download apk<br />
|
59 |
-
plague inc evolved mod apk all plagues unlocked<br />
|
60 |
-
plague inc evolved apk no verification needed<br />
|
61 |
-
plague inc evolved premium simulation game apk<br />
|
62 |
-
plague inc evolved modded game download for android<br />
|
63 |
-
plague inc evolved apk fast download link<br />
|
64 |
-
plague inc evolved mod apk all expansions unlocked<br />
|
65 |
-
plague inc evolved apk no survey required<br />
|
66 |
-
plague inc evolved premium strategy game mod apk<br />
|
67 |
-
plague inc evolved hacked game free download for android<br />
|
68 |
-
plague inc evolved apk low storage space required</p>
|
69 |
-
<ul>
|
70 |
-
<li>Buy the official version of the game from the Google Play Store or the developer's website for a reasonable price.</li>
|
71 |
-
<li>Use a VPN service or a proxy server to hide your IP address and location when downloading or playing the game.</li>
|
72 |
-
<li>Use an antivirus software or a firewall to protect your device from malware or viruses.</li>
|
73 |
-
<li>Backup your data regularly to avoid losing your progress or data.</li>
|
74 |
-
<li>Support the developer by rating, reviewing, or sharing the game with others.</li>
|
75 |
-
</ul>
|
76 |
-
<h2>How to play Plague Inc Evolved APK Premium?</h2>
|
77 |
-
<p>Plague Inc Evolved APK Premium is a strategy game that requires you to create and evolve a pathogen that can infect and kill all humans on Earth. The game is challenging but also rewarding, as you learn about different diseases, scenarios, and strategies. Here are some basic tips on how to play Plague Inc Evolved APK Premium.</p>
|
78 |
-
<h3>The basic gameplay and mechanics of creating and evolving a pathogen</h3>
|
79 |
-
<p>The basic gameplay of Plague Inc Evolved APK Premium is similar to the original game. You start by choosing a disease type, a scenario, and a difficulty level. Then, you choose a country to start your infection. You will see a world map with different countries, regions, climates, populations, etc. You will also see a dashboard with various information and options, such as your disease name, type, symptoms, transmissions, abilities, cure, DNA points, infection and death rates, news headlines, etc. Your goal is to evolve your pathogen by spending DNA points on different traits that can make it more infectious, lethal, or resistant. You can also use special abilities or cheats to influence the game. You have to balance your strategy between spreading your disease and avoiding detection or cure. You win the game when you infect and kill all humans on Earth. You lose the game if your disease is eradicated or if there are no healthy people left to infect.</p>
|
80 |
-
<h3>The different disease types, scenarios, and difficulty levels to choose from</h3>
|
81 |
-
<p>Plague Inc Evolved APK Premium offers a lot of variety and customization for your gameplay. You can choose from 10 different disease types that have different characteristics and challenges, such as bacteria, virus, fungus, parasite, prion, nano-virus, bio-weapon, neurax worm, necroa virus, and simian flu. You can also choose from 23 different scenarios that create different situations and objectives for your pandemic, such as a new strain of swine flu, a world in ice age, or a zombie apocalypse. You can also choose from 4 different difficulty levels that affect the game's realism and difficulty, such as casual, normal, brutal, or mega-brutal.</p>
|
82 |
-
<h3>The tips and tricks to master the game and achieve the best outcomes</h3>
|
83 |
-
<p>Plague Inc Evolved APK Premium is a game that requires a lot of strategy and planning. Here are some general tips and tricks that can help you master the game and achieve the best outcomes:</p>
|
84 |
-
<ul>
|
85 |
-
<li>Do some research on the disease type, scenario, and difficulty level you are playing. Learn about their strengths, weaknesses, and special features.</li>
|
86 |
-
<li>Choose a suitable starting country for your disease. Consider factors such as population density, climate, wealth, health care system, etc.</li>
|
87 |
-
<li>Evolve your disease according to your strategy. Focus on transmission traits to increase your infectivity, symptom traits to increase your lethality or severity, and ability traits to increase your resistance or adaptability.</li>
|
88 |
-
<li>Monitor the world map and the dashboard closely. Pay attention to the infection and death rates, the cure progress, the news headlines, the country information, etc.</li>
|
89 |
-
<li>Use your DNA points wisely. Save them for important traits or abilities, or spend them on devolving unwanted traits or abilities.</li>
|
90 |
-
<li>Use your special abilities or cheats strategically. Use them to speed up your infection or kill rate, to slow down the cure progress, to trigger events or mutations, etc.</li>
|
91 |
-
<li>Be flexible and adaptable. Adjust your strategy according to the changing situations and challenges.</li>
|
92 |
-
</ul>
|
93 |
-
<h2>Conclusion</h2>
|
94 |
-
<p>Plague Inc Evolved APK Premium is a strategy game that challenges you to infect the world with a deadly disease. It is a remake of the popular mobile game Plague Inc that adds new features and improvements. It is a game that simulates a global pandemic with realistic scenarios and data. It is a game that offers various features and modes for different challenges and experiences. It is a game that is fun and educational at the same time.</p>
|
95 |
-
<p>If you are interested in playing this game, you can download and install it from unofficial sources at your own risk. Alternatively, you can buy the official version of the game from the Google Play Store or the developer's website for a reasonable price. Either way, you will need an Android device that meets the requirements and a stable internet connection to play the game.</p>
|
96 |
-
<p>We hope this article has given you some useful information and tips about Plague Inc Evolved APK Premium. If you have any questions or comments about this game or this article, please feel free to leave them below. We would love to hear from you and help you out. Thank you for reading and happy gaming!</p>
|
97 |
-
<h2>FAQs</h2>
|
98 |
-
<h3>What are the differences between Plague Inc Evolved APK Premium and Plague Inc Evolved on Steam?</h3>
|
99 |
-
<p>Plague Inc Evolved APK Premium is a modified version of the game that offers some extra features and benefits, such as unlimited DNA points, unlocked genes and cheats, and no ads. Plague Inc Evolved on Steam is the official version of the game that requires you to pay a certain amount of money to buy it. It also offers some features that are not available on the mobile version, such as the scenario creator, the custom scenarios, and the multiplayer mode.</p>
|
100 |
-
<h3>Is Plague Inc Evolved APK Premium safe to download and play?</h3>
|
101 |
-
<p>Plague Inc Evolved APK Premium is not available on the official Google Play Store or the developer's website. Therefore, you will need to download and install it from a third-party source, which may involve some risks and challenges. You may get infected with malware, violate the developer's terms of service, lose your progress or data, or face legal issues. Therefore, you should be careful and cautious when downloading and installing the game from unofficial sources, and do it at your own risk.</p>
|
102 |
-
<h3>Can I play Plague Inc Evolved APK Premium offline?</h3>
|
103 |
-
<p>Plague Inc Evolved APK Premium is a game that requires an internet connection to download and install the game files. However, once you have installed the game, you can play it offline without any problems. You can enjoy the main mode, the speed run mode, and the co-op mode without an internet connection. However, you will need an internet connection to play the multiplayer mode, to access the custom scenarios, or to update the game.</p>
|
104 |
-
<h3>Can I play Plague Inc Evolved APK Premium with friends?</h3>
|
105 |
-
<p>Plague Inc Evolved APK Premium is a game that supports multiplayer mode that allows you to play against other players online. You can choose to play as a disease or as a human in a competitive or cooperative mode. You can also create or join a private lobby with your friends and see who can infect the world faster or better. However, you will need an internet connection and a valid account to play the multiplayer mode.</p>
|
106 |
-
<h3>Where can I find more information and resources about Plague Inc Evolved APK Premium?</h3>
|
107 |
-
<p>If you want to learn more about Plague Inc Evolved APK Premium, you can visit some of these websites that provide more information and resources about the game:</p>
|
108 |
-
<ul>
|
109 |
-
<li>[Plague Inc Wiki] - A wiki that contains detailed information about the game's features, mechanics, diseases, scenarios, etc.</li>
|
110 |
-
<li>[Plague Inc Forum] - A forum where you can interact with other players, share your strategies, tips, feedback, suggestions, etc.</li>
|
111 |
-
<li>[Plague Inc YouTube Channel] - A YouTube channel where you can watch videos of gameplay, tutorials, trailers, updates, etc.</li>
|
112 |
-
</ul></p> 197e85843d<br />
|
113 |
-
<br />
|
114 |
-
<br />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/2023Liu2023/bingo/src/components/welcome-screen.tsx
DELETED
@@ -1,34 +0,0 @@
|
|
1 |
-
import { useBing } from '@/lib/hooks/use-bing'
|
2 |
-
|
3 |
-
const exampleMessages = [
|
4 |
-
{
|
5 |
-
heading: '🧐 提出复杂问题',
|
6 |
-
message: `我可以为我挑剔的只吃橙色食物的孩子做什么饭?`
|
7 |
-
},
|
8 |
-
{
|
9 |
-
heading: '🙌 获取更好的答案',
|
10 |
-
message: '销量最高的 3 种宠物吸尘器有哪些优点和缺点?'
|
11 |
-
},
|
12 |
-
{
|
13 |
-
heading: '🎨 获得创意灵感',
|
14 |
-
message: `以海盗的口吻写一首关于外太空鳄鱼的俳句`
|
15 |
-
}
|
16 |
-
]
|
17 |
-
|
18 |
-
export function WelcomeScreen({ setInput }: Pick<ReturnType<typeof useBing>, 'setInput'>) {
|
19 |
-
return (
|
20 |
-
<div className="welcome-container flex">
|
21 |
-
{exampleMessages.map(example => (
|
22 |
-
<button key={example.heading} className="welcome-item w-4/5 sm:w-[240px]" type="button" onClick={() => setInput(example.message)}>
|
23 |
-
<div className="item-title">{example.heading}</div>
|
24 |
-
<div className="item-content">
|
25 |
-
<div className="item-body">
|
26 |
-
<div className="item-header"></div>
|
27 |
-
<div>“{example.message}”</div>
|
28 |
-
</div>
|
29 |
-
</div>
|
30 |
-
</button>
|
31 |
-
))}
|
32 |
-
</div>
|
33 |
-
)
|
34 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/232labs/VToonify/vtoonify/model/raft/core/update.py
DELETED
@@ -1,139 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn as nn
|
3 |
-
import torch.nn.functional as F
|
4 |
-
|
5 |
-
|
6 |
-
class FlowHead(nn.Module):
|
7 |
-
def __init__(self, input_dim=128, hidden_dim=256):
|
8 |
-
super(FlowHead, self).__init__()
|
9 |
-
self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1)
|
10 |
-
self.conv2 = nn.Conv2d(hidden_dim, 2, 3, padding=1)
|
11 |
-
self.relu = nn.ReLU(inplace=True)
|
12 |
-
|
13 |
-
def forward(self, x):
|
14 |
-
return self.conv2(self.relu(self.conv1(x)))
|
15 |
-
|
16 |
-
class ConvGRU(nn.Module):
|
17 |
-
def __init__(self, hidden_dim=128, input_dim=192+128):
|
18 |
-
super(ConvGRU, self).__init__()
|
19 |
-
self.convz = nn.Conv2d(hidden_dim+input_dim, hidden_dim, 3, padding=1)
|
20 |
-
self.convr = nn.Conv2d(hidden_dim+input_dim, hidden_dim, 3, padding=1)
|
21 |
-
self.convq = nn.Conv2d(hidden_dim+input_dim, hidden_dim, 3, padding=1)
|
22 |
-
|
23 |
-
def forward(self, h, x):
|
24 |
-
hx = torch.cat([h, x], dim=1)
|
25 |
-
|
26 |
-
z = torch.sigmoid(self.convz(hx))
|
27 |
-
r = torch.sigmoid(self.convr(hx))
|
28 |
-
q = torch.tanh(self.convq(torch.cat([r*h, x], dim=1)))
|
29 |
-
|
30 |
-
h = (1-z) * h + z * q
|
31 |
-
return h
|
32 |
-
|
33 |
-
class SepConvGRU(nn.Module):
|
34 |
-
def __init__(self, hidden_dim=128, input_dim=192+128):
|
35 |
-
super(SepConvGRU, self).__init__()
|
36 |
-
self.convz1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2))
|
37 |
-
self.convr1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2))
|
38 |
-
self.convq1 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (1,5), padding=(0,2))
|
39 |
-
|
40 |
-
self.convz2 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (5,1), padding=(2,0))
|
41 |
-
self.convr2 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (5,1), padding=(2,0))
|
42 |
-
self.convq2 = nn.Conv2d(hidden_dim+input_dim, hidden_dim, (5,1), padding=(2,0))
|
43 |
-
|
44 |
-
|
45 |
-
def forward(self, h, x):
|
46 |
-
# horizontal
|
47 |
-
hx = torch.cat([h, x], dim=1)
|
48 |
-
z = torch.sigmoid(self.convz1(hx))
|
49 |
-
r = torch.sigmoid(self.convr1(hx))
|
50 |
-
q = torch.tanh(self.convq1(torch.cat([r*h, x], dim=1)))
|
51 |
-
h = (1-z) * h + z * q
|
52 |
-
|
53 |
-
# vertical
|
54 |
-
hx = torch.cat([h, x], dim=1)
|
55 |
-
z = torch.sigmoid(self.convz2(hx))
|
56 |
-
r = torch.sigmoid(self.convr2(hx))
|
57 |
-
q = torch.tanh(self.convq2(torch.cat([r*h, x], dim=1)))
|
58 |
-
h = (1-z) * h + z * q
|
59 |
-
|
60 |
-
return h
|
61 |
-
|
62 |
-
class SmallMotionEncoder(nn.Module):
|
63 |
-
def __init__(self, args):
|
64 |
-
super(SmallMotionEncoder, self).__init__()
|
65 |
-
cor_planes = args.corr_levels * (2*args.corr_radius + 1)**2
|
66 |
-
self.convc1 = nn.Conv2d(cor_planes, 96, 1, padding=0)
|
67 |
-
self.convf1 = nn.Conv2d(2, 64, 7, padding=3)
|
68 |
-
self.convf2 = nn.Conv2d(64, 32, 3, padding=1)
|
69 |
-
self.conv = nn.Conv2d(128, 80, 3, padding=1)
|
70 |
-
|
71 |
-
def forward(self, flow, corr):
|
72 |
-
cor = F.relu(self.convc1(corr))
|
73 |
-
flo = F.relu(self.convf1(flow))
|
74 |
-
flo = F.relu(self.convf2(flo))
|
75 |
-
cor_flo = torch.cat([cor, flo], dim=1)
|
76 |
-
out = F.relu(self.conv(cor_flo))
|
77 |
-
return torch.cat([out, flow], dim=1)
|
78 |
-
|
79 |
-
class BasicMotionEncoder(nn.Module):
|
80 |
-
def __init__(self, args):
|
81 |
-
super(BasicMotionEncoder, self).__init__()
|
82 |
-
cor_planes = args.corr_levels * (2*args.corr_radius + 1)**2
|
83 |
-
self.convc1 = nn.Conv2d(cor_planes, 256, 1, padding=0)
|
84 |
-
self.convc2 = nn.Conv2d(256, 192, 3, padding=1)
|
85 |
-
self.convf1 = nn.Conv2d(2, 128, 7, padding=3)
|
86 |
-
self.convf2 = nn.Conv2d(128, 64, 3, padding=1)
|
87 |
-
self.conv = nn.Conv2d(64+192, 128-2, 3, padding=1)
|
88 |
-
|
89 |
-
def forward(self, flow, corr):
|
90 |
-
cor = F.relu(self.convc1(corr))
|
91 |
-
cor = F.relu(self.convc2(cor))
|
92 |
-
flo = F.relu(self.convf1(flow))
|
93 |
-
flo = F.relu(self.convf2(flo))
|
94 |
-
|
95 |
-
cor_flo = torch.cat([cor, flo], dim=1)
|
96 |
-
out = F.relu(self.conv(cor_flo))
|
97 |
-
return torch.cat([out, flow], dim=1)
|
98 |
-
|
99 |
-
class SmallUpdateBlock(nn.Module):
|
100 |
-
def __init__(self, args, hidden_dim=96):
|
101 |
-
super(SmallUpdateBlock, self).__init__()
|
102 |
-
self.encoder = SmallMotionEncoder(args)
|
103 |
-
self.gru = ConvGRU(hidden_dim=hidden_dim, input_dim=82+64)
|
104 |
-
self.flow_head = FlowHead(hidden_dim, hidden_dim=128)
|
105 |
-
|
106 |
-
def forward(self, net, inp, corr, flow):
|
107 |
-
motion_features = self.encoder(flow, corr)
|
108 |
-
inp = torch.cat([inp, motion_features], dim=1)
|
109 |
-
net = self.gru(net, inp)
|
110 |
-
delta_flow = self.flow_head(net)
|
111 |
-
|
112 |
-
return net, None, delta_flow
|
113 |
-
|
114 |
-
class BasicUpdateBlock(nn.Module):
|
115 |
-
def __init__(self, args, hidden_dim=128, input_dim=128):
|
116 |
-
super(BasicUpdateBlock, self).__init__()
|
117 |
-
self.args = args
|
118 |
-
self.encoder = BasicMotionEncoder(args)
|
119 |
-
self.gru = SepConvGRU(hidden_dim=hidden_dim, input_dim=128+hidden_dim)
|
120 |
-
self.flow_head = FlowHead(hidden_dim, hidden_dim=256)
|
121 |
-
|
122 |
-
self.mask = nn.Sequential(
|
123 |
-
nn.Conv2d(128, 256, 3, padding=1),
|
124 |
-
nn.ReLU(inplace=True),
|
125 |
-
nn.Conv2d(256, 64*9, 1, padding=0))
|
126 |
-
|
127 |
-
def forward(self, net, inp, corr, flow, upsample=True):
|
128 |
-
motion_features = self.encoder(flow, corr)
|
129 |
-
inp = torch.cat([inp, motion_features], dim=1)
|
130 |
-
|
131 |
-
net = self.gru(net, inp)
|
132 |
-
delta_flow = self.flow_head(net)
|
133 |
-
|
134 |
-
# scale mask to balence gradients
|
135 |
-
mask = .25 * self.mask(net)
|
136 |
-
return net, mask, delta_flow
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/44ov41za8i/FreeVC/speaker_encoder/model.py
DELETED
@@ -1,135 +0,0 @@
|
|
1 |
-
from speaker_encoder.params_model import *
|
2 |
-
from speaker_encoder.params_data import *
|
3 |
-
from scipy.interpolate import interp1d
|
4 |
-
from sklearn.metrics import roc_curve
|
5 |
-
from torch.nn.utils import clip_grad_norm_
|
6 |
-
from scipy.optimize import brentq
|
7 |
-
from torch import nn
|
8 |
-
import numpy as np
|
9 |
-
import torch
|
10 |
-
|
11 |
-
|
12 |
-
class SpeakerEncoder(nn.Module):
|
13 |
-
def __init__(self, device, loss_device):
|
14 |
-
super().__init__()
|
15 |
-
self.loss_device = loss_device
|
16 |
-
|
17 |
-
# Network defition
|
18 |
-
self.lstm = nn.LSTM(input_size=mel_n_channels, # 40
|
19 |
-
hidden_size=model_hidden_size, # 256
|
20 |
-
num_layers=model_num_layers, # 3
|
21 |
-
batch_first=True).to(device)
|
22 |
-
self.linear = nn.Linear(in_features=model_hidden_size,
|
23 |
-
out_features=model_embedding_size).to(device)
|
24 |
-
self.relu = torch.nn.ReLU().to(device)
|
25 |
-
|
26 |
-
# Cosine similarity scaling (with fixed initial parameter values)
|
27 |
-
self.similarity_weight = nn.Parameter(torch.tensor([10.])).to(loss_device)
|
28 |
-
self.similarity_bias = nn.Parameter(torch.tensor([-5.])).to(loss_device)
|
29 |
-
|
30 |
-
# Loss
|
31 |
-
self.loss_fn = nn.CrossEntropyLoss().to(loss_device)
|
32 |
-
|
33 |
-
def do_gradient_ops(self):
|
34 |
-
# Gradient scale
|
35 |
-
self.similarity_weight.grad *= 0.01
|
36 |
-
self.similarity_bias.grad *= 0.01
|
37 |
-
|
38 |
-
# Gradient clipping
|
39 |
-
clip_grad_norm_(self.parameters(), 3, norm_type=2)
|
40 |
-
|
41 |
-
def forward(self, utterances, hidden_init=None):
|
42 |
-
"""
|
43 |
-
Computes the embeddings of a batch of utterance spectrograms.
|
44 |
-
|
45 |
-
:param utterances: batch of mel-scale filterbanks of same duration as a tensor of shape
|
46 |
-
(batch_size, n_frames, n_channels)
|
47 |
-
:param hidden_init: initial hidden state of the LSTM as a tensor of shape (num_layers,
|
48 |
-
batch_size, hidden_size). Will default to a tensor of zeros if None.
|
49 |
-
:return: the embeddings as a tensor of shape (batch_size, embedding_size)
|
50 |
-
"""
|
51 |
-
# Pass the input through the LSTM layers and retrieve all outputs, the final hidden state
|
52 |
-
# and the final cell state.
|
53 |
-
out, (hidden, cell) = self.lstm(utterances, hidden_init)
|
54 |
-
|
55 |
-
# We take only the hidden state of the last layer
|
56 |
-
embeds_raw = self.relu(self.linear(hidden[-1]))
|
57 |
-
|
58 |
-
# L2-normalize it
|
59 |
-
embeds = embeds_raw / torch.norm(embeds_raw, dim=1, keepdim=True)
|
60 |
-
|
61 |
-
return embeds
|
62 |
-
|
63 |
-
def similarity_matrix(self, embeds):
|
64 |
-
"""
|
65 |
-
Computes the similarity matrix according the section 2.1 of GE2E.
|
66 |
-
|
67 |
-
:param embeds: the embeddings as a tensor of shape (speakers_per_batch,
|
68 |
-
utterances_per_speaker, embedding_size)
|
69 |
-
:return: the similarity matrix as a tensor of shape (speakers_per_batch,
|
70 |
-
utterances_per_speaker, speakers_per_batch)
|
71 |
-
"""
|
72 |
-
speakers_per_batch, utterances_per_speaker = embeds.shape[:2]
|
73 |
-
|
74 |
-
# Inclusive centroids (1 per speaker). Cloning is needed for reverse differentiation
|
75 |
-
centroids_incl = torch.mean(embeds, dim=1, keepdim=True)
|
76 |
-
centroids_incl = centroids_incl.clone() / torch.norm(centroids_incl, dim=2, keepdim=True)
|
77 |
-
|
78 |
-
# Exclusive centroids (1 per utterance)
|
79 |
-
centroids_excl = (torch.sum(embeds, dim=1, keepdim=True) - embeds)
|
80 |
-
centroids_excl /= (utterances_per_speaker - 1)
|
81 |
-
centroids_excl = centroids_excl.clone() / torch.norm(centroids_excl, dim=2, keepdim=True)
|
82 |
-
|
83 |
-
# Similarity matrix. The cosine similarity of already 2-normed vectors is simply the dot
|
84 |
-
# product of these vectors (which is just an element-wise multiplication reduced by a sum).
|
85 |
-
# We vectorize the computation for efficiency.
|
86 |
-
sim_matrix = torch.zeros(speakers_per_batch, utterances_per_speaker,
|
87 |
-
speakers_per_batch).to(self.loss_device)
|
88 |
-
mask_matrix = 1 - np.eye(speakers_per_batch, dtype=np.int)
|
89 |
-
for j in range(speakers_per_batch):
|
90 |
-
mask = np.where(mask_matrix[j])[0]
|
91 |
-
sim_matrix[mask, :, j] = (embeds[mask] * centroids_incl[j]).sum(dim=2)
|
92 |
-
sim_matrix[j, :, j] = (embeds[j] * centroids_excl[j]).sum(dim=1)
|
93 |
-
|
94 |
-
## Even more vectorized version (slower maybe because of transpose)
|
95 |
-
# sim_matrix2 = torch.zeros(speakers_per_batch, speakers_per_batch, utterances_per_speaker
|
96 |
-
# ).to(self.loss_device)
|
97 |
-
# eye = np.eye(speakers_per_batch, dtype=np.int)
|
98 |
-
# mask = np.where(1 - eye)
|
99 |
-
# sim_matrix2[mask] = (embeds[mask[0]] * centroids_incl[mask[1]]).sum(dim=2)
|
100 |
-
# mask = np.where(eye)
|
101 |
-
# sim_matrix2[mask] = (embeds * centroids_excl).sum(dim=2)
|
102 |
-
# sim_matrix2 = sim_matrix2.transpose(1, 2)
|
103 |
-
|
104 |
-
sim_matrix = sim_matrix * self.similarity_weight + self.similarity_bias
|
105 |
-
return sim_matrix
|
106 |
-
|
107 |
-
def loss(self, embeds):
|
108 |
-
"""
|
109 |
-
Computes the softmax loss according the section 2.1 of GE2E.
|
110 |
-
|
111 |
-
:param embeds: the embeddings as a tensor of shape (speakers_per_batch,
|
112 |
-
utterances_per_speaker, embedding_size)
|
113 |
-
:return: the loss and the EER for this batch of embeddings.
|
114 |
-
"""
|
115 |
-
speakers_per_batch, utterances_per_speaker = embeds.shape[:2]
|
116 |
-
|
117 |
-
# Loss
|
118 |
-
sim_matrix = self.similarity_matrix(embeds)
|
119 |
-
sim_matrix = sim_matrix.reshape((speakers_per_batch * utterances_per_speaker,
|
120 |
-
speakers_per_batch))
|
121 |
-
ground_truth = np.repeat(np.arange(speakers_per_batch), utterances_per_speaker)
|
122 |
-
target = torch.from_numpy(ground_truth).long().to(self.loss_device)
|
123 |
-
loss = self.loss_fn(sim_matrix, target)
|
124 |
-
|
125 |
-
# EER (not backpropagated)
|
126 |
-
with torch.no_grad():
|
127 |
-
inv_argmax = lambda i: np.eye(1, speakers_per_batch, i, dtype=np.int)[0]
|
128 |
-
labels = np.array([inv_argmax(i) for i in ground_truth])
|
129 |
-
preds = sim_matrix.detach().cpu().numpy()
|
130 |
-
|
131 |
-
# Snippet from https://yangcha.github.io/EER-ROC/
|
132 |
-
fpr, tpr, thresholds = roc_curve(labels.flatten(), preds.flatten())
|
133 |
-
eer = brentq(lambda x: 1. - x - interp1d(fpr, tpr)(x), 0., 1.)
|
134 |
-
|
135 |
-
return loss, eer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/4Taps/SadTalker/src/face3d/models/arcface_torch/docs/modelzoo.md
DELETED
File without changes
|
spaces/52Hz/CMFNet_deblurring/app.py
DELETED
@@ -1,37 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import gradio as gr
|
3 |
-
from PIL import Image
|
4 |
-
import torch
|
5 |
-
|
6 |
-
os.system(
|
7 |
-
'wget https://github.com/FanChiMao/CMFNet/releases/download/v0.0/deblur_GoPro_CMFNet.pth -P experiments/pretrained_models')
|
8 |
-
|
9 |
-
|
10 |
-
def inference(img):
|
11 |
-
os.system('mkdir test')
|
12 |
-
basewidth = 512
|
13 |
-
wpercent = (basewidth / float(img.size[0]))
|
14 |
-
hsize = int((float(img.size[1]) * float(wpercent)))
|
15 |
-
img = img.resize((basewidth, hsize), Image.BILINEAR)
|
16 |
-
img.save("test/1.png", "PNG")
|
17 |
-
os.system(
|
18 |
-
'python main_test_CMFNet.py --input_dir test --weights experiments/pretrained_models/deblur_GoPro_CMFNet.pth')
|
19 |
-
return 'results/1.png'
|
20 |
-
|
21 |
-
|
22 |
-
title = "Compound Multi-branch Feature Fusion for Image Restoration (Deblur)"
|
23 |
-
description = "Gradio demo for CMFNet. CMFNet achieves competitive performance on three tasks: image deblurring, image dehazing and image deraindrop. Here, we provide a demo for image deblur. To use it, simply upload your image, or click one of the examples to load them. Reference from: https://huggingface.co/akhaliq"
|
24 |
-
article = "<p style='text-align: center'><a href='https://' target='_blank'>Compound Multi-branch Feature Fusion for Real Image Restoration</a> | <a href='https://github.com/FanChiMao/CMFNet' target='_blank'>Github Repo</a></p> <center><img src='https://visitor-badge.glitch.me/badge?page_id=52Hz_CMFNet_deblurring' alt='visitor badge'></center>"
|
25 |
-
|
26 |
-
examples = [['images/Blur1.png'], ['images/Blur2.png'], ['images/Blur5.png'],]
|
27 |
-
gr.Interface(
|
28 |
-
inference,
|
29 |
-
[gr.inputs.Image(type="pil", label="Input")],
|
30 |
-
gr.outputs.Image(type="filepath", label="Output"),
|
31 |
-
title=title,
|
32 |
-
description=description,
|
33 |
-
article=article,
|
34 |
-
allow_flagging=False,
|
35 |
-
allow_screenshot=False,
|
36 |
-
examples=examples
|
37 |
-
).launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AB-TW/team-ai/documents/bussiness_context/NOTION_DB/Engineering Wiki 2402f5396a3244fdb3f1d135bdb0f3d6/Engineering Guidelines 4208cbd4733d4f6f94982f3fb24f6379.md
DELETED
@@ -1,39 +0,0 @@
|
|
1 |
-
# Engineering Guidelines
|
2 |
-
|
3 |
-
Last edited time: March 31, 2023 1:49 PM
|
4 |
-
Owner: Anonymous
|
5 |
-
Tags: Guides and Processes
|
6 |
-
|
7 |
-
<aside>
|
8 |
-
💡 Use this template to create guidelines for all of the engineers on your team. Add a table of contents by typing `/table of` and pressing `enter`.
|
9 |
-
|
10 |
-
</aside>
|
11 |
-
|
12 |
-
# Engineering philosophy
|
13 |
-
|
14 |
-
Summarize your team's approach to engineering here.
|
15 |
-
|
16 |
-
## History
|
17 |
-
|
18 |
-
Notes about how the current codebase evolved.
|
19 |
-
|
20 |
-
# Patterns to follow
|
21 |
-
|
22 |
-
- List patterns that engineers should follow here.
|
23 |
-
- You can create `inline code snippets` with the shortcut `cmd/ctrl + e`.
|
24 |
-
|
25 |
-
# Code samples
|
26 |
-
|
27 |
-
Add code blocks for common snippets. Type `/code` and press `enter`. Choose the language you're using from the dropdown at the bottom right corner. Hover to copy with one click.
|
28 |
-
|
29 |
-
```jsx
|
30 |
-
var a = 1;
|
31 |
-
while (a <= 10) {
|
32 |
-
document.write(a + "<br />");
|
33 |
-
a++;
|
34 |
-
}
|
35 |
-
```
|
36 |
-
|
37 |
-
# Further Reading
|
38 |
-
|
39 |
-
Check out this [Notion guide](https://www.notion.so/68c7c67047494fdb87d50185429df93e) to learn about more ways to create content.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIFILMS/StyleGANEX/models/mtcnn/mtcnn_pytorch/src/first_stage.py
DELETED
@@ -1,101 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
from torch.autograd import Variable
|
3 |
-
import math
|
4 |
-
from PIL import Image
|
5 |
-
import numpy as np
|
6 |
-
from .box_utils import nms, _preprocess
|
7 |
-
|
8 |
-
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
9 |
-
device = 'cuda:0'
|
10 |
-
|
11 |
-
|
12 |
-
def run_first_stage(image, net, scale, threshold):
|
13 |
-
"""Run P-Net, generate bounding boxes, and do NMS.
|
14 |
-
|
15 |
-
Arguments:
|
16 |
-
image: an instance of PIL.Image.
|
17 |
-
net: an instance of pytorch's nn.Module, P-Net.
|
18 |
-
scale: a float number,
|
19 |
-
scale width and height of the image by this number.
|
20 |
-
threshold: a float number,
|
21 |
-
threshold on the probability of a face when generating
|
22 |
-
bounding boxes from predictions of the net.
|
23 |
-
|
24 |
-
Returns:
|
25 |
-
a float numpy array of shape [n_boxes, 9],
|
26 |
-
bounding boxes with scores and offsets (4 + 1 + 4).
|
27 |
-
"""
|
28 |
-
|
29 |
-
# scale the image and convert it to a float array
|
30 |
-
width, height = image.size
|
31 |
-
sw, sh = math.ceil(width * scale), math.ceil(height * scale)
|
32 |
-
img = image.resize((sw, sh), Image.BILINEAR)
|
33 |
-
img = np.asarray(img, 'float32')
|
34 |
-
|
35 |
-
img = torch.FloatTensor(_preprocess(img)).to(device)
|
36 |
-
with torch.no_grad():
|
37 |
-
output = net(img)
|
38 |
-
probs = output[1].cpu().data.numpy()[0, 1, :, :]
|
39 |
-
offsets = output[0].cpu().data.numpy()
|
40 |
-
# probs: probability of a face at each sliding window
|
41 |
-
# offsets: transformations to true bounding boxes
|
42 |
-
|
43 |
-
boxes = _generate_bboxes(probs, offsets, scale, threshold)
|
44 |
-
if len(boxes) == 0:
|
45 |
-
return None
|
46 |
-
|
47 |
-
keep = nms(boxes[:, 0:5], overlap_threshold=0.5)
|
48 |
-
return boxes[keep]
|
49 |
-
|
50 |
-
|
51 |
-
def _generate_bboxes(probs, offsets, scale, threshold):
|
52 |
-
"""Generate bounding boxes at places
|
53 |
-
where there is probably a face.
|
54 |
-
|
55 |
-
Arguments:
|
56 |
-
probs: a float numpy array of shape [n, m].
|
57 |
-
offsets: a float numpy array of shape [1, 4, n, m].
|
58 |
-
scale: a float number,
|
59 |
-
width and height of the image were scaled by this number.
|
60 |
-
threshold: a float number.
|
61 |
-
|
62 |
-
Returns:
|
63 |
-
a float numpy array of shape [n_boxes, 9]
|
64 |
-
"""
|
65 |
-
|
66 |
-
# applying P-Net is equivalent, in some sense, to
|
67 |
-
# moving 12x12 window with stride 2
|
68 |
-
stride = 2
|
69 |
-
cell_size = 12
|
70 |
-
|
71 |
-
# indices of boxes where there is probably a face
|
72 |
-
inds = np.where(probs > threshold)
|
73 |
-
|
74 |
-
if inds[0].size == 0:
|
75 |
-
return np.array([])
|
76 |
-
|
77 |
-
# transformations of bounding boxes
|
78 |
-
tx1, ty1, tx2, ty2 = [offsets[0, i, inds[0], inds[1]] for i in range(4)]
|
79 |
-
# they are defined as:
|
80 |
-
# w = x2 - x1 + 1
|
81 |
-
# h = y2 - y1 + 1
|
82 |
-
# x1_true = x1 + tx1*w
|
83 |
-
# x2_true = x2 + tx2*w
|
84 |
-
# y1_true = y1 + ty1*h
|
85 |
-
# y2_true = y2 + ty2*h
|
86 |
-
|
87 |
-
offsets = np.array([tx1, ty1, tx2, ty2])
|
88 |
-
score = probs[inds[0], inds[1]]
|
89 |
-
|
90 |
-
# P-Net is applied to scaled images
|
91 |
-
# so we need to rescale bounding boxes back
|
92 |
-
bounding_boxes = np.vstack([
|
93 |
-
np.round((stride * inds[1] + 1.0) / scale),
|
94 |
-
np.round((stride * inds[0] + 1.0) / scale),
|
95 |
-
np.round((stride * inds[1] + 1.0 + cell_size) / scale),
|
96 |
-
np.round((stride * inds[0] + 1.0 + cell_size) / scale),
|
97 |
-
score, offsets
|
98 |
-
])
|
99 |
-
# why one is added?
|
100 |
-
|
101 |
-
return bounding_boxes.T
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIFILMS/generate_human_motion/pyrender/pyrender/utils.py
DELETED
@@ -1,115 +0,0 @@
|
|
1 |
-
import numpy as np
|
2 |
-
from PIL import Image
|
3 |
-
|
4 |
-
|
5 |
-
def format_color_vector(value, length):
|
6 |
-
"""Format a color vector.
|
7 |
-
"""
|
8 |
-
if isinstance(value, int):
|
9 |
-
value = value / 255.0
|
10 |
-
if isinstance(value, float):
|
11 |
-
value = np.repeat(value, length)
|
12 |
-
if isinstance(value, list) or isinstance(value, tuple):
|
13 |
-
value = np.array(value)
|
14 |
-
if isinstance(value, np.ndarray):
|
15 |
-
value = value.squeeze()
|
16 |
-
if np.issubdtype(value.dtype, np.integer):
|
17 |
-
value = (value / 255.0).astype(np.float32)
|
18 |
-
if value.ndim != 1:
|
19 |
-
raise ValueError('Format vector takes only 1-D vectors')
|
20 |
-
if length > value.shape[0]:
|
21 |
-
value = np.hstack((value, np.ones(length - value.shape[0])))
|
22 |
-
elif length < value.shape[0]:
|
23 |
-
value = value[:length]
|
24 |
-
else:
|
25 |
-
raise ValueError('Invalid vector data type')
|
26 |
-
|
27 |
-
return value.squeeze().astype(np.float32)
|
28 |
-
|
29 |
-
|
30 |
-
def format_color_array(value, shape):
|
31 |
-
"""Format an array of colors.
|
32 |
-
"""
|
33 |
-
# Convert uint8 to floating
|
34 |
-
value = np.asanyarray(value)
|
35 |
-
if np.issubdtype(value.dtype, np.integer):
|
36 |
-
value = (value / 255.0).astype(np.float32)
|
37 |
-
|
38 |
-
# Match up shapes
|
39 |
-
if value.ndim == 1:
|
40 |
-
value = np.tile(value, (shape[0],1))
|
41 |
-
if value.shape[1] < shape[1]:
|
42 |
-
nc = shape[1] - value.shape[1]
|
43 |
-
value = np.column_stack((value, np.ones((value.shape[0], nc))))
|
44 |
-
elif value.shape[1] > shape[1]:
|
45 |
-
value = value[:,:shape[1]]
|
46 |
-
return value.astype(np.float32)
|
47 |
-
|
48 |
-
|
49 |
-
def format_texture_source(texture, target_channels='RGB'):
|
50 |
-
"""Format a texture as a float32 np array.
|
51 |
-
"""
|
52 |
-
|
53 |
-
# Pass through None
|
54 |
-
if texture is None:
|
55 |
-
return None
|
56 |
-
|
57 |
-
# Convert PIL images into numpy arrays
|
58 |
-
if isinstance(texture, Image.Image):
|
59 |
-
if texture.mode == 'P' and target_channels in ('RGB', 'RGBA'):
|
60 |
-
texture = np.array(texture.convert(target_channels))
|
61 |
-
else:
|
62 |
-
texture = np.array(texture)
|
63 |
-
|
64 |
-
# Format numpy arrays
|
65 |
-
if isinstance(texture, np.ndarray):
|
66 |
-
if np.issubdtype(texture.dtype, np.floating):
|
67 |
-
texture = np.array(texture * 255.0, dtype=np.uint8)
|
68 |
-
elif np.issubdtype(texture.dtype, np.integer):
|
69 |
-
texture = texture.astype(np.uint8)
|
70 |
-
else:
|
71 |
-
raise TypeError('Invalid type {} for texture'.format(
|
72 |
-
type(texture)
|
73 |
-
))
|
74 |
-
|
75 |
-
# Format array by picking out correct texture channels or padding
|
76 |
-
if texture.ndim == 2:
|
77 |
-
texture = texture[:,:,np.newaxis]
|
78 |
-
if target_channels == 'R':
|
79 |
-
texture = texture[:,:,0]
|
80 |
-
texture = texture.squeeze()
|
81 |
-
elif target_channels == 'RG':
|
82 |
-
if texture.shape[2] == 1:
|
83 |
-
texture = np.repeat(texture, 2, axis=2)
|
84 |
-
else:
|
85 |
-
texture = texture[:,:,(0,1)]
|
86 |
-
elif target_channels == 'GB':
|
87 |
-
if texture.shape[2] == 1:
|
88 |
-
texture = np.repeat(texture, 2, axis=2)
|
89 |
-
elif texture.shape[2] > 2:
|
90 |
-
texture = texture[:,:,(1,2)]
|
91 |
-
elif target_channels == 'RGB':
|
92 |
-
if texture.shape[2] == 1:
|
93 |
-
texture = np.repeat(texture, 3, axis=2)
|
94 |
-
elif texture.shape[2] == 2:
|
95 |
-
raise ValueError('Cannot reformat 2-channel texture into RGB')
|
96 |
-
else:
|
97 |
-
texture = texture[:,:,(0,1,2)]
|
98 |
-
elif target_channels == 'RGBA':
|
99 |
-
if texture.shape[2] == 1:
|
100 |
-
texture = np.repeat(texture, 4, axis=2)
|
101 |
-
texture[:,:,3] = 255
|
102 |
-
elif texture.shape[2] == 2:
|
103 |
-
raise ValueError('Cannot reformat 2-channel texture into RGBA')
|
104 |
-
elif texture.shape[2] == 3:
|
105 |
-
tx = np.empty((texture.shape[0], texture.shape[1], 4), dtype=np.uint8)
|
106 |
-
tx[:,:,:3] = texture
|
107 |
-
tx[:,:,3] = 255
|
108 |
-
texture = tx
|
109 |
-
else:
|
110 |
-
raise ValueError('Invalid texture channel specification: {}'
|
111 |
-
.format(target_channels))
|
112 |
-
else:
|
113 |
-
raise TypeError('Invalid type {} for texture'.format(type(texture)))
|
114 |
-
|
115 |
-
return texture
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIGC-Audio/AudioGPT/text_to_speech/utils/audio/vad.py
DELETED
@@ -1,78 +0,0 @@
|
|
1 |
-
from skimage.transform import resize
|
2 |
-
import struct
|
3 |
-
import webrtcvad
|
4 |
-
from scipy.ndimage.morphology import binary_dilation
|
5 |
-
import librosa
|
6 |
-
import numpy as np
|
7 |
-
import pyloudnorm as pyln
|
8 |
-
import warnings
|
9 |
-
|
10 |
-
warnings.filterwarnings("ignore", message="Possible clipped samples in output")
|
11 |
-
|
12 |
-
int16_max = (2 ** 15) - 1
|
13 |
-
|
14 |
-
|
15 |
-
def trim_long_silences(path, sr=None, return_raw_wav=False, norm=True, vad_max_silence_length=12):
|
16 |
-
"""
|
17 |
-
Ensures that segments without voice in the waveform remain no longer than a
|
18 |
-
threshold determined by the VAD parameters in params.py.
|
19 |
-
:param wav: the raw waveform as a numpy array of floats
|
20 |
-
:param vad_max_silence_length: Maximum number of consecutive silent frames a segment can have.
|
21 |
-
:return: the same waveform with silences trimmed away (length <= original wav length)
|
22 |
-
"""
|
23 |
-
|
24 |
-
## Voice Activation Detection
|
25 |
-
# Window size of the VAD. Must be either 10, 20 or 30 milliseconds.
|
26 |
-
# This sets the granularity of the VAD. Should not need to be changed.
|
27 |
-
sampling_rate = 16000
|
28 |
-
wav_raw, sr = librosa.core.load(path, sr=sr)
|
29 |
-
|
30 |
-
if norm:
|
31 |
-
meter = pyln.Meter(sr) # create BS.1770 meter
|
32 |
-
loudness = meter.integrated_loudness(wav_raw)
|
33 |
-
wav_raw = pyln.normalize.loudness(wav_raw, loudness, -20.0)
|
34 |
-
if np.abs(wav_raw).max() > 1.0:
|
35 |
-
wav_raw = wav_raw / np.abs(wav_raw).max()
|
36 |
-
|
37 |
-
wav = librosa.resample(wav_raw, sr, sampling_rate, res_type='kaiser_best')
|
38 |
-
|
39 |
-
vad_window_length = 30 # In milliseconds
|
40 |
-
# Number of frames to average together when performing the moving average smoothing.
|
41 |
-
# The larger this value, the larger the VAD variations must be to not get smoothed out.
|
42 |
-
vad_moving_average_width = 8
|
43 |
-
|
44 |
-
# Compute the voice detection window size
|
45 |
-
samples_per_window = (vad_window_length * sampling_rate) // 1000
|
46 |
-
|
47 |
-
# Trim the end of the audio to have a multiple of the window size
|
48 |
-
wav = wav[:len(wav) - (len(wav) % samples_per_window)]
|
49 |
-
|
50 |
-
# Convert the float waveform to 16-bit mono PCM
|
51 |
-
pcm_wave = struct.pack("%dh" % len(wav), *(np.round(wav * int16_max)).astype(np.int16))
|
52 |
-
|
53 |
-
# Perform voice activation detection
|
54 |
-
voice_flags = []
|
55 |
-
vad = webrtcvad.Vad(mode=3)
|
56 |
-
for window_start in range(0, len(wav), samples_per_window):
|
57 |
-
window_end = window_start + samples_per_window
|
58 |
-
voice_flags.append(vad.is_speech(pcm_wave[window_start * 2:window_end * 2],
|
59 |
-
sample_rate=sampling_rate))
|
60 |
-
voice_flags = np.array(voice_flags)
|
61 |
-
|
62 |
-
# Smooth the voice detection with a moving average
|
63 |
-
def moving_average(array, width):
|
64 |
-
array_padded = np.concatenate((np.zeros((width - 1) // 2), array, np.zeros(width // 2)))
|
65 |
-
ret = np.cumsum(array_padded, dtype=float)
|
66 |
-
ret[width:] = ret[width:] - ret[:-width]
|
67 |
-
return ret[width - 1:] / width
|
68 |
-
|
69 |
-
audio_mask = moving_average(voice_flags, vad_moving_average_width)
|
70 |
-
audio_mask = np.round(audio_mask).astype(np.bool)
|
71 |
-
|
72 |
-
# Dilate the voiced regions
|
73 |
-
audio_mask = binary_dilation(audio_mask, np.ones(vad_max_silence_length + 1))
|
74 |
-
audio_mask = np.repeat(audio_mask, samples_per_window)
|
75 |
-
audio_mask = resize(audio_mask, (len(wav_raw),)) > 0
|
76 |
-
if return_raw_wav:
|
77 |
-
return wav_raw, audio_mask, sr
|
78 |
-
return wav_raw[audio_mask], audio_mask, sr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AIZero2Hero4Health/7-ClinicalTerminologyUIUX-GR/files/Readme.md
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
Files Directory - drop in examples here to ref by app.py
|
|
|
|
spaces/AUBADA-ALARABI/poetry1/README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Arabic Poetry Generator
|
3 |
-
emoji: 🐠
|
4 |
-
colorFrom: blue
|
5 |
-
colorTo: red
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.6
|
8 |
-
app_file: app.py
|
9 |
-
license: cc-by-nc-4.0
|
10 |
-
duplicated_from: aaaaaabbbbbbbdddddddduuuuulllll/poetry
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AchyuthGamer/OpenGPT/client/css/global.css
DELETED
@@ -1,70 +0,0 @@
|
|
1 |
-
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap");
|
2 |
-
* {
|
3 |
-
--font-1: "Inter", sans-serif;
|
4 |
-
--section-gap: 24px;
|
5 |
-
--border-radius-1: 8px;
|
6 |
-
margin: 0;
|
7 |
-
padding: 0;
|
8 |
-
box-sizing: border-box;
|
9 |
-
position: relative;
|
10 |
-
font-family: var(--font-1);
|
11 |
-
}
|
12 |
-
|
13 |
-
.theme-light {
|
14 |
-
--colour-1: #f5f5f5;
|
15 |
-
--colour-2: #000000;
|
16 |
-
--colour-3: #474747;
|
17 |
-
--colour-4: #949494;
|
18 |
-
--colour-5: #ebebeb;
|
19 |
-
--colour-6: #dadada;
|
20 |
-
|
21 |
-
--accent: #3a3a3a;
|
22 |
-
--blur-bg: #ffffff;
|
23 |
-
--blur-border: #dbdbdb;
|
24 |
-
--user-input: #282828;
|
25 |
-
--conversations: #666666;
|
26 |
-
}
|
27 |
-
|
28 |
-
.theme-dark {
|
29 |
-
--colour-1: #181818;
|
30 |
-
--colour-2: #ccc;
|
31 |
-
--colour-3: #dadada;
|
32 |
-
--colour-4: #f0f0f0;
|
33 |
-
--colour-5: #181818;
|
34 |
-
--colour-6: #242424;
|
35 |
-
|
36 |
-
--accent: #151718;
|
37 |
-
--blur-bg: #242627;
|
38 |
-
--blur-border: #242627;
|
39 |
-
--user-input: #f5f5f5;
|
40 |
-
--conversations: #555555;
|
41 |
-
}
|
42 |
-
|
43 |
-
html,
|
44 |
-
body {
|
45 |
-
background: var(--colour-1);
|
46 |
-
color: var(--colour-3);
|
47 |
-
}
|
48 |
-
|
49 |
-
ol,
|
50 |
-
ul {
|
51 |
-
padding-left: 20px;
|
52 |
-
}
|
53 |
-
|
54 |
-
.shown {
|
55 |
-
display: flex !important;
|
56 |
-
}
|
57 |
-
|
58 |
-
a:-webkit-any-link {
|
59 |
-
color: var(--accent);
|
60 |
-
}
|
61 |
-
|
62 |
-
pre {
|
63 |
-
white-space: pre-wrap;
|
64 |
-
}
|
65 |
-
|
66 |
-
@media screen and (max-height: 720px) {
|
67 |
-
:root {
|
68 |
-
--section-gap: 16px;
|
69 |
-
}
|
70 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Adr740/SmartHadithFR/README.md
DELETED
@@ -1,12 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: SmartHadithFR
|
3 |
-
emoji: 📚
|
4 |
-
colorFrom: yellow
|
5 |
-
colorTo: green
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.28.3
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
---
|
11 |
-
|
12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AgentVerse/agentVerse/agentverse/llms/base.py
DELETED
@@ -1,45 +0,0 @@
|
|
1 |
-
from abc import abstractmethod
|
2 |
-
from typing import Dict, Any
|
3 |
-
|
4 |
-
from pydantic import BaseModel, Field
|
5 |
-
|
6 |
-
|
7 |
-
class LLMResult(BaseModel):
|
8 |
-
content: str = ""
|
9 |
-
function_name: str = ""
|
10 |
-
function_arguments: Any = None
|
11 |
-
send_tokens: int = 0
|
12 |
-
recv_tokens: int = 0
|
13 |
-
total_tokens: int = 0
|
14 |
-
|
15 |
-
|
16 |
-
class BaseModelArgs(BaseModel):
|
17 |
-
pass
|
18 |
-
|
19 |
-
|
20 |
-
class BaseLLM(BaseModel):
|
21 |
-
args: BaseModelArgs = Field(default_factory=BaseModelArgs)
|
22 |
-
max_retry: int = Field(default=3)
|
23 |
-
|
24 |
-
@abstractmethod
|
25 |
-
def get_spend(self) -> float:
|
26 |
-
"""
|
27 |
-
Number of USD spent
|
28 |
-
"""
|
29 |
-
return -1.0
|
30 |
-
|
31 |
-
@abstractmethod
|
32 |
-
def generate_response(self, **kwargs) -> LLMResult:
|
33 |
-
pass
|
34 |
-
|
35 |
-
@abstractmethod
|
36 |
-
def agenerate_response(self, **kwargs) -> LLMResult:
|
37 |
-
pass
|
38 |
-
|
39 |
-
|
40 |
-
class BaseChatModel(BaseLLM):
|
41 |
-
pass
|
42 |
-
|
43 |
-
|
44 |
-
class BaseCompletionModel(BaseLLM):
|
45 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/shakeposition-plugin.d.ts
DELETED
@@ -1,9 +0,0 @@
|
|
1 |
-
import Shake from './shakeposition';
|
2 |
-
|
3 |
-
export default class ShakePlugin extends Phaser.Plugins.BasePlugin {
|
4 |
-
add(
|
5 |
-
gameObject: Phaser.GameObjects.GameObject,
|
6 |
-
config?: Shake.IConfig
|
7 |
-
): Shake;
|
8 |
-
|
9 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/spinner/grid/Factory.d.ts
DELETED
@@ -1,6 +0,0 @@
|
|
1 |
-
import Grid from './Grid';
|
2 |
-
import Base from '../base/Base';
|
3 |
-
|
4 |
-
export default function Factory(
|
5 |
-
config?: Base.IConfig
|
6 |
-
): Grid;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Aityz/Aityz-3B/README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Aityz 3B
|
3 |
-
emoji: 📚
|
4 |
-
colorFrom: blue
|
5 |
-
colorTo: gray
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.35.2
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: gpl-3.0
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AkitoP/umamusume_bert_vits2/text/tone_sandhi.py
DELETED
@@ -1,769 +0,0 @@
|
|
1 |
-
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
# you may not use this file except in compliance with the License.
|
5 |
-
# You may obtain a copy of the License at
|
6 |
-
#
|
7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
#
|
9 |
-
# Unless required by applicable law or agreed to in writing, software
|
10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
# See the License for the specific language governing permissions and
|
13 |
-
# limitations under the License.
|
14 |
-
from typing import List
|
15 |
-
from typing import Tuple
|
16 |
-
|
17 |
-
import jieba
|
18 |
-
from pypinyin import lazy_pinyin
|
19 |
-
from pypinyin import Style
|
20 |
-
|
21 |
-
|
22 |
-
class ToneSandhi:
|
23 |
-
def __init__(self):
|
24 |
-
self.must_neural_tone_words = {
|
25 |
-
"麻烦",
|
26 |
-
"麻利",
|
27 |
-
"鸳鸯",
|
28 |
-
"高粱",
|
29 |
-
"骨头",
|
30 |
-
"骆驼",
|
31 |
-
"马虎",
|
32 |
-
"首饰",
|
33 |
-
"馒头",
|
34 |
-
"馄饨",
|
35 |
-
"风筝",
|
36 |
-
"难为",
|
37 |
-
"队伍",
|
38 |
-
"阔气",
|
39 |
-
"闺女",
|
40 |
-
"门道",
|
41 |
-
"锄头",
|
42 |
-
"铺盖",
|
43 |
-
"铃铛",
|
44 |
-
"铁匠",
|
45 |
-
"钥匙",
|
46 |
-
"里脊",
|
47 |
-
"里头",
|
48 |
-
"部分",
|
49 |
-
"那么",
|
50 |
-
"道士",
|
51 |
-
"造化",
|
52 |
-
"迷糊",
|
53 |
-
"连累",
|
54 |
-
"这么",
|
55 |
-
"这个",
|
56 |
-
"运气",
|
57 |
-
"过去",
|
58 |
-
"软和",
|
59 |
-
"转悠",
|
60 |
-
"踏实",
|
61 |
-
"跳蚤",
|
62 |
-
"跟头",
|
63 |
-
"趔趄",
|
64 |
-
"财主",
|
65 |
-
"豆腐",
|
66 |
-
"讲究",
|
67 |
-
"记性",
|
68 |
-
"记号",
|
69 |
-
"认识",
|
70 |
-
"规矩",
|
71 |
-
"见识",
|
72 |
-
"裁缝",
|
73 |
-
"补丁",
|
74 |
-
"衣裳",
|
75 |
-
"衣服",
|
76 |
-
"衙门",
|
77 |
-
"街坊",
|
78 |
-
"行李",
|
79 |
-
"行当",
|
80 |
-
"蛤蟆",
|
81 |
-
"蘑菇",
|
82 |
-
"薄荷",
|
83 |
-
"葫芦",
|
84 |
-
"葡萄",
|
85 |
-
"萝卜",
|
86 |
-
"荸荠",
|
87 |
-
"苗条",
|
88 |
-
"苗头",
|
89 |
-
"苍蝇",
|
90 |
-
"芝麻",
|
91 |
-
"舒服",
|
92 |
-
"舒坦",
|
93 |
-
"舌头",
|
94 |
-
"自在",
|
95 |
-
"膏药",
|
96 |
-
"脾气",
|
97 |
-
"脑袋",
|
98 |
-
"脊梁",
|
99 |
-
"能耐",
|
100 |
-
"胳膊",
|
101 |
-
"胭脂",
|
102 |
-
"胡萝",
|
103 |
-
"胡琴",
|
104 |
-
"胡同",
|
105 |
-
"聪明",
|
106 |
-
"耽误",
|
107 |
-
"耽搁",
|
108 |
-
"耷拉",
|
109 |
-
"耳朵",
|
110 |
-
"老爷",
|
111 |
-
"老实",
|
112 |
-
"老婆",
|
113 |
-
"老头",
|
114 |
-
"老太",
|
115 |
-
"翻腾",
|
116 |
-
"罗嗦",
|
117 |
-
"罐头",
|
118 |
-
"编辑",
|
119 |
-
"结实",
|
120 |
-
"红火",
|
121 |
-
"累赘",
|
122 |
-
"糨糊",
|
123 |
-
"糊涂",
|
124 |
-
"精神",
|
125 |
-
"粮食",
|
126 |
-
"簸箕",
|
127 |
-
"篱笆",
|
128 |
-
"算计",
|
129 |
-
"算盘",
|
130 |
-
"答应",
|
131 |
-
"笤帚",
|
132 |
-
"笑语",
|
133 |
-
"笑话",
|
134 |
-
"窟窿",
|
135 |
-
"窝囊",
|
136 |
-
"窗户",
|
137 |
-
"稳当",
|
138 |
-
"稀罕",
|
139 |
-
"称呼",
|
140 |
-
"秧歌",
|
141 |
-
"秀气",
|
142 |
-
"秀才",
|
143 |
-
"福气",
|
144 |
-
"祖宗",
|
145 |
-
"砚台",
|
146 |
-
"码头",
|
147 |
-
"石榴",
|
148 |
-
"石头",
|
149 |
-
"石匠",
|
150 |
-
"知识",
|
151 |
-
"眼睛",
|
152 |
-
"眯缝",
|
153 |
-
"眨巴",
|
154 |
-
"眉毛",
|
155 |
-
"相声",
|
156 |
-
"盘算",
|
157 |
-
"白净",
|
158 |
-
"痢疾",
|
159 |
-
"痛快",
|
160 |
-
"疟疾",
|
161 |
-
"疙瘩",
|
162 |
-
"疏忽",
|
163 |
-
"畜生",
|
164 |
-
"生意",
|
165 |
-
"甘蔗",
|
166 |
-
"琵琶",
|
167 |
-
"琢磨",
|
168 |
-
"琉璃",
|
169 |
-
"玻璃",
|
170 |
-
"玫瑰",
|
171 |
-
"玄乎",
|
172 |
-
"狐狸",
|
173 |
-
"状元",
|
174 |
-
"特务",
|
175 |
-
"牲口",
|
176 |
-
"牙碜",
|
177 |
-
"牌楼",
|
178 |
-
"爽快",
|
179 |
-
"爱人",
|
180 |
-
"热闹",
|
181 |
-
"烧饼",
|
182 |
-
"烟筒",
|
183 |
-
"烂糊",
|
184 |
-
"点心",
|
185 |
-
"炊帚",
|
186 |
-
"灯笼",
|
187 |
-
"火候",
|
188 |
-
"漂亮",
|
189 |
-
"滑溜",
|
190 |
-
"溜达",
|
191 |
-
"温和",
|
192 |
-
"清楚",
|
193 |
-
"消息",
|
194 |
-
"浪头",
|
195 |
-
"活泼",
|
196 |
-
"比方",
|
197 |
-
"正经",
|
198 |
-
"欺负",
|
199 |
-
"模糊",
|
200 |
-
"槟榔",
|
201 |
-
"棺材",
|
202 |
-
"棒槌",
|
203 |
-
"棉花",
|
204 |
-
"核桃",
|
205 |
-
"栅栏",
|
206 |
-
"柴火",
|
207 |
-
"架势",
|
208 |
-
"枕头",
|
209 |
-
"枇杷",
|
210 |
-
"机灵",
|
211 |
-
"本事",
|
212 |
-
"木头",
|
213 |
-
"木匠",
|
214 |
-
"朋友",
|
215 |
-
"月饼",
|
216 |
-
"月亮",
|
217 |
-
"暖和",
|
218 |
-
"明白",
|
219 |
-
"时候",
|
220 |
-
"新鲜",
|
221 |
-
"故事",
|
222 |
-
"收拾",
|
223 |
-
"收成",
|
224 |
-
"提防",
|
225 |
-
"挖苦",
|
226 |
-
"挑剔",
|
227 |
-
"指甲",
|
228 |
-
"指头",
|
229 |
-
"拾掇",
|
230 |
-
"拳头",
|
231 |
-
"拨弄",
|
232 |
-
"招牌",
|
233 |
-
"招呼",
|
234 |
-
"抬举",
|
235 |
-
"护士",
|
236 |
-
"折腾",
|
237 |
-
"扫帚",
|
238 |
-
"打量",
|
239 |
-
"打算",
|
240 |
-
"打点",
|
241 |
-
"打扮",
|
242 |
-
"打听",
|
243 |
-
"打发",
|
244 |
-
"扎实",
|
245 |
-
"扁担",
|
246 |
-
"戒指",
|
247 |
-
"懒得",
|
248 |
-
"意识",
|
249 |
-
"意思",
|
250 |
-
"情形",
|
251 |
-
"悟性",
|
252 |
-
"怪物",
|
253 |
-
"思量",
|
254 |
-
"怎么",
|
255 |
-
"念头",
|
256 |
-
"念叨",
|
257 |
-
"快活",
|
258 |
-
"忙活",
|
259 |
-
"志气",
|
260 |
-
"心思",
|
261 |
-
"得罪",
|
262 |
-
"张罗",
|
263 |
-
"弟兄",
|
264 |
-
"开通",
|
265 |
-
"应酬",
|
266 |
-
"庄稼",
|
267 |
-
"干事",
|
268 |
-
"帮手",
|
269 |
-
"帐篷",
|
270 |
-
"希罕",
|
271 |
-
"师父",
|
272 |
-
"师傅",
|
273 |
-
"巴结",
|
274 |
-
"巴掌",
|
275 |
-
"差事",
|
276 |
-
"工夫",
|
277 |
-
"岁数",
|
278 |
-
"屁股",
|
279 |
-
"尾巴",
|
280 |
-
"少爷",
|
281 |
-
"小气",
|
282 |
-
"小伙",
|
283 |
-
"将就",
|
284 |
-
"对头",
|
285 |
-
"对付",
|
286 |
-
"寡妇",
|
287 |
-
"家伙",
|
288 |
-
"客气",
|
289 |
-
"实在",
|
290 |
-
"官司",
|
291 |
-
"学问",
|
292 |
-
"学生",
|
293 |
-
"字号",
|
294 |
-
"嫁妆",
|
295 |
-
"媳妇",
|
296 |
-
"媒人",
|
297 |
-
"婆家",
|
298 |
-
"娘家",
|
299 |
-
"委屈",
|
300 |
-
"姑娘",
|
301 |
-
"姐夫",
|
302 |
-
"妯娌",
|
303 |
-
"妥当",
|
304 |
-
"妖精",
|
305 |
-
"奴才",
|
306 |
-
"女婿",
|
307 |
-
"头发",
|
308 |
-
"太阳",
|
309 |
-
"大爷",
|
310 |
-
"大方",
|
311 |
-
"大意",
|
312 |
-
"大夫",
|
313 |
-
"多少",
|
314 |
-
"多么",
|
315 |
-
"外甥",
|
316 |
-
"壮实",
|
317 |
-
"地道",
|
318 |
-
"地方",
|
319 |
-
"在乎",
|
320 |
-
"困难",
|
321 |
-
"嘴巴",
|
322 |
-
"嘱咐",
|
323 |
-
"嘟囔",
|
324 |
-
"嘀咕",
|
325 |
-
"喜欢",
|
326 |
-
"喇嘛",
|
327 |
-
"喇叭",
|
328 |
-
"商量",
|
329 |
-
"唾沫",
|
330 |
-
"哑巴",
|
331 |
-
"哈欠",
|
332 |
-
"哆嗦",
|
333 |
-
"咳嗽",
|
334 |
-
"和尚",
|
335 |
-
"告诉",
|
336 |
-
"告示",
|
337 |
-
"含糊",
|
338 |
-
"吓唬",
|
339 |
-
"后头",
|
340 |
-
"名字",
|
341 |
-
"名堂",
|
342 |
-
"合同",
|
343 |
-
"吆喝",
|
344 |
-
"叫唤",
|
345 |
-
"口袋",
|
346 |
-
"厚道",
|
347 |
-
"厉害",
|
348 |
-
"千斤",
|
349 |
-
"包袱",
|
350 |
-
"包涵",
|
351 |
-
"匀称",
|
352 |
-
"勤快",
|
353 |
-
"动静",
|
354 |
-
"动弹",
|
355 |
-
"功夫",
|
356 |
-
"力气",
|
357 |
-
"前头",
|
358 |
-
"刺猬",
|
359 |
-
"刺激",
|
360 |
-
"别扭",
|
361 |
-
"利落",
|
362 |
-
"利索",
|
363 |
-
"利害",
|
364 |
-
"分析",
|
365 |
-
"出息",
|
366 |
-
"凑合",
|
367 |
-
"凉快",
|
368 |
-
"冷战",
|
369 |
-
"冤枉",
|
370 |
-
"冒失",
|
371 |
-
"养活",
|
372 |
-
"关系",
|
373 |
-
"先生",
|
374 |
-
"兄弟",
|
375 |
-
"便宜",
|
376 |
-
"使唤",
|
377 |
-
"佩服",
|
378 |
-
"作坊",
|
379 |
-
"体面",
|
380 |
-
"位置",
|
381 |
-
"似的",
|
382 |
-
"伙计",
|
383 |
-
"休息",
|
384 |
-
"什么",
|
385 |
-
"人家",
|
386 |
-
"亲戚",
|
387 |
-
"亲家",
|
388 |
-
"交情",
|
389 |
-
"云彩",
|
390 |
-
"事情",
|
391 |
-
"买卖",
|
392 |
-
"主意",
|
393 |
-
"丫头",
|
394 |
-
"丧气",
|
395 |
-
"两口",
|
396 |
-
"东西",
|
397 |
-
"东家",
|
398 |
-
"世故",
|
399 |
-
"不由",
|
400 |
-
"不在",
|
401 |
-
"下水",
|
402 |
-
"下巴",
|
403 |
-
"上头",
|
404 |
-
"上司",
|
405 |
-
"丈夫",
|
406 |
-
"丈人",
|
407 |
-
"一辈",
|
408 |
-
"那个",
|
409 |
-
"菩萨",
|
410 |
-
"父亲",
|
411 |
-
"母亲",
|
412 |
-
"咕噜",
|
413 |
-
"邋遢",
|
414 |
-
"费用",
|
415 |
-
"冤家",
|
416 |
-
"甜头",
|
417 |
-
"介绍",
|
418 |
-
"荒唐",
|
419 |
-
"大人",
|
420 |
-
"泥鳅",
|
421 |
-
"幸福",
|
422 |
-
"熟悉",
|
423 |
-
"计划",
|
424 |
-
"扑腾",
|
425 |
-
"蜡烛",
|
426 |
-
"姥爷",
|
427 |
-
"照顾",
|
428 |
-
"喉咙",
|
429 |
-
"吉他",
|
430 |
-
"弄堂",
|
431 |
-
"蚂蚱",
|
432 |
-
"凤凰",
|
433 |
-
"拖沓",
|
434 |
-
"寒碜",
|
435 |
-
"糟蹋",
|
436 |
-
"倒腾",
|
437 |
-
"报复",
|
438 |
-
"逻辑",
|
439 |
-
"盘缠",
|
440 |
-
"喽啰",
|
441 |
-
"牢骚",
|
442 |
-
"咖喱",
|
443 |
-
"扫把",
|
444 |
-
"惦记",
|
445 |
-
}
|
446 |
-
self.must_not_neural_tone_words = {
|
447 |
-
"男子",
|
448 |
-
"女子",
|
449 |
-
"分子",
|
450 |
-
"原子",
|
451 |
-
"量子",
|
452 |
-
"莲子",
|
453 |
-
"石子",
|
454 |
-
"瓜子",
|
455 |
-
"电子",
|
456 |
-
"人人",
|
457 |
-
"虎虎",
|
458 |
-
}
|
459 |
-
self.punc = ":,;。?!“”‘’':,;.?!"
|
460 |
-
|
461 |
-
# the meaning of jieba pos tag: https://blog.csdn.net/weixin_44174352/article/details/113731041
|
462 |
-
# e.g.
|
463 |
-
# word: "家里"
|
464 |
-
# pos: "s"
|
465 |
-
# finals: ['ia1', 'i3']
|
466 |
-
def _neural_sandhi(self, word: str, pos: str, finals: List[str]) -> List[str]:
|
467 |
-
# reduplication words for n. and v. e.g. 奶奶, 试试, 旺旺
|
468 |
-
for j, item in enumerate(word):
|
469 |
-
if (
|
470 |
-
j - 1 >= 0
|
471 |
-
and item == word[j - 1]
|
472 |
-
and pos[0] in {"n", "v", "a"}
|
473 |
-
and word not in self.must_not_neural_tone_words
|
474 |
-
):
|
475 |
-
finals[j] = finals[j][:-1] + "5"
|
476 |
-
ge_idx = word.find("个")
|
477 |
-
if len(word) >= 1 and word[-1] in "吧呢啊呐噻嘛吖嗨呐哦哒额滴哩哟喽啰耶喔诶":
|
478 |
-
finals[-1] = finals[-1][:-1] + "5"
|
479 |
-
elif len(word) >= 1 and word[-1] in "的地得":
|
480 |
-
finals[-1] = finals[-1][:-1] + "5"
|
481 |
-
# e.g. 走了, 看着, 去过
|
482 |
-
# elif len(word) == 1 and word in "了着过" and pos in {"ul", "uz", "ug"}:
|
483 |
-
# finals[-1] = finals[-1][:-1] + "5"
|
484 |
-
elif (
|
485 |
-
len(word) > 1
|
486 |
-
and word[-1] in "们子"
|
487 |
-
and pos in {"r", "n"}
|
488 |
-
and word not in self.must_not_neural_tone_words
|
489 |
-
):
|
490 |
-
finals[-1] = finals[-1][:-1] + "5"
|
491 |
-
# e.g. 桌上, 地下, 家里
|
492 |
-
elif len(word) > 1 and word[-1] in "上下里" and pos in {"s", "l", "f"}:
|
493 |
-
finals[-1] = finals[-1][:-1] + "5"
|
494 |
-
# e.g. 上来, 下去
|
495 |
-
elif len(word) > 1 and word[-1] in "来去" and word[-2] in "上下进出回过起开":
|
496 |
-
finals[-1] = finals[-1][:-1] + "5"
|
497 |
-
# 个做量词
|
498 |
-
elif (
|
499 |
-
ge_idx >= 1
|
500 |
-
and (word[ge_idx - 1].isnumeric() or word[ge_idx - 1] in "几有两半多各整每做是")
|
501 |
-
) or word == "个":
|
502 |
-
finals[ge_idx] = finals[ge_idx][:-1] + "5"
|
503 |
-
else:
|
504 |
-
if (
|
505 |
-
word in self.must_neural_tone_words
|
506 |
-
or word[-2:] in self.must_neural_tone_words
|
507 |
-
):
|
508 |
-
finals[-1] = finals[-1][:-1] + "5"
|
509 |
-
|
510 |
-
word_list = self._split_word(word)
|
511 |
-
finals_list = [finals[: len(word_list[0])], finals[len(word_list[0]) :]]
|
512 |
-
for i, word in enumerate(word_list):
|
513 |
-
# conventional neural in Chinese
|
514 |
-
if (
|
515 |
-
word in self.must_neural_tone_words
|
516 |
-
or word[-2:] in self.must_neural_tone_words
|
517 |
-
):
|
518 |
-
finals_list[i][-1] = finals_list[i][-1][:-1] + "5"
|
519 |
-
finals = sum(finals_list, [])
|
520 |
-
return finals
|
521 |
-
|
522 |
-
def _bu_sandhi(self, word: str, finals: List[str]) -> List[str]:
|
523 |
-
# e.g. 看不懂
|
524 |
-
if len(word) == 3 and word[1] == "不":
|
525 |
-
finals[1] = finals[1][:-1] + "5"
|
526 |
-
else:
|
527 |
-
for i, char in enumerate(word):
|
528 |
-
# "不" before tone4 should be bu2, e.g. 不怕
|
529 |
-
if char == "不" and i + 1 < len(word) and finals[i + 1][-1] == "4":
|
530 |
-
finals[i] = finals[i][:-1] + "2"
|
531 |
-
return finals
|
532 |
-
|
533 |
-
def _yi_sandhi(self, word: str, finals: List[str]) -> List[str]:
|
534 |
-
# "一" in number sequences, e.g. 一零零, 二一零
|
535 |
-
if word.find("一") != -1 and all(
|
536 |
-
[item.isnumeric() for item in word if item != "一"]
|
537 |
-
):
|
538 |
-
return finals
|
539 |
-
# "一" between reduplication words should be yi5, e.g. 看一看
|
540 |
-
elif len(word) == 3 and word[1] == "一" and word[0] == word[-1]:
|
541 |
-
finals[1] = finals[1][:-1] + "5"
|
542 |
-
# when "一" is ordinal word, it should be yi1
|
543 |
-
elif word.startswith("第一"):
|
544 |
-
finals[1] = finals[1][:-1] + "1"
|
545 |
-
else:
|
546 |
-
for i, char in enumerate(word):
|
547 |
-
if char == "一" and i + 1 < len(word):
|
548 |
-
# "一" before tone4 should be yi2, e.g. 一段
|
549 |
-
if finals[i + 1][-1] == "4":
|
550 |
-
finals[i] = finals[i][:-1] + "2"
|
551 |
-
# "一" before non-tone4 should be yi4, e.g. 一天
|
552 |
-
else:
|
553 |
-
# "一" 后面如果是标点,还读一声
|
554 |
-
if word[i + 1] not in self.punc:
|
555 |
-
finals[i] = finals[i][:-1] + "4"
|
556 |
-
return finals
|
557 |
-
|
558 |
-
def _split_word(self, word: str) -> List[str]:
|
559 |
-
word_list = jieba.cut_for_search(word)
|
560 |
-
word_list = sorted(word_list, key=lambda i: len(i), reverse=False)
|
561 |
-
first_subword = word_list[0]
|
562 |
-
first_begin_idx = word.find(first_subword)
|
563 |
-
if first_begin_idx == 0:
|
564 |
-
second_subword = word[len(first_subword) :]
|
565 |
-
new_word_list = [first_subword, second_subword]
|
566 |
-
else:
|
567 |
-
second_subword = word[: -len(first_subword)]
|
568 |
-
new_word_list = [second_subword, first_subword]
|
569 |
-
return new_word_list
|
570 |
-
|
571 |
-
def _three_sandhi(self, word: str, finals: List[str]) -> List[str]:
|
572 |
-
if len(word) == 2 and self._all_tone_three(finals):
|
573 |
-
finals[0] = finals[0][:-1] + "2"
|
574 |
-
elif len(word) == 3:
|
575 |
-
word_list = self._split_word(word)
|
576 |
-
if self._all_tone_three(finals):
|
577 |
-
# disyllabic + monosyllabic, e.g. 蒙古/包
|
578 |
-
if len(word_list[0]) == 2:
|
579 |
-
finals[0] = finals[0][:-1] + "2"
|
580 |
-
finals[1] = finals[1][:-1] + "2"
|
581 |
-
# monosyllabic + disyllabic, e.g. 纸/老虎
|
582 |
-
elif len(word_list[0]) == 1:
|
583 |
-
finals[1] = finals[1][:-1] + "2"
|
584 |
-
else:
|
585 |
-
finals_list = [finals[: len(word_list[0])], finals[len(word_list[0]) :]]
|
586 |
-
if len(finals_list) == 2:
|
587 |
-
for i, sub in enumerate(finals_list):
|
588 |
-
# e.g. 所有/人
|
589 |
-
if self._all_tone_three(sub) and len(sub) == 2:
|
590 |
-
finals_list[i][0] = finals_list[i][0][:-1] + "2"
|
591 |
-
# e.g. 好/喜欢
|
592 |
-
elif (
|
593 |
-
i == 1
|
594 |
-
and not self._all_tone_three(sub)
|
595 |
-
and finals_list[i][0][-1] == "3"
|
596 |
-
and finals_list[0][-1][-1] == "3"
|
597 |
-
):
|
598 |
-
finals_list[0][-1] = finals_list[0][-1][:-1] + "2"
|
599 |
-
finals = sum(finals_list, [])
|
600 |
-
# split idiom into two words who's length is 2
|
601 |
-
elif len(word) == 4:
|
602 |
-
finals_list = [finals[:2], finals[2:]]
|
603 |
-
finals = []
|
604 |
-
for sub in finals_list:
|
605 |
-
if self._all_tone_three(sub):
|
606 |
-
sub[0] = sub[0][:-1] + "2"
|
607 |
-
finals += sub
|
608 |
-
|
609 |
-
return finals
|
610 |
-
|
611 |
-
def _all_tone_three(self, finals: List[str]) -> bool:
|
612 |
-
return all(x[-1] == "3" for x in finals)
|
613 |
-
|
614 |
-
# merge "不" and the word behind it
|
615 |
-
# if don't merge, "不" sometimes appears alone according to jieba, which may occur sandhi error
|
616 |
-
def _merge_bu(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
|
617 |
-
new_seg = []
|
618 |
-
last_word = ""
|
619 |
-
for word, pos in seg:
|
620 |
-
if last_word == "不":
|
621 |
-
word = last_word + word
|
622 |
-
if word != "不":
|
623 |
-
new_seg.append((word, pos))
|
624 |
-
last_word = word[:]
|
625 |
-
if last_word == "不":
|
626 |
-
new_seg.append((last_word, "d"))
|
627 |
-
last_word = ""
|
628 |
-
return new_seg
|
629 |
-
|
630 |
-
# function 1: merge "一" and reduplication words in it's left and right, e.g. "听","一","听" ->"听一听"
|
631 |
-
# function 2: merge single "一" and the word behind it
|
632 |
-
# if don't merge, "一" sometimes appears alone according to jieba, which may occur sandhi error
|
633 |
-
# e.g.
|
634 |
-
# input seg: [('听', 'v'), ('一', 'm'), ('听', 'v')]
|
635 |
-
# output seg: [['听一听', 'v']]
|
636 |
-
def _merge_yi(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
|
637 |
-
new_seg = []
|
638 |
-
# function 1
|
639 |
-
for i, (word, pos) in enumerate(seg):
|
640 |
-
if (
|
641 |
-
i - 1 >= 0
|
642 |
-
and word == "一"
|
643 |
-
and i + 1 < len(seg)
|
644 |
-
and seg[i - 1][0] == seg[i + 1][0]
|
645 |
-
and seg[i - 1][1] == "v"
|
646 |
-
):
|
647 |
-
new_seg[i - 1][0] = new_seg[i - 1][0] + "一" + new_seg[i - 1][0]
|
648 |
-
else:
|
649 |
-
if (
|
650 |
-
i - 2 >= 0
|
651 |
-
and seg[i - 1][0] == "一"
|
652 |
-
and seg[i - 2][0] == word
|
653 |
-
and pos == "v"
|
654 |
-
):
|
655 |
-
continue
|
656 |
-
else:
|
657 |
-
new_seg.append([word, pos])
|
658 |
-
seg = new_seg
|
659 |
-
new_seg = []
|
660 |
-
# function 2
|
661 |
-
for i, (word, pos) in enumerate(seg):
|
662 |
-
if new_seg and new_seg[-1][0] == "一":
|
663 |
-
new_seg[-1][0] = new_seg[-1][0] + word
|
664 |
-
else:
|
665 |
-
new_seg.append([word, pos])
|
666 |
-
return new_seg
|
667 |
-
|
668 |
-
# the first and the second words are all_tone_three
|
669 |
-
def _merge_continuous_three_tones(
|
670 |
-
self, seg: List[Tuple[str, str]]
|
671 |
-
) -> List[Tuple[str, str]]:
|
672 |
-
new_seg = []
|
673 |
-
sub_finals_list = [
|
674 |
-
lazy_pinyin(word, neutral_tone_with_five=True, style=Style.FINALS_TONE3)
|
675 |
-
for (word, pos) in seg
|
676 |
-
]
|
677 |
-
assert len(sub_finals_list) == len(seg)
|
678 |
-
merge_last = [False] * len(seg)
|
679 |
-
for i, (word, pos) in enumerate(seg):
|
680 |
-
if (
|
681 |
-
i - 1 >= 0
|
682 |
-
and self._all_tone_three(sub_finals_list[i - 1])
|
683 |
-
and self._all_tone_three(sub_finals_list[i])
|
684 |
-
and not merge_last[i - 1]
|
685 |
-
):
|
686 |
-
# if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi
|
687 |
-
if (
|
688 |
-
not self._is_reduplication(seg[i - 1][0])
|
689 |
-
and len(seg[i - 1][0]) + len(seg[i][0]) <= 3
|
690 |
-
):
|
691 |
-
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
692 |
-
merge_last[i] = True
|
693 |
-
else:
|
694 |
-
new_seg.append([word, pos])
|
695 |
-
else:
|
696 |
-
new_seg.append([word, pos])
|
697 |
-
|
698 |
-
return new_seg
|
699 |
-
|
700 |
-
def _is_reduplication(self, word: str) -> bool:
|
701 |
-
return len(word) == 2 and word[0] == word[1]
|
702 |
-
|
703 |
-
# the last char of first word and the first char of second word is tone_three
|
704 |
-
def _merge_continuous_three_tones_2(
|
705 |
-
self, seg: List[Tuple[str, str]]
|
706 |
-
) -> List[Tuple[str, str]]:
|
707 |
-
new_seg = []
|
708 |
-
sub_finals_list = [
|
709 |
-
lazy_pinyin(word, neutral_tone_with_five=True, style=Style.FINALS_TONE3)
|
710 |
-
for (word, pos) in seg
|
711 |
-
]
|
712 |
-
assert len(sub_finals_list) == len(seg)
|
713 |
-
merge_last = [False] * len(seg)
|
714 |
-
for i, (word, pos) in enumerate(seg):
|
715 |
-
if (
|
716 |
-
i - 1 >= 0
|
717 |
-
and sub_finals_list[i - 1][-1][-1] == "3"
|
718 |
-
and sub_finals_list[i][0][-1] == "3"
|
719 |
-
and not merge_last[i - 1]
|
720 |
-
):
|
721 |
-
# if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi
|
722 |
-
if (
|
723 |
-
not self._is_reduplication(seg[i - 1][0])
|
724 |
-
and len(seg[i - 1][0]) + len(seg[i][0]) <= 3
|
725 |
-
):
|
726 |
-
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
727 |
-
merge_last[i] = True
|
728 |
-
else:
|
729 |
-
new_seg.append([word, pos])
|
730 |
-
else:
|
731 |
-
new_seg.append([word, pos])
|
732 |
-
return new_seg
|
733 |
-
|
734 |
-
def _merge_er(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
|
735 |
-
new_seg = []
|
736 |
-
for i, (word, pos) in enumerate(seg):
|
737 |
-
if i - 1 >= 0 and word == "儿" and seg[i - 1][0] != "#":
|
738 |
-
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
739 |
-
else:
|
740 |
-
new_seg.append([word, pos])
|
741 |
-
return new_seg
|
742 |
-
|
743 |
-
def _merge_reduplication(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
|
744 |
-
new_seg = []
|
745 |
-
for i, (word, pos) in enumerate(seg):
|
746 |
-
if new_seg and word == new_seg[-1][0]:
|
747 |
-
new_seg[-1][0] = new_seg[-1][0] + seg[i][0]
|
748 |
-
else:
|
749 |
-
new_seg.append([word, pos])
|
750 |
-
return new_seg
|
751 |
-
|
752 |
-
def pre_merge_for_modify(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
|
753 |
-
seg = self._merge_bu(seg)
|
754 |
-
try:
|
755 |
-
seg = self._merge_yi(seg)
|
756 |
-
except:
|
757 |
-
print("_merge_yi failed")
|
758 |
-
seg = self._merge_reduplication(seg)
|
759 |
-
seg = self._merge_continuous_three_tones(seg)
|
760 |
-
seg = self._merge_continuous_three_tones_2(seg)
|
761 |
-
seg = self._merge_er(seg)
|
762 |
-
return seg
|
763 |
-
|
764 |
-
def modified_tone(self, word: str, pos: str, finals: List[str]) -> List[str]:
|
765 |
-
finals = self._bu_sandhi(word, finals)
|
766 |
-
finals = self._yi_sandhi(word, finals)
|
767 |
-
finals = self._neural_sandhi(word, pos, finals)
|
768 |
-
finals = self._three_sandhi(word, finals)
|
769 |
-
return finals
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AlgoveraAI/web3-wallet/README.md
DELETED
@@ -1,37 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Web3 Wallet
|
3 |
-
emoji: 💳
|
4 |
-
colorFrom: pink
|
5 |
-
colorTo: yellow
|
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/Alycer/VITS-Umamusume-voice-synthesizer/text/english.py
DELETED
@@ -1,188 +0,0 @@
|
|
1 |
-
""" from https://github.com/keithito/tacotron """
|
2 |
-
|
3 |
-
'''
|
4 |
-
Cleaners are transformations that run over the input text at both training and eval time.
|
5 |
-
|
6 |
-
Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
|
7 |
-
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
|
8 |
-
1. "english_cleaners" for English text
|
9 |
-
2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
|
10 |
-
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
|
11 |
-
3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
|
12 |
-
the symbols in symbols.py to match your data).
|
13 |
-
'''
|
14 |
-
|
15 |
-
|
16 |
-
# Regular expression matching whitespace:
|
17 |
-
|
18 |
-
|
19 |
-
import re
|
20 |
-
import inflect
|
21 |
-
from unidecode import unidecode
|
22 |
-
import eng_to_ipa as ipa
|
23 |
-
_inflect = inflect.engine()
|
24 |
-
_comma_number_re = re.compile(r'([0-9][0-9\,]+[0-9])')
|
25 |
-
_decimal_number_re = re.compile(r'([0-9]+\.[0-9]+)')
|
26 |
-
_pounds_re = re.compile(r'£([0-9\,]*[0-9]+)')
|
27 |
-
_dollars_re = re.compile(r'\$([0-9\.\,]*[0-9]+)')
|
28 |
-
_ordinal_re = re.compile(r'[0-9]+(st|nd|rd|th)')
|
29 |
-
_number_re = re.compile(r'[0-9]+')
|
30 |
-
|
31 |
-
# List of (regular expression, replacement) pairs for abbreviations:
|
32 |
-
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
|
33 |
-
('mrs', 'misess'),
|
34 |
-
('mr', 'mister'),
|
35 |
-
('dr', 'doctor'),
|
36 |
-
('st', 'saint'),
|
37 |
-
('co', 'company'),
|
38 |
-
('jr', 'junior'),
|
39 |
-
('maj', 'major'),
|
40 |
-
('gen', 'general'),
|
41 |
-
('drs', 'doctors'),
|
42 |
-
('rev', 'reverend'),
|
43 |
-
('lt', 'lieutenant'),
|
44 |
-
('hon', 'honorable'),
|
45 |
-
('sgt', 'sergeant'),
|
46 |
-
('capt', 'captain'),
|
47 |
-
('esq', 'esquire'),
|
48 |
-
('ltd', 'limited'),
|
49 |
-
('col', 'colonel'),
|
50 |
-
('ft', 'fort'),
|
51 |
-
]]
|
52 |
-
|
53 |
-
|
54 |
-
# List of (ipa, lazy ipa) pairs:
|
55 |
-
_lazy_ipa = [(re.compile('%s' % x[0]), x[1]) for x in [
|
56 |
-
('r', 'ɹ'),
|
57 |
-
('æ', 'e'),
|
58 |
-
('ɑ', 'a'),
|
59 |
-
('ɔ', 'o'),
|
60 |
-
('ð', 'z'),
|
61 |
-
('θ', 's'),
|
62 |
-
('ɛ', 'e'),
|
63 |
-
('ɪ', 'i'),
|
64 |
-
('ʊ', 'u'),
|
65 |
-
('ʒ', 'ʥ'),
|
66 |
-
('ʤ', 'ʥ'),
|
67 |
-
('ˈ', '↓'),
|
68 |
-
]]
|
69 |
-
|
70 |
-
# List of (ipa, lazy ipa2) pairs:
|
71 |
-
_lazy_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [
|
72 |
-
('r', 'ɹ'),
|
73 |
-
('ð', 'z'),
|
74 |
-
('θ', 's'),
|
75 |
-
('ʒ', 'ʑ'),
|
76 |
-
('ʤ', 'dʑ'),
|
77 |
-
('ˈ', '↓'),
|
78 |
-
]]
|
79 |
-
|
80 |
-
# List of (ipa, ipa2) pairs
|
81 |
-
_ipa_to_ipa2 = [(re.compile('%s' % x[0]), x[1]) for x in [
|
82 |
-
('r', 'ɹ'),
|
83 |
-
('ʤ', 'dʒ'),
|
84 |
-
('ʧ', 'tʃ')
|
85 |
-
]]
|
86 |
-
|
87 |
-
|
88 |
-
def expand_abbreviations(text):
|
89 |
-
for regex, replacement in _abbreviations:
|
90 |
-
text = re.sub(regex, replacement, text)
|
91 |
-
return text
|
92 |
-
|
93 |
-
|
94 |
-
def collapse_whitespace(text):
|
95 |
-
return re.sub(r'\s+', ' ', text)
|
96 |
-
|
97 |
-
|
98 |
-
def _remove_commas(m):
|
99 |
-
return m.group(1).replace(',', '')
|
100 |
-
|
101 |
-
|
102 |
-
def _expand_decimal_point(m):
|
103 |
-
return m.group(1).replace('.', ' point ')
|
104 |
-
|
105 |
-
|
106 |
-
def _expand_dollars(m):
|
107 |
-
match = m.group(1)
|
108 |
-
parts = match.split('.')
|
109 |
-
if len(parts) > 2:
|
110 |
-
return match + ' dollars' # Unexpected format
|
111 |
-
dollars = int(parts[0]) if parts[0] else 0
|
112 |
-
cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0
|
113 |
-
if dollars and cents:
|
114 |
-
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
|
115 |
-
cent_unit = 'cent' if cents == 1 else 'cents'
|
116 |
-
return '%s %s, %s %s' % (dollars, dollar_unit, cents, cent_unit)
|
117 |
-
elif dollars:
|
118 |
-
dollar_unit = 'dollar' if dollars == 1 else 'dollars'
|
119 |
-
return '%s %s' % (dollars, dollar_unit)
|
120 |
-
elif cents:
|
121 |
-
cent_unit = 'cent' if cents == 1 else 'cents'
|
122 |
-
return '%s %s' % (cents, cent_unit)
|
123 |
-
else:
|
124 |
-
return 'zero dollars'
|
125 |
-
|
126 |
-
|
127 |
-
def _expand_ordinal(m):
|
128 |
-
return _inflect.number_to_words(m.group(0))
|
129 |
-
|
130 |
-
|
131 |
-
def _expand_number(m):
|
132 |
-
num = int(m.group(0))
|
133 |
-
if num > 1000 and num < 3000:
|
134 |
-
if num == 2000:
|
135 |
-
return 'two thousand'
|
136 |
-
elif num > 2000 and num < 2010:
|
137 |
-
return 'two thousand ' + _inflect.number_to_words(num % 100)
|
138 |
-
elif num % 100 == 0:
|
139 |
-
return _inflect.number_to_words(num // 100) + ' hundred'
|
140 |
-
else:
|
141 |
-
return _inflect.number_to_words(num, andword='', zero='oh', group=2).replace(', ', ' ')
|
142 |
-
else:
|
143 |
-
return _inflect.number_to_words(num, andword='')
|
144 |
-
|
145 |
-
|
146 |
-
def normalize_numbers(text):
|
147 |
-
text = re.sub(_comma_number_re, _remove_commas, text)
|
148 |
-
text = re.sub(_pounds_re, r'\1 pounds', text)
|
149 |
-
text = re.sub(_dollars_re, _expand_dollars, text)
|
150 |
-
text = re.sub(_decimal_number_re, _expand_decimal_point, text)
|
151 |
-
text = re.sub(_ordinal_re, _expand_ordinal, text)
|
152 |
-
text = re.sub(_number_re, _expand_number, text)
|
153 |
-
return text
|
154 |
-
|
155 |
-
|
156 |
-
def mark_dark_l(text):
|
157 |
-
return re.sub(r'l([^aeiouæɑɔəɛɪʊ ]*(?: |$))', lambda x: 'ɫ'+x.group(1), text)
|
158 |
-
|
159 |
-
|
160 |
-
def english_to_ipa(text):
|
161 |
-
text = unidecode(text).lower()
|
162 |
-
text = expand_abbreviations(text)
|
163 |
-
text = normalize_numbers(text)
|
164 |
-
phonemes = ipa.convert(text)
|
165 |
-
phonemes = collapse_whitespace(phonemes)
|
166 |
-
return phonemes
|
167 |
-
|
168 |
-
|
169 |
-
def english_to_lazy_ipa(text):
|
170 |
-
text = english_to_ipa(text)
|
171 |
-
for regex, replacement in _lazy_ipa:
|
172 |
-
text = re.sub(regex, replacement, text)
|
173 |
-
return text
|
174 |
-
|
175 |
-
|
176 |
-
def english_to_ipa2(text):
|
177 |
-
text = english_to_ipa(text)
|
178 |
-
text = mark_dark_l(text)
|
179 |
-
for regex, replacement in _ipa_to_ipa2:
|
180 |
-
text = re.sub(regex, replacement, text)
|
181 |
-
return text.replace('...', '…')
|
182 |
-
|
183 |
-
|
184 |
-
def english_to_lazy_ipa2(text):
|
185 |
-
text = english_to_ipa(text)
|
186 |
-
for regex, replacement in _lazy_ipa2:
|
187 |
-
text = re.sub(regex, replacement, text)
|
188 |
-
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Amrrs/DragGan-Inversion/PTI/models/e4e/stylegan2/op/upfirdn2d.py
DELETED
@@ -1,60 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
import torch
|
4 |
-
from torch.nn import functional as F
|
5 |
-
|
6 |
-
|
7 |
-
module_path = os.path.dirname(__file__)
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
|
12 |
-
out = upfirdn2d_native(
|
13 |
-
input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]
|
14 |
-
)
|
15 |
-
|
16 |
-
return out
|
17 |
-
|
18 |
-
|
19 |
-
def upfirdn2d_native(
|
20 |
-
input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1
|
21 |
-
):
|
22 |
-
_, channel, in_h, in_w = input.shape
|
23 |
-
input = input.reshape(-1, in_h, in_w, 1)
|
24 |
-
|
25 |
-
_, in_h, in_w, minor = input.shape
|
26 |
-
kernel_h, kernel_w = kernel.shape
|
27 |
-
|
28 |
-
out = input.view(-1, in_h, 1, in_w, 1, minor)
|
29 |
-
out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
|
30 |
-
out = out.view(-1, in_h * up_y, in_w * up_x, minor)
|
31 |
-
|
32 |
-
out = F.pad(
|
33 |
-
out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]
|
34 |
-
)
|
35 |
-
out = out[
|
36 |
-
:,
|
37 |
-
max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0),
|
38 |
-
max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0),
|
39 |
-
:,
|
40 |
-
]
|
41 |
-
|
42 |
-
out = out.permute(0, 3, 1, 2)
|
43 |
-
out = out.reshape(
|
44 |
-
[-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]
|
45 |
-
)
|
46 |
-
w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
|
47 |
-
out = F.conv2d(out, w)
|
48 |
-
out = out.reshape(
|
49 |
-
-1,
|
50 |
-
minor,
|
51 |
-
in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
|
52 |
-
in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1,
|
53 |
-
)
|
54 |
-
out = out.permute(0, 2, 3, 1)
|
55 |
-
out = out[:, ::down_y, ::down_x, :]
|
56 |
-
|
57 |
-
out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
|
58 |
-
out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
|
59 |
-
|
60 |
-
return out.view(-1, channel, out_h, out_w)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/en/optimization/mps.md
DELETED
@@ -1,67 +0,0 @@
|
|
1 |
-
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
2 |
-
|
3 |
-
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
4 |
-
the License. You may obtain a copy of the License at
|
5 |
-
|
6 |
-
http://www.apache.org/licenses/LICENSE-2.0
|
7 |
-
|
8 |
-
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
9 |
-
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
10 |
-
specific language governing permissions and limitations under the License.
|
11 |
-
-->
|
12 |
-
|
13 |
-
# How to use Stable Diffusion in Apple Silicon (M1/M2)
|
14 |
-
|
15 |
-
🤗 Diffusers is compatible with Apple silicon for Stable Diffusion inference, using the PyTorch `mps` device. These are the steps you need to follow to use your M1 or M2 computer with Stable Diffusion.
|
16 |
-
|
17 |
-
## Requirements
|
18 |
-
|
19 |
-
- Mac computer with Apple silicon (M1/M2) hardware.
|
20 |
-
- macOS 12.6 or later (13.0 or later recommended).
|
21 |
-
- arm64 version of Python.
|
22 |
-
- PyTorch 2.0 (recommended) or 1.13 (minimum version supported for `mps`). You can install it with `pip` or `conda` using the instructions in https://pytorch.org/get-started/locally/.
|
23 |
-
|
24 |
-
|
25 |
-
## Inference Pipeline
|
26 |
-
|
27 |
-
The snippet below demonstrates how to use the `mps` backend using the familiar `to()` interface to move the Stable Diffusion pipeline to your M1 or M2 device.
|
28 |
-
|
29 |
-
<Tip warning={true}>
|
30 |
-
|
31 |
-
**If you are using PyTorch 1.13** you need to "prime" the pipeline using an additional one-time pass through it. This is a temporary workaround for a weird issue we detected: the first inference pass produces slightly different results than subsequent ones. You only need to do this pass once, and it's ok to use just one inference step and discard the result.
|
32 |
-
|
33 |
-
</Tip>
|
34 |
-
|
35 |
-
We strongly recommend you use PyTorch 2 or better, as it solves a number of problems like the one described in the previous tip.
|
36 |
-
|
37 |
-
```python
|
38 |
-
from diffusers import DiffusionPipeline
|
39 |
-
|
40 |
-
pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
|
41 |
-
pipe = pipe.to("mps")
|
42 |
-
|
43 |
-
# Recommended if your computer has < 64 GB of RAM
|
44 |
-
pipe.enable_attention_slicing()
|
45 |
-
|
46 |
-
prompt = "a photo of an astronaut riding a horse on mars"
|
47 |
-
|
48 |
-
# First-time "warmup" pass if PyTorch version is 1.13 (see explanation above)
|
49 |
-
_ = pipe(prompt, num_inference_steps=1)
|
50 |
-
|
51 |
-
# Results match those from the CPU device after the warmup pass.
|
52 |
-
image = pipe(prompt).images[0]
|
53 |
-
```
|
54 |
-
|
55 |
-
## Performance Recommendations
|
56 |
-
|
57 |
-
M1/M2 performance is very sensitive to memory pressure. The system will automatically swap if it needs to, but performance will degrade significantly when it does.
|
58 |
-
|
59 |
-
We recommend you use _attention slicing_ to reduce memory pressure during inference and prevent swapping, particularly if your computer has less than 64 GB of system RAM, or if you generate images at non-standard resolutions larger than 512 × 512 pixels. Attention slicing performs the costly attention operation in multiple steps instead of all at once. It usually has a performance impact of ~20% in computers without universal memory, but we have observed _better performance_ in most Apple Silicon computers, unless you have 64 GB or more.
|
60 |
-
|
61 |
-
```python
|
62 |
-
pipeline.enable_attention_slicing()
|
63 |
-
```
|
64 |
-
|
65 |
-
## Known Issues
|
66 |
-
|
67 |
-
- Generating multiple prompts in a batch [crashes or doesn't work reliably](https://github.com/huggingface/diffusers/issues/363). We believe this is related to the [`mps` backend in PyTorch](https://github.com/pytorch/pytorch/issues/84039). This is being resolved, but for now we recommend to iterate instead of batching.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/tests/schedulers/test_scheduler_heun.py
DELETED
@@ -1,160 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
|
3 |
-
from diffusers import HeunDiscreteScheduler
|
4 |
-
from diffusers.utils import torch_device
|
5 |
-
|
6 |
-
from .test_schedulers import SchedulerCommonTest
|
7 |
-
|
8 |
-
|
9 |
-
class HeunDiscreteSchedulerTest(SchedulerCommonTest):
|
10 |
-
scheduler_classes = (HeunDiscreteScheduler,)
|
11 |
-
num_inference_steps = 10
|
12 |
-
|
13 |
-
def get_scheduler_config(self, **kwargs):
|
14 |
-
config = {
|
15 |
-
"num_train_timesteps": 1100,
|
16 |
-
"beta_start": 0.0001,
|
17 |
-
"beta_end": 0.02,
|
18 |
-
"beta_schedule": "linear",
|
19 |
-
}
|
20 |
-
|
21 |
-
config.update(**kwargs)
|
22 |
-
return config
|
23 |
-
|
24 |
-
def test_timesteps(self):
|
25 |
-
for timesteps in [10, 50, 100, 1000]:
|
26 |
-
self.check_over_configs(num_train_timesteps=timesteps)
|
27 |
-
|
28 |
-
def test_betas(self):
|
29 |
-
for beta_start, beta_end in zip([0.00001, 0.0001, 0.001], [0.0002, 0.002, 0.02]):
|
30 |
-
self.check_over_configs(beta_start=beta_start, beta_end=beta_end)
|
31 |
-
|
32 |
-
def test_schedules(self):
|
33 |
-
for schedule in ["linear", "scaled_linear", "exp"]:
|
34 |
-
self.check_over_configs(beta_schedule=schedule)
|
35 |
-
|
36 |
-
def test_clip_sample(self):
|
37 |
-
for clip_sample_range in [1.0, 2.0, 3.0]:
|
38 |
-
self.check_over_configs(clip_sample_range=clip_sample_range, clip_sample=True)
|
39 |
-
|
40 |
-
def test_prediction_type(self):
|
41 |
-
for prediction_type in ["epsilon", "v_prediction", "sample"]:
|
42 |
-
self.check_over_configs(prediction_type=prediction_type)
|
43 |
-
|
44 |
-
def test_full_loop_no_noise(self):
|
45 |
-
scheduler_class = self.scheduler_classes[0]
|
46 |
-
scheduler_config = self.get_scheduler_config()
|
47 |
-
scheduler = scheduler_class(**scheduler_config)
|
48 |
-
|
49 |
-
scheduler.set_timesteps(self.num_inference_steps)
|
50 |
-
|
51 |
-
model = self.dummy_model()
|
52 |
-
sample = self.dummy_sample_deter * scheduler.init_noise_sigma
|
53 |
-
sample = sample.to(torch_device)
|
54 |
-
|
55 |
-
for i, t in enumerate(scheduler.timesteps):
|
56 |
-
sample = scheduler.scale_model_input(sample, t)
|
57 |
-
|
58 |
-
model_output = model(sample, t)
|
59 |
-
|
60 |
-
output = scheduler.step(model_output, t, sample)
|
61 |
-
sample = output.prev_sample
|
62 |
-
|
63 |
-
result_sum = torch.sum(torch.abs(sample))
|
64 |
-
result_mean = torch.mean(torch.abs(sample))
|
65 |
-
|
66 |
-
if torch_device in ["cpu", "mps"]:
|
67 |
-
assert abs(result_sum.item() - 0.1233) < 1e-2
|
68 |
-
assert abs(result_mean.item() - 0.0002) < 1e-3
|
69 |
-
else:
|
70 |
-
# CUDA
|
71 |
-
assert abs(result_sum.item() - 0.1233) < 1e-2
|
72 |
-
assert abs(result_mean.item() - 0.0002) < 1e-3
|
73 |
-
|
74 |
-
def test_full_loop_with_v_prediction(self):
|
75 |
-
scheduler_class = self.scheduler_classes[0]
|
76 |
-
scheduler_config = self.get_scheduler_config(prediction_type="v_prediction")
|
77 |
-
scheduler = scheduler_class(**scheduler_config)
|
78 |
-
|
79 |
-
scheduler.set_timesteps(self.num_inference_steps)
|
80 |
-
|
81 |
-
model = self.dummy_model()
|
82 |
-
sample = self.dummy_sample_deter * scheduler.init_noise_sigma
|
83 |
-
sample = sample.to(torch_device)
|
84 |
-
|
85 |
-
for i, t in enumerate(scheduler.timesteps):
|
86 |
-
sample = scheduler.scale_model_input(sample, t)
|
87 |
-
|
88 |
-
model_output = model(sample, t)
|
89 |
-
|
90 |
-
output = scheduler.step(model_output, t, sample)
|
91 |
-
sample = output.prev_sample
|
92 |
-
|
93 |
-
result_sum = torch.sum(torch.abs(sample))
|
94 |
-
result_mean = torch.mean(torch.abs(sample))
|
95 |
-
|
96 |
-
if torch_device in ["cpu", "mps"]:
|
97 |
-
assert abs(result_sum.item() - 4.6934e-07) < 1e-2
|
98 |
-
assert abs(result_mean.item() - 6.1112e-10) < 1e-3
|
99 |
-
else:
|
100 |
-
# CUDA
|
101 |
-
assert abs(result_sum.item() - 4.693428650170972e-07) < 1e-2
|
102 |
-
assert abs(result_mean.item() - 0.0002) < 1e-3
|
103 |
-
|
104 |
-
def test_full_loop_device(self):
|
105 |
-
scheduler_class = self.scheduler_classes[0]
|
106 |
-
scheduler_config = self.get_scheduler_config()
|
107 |
-
scheduler = scheduler_class(**scheduler_config)
|
108 |
-
|
109 |
-
scheduler.set_timesteps(self.num_inference_steps, device=torch_device)
|
110 |
-
|
111 |
-
model = self.dummy_model()
|
112 |
-
sample = self.dummy_sample_deter.to(torch_device) * scheduler.init_noise_sigma
|
113 |
-
|
114 |
-
for t in scheduler.timesteps:
|
115 |
-
sample = scheduler.scale_model_input(sample, t)
|
116 |
-
|
117 |
-
model_output = model(sample, t)
|
118 |
-
|
119 |
-
output = scheduler.step(model_output, t, sample)
|
120 |
-
sample = output.prev_sample
|
121 |
-
|
122 |
-
result_sum = torch.sum(torch.abs(sample))
|
123 |
-
result_mean = torch.mean(torch.abs(sample))
|
124 |
-
|
125 |
-
if str(torch_device).startswith("cpu"):
|
126 |
-
# The following sum varies between 148 and 156 on mps. Why?
|
127 |
-
assert abs(result_sum.item() - 0.1233) < 1e-2
|
128 |
-
assert abs(result_mean.item() - 0.0002) < 1e-3
|
129 |
-
elif str(torch_device).startswith("mps"):
|
130 |
-
# Larger tolerance on mps
|
131 |
-
assert abs(result_mean.item() - 0.0002) < 1e-2
|
132 |
-
else:
|
133 |
-
# CUDA
|
134 |
-
assert abs(result_sum.item() - 0.1233) < 1e-2
|
135 |
-
assert abs(result_mean.item() - 0.0002) < 1e-3
|
136 |
-
|
137 |
-
def test_full_loop_device_karras_sigmas(self):
|
138 |
-
scheduler_class = self.scheduler_classes[0]
|
139 |
-
scheduler_config = self.get_scheduler_config()
|
140 |
-
scheduler = scheduler_class(**scheduler_config, use_karras_sigmas=True)
|
141 |
-
|
142 |
-
scheduler.set_timesteps(self.num_inference_steps, device=torch_device)
|
143 |
-
|
144 |
-
model = self.dummy_model()
|
145 |
-
sample = self.dummy_sample_deter.to(torch_device) * scheduler.init_noise_sigma
|
146 |
-
sample = sample.to(torch_device)
|
147 |
-
|
148 |
-
for t in scheduler.timesteps:
|
149 |
-
sample = scheduler.scale_model_input(sample, t)
|
150 |
-
|
151 |
-
model_output = model(sample, t)
|
152 |
-
|
153 |
-
output = scheduler.step(model_output, t, sample)
|
154 |
-
sample = output.prev_sample
|
155 |
-
|
156 |
-
result_sum = torch.sum(torch.abs(sample))
|
157 |
-
result_mean = torch.mean(torch.abs(sample))
|
158 |
-
|
159 |
-
assert abs(result_sum.item() - 0.00015) < 1e-2
|
160 |
-
assert abs(result_mean.item() - 1.9869554535034695e-07) < 1e-2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Andy1621/uniformer_image_detection/mmdet/models/losses/__init__.py
DELETED
@@ -1,29 +0,0 @@
|
|
1 |
-
from .accuracy import Accuracy, accuracy
|
2 |
-
from .ae_loss import AssociativeEmbeddingLoss
|
3 |
-
from .balanced_l1_loss import BalancedL1Loss, balanced_l1_loss
|
4 |
-
from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy,
|
5 |
-
cross_entropy, mask_cross_entropy)
|
6 |
-
from .focal_loss import FocalLoss, sigmoid_focal_loss
|
7 |
-
from .gaussian_focal_loss import GaussianFocalLoss
|
8 |
-
from .gfocal_loss import DistributionFocalLoss, QualityFocalLoss
|
9 |
-
from .ghm_loss import GHMC, GHMR
|
10 |
-
from .iou_loss import (BoundedIoULoss, CIoULoss, DIoULoss, GIoULoss, IoULoss,
|
11 |
-
bounded_iou_loss, iou_loss)
|
12 |
-
from .kd_loss import KnowledgeDistillationKLDivLoss
|
13 |
-
from .mse_loss import MSELoss, mse_loss
|
14 |
-
from .pisa_loss import carl_loss, isr_p
|
15 |
-
from .smooth_l1_loss import L1Loss, SmoothL1Loss, l1_loss, smooth_l1_loss
|
16 |
-
from .utils import reduce_loss, weight_reduce_loss, weighted_loss
|
17 |
-
from .varifocal_loss import VarifocalLoss
|
18 |
-
|
19 |
-
__all__ = [
|
20 |
-
'accuracy', 'Accuracy', 'cross_entropy', 'binary_cross_entropy',
|
21 |
-
'mask_cross_entropy', 'CrossEntropyLoss', 'sigmoid_focal_loss',
|
22 |
-
'FocalLoss', 'smooth_l1_loss', 'SmoothL1Loss', 'balanced_l1_loss',
|
23 |
-
'BalancedL1Loss', 'mse_loss', 'MSELoss', 'iou_loss', 'bounded_iou_loss',
|
24 |
-
'IoULoss', 'BoundedIoULoss', 'GIoULoss', 'DIoULoss', 'CIoULoss', 'GHMC',
|
25 |
-
'GHMR', 'reduce_loss', 'weight_reduce_loss', 'weighted_loss', 'L1Loss',
|
26 |
-
'l1_loss', 'isr_p', 'carl_loss', 'AssociativeEmbeddingLoss',
|
27 |
-
'GaussianFocalLoss', 'QualityFocalLoss', 'DistributionFocalLoss',
|
28 |
-
'VarifocalLoss', 'KnowledgeDistillationKLDivLoss'
|
29 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AnimalEquality/chatbot/lv_recipe_chatbot/app.py
DELETED
@@ -1,170 +0,0 @@
|
|
1 |
-
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_app.ipynb.
|
2 |
-
|
3 |
-
# %% auto 0
|
4 |
-
__all__ = ['ConversationBot', 'create_demo']
|
5 |
-
|
6 |
-
# %% ../nbs/01_app.ipynb 3
|
7 |
-
import copy
|
8 |
-
import os
|
9 |
-
|
10 |
-
import gradio as gr
|
11 |
-
from langchain import LLMChain, OpenAI, PromptTemplate
|
12 |
-
from langchain.agents import (
|
13 |
-
AgentExecutor,
|
14 |
-
AgentType,
|
15 |
-
OpenAIFunctionsAgent,
|
16 |
-
Tool,
|
17 |
-
initialize_agent,
|
18 |
-
load_tools,
|
19 |
-
)
|
20 |
-
from langchain.chains import ConversationChain
|
21 |
-
from langchain.chat_models import ChatOpenAI
|
22 |
-
from langchain.memory import ChatMessageHistory, ConversationBufferMemory
|
23 |
-
from langchain.prompts.chat import (
|
24 |
-
ChatPromptTemplate,
|
25 |
-
HumanMessagePromptTemplate,
|
26 |
-
MessagesPlaceholder,
|
27 |
-
)
|
28 |
-
from PIL import Image
|
29 |
-
|
30 |
-
import constants
|
31 |
-
from .engineer_prompt import INIT_PROMPT
|
32 |
-
from lv_recipe_chatbot.ingredient_vision import (
|
33 |
-
SAMPLE_IMG_DIR,
|
34 |
-
BlipImageCaptioning,
|
35 |
-
VeganIngredientFinder,
|
36 |
-
format_image,
|
37 |
-
)
|
38 |
-
from .vegan_recipe_tools import vegan_recipe_edamam_search
|
39 |
-
|
40 |
-
# %% ../nbs/01_app.ipynb 16
|
41 |
-
class ConversationBot:
|
42 |
-
memory_key: str = "chat_history"
|
43 |
-
|
44 |
-
def __init__(
|
45 |
-
self,
|
46 |
-
vegan_ingred_finder: VeganIngredientFinder,
|
47 |
-
img_cap: BlipImageCaptioning,
|
48 |
-
verbose: bool = True,
|
49 |
-
):
|
50 |
-
self.llm = ChatOpenAI(temperature=0.1, verbose=verbose)
|
51 |
-
self.init_prompt = copy.deepcopy(INIT_PROMPT)
|
52 |
-
self.img_cap = img_cap
|
53 |
-
self.vegan_ingred_finder = vegan_ingred_finder
|
54 |
-
self.verbose = verbose
|
55 |
-
init_prompt_msgs = self.init_prompt.messages
|
56 |
-
self.ai_prompt_questions = {
|
57 |
-
"ingredients": init_prompt_msgs[1],
|
58 |
-
"allergies": init_prompt_msgs[3],
|
59 |
-
"recipe_open_params": init_prompt_msgs[5],
|
60 |
-
}
|
61 |
-
|
62 |
-
def respond(self, user_msg, chat_history):
|
63 |
-
response = self._get_bot_response(user_msg, chat_history)
|
64 |
-
chat_history.append((user_msg, response))
|
65 |
-
return "", chat_history
|
66 |
-
|
67 |
-
def init_agent_executor(self, chat_msgs):
|
68 |
-
tools = [vegan_recipe_edamam_search]
|
69 |
-
prompt = OpenAIFunctionsAgent.create_prompt(
|
70 |
-
system_message=self.init_prompt.messages[0],
|
71 |
-
extra_prompt_messages=chat_msgs
|
72 |
-
+ [MessagesPlaceholder(variable_name=self.memory_key)],
|
73 |
-
)
|
74 |
-
self.memory = ConversationBufferMemory(
|
75 |
-
chat_memory=ChatMessageHistory(messages=chat_msgs),
|
76 |
-
return_messages=True,
|
77 |
-
memory_key=self.memory_key,
|
78 |
-
)
|
79 |
-
self.agent_executor = AgentExecutor(
|
80 |
-
agent=OpenAIFunctionsAgent(llm=self.llm, tools=tools, prompt=prompt),
|
81 |
-
tools=tools,
|
82 |
-
memory=self.memory,
|
83 |
-
verbose=True,
|
84 |
-
)
|
85 |
-
|
86 |
-
def reset(self):
|
87 |
-
self.memory.clear()
|
88 |
-
self.init_prompt = copy.deepcopy(INIT_PROMPT)
|
89 |
-
|
90 |
-
def run_img(self, image: str):
|
91 |
-
desc = self.img_cap.inference(format_image(image))
|
92 |
-
answer = self.vegan_ingred_finder.list_ingredients(image)
|
93 |
-
msg = f"""I uploaded an image that may contain vegan ingredients.
|
94 |
-
The description of the image is: `{desc}`.
|
95 |
-
The extracted ingredients are:
|
96 |
-
```
|
97 |
-
{answer}
|
98 |
-
```"""
|
99 |
-
base_prompt = INIT_PROMPT.messages[2].prompt.template
|
100 |
-
new_prompt = f"{msg}I may type some more ingredients below.\n{base_prompt}"
|
101 |
-
self.init_prompt.messages[2].prompt.template = new_prompt
|
102 |
-
return msg
|
103 |
-
|
104 |
-
def _get_bot_response(self, user_msg: str, chat_history) -> str:
|
105 |
-
if len(chat_history) < 2:
|
106 |
-
return self.ai_prompt_questions["allergies"].prompt.template
|
107 |
-
|
108 |
-
if len(chat_history) < 3:
|
109 |
-
return self.ai_prompt_questions["recipe_open_params"].prompt.template
|
110 |
-
|
111 |
-
if len(chat_history) < 4:
|
112 |
-
user = 0
|
113 |
-
ai = 1
|
114 |
-
user_msgs = [msg_pair[user] for msg_pair in chat_history[1:]]
|
115 |
-
f_init_prompt = self.init_prompt.format_prompt(
|
116 |
-
ingredients=user_msgs[0],
|
117 |
-
allergies=user_msgs[1],
|
118 |
-
recipe_freeform_input=user_msg,
|
119 |
-
)
|
120 |
-
chat_msgs = f_init_prompt.to_messages()
|
121 |
-
results = self.llm.generate([chat_msgs])
|
122 |
-
chat_msgs.append(results.generations[0][0].message)
|
123 |
-
# prepare the agent to takeover from this point
|
124 |
-
self.init_agent_executor(chat_msgs)
|
125 |
-
return self.agent_executor.run("Search for a vegan recipe with that query")
|
126 |
-
|
127 |
-
response = self.agent_executor.run(input=user_msg)
|
128 |
-
return response
|
129 |
-
|
130 |
-
# %% ../nbs/01_app.ipynb 20
|
131 |
-
def create_demo(bot: ConversationBot):
|
132 |
-
sample_images = []
|
133 |
-
all_imgs = [f"{SAMPLE_IMG_DIR}/{img}" for img in os.listdir(SAMPLE_IMG_DIR)]
|
134 |
-
for i, img in enumerate(all_imgs):
|
135 |
-
if i in [
|
136 |
-
1,
|
137 |
-
2,
|
138 |
-
3,
|
139 |
-
]:
|
140 |
-
sample_images.append(img)
|
141 |
-
with gr.Blocks() as demo:
|
142 |
-
gr_img = gr.Image(type="filepath")
|
143 |
-
btn = gr.Button(value="Submit image")
|
144 |
-
ingredients_msg = gr.Text(label="Ingredients from image")
|
145 |
-
btn.click(bot.run_img, inputs=[gr_img], outputs=[ingredients_msg])
|
146 |
-
gr.Examples(
|
147 |
-
examples=sample_images,
|
148 |
-
inputs=gr_img,
|
149 |
-
)
|
150 |
-
|
151 |
-
chatbot = gr.Chatbot(
|
152 |
-
value=[(None, bot.ai_prompt_questions["ingredients"].prompt.template)]
|
153 |
-
)
|
154 |
-
|
155 |
-
msg = gr.Textbox()
|
156 |
-
# clear = gr.Button("Clear")
|
157 |
-
gr.Markdown(
|
158 |
-
"""
|
159 |
-
**🔃Refresh the page to start from scratch🔃**
|
160 |
-
|
161 |
-
Recipe search tool powered by the [Edamam API](https://www.edamam.com/)
|
162 |
-
|
163 |
-

|
164 |
-
"""
|
165 |
-
)
|
166 |
-
msg.submit(
|
167 |
-
fn=bot.respond, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=False
|
168 |
-
)
|
169 |
-
# clear.click(lambda: None, None, chatbot, queue=False).then(bot.reset)
|
170 |
-
return demo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Anonymous-sub/Rerender/src/img_util.py
DELETED
@@ -1,25 +0,0 @@
|
|
1 |
-
import einops
|
2 |
-
import torch
|
3 |
-
import torch.nn.functional as F
|
4 |
-
|
5 |
-
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
6 |
-
|
7 |
-
|
8 |
-
@torch.no_grad()
|
9 |
-
def find_flat_region(mask):
|
10 |
-
device = mask.device
|
11 |
-
kernel_x = torch.Tensor([[-1, 0, 1], [-1, 0, 1],
|
12 |
-
[-1, 0, 1]]).unsqueeze(0).unsqueeze(0).to(device)
|
13 |
-
kernel_y = torch.Tensor([[-1, -1, -1], [0, 0, 0],
|
14 |
-
[1, 1, 1]]).unsqueeze(0).unsqueeze(0).to(device)
|
15 |
-
mask_ = F.pad(mask.unsqueeze(0), (1, 1, 1, 1), mode='replicate')
|
16 |
-
|
17 |
-
grad_x = torch.nn.functional.conv2d(mask_, kernel_x)
|
18 |
-
grad_y = torch.nn.functional.conv2d(mask_, kernel_y)
|
19 |
-
return ((abs(grad_x) + abs(grad_y)) == 0).float()[0]
|
20 |
-
|
21 |
-
|
22 |
-
def numpy2tensor(img):
|
23 |
-
x0 = torch.from_numpy(img.copy()).float().to(device) / 255.0 * 2.0 - 1.
|
24 |
-
x0 = torch.stack([x0], dim=0)
|
25 |
-
return einops.rearrange(x0, 'b h w c -> b c h w').clone()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Arnx/MusicGenXvAKN/README.md
DELETED
@@ -1,141 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: MusicGen
|
3 |
-
python_version: '3.9'
|
4 |
-
tags:
|
5 |
-
- music generation
|
6 |
-
- language models
|
7 |
-
- LLMs
|
8 |
-
app_file: app.py
|
9 |
-
emoji: 🎵
|
10 |
-
colorFrom: white
|
11 |
-
colorTo: blue
|
12 |
-
sdk: gradio
|
13 |
-
sdk_version: 3.34.0
|
14 |
-
pinned: true
|
15 |
-
license: cc-by-nc-4.0
|
16 |
-
duplicated_from: facebook/MusicGen
|
17 |
-
---
|
18 |
-
# Audiocraft
|
19 |
-

|
20 |
-

|
21 |
-

|
22 |
-
|
23 |
-
Audiocraft is a PyTorch library for deep learning research on audio generation. At the moment, it contains the code for MusicGen, a state-of-the-art controllable text-to-music model.
|
24 |
-
|
25 |
-
## MusicGen
|
26 |
-
|
27 |
-
Audiocraft provides the code and models for MusicGen, [a simple and controllable model for music generation][arxiv]. MusicGen is a single stage auto-regressive
|
28 |
-
Transformer model trained over a 32kHz <a href="https://github.com/facebookresearch/encodec">EnCodec tokenizer</a> with 4 codebooks sampled at 50 Hz. Unlike existing methods like [MusicLM](https://arxiv.org/abs/2301.11325), MusicGen doesn't require a self-supervised semantic representation, and it generates
|
29 |
-
all 4 codebooks in one pass. By introducing a small delay between the codebooks, we show we can predict
|
30 |
-
them in parallel, thus having only 50 auto-regressive steps per second of audio.
|
31 |
-
Check out our [sample page][musicgen_samples] or test the available demo!
|
32 |
-
|
33 |
-
<a target="_blank" href="https://colab.research.google.com/drive/1-Xe9NCdIs2sCUbiSmwHXozK6AAhMm7_i?usp=sharing">
|
34 |
-
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
|
35 |
-
</a>
|
36 |
-
<a target="_blank" href="https://huggingface.co/spaces/facebook/MusicGen">
|
37 |
-
<img src="https://huggingface.co/datasets/huggingface/badges/raw/main/open-in-hf-spaces-sm.svg" alt="Open in HugginFace"/>
|
38 |
-
</a>
|
39 |
-
<br>
|
40 |
-
|
41 |
-
We use 20K hours of licensed music to train MusicGen. Specifically, we rely on an internal dataset of 10K high-quality music tracks, and on the ShutterStock and Pond5 music data.
|
42 |
-
|
43 |
-
## Installation
|
44 |
-
Audiocraft requires Python 3.9, PyTorch 2.0.0, and a GPU with at least 16 GB of memory (for the medium-sized model). To install Audiocraft, you can run the following:
|
45 |
-
|
46 |
-
```shell
|
47 |
-
# Best to make sure you have torch installed first, in particular before installing xformers.
|
48 |
-
# Don't run this if you already have PyTorch installed.
|
49 |
-
pip install 'torch>=2.0'
|
50 |
-
# Then proceed to one of the following
|
51 |
-
pip install -U audiocraft # stable release
|
52 |
-
pip install -U git+https://[email protected]/facebookresearch/audiocraft#egg=audiocraft # bleeding edge
|
53 |
-
pip install -e . # or if you cloned the repo locally
|
54 |
-
```
|
55 |
-
|
56 |
-
## Usage
|
57 |
-
We offer a number of way to interact with MusicGen:
|
58 |
-
1. A demo is also available on the [`facebook/MusicGen` HuggingFace Space](https://huggingface.co/spaces/facebook/MusicGen) (huge thanks to all the HF team for their support).
|
59 |
-
2. You can run the Gradio demo in Colab: [colab notebook](https://colab.research.google.com/drive/1fxGqfg96RBUvGxZ1XXN07s3DthrKUl4-?usp=sharing).
|
60 |
-
3. You can use the gradio demo locally by running `python app.py`.
|
61 |
-
4. You can play with MusicGen by running the jupyter notebook at [`demo.ipynb`](./demo.ipynb) locally (if you have a GPU).
|
62 |
-
5. Finally, checkout [@camenduru Colab page](https://github.com/camenduru/MusicGen-colab) which is regularly
|
63 |
-
updated with contributions from @camenduru and the community.
|
64 |
-
|
65 |
-
## API
|
66 |
-
|
67 |
-
We provide a simple API and 4 pre-trained models. The pre trained models are:
|
68 |
-
- `small`: 300M model, text to music only - [🤗 Hub](https://huggingface.co/facebook/musicgen-small)
|
69 |
-
- `medium`: 1.5B model, text to music only - [🤗 Hub](https://huggingface.co/facebook/musicgen-medium)
|
70 |
-
- `melody`: 1.5B model, text to music and text+melody to music - [🤗 Hub](https://huggingface.co/facebook/musicgen-melody)
|
71 |
-
- `large`: 3.3B model, text to music only - [🤗 Hub](https://huggingface.co/facebook/musicgen-large)
|
72 |
-
|
73 |
-
We observe the best trade-off between quality and compute with the `medium` or `melody` model.
|
74 |
-
In order to use MusicGen locally **you must have a GPU**. We recommend 16GB of memory, but smaller
|
75 |
-
GPUs will be able to generate short sequences, or longer sequences with the `small` model.
|
76 |
-
|
77 |
-
**Note**: Please make sure to have [ffmpeg](https://ffmpeg.org/download.html) installed when using newer version of `torchaudio`.
|
78 |
-
You can install it with:
|
79 |
-
```
|
80 |
-
apt-get install ffmpeg
|
81 |
-
```
|
82 |
-
|
83 |
-
See after a quick example for using the API.
|
84 |
-
|
85 |
-
```python
|
86 |
-
import torchaudio
|
87 |
-
from audiocraft.models import MusicGen
|
88 |
-
from audiocraft.data.audio import audio_write
|
89 |
-
|
90 |
-
model = MusicGen.get_pretrained('melody')
|
91 |
-
model.set_generation_params(duration=8) # generate 8 seconds.
|
92 |
-
wav = model.generate_unconditional(4) # generates 4 unconditional audio samples
|
93 |
-
descriptions = ['happy rock', 'energetic EDM', 'sad jazz']
|
94 |
-
wav = model.generate(descriptions) # generates 3 samples.
|
95 |
-
|
96 |
-
melody, sr = torchaudio.load('./assets/bach.mp3')
|
97 |
-
# generates using the melody from the given audio and the provided descriptions.
|
98 |
-
wav = model.generate_with_chroma(descriptions, melody[None].expand(3, -1, -1), sr)
|
99 |
-
|
100 |
-
for idx, one_wav in enumerate(wav):
|
101 |
-
# Will save under {idx}.wav, with loudness normalization at -14 db LUFS.
|
102 |
-
audio_write(f'{idx}', one_wav.cpu(), model.sample_rate, strategy="loudness", loudness_compressor=True)
|
103 |
-
```
|
104 |
-
|
105 |
-
|
106 |
-
## Model Card
|
107 |
-
|
108 |
-
See [the model card page](./MODEL_CARD.md).
|
109 |
-
|
110 |
-
## FAQ
|
111 |
-
|
112 |
-
#### Will the training code be released?
|
113 |
-
|
114 |
-
Yes. We will soon release the training code for MusicGen and EnCodec.
|
115 |
-
|
116 |
-
|
117 |
-
#### I need help on Windows
|
118 |
-
|
119 |
-
@FurkanGozukara made a complete tutorial for [Audiocraft/MusicGen on Windows](https://youtu.be/v-YpvPkhdO4)
|
120 |
-
|
121 |
-
#### I need help for running the demo on Colab
|
122 |
-
|
123 |
-
Check [@camenduru tutorial on Youtube](https://www.youtube.com/watch?v=EGfxuTy9Eeo).
|
124 |
-
|
125 |
-
|
126 |
-
## Citation
|
127 |
-
```
|
128 |
-
@article{copet2023simple,
|
129 |
-
title={Simple and Controllable Music Generation},
|
130 |
-
author={Jade Copet and Felix Kreuk and Itai Gat and Tal Remez and David Kant and Gabriel Synnaeve and Yossi Adi and Alexandre Défossez},
|
131 |
-
year={2023},
|
132 |
-
journal={arXiv preprint arXiv:2306.05284},
|
133 |
-
}
|
134 |
-
```
|
135 |
-
|
136 |
-
## License
|
137 |
-
* The code in this repository is released under the MIT license as found in the [LICENSE file](LICENSE).
|
138 |
-
* The weights in this repository are released under the CC-BY-NC 4.0 license as found in the [LICENSE_weights file](LICENSE_weights).
|
139 |
-
|
140 |
-
[arxiv]: https://arxiv.org/abs/2306.05284
|
141 |
-
[musicgen_samples]: https://ai.honu.io/papers/musicgen/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/pip/_vendor/rich/cells.py
DELETED
@@ -1,154 +0,0 @@
|
|
1 |
-
import re
|
2 |
-
from functools import lru_cache
|
3 |
-
from typing import Callable, List
|
4 |
-
|
5 |
-
from ._cell_widths import CELL_WIDTHS
|
6 |
-
|
7 |
-
# Regex to match sequence of the most common character ranges
|
8 |
-
_is_single_cell_widths = re.compile("^[\u0020-\u006f\u00a0\u02ff\u0370-\u0482]*$").match
|
9 |
-
|
10 |
-
|
11 |
-
@lru_cache(4096)
|
12 |
-
def cached_cell_len(text: str) -> int:
|
13 |
-
"""Get the number of cells required to display text.
|
14 |
-
|
15 |
-
This method always caches, which may use up a lot of memory. It is recommended to use
|
16 |
-
`cell_len` over this method.
|
17 |
-
|
18 |
-
Args:
|
19 |
-
text (str): Text to display.
|
20 |
-
|
21 |
-
Returns:
|
22 |
-
int: Get the number of cells required to display text.
|
23 |
-
"""
|
24 |
-
_get_size = get_character_cell_size
|
25 |
-
total_size = sum(_get_size(character) for character in text)
|
26 |
-
return total_size
|
27 |
-
|
28 |
-
|
29 |
-
def cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int:
|
30 |
-
"""Get the number of cells required to display text.
|
31 |
-
|
32 |
-
Args:
|
33 |
-
text (str): Text to display.
|
34 |
-
|
35 |
-
Returns:
|
36 |
-
int: Get the number of cells required to display text.
|
37 |
-
"""
|
38 |
-
if len(text) < 512:
|
39 |
-
return _cell_len(text)
|
40 |
-
_get_size = get_character_cell_size
|
41 |
-
total_size = sum(_get_size(character) for character in text)
|
42 |
-
return total_size
|
43 |
-
|
44 |
-
|
45 |
-
@lru_cache(maxsize=4096)
|
46 |
-
def get_character_cell_size(character: str) -> int:
|
47 |
-
"""Get the cell size of a character.
|
48 |
-
|
49 |
-
Args:
|
50 |
-
character (str): A single character.
|
51 |
-
|
52 |
-
Returns:
|
53 |
-
int: Number of cells (0, 1 or 2) occupied by that character.
|
54 |
-
"""
|
55 |
-
return _get_codepoint_cell_size(ord(character))
|
56 |
-
|
57 |
-
|
58 |
-
@lru_cache(maxsize=4096)
|
59 |
-
def _get_codepoint_cell_size(codepoint: int) -> int:
|
60 |
-
"""Get the cell size of a character.
|
61 |
-
|
62 |
-
Args:
|
63 |
-
codepoint (int): Codepoint of a character.
|
64 |
-
|
65 |
-
Returns:
|
66 |
-
int: Number of cells (0, 1 or 2) occupied by that character.
|
67 |
-
"""
|
68 |
-
|
69 |
-
_table = CELL_WIDTHS
|
70 |
-
lower_bound = 0
|
71 |
-
upper_bound = len(_table) - 1
|
72 |
-
index = (lower_bound + upper_bound) // 2
|
73 |
-
while True:
|
74 |
-
start, end, width = _table[index]
|
75 |
-
if codepoint < start:
|
76 |
-
upper_bound = index - 1
|
77 |
-
elif codepoint > end:
|
78 |
-
lower_bound = index + 1
|
79 |
-
else:
|
80 |
-
return 0 if width == -1 else width
|
81 |
-
if upper_bound < lower_bound:
|
82 |
-
break
|
83 |
-
index = (lower_bound + upper_bound) // 2
|
84 |
-
return 1
|
85 |
-
|
86 |
-
|
87 |
-
def set_cell_size(text: str, total: int) -> str:
|
88 |
-
"""Set the length of a string to fit within given number of cells."""
|
89 |
-
|
90 |
-
if _is_single_cell_widths(text):
|
91 |
-
size = len(text)
|
92 |
-
if size < total:
|
93 |
-
return text + " " * (total - size)
|
94 |
-
return text[:total]
|
95 |
-
|
96 |
-
if total <= 0:
|
97 |
-
return ""
|
98 |
-
cell_size = cell_len(text)
|
99 |
-
if cell_size == total:
|
100 |
-
return text
|
101 |
-
if cell_size < total:
|
102 |
-
return text + " " * (total - cell_size)
|
103 |
-
|
104 |
-
start = 0
|
105 |
-
end = len(text)
|
106 |
-
|
107 |
-
# Binary search until we find the right size
|
108 |
-
while True:
|
109 |
-
pos = (start + end) // 2
|
110 |
-
before = text[: pos + 1]
|
111 |
-
before_len = cell_len(before)
|
112 |
-
if before_len == total + 1 and cell_len(before[-1]) == 2:
|
113 |
-
return before[:-1] + " "
|
114 |
-
if before_len == total:
|
115 |
-
return before
|
116 |
-
if before_len > total:
|
117 |
-
end = pos
|
118 |
-
else:
|
119 |
-
start = pos
|
120 |
-
|
121 |
-
|
122 |
-
# TODO: This is inefficient
|
123 |
-
# TODO: This might not work with CWJ type characters
|
124 |
-
def chop_cells(text: str, max_size: int, position: int = 0) -> List[str]:
|
125 |
-
"""Break text in to equal (cell) length strings, returning the characters in reverse
|
126 |
-
order"""
|
127 |
-
_get_character_cell_size = get_character_cell_size
|
128 |
-
characters = [
|
129 |
-
(character, _get_character_cell_size(character)) for character in text
|
130 |
-
]
|
131 |
-
total_size = position
|
132 |
-
lines: List[List[str]] = [[]]
|
133 |
-
append = lines[-1].append
|
134 |
-
|
135 |
-
for character, size in reversed(characters):
|
136 |
-
if total_size + size > max_size:
|
137 |
-
lines.append([character])
|
138 |
-
append = lines[-1].append
|
139 |
-
total_size = size
|
140 |
-
else:
|
141 |
-
total_size += size
|
142 |
-
append(character)
|
143 |
-
|
144 |
-
return ["".join(line) for line in lines]
|
145 |
-
|
146 |
-
|
147 |
-
if __name__ == "__main__": # pragma: no cover
|
148 |
-
|
149 |
-
print(get_character_cell_size("😽"))
|
150 |
-
for line in chop_cells("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", 8):
|
151 |
-
print(line)
|
152 |
-
for n in range(80, 1, -1):
|
153 |
-
print(set_cell_size("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", n) + "|")
|
154 |
-
print("x" * n)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/AutoLLM/ArxivDigest/README.md
DELETED
@@ -1,13 +0,0 @@
|
|
1 |
-
---
|
2 |
-
title: Arxiv Digest
|
3 |
-
emoji: 👁
|
4 |
-
colorFrom: pink
|
5 |
-
colorTo: red
|
6 |
-
sdk: gradio
|
7 |
-
sdk_version: 3.29.0
|
8 |
-
app_file: app.py
|
9 |
-
pinned: false
|
10 |
-
license: mit
|
11 |
-
---
|
12 |
-
|
13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/configs/Detectron1-Comparisons/README.md
DELETED
@@ -1,84 +0,0 @@
|
|
1 |
-
|
2 |
-
Detectron2 model zoo's experimental settings and a few implementation details are different from Detectron.
|
3 |
-
|
4 |
-
The differences in implementation details are shared in
|
5 |
-
[Compatibility with Other Libraries](../../docs/notes/compatibility.md).
|
6 |
-
|
7 |
-
The differences in model zoo's experimental settings include:
|
8 |
-
* Use scale augmentation during training. This improves AP with lower training cost.
|
9 |
-
* Use L1 loss instead of smooth L1 loss for simplicity. This sometimes improves box AP but may
|
10 |
-
affect other AP.
|
11 |
-
* Use `POOLER_SAMPLING_RATIO=0` instead of 2. This does not significantly affect AP.
|
12 |
-
* Use `ROIAlignV2`. This does not significantly affect AP.
|
13 |
-
|
14 |
-
In this directory, we provide a few configs that __do not__ have the above changes.
|
15 |
-
They mimic Detectron's behavior as close as possible,
|
16 |
-
and provide a fair comparison of accuracy and speed against Detectron.
|
17 |
-
|
18 |
-
<!--
|
19 |
-
./gen_html_table.py --config 'Detectron1-Comparisons/*.yaml' --name "Faster R-CNN" "Keypoint R-CNN" "Mask R-CNN" --fields lr_sched train_speed inference_speed mem box_AP mask_AP keypoint_AP --base-dir ../../../configs/Detectron1-Comparisons
|
20 |
-
-->
|
21 |
-
|
22 |
-
|
23 |
-
<table><tbody>
|
24 |
-
<!-- START TABLE -->
|
25 |
-
<!-- TABLE HEADER -->
|
26 |
-
<th valign="bottom">Name</th>
|
27 |
-
<th valign="bottom">lr<br/>sched</th>
|
28 |
-
<th valign="bottom">train<br/>time<br/>(s/iter)</th>
|
29 |
-
<th valign="bottom">inference<br/>time<br/>(s/im)</th>
|
30 |
-
<th valign="bottom">train<br/>mem<br/>(GB)</th>
|
31 |
-
<th valign="bottom">box<br/>AP</th>
|
32 |
-
<th valign="bottom">mask<br/>AP</th>
|
33 |
-
<th valign="bottom">kp.<br/>AP</th>
|
34 |
-
<th valign="bottom">model id</th>
|
35 |
-
<th valign="bottom">download</th>
|
36 |
-
<!-- TABLE BODY -->
|
37 |
-
<!-- ROW: faster_rcnn_R_50_FPN_noaug_1x -->
|
38 |
-
<tr><td align="left"><a href="faster_rcnn_R_50_FPN_noaug_1x.yaml">Faster R-CNN</a></td>
|
39 |
-
<td align="center">1x</td>
|
40 |
-
<td align="center">0.219</td>
|
41 |
-
<td align="center">0.038</td>
|
42 |
-
<td align="center">3.1</td>
|
43 |
-
<td align="center">36.9</td>
|
44 |
-
<td align="center"></td>
|
45 |
-
<td align="center"></td>
|
46 |
-
<td align="center">137781054</td>
|
47 |
-
<td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Detectron1-Comparisons/faster_rcnn_R_50_FPN_noaug_1x/137781054/model_final_7ab50c.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Detectron1-Comparisons/faster_rcnn_R_50_FPN_noaug_1x/137781054/metrics.json">metrics</a></td>
|
48 |
-
</tr>
|
49 |
-
<!-- ROW: keypoint_rcnn_R_50_FPN_1x -->
|
50 |
-
<tr><td align="left"><a href="keypoint_rcnn_R_50_FPN_1x.yaml">Keypoint R-CNN</a></td>
|
51 |
-
<td align="center">1x</td>
|
52 |
-
<td align="center">0.313</td>
|
53 |
-
<td align="center">0.071</td>
|
54 |
-
<td align="center">5.0</td>
|
55 |
-
<td align="center">53.1</td>
|
56 |
-
<td align="center"></td>
|
57 |
-
<td align="center">64.2</td>
|
58 |
-
<td align="center">137781195</td>
|
59 |
-
<td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Detectron1-Comparisons/keypoint_rcnn_R_50_FPN_1x/137781195/model_final_cce136.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Detectron1-Comparisons/keypoint_rcnn_R_50_FPN_1x/137781195/metrics.json">metrics</a></td>
|
60 |
-
</tr>
|
61 |
-
<!-- ROW: mask_rcnn_R_50_FPN_noaug_1x -->
|
62 |
-
<tr><td align="left"><a href="mask_rcnn_R_50_FPN_noaug_1x.yaml">Mask R-CNN</a></td>
|
63 |
-
<td align="center">1x</td>
|
64 |
-
<td align="center">0.273</td>
|
65 |
-
<td align="center">0.043</td>
|
66 |
-
<td align="center">3.4</td>
|
67 |
-
<td align="center">37.8</td>
|
68 |
-
<td align="center">34.9</td>
|
69 |
-
<td align="center"></td>
|
70 |
-
<td align="center">137781281</td>
|
71 |
-
<td align="center"><a href="https://dl.fbaipublicfiles.com/detectron2/Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x/137781281/model_final_62ca52.pkl">model</a> | <a href="https://dl.fbaipublicfiles.com/detectron2/Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x/137781281/metrics.json">metrics</a></td>
|
72 |
-
</tr>
|
73 |
-
</tbody></table>
|
74 |
-
|
75 |
-
## Comparisons:
|
76 |
-
|
77 |
-
* Faster R-CNN: Detectron's AP is 36.7, similar to ours.
|
78 |
-
* Keypoint R-CNN: Detectron's AP is box 53.6, keypoint 64.2. Fixing a Detectron's
|
79 |
-
[bug](https://github.com/facebookresearch/Detectron/issues/459) lead to a drop in box AP, and can be
|
80 |
-
compensated back by some parameter tuning.
|
81 |
-
* Mask R-CNN: Detectron's AP is box 37.7, mask 33.9. We're 1 AP better in mask AP, due to more correct implementation.
|
82 |
-
See [this article](https://ppwwyyxx.com/blog/2021/Where-are-Pixels/) for details.
|
83 |
-
|
84 |
-
For speed comparison, see [benchmarks](https://detectron2.readthedocs.io/notes/benchmarks.html).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/modeling/backbone/regnet.py
DELETED
@@ -1,452 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
2 |
-
"""
|
3 |
-
Implementation of RegNet models from :paper:`dds` and :paper:`scaling`.
|
4 |
-
|
5 |
-
This code is adapted from https://github.com/facebookresearch/pycls with minimal modifications.
|
6 |
-
Some code duplication exists between RegNet and ResNets (e.g., ResStem) in order to simplify
|
7 |
-
model loading.
|
8 |
-
"""
|
9 |
-
|
10 |
-
import numpy as np
|
11 |
-
from torch import nn
|
12 |
-
|
13 |
-
from detectron2.layers import CNNBlockBase, ShapeSpec, get_norm
|
14 |
-
|
15 |
-
from .backbone import Backbone
|
16 |
-
|
17 |
-
__all__ = [
|
18 |
-
"AnyNet",
|
19 |
-
"RegNet",
|
20 |
-
"ResStem",
|
21 |
-
"SimpleStem",
|
22 |
-
"VanillaBlock",
|
23 |
-
"ResBasicBlock",
|
24 |
-
"ResBottleneckBlock",
|
25 |
-
]
|
26 |
-
|
27 |
-
|
28 |
-
def conv2d(w_in, w_out, k, *, stride=1, groups=1, bias=False):
|
29 |
-
"""Helper for building a conv2d layer."""
|
30 |
-
assert k % 2 == 1, "Only odd size kernels supported to avoid padding issues."
|
31 |
-
s, p, g, b = stride, (k - 1) // 2, groups, bias
|
32 |
-
return nn.Conv2d(w_in, w_out, k, stride=s, padding=p, groups=g, bias=b)
|
33 |
-
|
34 |
-
|
35 |
-
def gap2d():
|
36 |
-
"""Helper for building a global average pooling layer."""
|
37 |
-
return nn.AdaptiveAvgPool2d((1, 1))
|
38 |
-
|
39 |
-
|
40 |
-
def pool2d(k, *, stride=1):
|
41 |
-
"""Helper for building a pool2d layer."""
|
42 |
-
assert k % 2 == 1, "Only odd size kernels supported to avoid padding issues."
|
43 |
-
return nn.MaxPool2d(k, stride=stride, padding=(k - 1) // 2)
|
44 |
-
|
45 |
-
|
46 |
-
def init_weights(m):
|
47 |
-
"""Performs ResNet-style weight initialization."""
|
48 |
-
if isinstance(m, nn.Conv2d):
|
49 |
-
# Note that there is no bias due to BN
|
50 |
-
fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
51 |
-
m.weight.data.normal_(mean=0.0, std=np.sqrt(2.0 / fan_out))
|
52 |
-
elif isinstance(m, nn.BatchNorm2d):
|
53 |
-
m.weight.data.fill_(1.0)
|
54 |
-
m.bias.data.zero_()
|
55 |
-
elif isinstance(m, nn.Linear):
|
56 |
-
m.weight.data.normal_(mean=0.0, std=0.01)
|
57 |
-
m.bias.data.zero_()
|
58 |
-
|
59 |
-
|
60 |
-
class ResStem(CNNBlockBase):
|
61 |
-
"""ResNet stem for ImageNet: 7x7, BN, AF, MaxPool."""
|
62 |
-
|
63 |
-
def __init__(self, w_in, w_out, norm, activation_class):
|
64 |
-
super().__init__(w_in, w_out, 4)
|
65 |
-
self.conv = conv2d(w_in, w_out, 7, stride=2)
|
66 |
-
self.bn = get_norm(norm, w_out)
|
67 |
-
self.af = activation_class()
|
68 |
-
self.pool = pool2d(3, stride=2)
|
69 |
-
|
70 |
-
def forward(self, x):
|
71 |
-
for layer in self.children():
|
72 |
-
x = layer(x)
|
73 |
-
return x
|
74 |
-
|
75 |
-
|
76 |
-
class SimpleStem(CNNBlockBase):
|
77 |
-
"""Simple stem for ImageNet: 3x3, BN, AF."""
|
78 |
-
|
79 |
-
def __init__(self, w_in, w_out, norm, activation_class):
|
80 |
-
super().__init__(w_in, w_out, 2)
|
81 |
-
self.conv = conv2d(w_in, w_out, 3, stride=2)
|
82 |
-
self.bn = get_norm(norm, w_out)
|
83 |
-
self.af = activation_class()
|
84 |
-
|
85 |
-
def forward(self, x):
|
86 |
-
for layer in self.children():
|
87 |
-
x = layer(x)
|
88 |
-
return x
|
89 |
-
|
90 |
-
|
91 |
-
class SE(nn.Module):
|
92 |
-
"""Squeeze-and-Excitation (SE) block: AvgPool, FC, Act, FC, Sigmoid."""
|
93 |
-
|
94 |
-
def __init__(self, w_in, w_se, activation_class):
|
95 |
-
super().__init__()
|
96 |
-
self.avg_pool = gap2d()
|
97 |
-
self.f_ex = nn.Sequential(
|
98 |
-
conv2d(w_in, w_se, 1, bias=True),
|
99 |
-
activation_class(),
|
100 |
-
conv2d(w_se, w_in, 1, bias=True),
|
101 |
-
nn.Sigmoid(),
|
102 |
-
)
|
103 |
-
|
104 |
-
def forward(self, x):
|
105 |
-
return x * self.f_ex(self.avg_pool(x))
|
106 |
-
|
107 |
-
|
108 |
-
class VanillaBlock(CNNBlockBase):
|
109 |
-
"""Vanilla block: [3x3 conv, BN, Relu] x2."""
|
110 |
-
|
111 |
-
def __init__(self, w_in, w_out, stride, norm, activation_class, _params):
|
112 |
-
super().__init__(w_in, w_out, stride)
|
113 |
-
self.a = conv2d(w_in, w_out, 3, stride=stride)
|
114 |
-
self.a_bn = get_norm(norm, w_out)
|
115 |
-
self.a_af = activation_class()
|
116 |
-
self.b = conv2d(w_out, w_out, 3)
|
117 |
-
self.b_bn = get_norm(norm, w_out)
|
118 |
-
self.b_af = activation_class()
|
119 |
-
|
120 |
-
def forward(self, x):
|
121 |
-
for layer in self.children():
|
122 |
-
x = layer(x)
|
123 |
-
return x
|
124 |
-
|
125 |
-
|
126 |
-
class BasicTransform(nn.Module):
|
127 |
-
"""Basic transformation: [3x3 conv, BN, Relu] x2."""
|
128 |
-
|
129 |
-
def __init__(self, w_in, w_out, stride, norm, activation_class, _params):
|
130 |
-
super().__init__()
|
131 |
-
self.a = conv2d(w_in, w_out, 3, stride=stride)
|
132 |
-
self.a_bn = get_norm(norm, w_out)
|
133 |
-
self.a_af = activation_class()
|
134 |
-
self.b = conv2d(w_out, w_out, 3)
|
135 |
-
self.b_bn = get_norm(norm, w_out)
|
136 |
-
self.b_bn.final_bn = True
|
137 |
-
|
138 |
-
def forward(self, x):
|
139 |
-
for layer in self.children():
|
140 |
-
x = layer(x)
|
141 |
-
return x
|
142 |
-
|
143 |
-
|
144 |
-
class ResBasicBlock(CNNBlockBase):
|
145 |
-
"""Residual basic block: x + f(x), f = basic transform."""
|
146 |
-
|
147 |
-
def __init__(self, w_in, w_out, stride, norm, activation_class, params):
|
148 |
-
super().__init__(w_in, w_out, stride)
|
149 |
-
self.proj, self.bn = None, None
|
150 |
-
if (w_in != w_out) or (stride != 1):
|
151 |
-
self.proj = conv2d(w_in, w_out, 1, stride=stride)
|
152 |
-
self.bn = get_norm(norm, w_out)
|
153 |
-
self.f = BasicTransform(w_in, w_out, stride, norm, activation_class, params)
|
154 |
-
self.af = activation_class()
|
155 |
-
|
156 |
-
def forward(self, x):
|
157 |
-
x_p = self.bn(self.proj(x)) if self.proj else x
|
158 |
-
return self.af(x_p + self.f(x))
|
159 |
-
|
160 |
-
|
161 |
-
class BottleneckTransform(nn.Module):
|
162 |
-
"""Bottleneck transformation: 1x1, 3x3 [+SE], 1x1."""
|
163 |
-
|
164 |
-
def __init__(self, w_in, w_out, stride, norm, activation_class, params):
|
165 |
-
super().__init__()
|
166 |
-
w_b = int(round(w_out * params["bot_mul"]))
|
167 |
-
w_se = int(round(w_in * params["se_r"]))
|
168 |
-
groups = w_b // params["group_w"]
|
169 |
-
self.a = conv2d(w_in, w_b, 1)
|
170 |
-
self.a_bn = get_norm(norm, w_b)
|
171 |
-
self.a_af = activation_class()
|
172 |
-
self.b = conv2d(w_b, w_b, 3, stride=stride, groups=groups)
|
173 |
-
self.b_bn = get_norm(norm, w_b)
|
174 |
-
self.b_af = activation_class()
|
175 |
-
self.se = SE(w_b, w_se, activation_class) if w_se else None
|
176 |
-
self.c = conv2d(w_b, w_out, 1)
|
177 |
-
self.c_bn = get_norm(norm, w_out)
|
178 |
-
self.c_bn.final_bn = True
|
179 |
-
|
180 |
-
def forward(self, x):
|
181 |
-
for layer in self.children():
|
182 |
-
x = layer(x)
|
183 |
-
return x
|
184 |
-
|
185 |
-
|
186 |
-
class ResBottleneckBlock(CNNBlockBase):
|
187 |
-
"""Residual bottleneck block: x + f(x), f = bottleneck transform."""
|
188 |
-
|
189 |
-
def __init__(self, w_in, w_out, stride, norm, activation_class, params):
|
190 |
-
super().__init__(w_in, w_out, stride)
|
191 |
-
self.proj, self.bn = None, None
|
192 |
-
if (w_in != w_out) or (stride != 1):
|
193 |
-
self.proj = conv2d(w_in, w_out, 1, stride=stride)
|
194 |
-
self.bn = get_norm(norm, w_out)
|
195 |
-
self.f = BottleneckTransform(w_in, w_out, stride, norm, activation_class, params)
|
196 |
-
self.af = activation_class()
|
197 |
-
|
198 |
-
def forward(self, x):
|
199 |
-
x_p = self.bn(self.proj(x)) if self.proj else x
|
200 |
-
return self.af(x_p + self.f(x))
|
201 |
-
|
202 |
-
|
203 |
-
class AnyStage(nn.Module):
|
204 |
-
"""AnyNet stage (sequence of blocks w/ the same output shape)."""
|
205 |
-
|
206 |
-
def __init__(self, w_in, w_out, stride, d, block_class, norm, activation_class, params):
|
207 |
-
super().__init__()
|
208 |
-
for i in range(d):
|
209 |
-
block = block_class(w_in, w_out, stride, norm, activation_class, params)
|
210 |
-
self.add_module("b{}".format(i + 1), block)
|
211 |
-
stride, w_in = 1, w_out
|
212 |
-
|
213 |
-
def forward(self, x):
|
214 |
-
for block in self.children():
|
215 |
-
x = block(x)
|
216 |
-
return x
|
217 |
-
|
218 |
-
|
219 |
-
class AnyNet(Backbone):
|
220 |
-
"""AnyNet model. See :paper:`dds`."""
|
221 |
-
|
222 |
-
def __init__(
|
223 |
-
self,
|
224 |
-
*,
|
225 |
-
stem_class,
|
226 |
-
stem_width,
|
227 |
-
block_class,
|
228 |
-
depths,
|
229 |
-
widths,
|
230 |
-
group_widths,
|
231 |
-
strides,
|
232 |
-
bottleneck_ratios,
|
233 |
-
se_ratio,
|
234 |
-
activation_class,
|
235 |
-
freeze_at=0,
|
236 |
-
norm="BN",
|
237 |
-
out_features=None,
|
238 |
-
):
|
239 |
-
"""
|
240 |
-
Args:
|
241 |
-
stem_class (callable): A callable taking 4 arguments (channels in, channels out,
|
242 |
-
normalization, callable returning an activation function) that returns another
|
243 |
-
callable implementing the stem module.
|
244 |
-
stem_width (int): The number of output channels that the stem produces.
|
245 |
-
block_class (callable): A callable taking 6 arguments (channels in, channels out,
|
246 |
-
stride, normalization, callable returning an activation function, a dict of
|
247 |
-
block-specific parameters) that returns another callable implementing the repeated
|
248 |
-
block module.
|
249 |
-
depths (list[int]): Number of blocks in each stage.
|
250 |
-
widths (list[int]): For each stage, the number of output channels of each block.
|
251 |
-
group_widths (list[int]): For each stage, the number of channels per group in group
|
252 |
-
convolution, if the block uses group convolution.
|
253 |
-
strides (list[int]): The stride that each network stage applies to its input.
|
254 |
-
bottleneck_ratios (list[float]): For each stage, the ratio of the number of bottleneck
|
255 |
-
channels to the number of block input channels (or, equivalently, output channels),
|
256 |
-
if the block uses a bottleneck.
|
257 |
-
se_ratio (float): The ratio of the number of channels used inside the squeeze-excitation
|
258 |
-
(SE) module to it number of input channels, if SE the block uses SE.
|
259 |
-
activation_class (callable): A callable taking no arguments that returns another
|
260 |
-
callable implementing an activation function.
|
261 |
-
freeze_at (int): The number of stages at the beginning to freeze.
|
262 |
-
see :meth:`freeze` for detailed explanation.
|
263 |
-
norm (str or callable): normalization for all conv layers.
|
264 |
-
See :func:`layers.get_norm` for supported format.
|
265 |
-
out_features (list[str]): name of the layers whose outputs should
|
266 |
-
be returned in forward. RegNet's use "stem" and "s1", "s2", etc for the stages after
|
267 |
-
the stem. If None, will return the output of the last layer.
|
268 |
-
"""
|
269 |
-
super().__init__()
|
270 |
-
self.stem = stem_class(3, stem_width, norm, activation_class)
|
271 |
-
|
272 |
-
current_stride = self.stem.stride
|
273 |
-
self._out_feature_strides = {"stem": current_stride}
|
274 |
-
self._out_feature_channels = {"stem": self.stem.out_channels}
|
275 |
-
self.stages_and_names = []
|
276 |
-
prev_w = stem_width
|
277 |
-
|
278 |
-
for i, (d, w, s, b, g) in enumerate(
|
279 |
-
zip(depths, widths, strides, bottleneck_ratios, group_widths)
|
280 |
-
):
|
281 |
-
params = {"bot_mul": b, "group_w": g, "se_r": se_ratio}
|
282 |
-
stage = AnyStage(prev_w, w, s, d, block_class, norm, activation_class, params)
|
283 |
-
name = "s{}".format(i + 1)
|
284 |
-
self.add_module(name, stage)
|
285 |
-
self.stages_and_names.append((stage, name))
|
286 |
-
self._out_feature_strides[name] = current_stride = int(
|
287 |
-
current_stride * np.prod([k.stride for k in stage.children()])
|
288 |
-
)
|
289 |
-
self._out_feature_channels[name] = list(stage.children())[-1].out_channels
|
290 |
-
prev_w = w
|
291 |
-
|
292 |
-
self.apply(init_weights)
|
293 |
-
|
294 |
-
if out_features is None:
|
295 |
-
out_features = [name]
|
296 |
-
self._out_features = out_features
|
297 |
-
assert len(self._out_features)
|
298 |
-
children = [x[0] for x in self.named_children()]
|
299 |
-
for out_feature in self._out_features:
|
300 |
-
assert out_feature in children, "Available children: {} does not include {}".format(
|
301 |
-
", ".join(children), out_feature
|
302 |
-
)
|
303 |
-
self.freeze(freeze_at)
|
304 |
-
|
305 |
-
def forward(self, x):
|
306 |
-
"""
|
307 |
-
Args:
|
308 |
-
x: Tensor of shape (N,C,H,W). H, W must be a multiple of ``self.size_divisibility``.
|
309 |
-
|
310 |
-
Returns:
|
311 |
-
dict[str->Tensor]: names and the corresponding features
|
312 |
-
"""
|
313 |
-
assert x.dim() == 4, f"Model takes an input of shape (N, C, H, W). Got {x.shape} instead!"
|
314 |
-
outputs = {}
|
315 |
-
x = self.stem(x)
|
316 |
-
if "stem" in self._out_features:
|
317 |
-
outputs["stem"] = x
|
318 |
-
for stage, name in self.stages_and_names:
|
319 |
-
x = stage(x)
|
320 |
-
if name in self._out_features:
|
321 |
-
outputs[name] = x
|
322 |
-
return outputs
|
323 |
-
|
324 |
-
def output_shape(self):
|
325 |
-
return {
|
326 |
-
name: ShapeSpec(
|
327 |
-
channels=self._out_feature_channels[name], stride=self._out_feature_strides[name]
|
328 |
-
)
|
329 |
-
for name in self._out_features
|
330 |
-
}
|
331 |
-
|
332 |
-
def freeze(self, freeze_at=0):
|
333 |
-
"""
|
334 |
-
Freeze the first several stages of the model. Commonly used in fine-tuning.
|
335 |
-
|
336 |
-
Layers that produce the same feature map spatial size are defined as one
|
337 |
-
"stage" by :paper:`FPN`.
|
338 |
-
|
339 |
-
Args:
|
340 |
-
freeze_at (int): number of stages to freeze.
|
341 |
-
`1` means freezing the stem. `2` means freezing the stem and
|
342 |
-
one residual stage, etc.
|
343 |
-
|
344 |
-
Returns:
|
345 |
-
nn.Module: this model itself
|
346 |
-
"""
|
347 |
-
if freeze_at >= 1:
|
348 |
-
self.stem.freeze()
|
349 |
-
for idx, (stage, _) in enumerate(self.stages_and_names, start=2):
|
350 |
-
if freeze_at >= idx:
|
351 |
-
for block in stage.children():
|
352 |
-
block.freeze()
|
353 |
-
return self
|
354 |
-
|
355 |
-
|
356 |
-
def adjust_block_compatibility(ws, bs, gs):
|
357 |
-
"""Adjusts the compatibility of widths, bottlenecks, and groups."""
|
358 |
-
assert len(ws) == len(bs) == len(gs)
|
359 |
-
assert all(w > 0 and b > 0 and g > 0 for w, b, g in zip(ws, bs, gs))
|
360 |
-
vs = [int(max(1, w * b)) for w, b in zip(ws, bs)]
|
361 |
-
gs = [int(min(g, v)) for g, v in zip(gs, vs)]
|
362 |
-
ms = [np.lcm(g, b) if b > 1 else g for g, b in zip(gs, bs)]
|
363 |
-
vs = [max(m, int(round(v / m) * m)) for v, m in zip(vs, ms)]
|
364 |
-
ws = [int(v / b) for v, b in zip(vs, bs)]
|
365 |
-
assert all(w * b % g == 0 for w, b, g in zip(ws, bs, gs))
|
366 |
-
return ws, bs, gs
|
367 |
-
|
368 |
-
|
369 |
-
def generate_regnet_parameters(w_a, w_0, w_m, d, q=8):
|
370 |
-
"""Generates per stage widths and depths from RegNet parameters."""
|
371 |
-
assert w_a >= 0 and w_0 > 0 and w_m > 1 and w_0 % q == 0
|
372 |
-
# Generate continuous per-block ws
|
373 |
-
ws_cont = np.arange(d) * w_a + w_0
|
374 |
-
# Generate quantized per-block ws
|
375 |
-
ks = np.round(np.log(ws_cont / w_0) / np.log(w_m))
|
376 |
-
ws_all = w_0 * np.power(w_m, ks)
|
377 |
-
ws_all = np.round(np.divide(ws_all, q)).astype(int) * q
|
378 |
-
# Generate per stage ws and ds (assumes ws_all are sorted)
|
379 |
-
ws, ds = np.unique(ws_all, return_counts=True)
|
380 |
-
# Compute number of actual stages and total possible stages
|
381 |
-
num_stages, total_stages = len(ws), ks.max() + 1
|
382 |
-
# Convert numpy arrays to lists and return
|
383 |
-
ws, ds, ws_all, ws_cont = (x.tolist() for x in (ws, ds, ws_all, ws_cont))
|
384 |
-
return ws, ds, num_stages, total_stages, ws_all, ws_cont
|
385 |
-
|
386 |
-
|
387 |
-
class RegNet(AnyNet):
|
388 |
-
"""RegNet model. See :paper:`dds`."""
|
389 |
-
|
390 |
-
def __init__(
|
391 |
-
self,
|
392 |
-
*,
|
393 |
-
stem_class,
|
394 |
-
stem_width,
|
395 |
-
block_class,
|
396 |
-
depth,
|
397 |
-
w_a,
|
398 |
-
w_0,
|
399 |
-
w_m,
|
400 |
-
group_width,
|
401 |
-
stride=2,
|
402 |
-
bottleneck_ratio=1.0,
|
403 |
-
se_ratio=0.0,
|
404 |
-
activation_class=None,
|
405 |
-
freeze_at=0,
|
406 |
-
norm="BN",
|
407 |
-
out_features=None,
|
408 |
-
):
|
409 |
-
"""
|
410 |
-
Build a RegNet from the parameterization described in :paper:`dds` Section 3.3.
|
411 |
-
|
412 |
-
Args:
|
413 |
-
See :class:`AnyNet` for arguments that are not listed here.
|
414 |
-
depth (int): Total number of blocks in the RegNet.
|
415 |
-
w_a (float): Factor by which block width would increase prior to quantizing block widths
|
416 |
-
by stage. See :paper:`dds` Section 3.3.
|
417 |
-
w_0 (int): Initial block width. See :paper:`dds` Section 3.3.
|
418 |
-
w_m (float): Parameter controlling block width quantization.
|
419 |
-
See :paper:`dds` Section 3.3.
|
420 |
-
group_width (int): Number of channels per group in group convolution, if the block uses
|
421 |
-
group convolution.
|
422 |
-
bottleneck_ratio (float): The ratio of the number of bottleneck channels to the number
|
423 |
-
of block input channels (or, equivalently, output channels), if the block uses a
|
424 |
-
bottleneck.
|
425 |
-
stride (int): The stride that each network stage applies to its input.
|
426 |
-
"""
|
427 |
-
ws, ds = generate_regnet_parameters(w_a, w_0, w_m, depth)[0:2]
|
428 |
-
ss = [stride for _ in ws]
|
429 |
-
bs = [bottleneck_ratio for _ in ws]
|
430 |
-
gs = [group_width for _ in ws]
|
431 |
-
ws, bs, gs = adjust_block_compatibility(ws, bs, gs)
|
432 |
-
|
433 |
-
def default_activation_class():
|
434 |
-
return nn.ReLU(inplace=True)
|
435 |
-
|
436 |
-
super().__init__(
|
437 |
-
stem_class=stem_class,
|
438 |
-
stem_width=stem_width,
|
439 |
-
block_class=block_class,
|
440 |
-
depths=ds,
|
441 |
-
widths=ws,
|
442 |
-
strides=ss,
|
443 |
-
group_widths=gs,
|
444 |
-
bottleneck_ratios=bs,
|
445 |
-
se_ratio=se_ratio,
|
446 |
-
activation_class=default_activation_class
|
447 |
-
if activation_class is None
|
448 |
-
else activation_class,
|
449 |
-
freeze_at=freeze_at,
|
450 |
-
norm=norm,
|
451 |
-
out_features=out_features,
|
452 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/BatuhanYilmaz/Whisper-Auto-Subtitled-Video-Generator/languages.py
DELETED
@@ -1,101 +0,0 @@
|
|
1 |
-
LANGUAGES = {
|
2 |
-
"en": "eng",
|
3 |
-
"zh": "zho",
|
4 |
-
"de": "deu",
|
5 |
-
"es": "spa",
|
6 |
-
"ru": "rus",
|
7 |
-
"ko": "kor",
|
8 |
-
"fr": "fra",
|
9 |
-
"ja": "jpn",
|
10 |
-
"pt": "por",
|
11 |
-
"tr": "tur",
|
12 |
-
"pl": "pol",
|
13 |
-
"ca": "cat",
|
14 |
-
"nl": "nld",
|
15 |
-
"ar": "ara",
|
16 |
-
"sv": "swe",
|
17 |
-
"it": "ita",
|
18 |
-
"id": "ind",
|
19 |
-
"hi": "hin",
|
20 |
-
"fi": "fin",
|
21 |
-
"vi": "vie",
|
22 |
-
"iw": "heb",
|
23 |
-
"uk": "ukr",
|
24 |
-
"el": "ell",
|
25 |
-
"ms": "msa",
|
26 |
-
"cs": "ces",
|
27 |
-
"ro": "ron",
|
28 |
-
"da": "dan",
|
29 |
-
"hu": "hun",
|
30 |
-
"ta": "tam",
|
31 |
-
"no": "nor",
|
32 |
-
"th": "tha",
|
33 |
-
"ur": "urd",
|
34 |
-
"hr": "hrv",
|
35 |
-
"bg": "bul",
|
36 |
-
"lt": "lit",
|
37 |
-
"la": "lat",
|
38 |
-
"mi": "mri",
|
39 |
-
"ml": "mal",
|
40 |
-
"cy": "cym",
|
41 |
-
"sk": "slk",
|
42 |
-
"te": "tel",
|
43 |
-
"fa": "fas",
|
44 |
-
"lv": "lav",
|
45 |
-
"bn": "ben",
|
46 |
-
"sr": "srp",
|
47 |
-
"az": "aze",
|
48 |
-
"sl": "slv",
|
49 |
-
"kn": "kan",
|
50 |
-
"et": "est",
|
51 |
-
"mk": "mkd",
|
52 |
-
"br": "bre",
|
53 |
-
"eu": "eus",
|
54 |
-
"is": "isl",
|
55 |
-
"hy": "hye",
|
56 |
-
"ne": "nep",
|
57 |
-
"mn": "mon",
|
58 |
-
"bs": "bos",
|
59 |
-
"kk": "kaz",
|
60 |
-
"sq": "sqi",
|
61 |
-
"sw": "swa",
|
62 |
-
"gl": "glg",
|
63 |
-
"mr": "mar",
|
64 |
-
"pa": "pan",
|
65 |
-
"si": "sin",
|
66 |
-
"km": "khm",
|
67 |
-
"sn": "sna",
|
68 |
-
"yo": "yor",
|
69 |
-
"so": "som",
|
70 |
-
"af": "afr",
|
71 |
-
"oc": "oci",
|
72 |
-
"ka": "kat",
|
73 |
-
"be": "bel",
|
74 |
-
"tg": "tgk",
|
75 |
-
"sd": "snd",
|
76 |
-
"gu": "guj",
|
77 |
-
"am": "amh",
|
78 |
-
"yi": "yid",
|
79 |
-
"lo": "lao",
|
80 |
-
"uz": "uzb",
|
81 |
-
"fo": "fao",
|
82 |
-
"ht": "hat",
|
83 |
-
"ps": "pus",
|
84 |
-
"tk": "tuk",
|
85 |
-
"nn": "nno",
|
86 |
-
"mt": "mlt",
|
87 |
-
"sa": "san",
|
88 |
-
"lb": "ltz",
|
89 |
-
"my": "mya",
|
90 |
-
"bo": "bod",
|
91 |
-
"tl": "tgl",
|
92 |
-
"mg": "mlg",
|
93 |
-
"as": "asm",
|
94 |
-
"tt": "tat",
|
95 |
-
"haw": "haw",
|
96 |
-
"ln": "lin",
|
97 |
-
"ha": "hau",
|
98 |
-
"ba": "bak",
|
99 |
-
"jw": "jav",
|
100 |
-
"su": "sun",
|
101 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/req/req_uninstall.py
DELETED
@@ -1,650 +0,0 @@
|
|
1 |
-
import functools
|
2 |
-
import os
|
3 |
-
import sys
|
4 |
-
import sysconfig
|
5 |
-
from importlib.util import cache_from_source
|
6 |
-
from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple
|
7 |
-
|
8 |
-
from pip._internal.exceptions import UninstallationError
|
9 |
-
from pip._internal.locations import get_bin_prefix, get_bin_user
|
10 |
-
from pip._internal.metadata import BaseDistribution
|
11 |
-
from pip._internal.utils.compat import WINDOWS
|
12 |
-
from pip._internal.utils.egg_link import egg_link_path_from_location
|
13 |
-
from pip._internal.utils.logging import getLogger, indent_log
|
14 |
-
from pip._internal.utils.misc import ask, normalize_path, renames, rmtree
|
15 |
-
from pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory
|
16 |
-
from pip._internal.utils.virtualenv import running_under_virtualenv
|
17 |
-
|
18 |
-
logger = getLogger(__name__)
|
19 |
-
|
20 |
-
|
21 |
-
def _script_names(
|
22 |
-
bin_dir: str, script_name: str, is_gui: bool
|
23 |
-
) -> Generator[str, None, None]:
|
24 |
-
"""Create the fully qualified name of the files created by
|
25 |
-
{console,gui}_scripts for the given ``dist``.
|
26 |
-
Returns the list of file names
|
27 |
-
"""
|
28 |
-
exe_name = os.path.join(bin_dir, script_name)
|
29 |
-
yield exe_name
|
30 |
-
if not WINDOWS:
|
31 |
-
return
|
32 |
-
yield f"{exe_name}.exe"
|
33 |
-
yield f"{exe_name}.exe.manifest"
|
34 |
-
if is_gui:
|
35 |
-
yield f"{exe_name}-script.pyw"
|
36 |
-
else:
|
37 |
-
yield f"{exe_name}-script.py"
|
38 |
-
|
39 |
-
|
40 |
-
def _unique(
|
41 |
-
fn: Callable[..., Generator[Any, None, None]]
|
42 |
-
) -> Callable[..., Generator[Any, None, None]]:
|
43 |
-
@functools.wraps(fn)
|
44 |
-
def unique(*args: Any, **kw: Any) -> Generator[Any, None, None]:
|
45 |
-
seen: Set[Any] = set()
|
46 |
-
for item in fn(*args, **kw):
|
47 |
-
if item not in seen:
|
48 |
-
seen.add(item)
|
49 |
-
yield item
|
50 |
-
|
51 |
-
return unique
|
52 |
-
|
53 |
-
|
54 |
-
@_unique
|
55 |
-
def uninstallation_paths(dist: BaseDistribution) -> Generator[str, None, None]:
|
56 |
-
"""
|
57 |
-
Yield all the uninstallation paths for dist based on RECORD-without-.py[co]
|
58 |
-
|
59 |
-
Yield paths to all the files in RECORD. For each .py file in RECORD, add
|
60 |
-
the .pyc and .pyo in the same directory.
|
61 |
-
|
62 |
-
UninstallPathSet.add() takes care of the __pycache__ .py[co].
|
63 |
-
|
64 |
-
If RECORD is not found, raises UninstallationError,
|
65 |
-
with possible information from the INSTALLER file.
|
66 |
-
|
67 |
-
https://packaging.python.org/specifications/recording-installed-packages/
|
68 |
-
"""
|
69 |
-
location = dist.location
|
70 |
-
assert location is not None, "not installed"
|
71 |
-
|
72 |
-
entries = dist.iter_declared_entries()
|
73 |
-
if entries is None:
|
74 |
-
msg = "Cannot uninstall {dist}, RECORD file not found.".format(dist=dist)
|
75 |
-
installer = dist.installer
|
76 |
-
if not installer or installer == "pip":
|
77 |
-
dep = "{}=={}".format(dist.raw_name, dist.version)
|
78 |
-
msg += (
|
79 |
-
" You might be able to recover from this via: "
|
80 |
-
"'pip install --force-reinstall --no-deps {}'.".format(dep)
|
81 |
-
)
|
82 |
-
else:
|
83 |
-
msg += " Hint: The package was installed by {}.".format(installer)
|
84 |
-
raise UninstallationError(msg)
|
85 |
-
|
86 |
-
for entry in entries:
|
87 |
-
path = os.path.join(location, entry)
|
88 |
-
yield path
|
89 |
-
if path.endswith(".py"):
|
90 |
-
dn, fn = os.path.split(path)
|
91 |
-
base = fn[:-3]
|
92 |
-
path = os.path.join(dn, base + ".pyc")
|
93 |
-
yield path
|
94 |
-
path = os.path.join(dn, base + ".pyo")
|
95 |
-
yield path
|
96 |
-
|
97 |
-
|
98 |
-
def compact(paths: Iterable[str]) -> Set[str]:
|
99 |
-
"""Compact a path set to contain the minimal number of paths
|
100 |
-
necessary to contain all paths in the set. If /a/path/ and
|
101 |
-
/a/path/to/a/file.txt are both in the set, leave only the
|
102 |
-
shorter path."""
|
103 |
-
|
104 |
-
sep = os.path.sep
|
105 |
-
short_paths: Set[str] = set()
|
106 |
-
for path in sorted(paths, key=len):
|
107 |
-
should_skip = any(
|
108 |
-
path.startswith(shortpath.rstrip("*"))
|
109 |
-
and path[len(shortpath.rstrip("*").rstrip(sep))] == sep
|
110 |
-
for shortpath in short_paths
|
111 |
-
)
|
112 |
-
if not should_skip:
|
113 |
-
short_paths.add(path)
|
114 |
-
return short_paths
|
115 |
-
|
116 |
-
|
117 |
-
def compress_for_rename(paths: Iterable[str]) -> Set[str]:
|
118 |
-
"""Returns a set containing the paths that need to be renamed.
|
119 |
-
|
120 |
-
This set may include directories when the original sequence of paths
|
121 |
-
included every file on disk.
|
122 |
-
"""
|
123 |
-
case_map = {os.path.normcase(p): p for p in paths}
|
124 |
-
remaining = set(case_map)
|
125 |
-
unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len)
|
126 |
-
wildcards: Set[str] = set()
|
127 |
-
|
128 |
-
def norm_join(*a: str) -> str:
|
129 |
-
return os.path.normcase(os.path.join(*a))
|
130 |
-
|
131 |
-
for root in unchecked:
|
132 |
-
if any(os.path.normcase(root).startswith(w) for w in wildcards):
|
133 |
-
# This directory has already been handled.
|
134 |
-
continue
|
135 |
-
|
136 |
-
all_files: Set[str] = set()
|
137 |
-
all_subdirs: Set[str] = set()
|
138 |
-
for dirname, subdirs, files in os.walk(root):
|
139 |
-
all_subdirs.update(norm_join(root, dirname, d) for d in subdirs)
|
140 |
-
all_files.update(norm_join(root, dirname, f) for f in files)
|
141 |
-
# If all the files we found are in our remaining set of files to
|
142 |
-
# remove, then remove them from the latter set and add a wildcard
|
143 |
-
# for the directory.
|
144 |
-
if not (all_files - remaining):
|
145 |
-
remaining.difference_update(all_files)
|
146 |
-
wildcards.add(root + os.sep)
|
147 |
-
|
148 |
-
return set(map(case_map.__getitem__, remaining)) | wildcards
|
149 |
-
|
150 |
-
|
151 |
-
def compress_for_output_listing(paths: Iterable[str]) -> Tuple[Set[str], Set[str]]:
|
152 |
-
"""Returns a tuple of 2 sets of which paths to display to user
|
153 |
-
|
154 |
-
The first set contains paths that would be deleted. Files of a package
|
155 |
-
are not added and the top-level directory of the package has a '*' added
|
156 |
-
at the end - to signify that all it's contents are removed.
|
157 |
-
|
158 |
-
The second set contains files that would have been skipped in the above
|
159 |
-
folders.
|
160 |
-
"""
|
161 |
-
|
162 |
-
will_remove = set(paths)
|
163 |
-
will_skip = set()
|
164 |
-
|
165 |
-
# Determine folders and files
|
166 |
-
folders = set()
|
167 |
-
files = set()
|
168 |
-
for path in will_remove:
|
169 |
-
if path.endswith(".pyc"):
|
170 |
-
continue
|
171 |
-
if path.endswith("__init__.py") or ".dist-info" in path:
|
172 |
-
folders.add(os.path.dirname(path))
|
173 |
-
files.add(path)
|
174 |
-
|
175 |
-
# probably this one https://github.com/python/mypy/issues/390
|
176 |
-
_normcased_files = set(map(os.path.normcase, files)) # type: ignore
|
177 |
-
|
178 |
-
folders = compact(folders)
|
179 |
-
|
180 |
-
# This walks the tree using os.walk to not miss extra folders
|
181 |
-
# that might get added.
|
182 |
-
for folder in folders:
|
183 |
-
for dirpath, _, dirfiles in os.walk(folder):
|
184 |
-
for fname in dirfiles:
|
185 |
-
if fname.endswith(".pyc"):
|
186 |
-
continue
|
187 |
-
|
188 |
-
file_ = os.path.join(dirpath, fname)
|
189 |
-
if (
|
190 |
-
os.path.isfile(file_)
|
191 |
-
and os.path.normcase(file_) not in _normcased_files
|
192 |
-
):
|
193 |
-
# We are skipping this file. Add it to the set.
|
194 |
-
will_skip.add(file_)
|
195 |
-
|
196 |
-
will_remove = files | {os.path.join(folder, "*") for folder in folders}
|
197 |
-
|
198 |
-
return will_remove, will_skip
|
199 |
-
|
200 |
-
|
201 |
-
class StashedUninstallPathSet:
|
202 |
-
"""A set of file rename operations to stash files while
|
203 |
-
tentatively uninstalling them."""
|
204 |
-
|
205 |
-
def __init__(self) -> None:
|
206 |
-
# Mapping from source file root to [Adjacent]TempDirectory
|
207 |
-
# for files under that directory.
|
208 |
-
self._save_dirs: Dict[str, TempDirectory] = {}
|
209 |
-
# (old path, new path) tuples for each move that may need
|
210 |
-
# to be undone.
|
211 |
-
self._moves: List[Tuple[str, str]] = []
|
212 |
-
|
213 |
-
def _get_directory_stash(self, path: str) -> str:
|
214 |
-
"""Stashes a directory.
|
215 |
-
|
216 |
-
Directories are stashed adjacent to their original location if
|
217 |
-
possible, or else moved/copied into the user's temp dir."""
|
218 |
-
|
219 |
-
try:
|
220 |
-
save_dir: TempDirectory = AdjacentTempDirectory(path)
|
221 |
-
except OSError:
|
222 |
-
save_dir = TempDirectory(kind="uninstall")
|
223 |
-
self._save_dirs[os.path.normcase(path)] = save_dir
|
224 |
-
|
225 |
-
return save_dir.path
|
226 |
-
|
227 |
-
def _get_file_stash(self, path: str) -> str:
|
228 |
-
"""Stashes a file.
|
229 |
-
|
230 |
-
If no root has been provided, one will be created for the directory
|
231 |
-
in the user's temp directory."""
|
232 |
-
path = os.path.normcase(path)
|
233 |
-
head, old_head = os.path.dirname(path), None
|
234 |
-
save_dir = None
|
235 |
-
|
236 |
-
while head != old_head:
|
237 |
-
try:
|
238 |
-
save_dir = self._save_dirs[head]
|
239 |
-
break
|
240 |
-
except KeyError:
|
241 |
-
pass
|
242 |
-
head, old_head = os.path.dirname(head), head
|
243 |
-
else:
|
244 |
-
# Did not find any suitable root
|
245 |
-
head = os.path.dirname(path)
|
246 |
-
save_dir = TempDirectory(kind="uninstall")
|
247 |
-
self._save_dirs[head] = save_dir
|
248 |
-
|
249 |
-
relpath = os.path.relpath(path, head)
|
250 |
-
if relpath and relpath != os.path.curdir:
|
251 |
-
return os.path.join(save_dir.path, relpath)
|
252 |
-
return save_dir.path
|
253 |
-
|
254 |
-
def stash(self, path: str) -> str:
|
255 |
-
"""Stashes the directory or file and returns its new location.
|
256 |
-
Handle symlinks as files to avoid modifying the symlink targets.
|
257 |
-
"""
|
258 |
-
path_is_dir = os.path.isdir(path) and not os.path.islink(path)
|
259 |
-
if path_is_dir:
|
260 |
-
new_path = self._get_directory_stash(path)
|
261 |
-
else:
|
262 |
-
new_path = self._get_file_stash(path)
|
263 |
-
|
264 |
-
self._moves.append((path, new_path))
|
265 |
-
if path_is_dir and os.path.isdir(new_path):
|
266 |
-
# If we're moving a directory, we need to
|
267 |
-
# remove the destination first or else it will be
|
268 |
-
# moved to inside the existing directory.
|
269 |
-
# We just created new_path ourselves, so it will
|
270 |
-
# be removable.
|
271 |
-
os.rmdir(new_path)
|
272 |
-
renames(path, new_path)
|
273 |
-
return new_path
|
274 |
-
|
275 |
-
def commit(self) -> None:
|
276 |
-
"""Commits the uninstall by removing stashed files."""
|
277 |
-
for _, save_dir in self._save_dirs.items():
|
278 |
-
save_dir.cleanup()
|
279 |
-
self._moves = []
|
280 |
-
self._save_dirs = {}
|
281 |
-
|
282 |
-
def rollback(self) -> None:
|
283 |
-
"""Undoes the uninstall by moving stashed files back."""
|
284 |
-
for p in self._moves:
|
285 |
-
logger.info("Moving to %s\n from %s", *p)
|
286 |
-
|
287 |
-
for new_path, path in self._moves:
|
288 |
-
try:
|
289 |
-
logger.debug("Replacing %s from %s", new_path, path)
|
290 |
-
if os.path.isfile(new_path) or os.path.islink(new_path):
|
291 |
-
os.unlink(new_path)
|
292 |
-
elif os.path.isdir(new_path):
|
293 |
-
rmtree(new_path)
|
294 |
-
renames(path, new_path)
|
295 |
-
except OSError as ex:
|
296 |
-
logger.error("Failed to restore %s", new_path)
|
297 |
-
logger.debug("Exception: %s", ex)
|
298 |
-
|
299 |
-
self.commit()
|
300 |
-
|
301 |
-
@property
|
302 |
-
def can_rollback(self) -> bool:
|
303 |
-
return bool(self._moves)
|
304 |
-
|
305 |
-
|
306 |
-
class UninstallPathSet:
|
307 |
-
"""A set of file paths to be removed in the uninstallation of a
|
308 |
-
requirement."""
|
309 |
-
|
310 |
-
def __init__(self, dist: BaseDistribution) -> None:
|
311 |
-
self._paths: Set[str] = set()
|
312 |
-
self._refuse: Set[str] = set()
|
313 |
-
self._pth: Dict[str, UninstallPthEntries] = {}
|
314 |
-
self._dist = dist
|
315 |
-
self._moved_paths = StashedUninstallPathSet()
|
316 |
-
# Create local cache of normalize_path results. Creating an UninstallPathSet
|
317 |
-
# can result in hundreds/thousands of redundant calls to normalize_path with
|
318 |
-
# the same args, which hurts performance.
|
319 |
-
self._normalize_path_cached = functools.lru_cache()(normalize_path)
|
320 |
-
|
321 |
-
def _permitted(self, path: str) -> bool:
|
322 |
-
"""
|
323 |
-
Return True if the given path is one we are permitted to
|
324 |
-
remove/modify, False otherwise.
|
325 |
-
|
326 |
-
"""
|
327 |
-
# aka is_local, but caching normalized sys.prefix
|
328 |
-
if not running_under_virtualenv():
|
329 |
-
return True
|
330 |
-
return path.startswith(self._normalize_path_cached(sys.prefix))
|
331 |
-
|
332 |
-
def add(self, path: str) -> None:
|
333 |
-
head, tail = os.path.split(path)
|
334 |
-
|
335 |
-
# we normalize the head to resolve parent directory symlinks, but not
|
336 |
-
# the tail, since we only want to uninstall symlinks, not their targets
|
337 |
-
path = os.path.join(self._normalize_path_cached(head), os.path.normcase(tail))
|
338 |
-
|
339 |
-
if not os.path.exists(path):
|
340 |
-
return
|
341 |
-
if self._permitted(path):
|
342 |
-
self._paths.add(path)
|
343 |
-
else:
|
344 |
-
self._refuse.add(path)
|
345 |
-
|
346 |
-
# __pycache__ files can show up after 'installed-files.txt' is created,
|
347 |
-
# due to imports
|
348 |
-
if os.path.splitext(path)[1] == ".py":
|
349 |
-
self.add(cache_from_source(path))
|
350 |
-
|
351 |
-
def add_pth(self, pth_file: str, entry: str) -> None:
|
352 |
-
pth_file = self._normalize_path_cached(pth_file)
|
353 |
-
if self._permitted(pth_file):
|
354 |
-
if pth_file not in self._pth:
|
355 |
-
self._pth[pth_file] = UninstallPthEntries(pth_file)
|
356 |
-
self._pth[pth_file].add(entry)
|
357 |
-
else:
|
358 |
-
self._refuse.add(pth_file)
|
359 |
-
|
360 |
-
def remove(self, auto_confirm: bool = False, verbose: bool = False) -> None:
|
361 |
-
"""Remove paths in ``self._paths`` with confirmation (unless
|
362 |
-
``auto_confirm`` is True)."""
|
363 |
-
|
364 |
-
if not self._paths:
|
365 |
-
logger.info(
|
366 |
-
"Can't uninstall '%s'. No files were found to uninstall.",
|
367 |
-
self._dist.raw_name,
|
368 |
-
)
|
369 |
-
return
|
370 |
-
|
371 |
-
dist_name_version = f"{self._dist.raw_name}-{self._dist.version}"
|
372 |
-
logger.info("Uninstalling %s:", dist_name_version)
|
373 |
-
|
374 |
-
with indent_log():
|
375 |
-
if auto_confirm or self._allowed_to_proceed(verbose):
|
376 |
-
moved = self._moved_paths
|
377 |
-
|
378 |
-
for_rename = compress_for_rename(self._paths)
|
379 |
-
|
380 |
-
for path in sorted(compact(for_rename)):
|
381 |
-
moved.stash(path)
|
382 |
-
logger.verbose("Removing file or directory %s", path)
|
383 |
-
|
384 |
-
for pth in self._pth.values():
|
385 |
-
pth.remove()
|
386 |
-
|
387 |
-
logger.info("Successfully uninstalled %s", dist_name_version)
|
388 |
-
|
389 |
-
def _allowed_to_proceed(self, verbose: bool) -> bool:
|
390 |
-
"""Display which files would be deleted and prompt for confirmation"""
|
391 |
-
|
392 |
-
def _display(msg: str, paths: Iterable[str]) -> None:
|
393 |
-
if not paths:
|
394 |
-
return
|
395 |
-
|
396 |
-
logger.info(msg)
|
397 |
-
with indent_log():
|
398 |
-
for path in sorted(compact(paths)):
|
399 |
-
logger.info(path)
|
400 |
-
|
401 |
-
if not verbose:
|
402 |
-
will_remove, will_skip = compress_for_output_listing(self._paths)
|
403 |
-
else:
|
404 |
-
# In verbose mode, display all the files that are going to be
|
405 |
-
# deleted.
|
406 |
-
will_remove = set(self._paths)
|
407 |
-
will_skip = set()
|
408 |
-
|
409 |
-
_display("Would remove:", will_remove)
|
410 |
-
_display("Would not remove (might be manually added):", will_skip)
|
411 |
-
_display("Would not remove (outside of prefix):", self._refuse)
|
412 |
-
if verbose:
|
413 |
-
_display("Will actually move:", compress_for_rename(self._paths))
|
414 |
-
|
415 |
-
return ask("Proceed (Y/n)? ", ("y", "n", "")) != "n"
|
416 |
-
|
417 |
-
def rollback(self) -> None:
|
418 |
-
"""Rollback the changes previously made by remove()."""
|
419 |
-
if not self._moved_paths.can_rollback:
|
420 |
-
logger.error(
|
421 |
-
"Can't roll back %s; was not uninstalled",
|
422 |
-
self._dist.raw_name,
|
423 |
-
)
|
424 |
-
return
|
425 |
-
logger.info("Rolling back uninstall of %s", self._dist.raw_name)
|
426 |
-
self._moved_paths.rollback()
|
427 |
-
for pth in self._pth.values():
|
428 |
-
pth.rollback()
|
429 |
-
|
430 |
-
def commit(self) -> None:
|
431 |
-
"""Remove temporary save dir: rollback will no longer be possible."""
|
432 |
-
self._moved_paths.commit()
|
433 |
-
|
434 |
-
@classmethod
|
435 |
-
def from_dist(cls, dist: BaseDistribution) -> "UninstallPathSet":
|
436 |
-
dist_location = dist.location
|
437 |
-
info_location = dist.info_location
|
438 |
-
if dist_location is None:
|
439 |
-
logger.info(
|
440 |
-
"Not uninstalling %s since it is not installed",
|
441 |
-
dist.canonical_name,
|
442 |
-
)
|
443 |
-
return cls(dist)
|
444 |
-
|
445 |
-
normalized_dist_location = normalize_path(dist_location)
|
446 |
-
if not dist.local:
|
447 |
-
logger.info(
|
448 |
-
"Not uninstalling %s at %s, outside environment %s",
|
449 |
-
dist.canonical_name,
|
450 |
-
normalized_dist_location,
|
451 |
-
sys.prefix,
|
452 |
-
)
|
453 |
-
return cls(dist)
|
454 |
-
|
455 |
-
if normalized_dist_location in {
|
456 |
-
p
|
457 |
-
for p in {sysconfig.get_path("stdlib"), sysconfig.get_path("platstdlib")}
|
458 |
-
if p
|
459 |
-
}:
|
460 |
-
logger.info(
|
461 |
-
"Not uninstalling %s at %s, as it is in the standard library.",
|
462 |
-
dist.canonical_name,
|
463 |
-
normalized_dist_location,
|
464 |
-
)
|
465 |
-
return cls(dist)
|
466 |
-
|
467 |
-
paths_to_remove = cls(dist)
|
468 |
-
develop_egg_link = egg_link_path_from_location(dist.raw_name)
|
469 |
-
|
470 |
-
# Distribution is installed with metadata in a "flat" .egg-info
|
471 |
-
# directory. This means it is not a modern .dist-info installation, an
|
472 |
-
# egg, or legacy editable.
|
473 |
-
setuptools_flat_installation = (
|
474 |
-
dist.installed_with_setuptools_egg_info
|
475 |
-
and info_location is not None
|
476 |
-
and os.path.exists(info_location)
|
477 |
-
# If dist is editable and the location points to a ``.egg-info``,
|
478 |
-
# we are in fact in the legacy editable case.
|
479 |
-
and not info_location.endswith(f"{dist.setuptools_filename}.egg-info")
|
480 |
-
)
|
481 |
-
|
482 |
-
# Uninstall cases order do matter as in the case of 2 installs of the
|
483 |
-
# same package, pip needs to uninstall the currently detected version
|
484 |
-
if setuptools_flat_installation:
|
485 |
-
if info_location is not None:
|
486 |
-
paths_to_remove.add(info_location)
|
487 |
-
installed_files = dist.iter_declared_entries()
|
488 |
-
if installed_files is not None:
|
489 |
-
for installed_file in installed_files:
|
490 |
-
paths_to_remove.add(os.path.join(dist_location, installed_file))
|
491 |
-
# FIXME: need a test for this elif block
|
492 |
-
# occurs with --single-version-externally-managed/--record outside
|
493 |
-
# of pip
|
494 |
-
elif dist.is_file("top_level.txt"):
|
495 |
-
try:
|
496 |
-
namespace_packages = dist.read_text("namespace_packages.txt")
|
497 |
-
except FileNotFoundError:
|
498 |
-
namespaces = []
|
499 |
-
else:
|
500 |
-
namespaces = namespace_packages.splitlines(keepends=False)
|
501 |
-
for top_level_pkg in [
|
502 |
-
p
|
503 |
-
for p in dist.read_text("top_level.txt").splitlines()
|
504 |
-
if p and p not in namespaces
|
505 |
-
]:
|
506 |
-
path = os.path.join(dist_location, top_level_pkg)
|
507 |
-
paths_to_remove.add(path)
|
508 |
-
paths_to_remove.add(f"{path}.py")
|
509 |
-
paths_to_remove.add(f"{path}.pyc")
|
510 |
-
paths_to_remove.add(f"{path}.pyo")
|
511 |
-
|
512 |
-
elif dist.installed_by_distutils:
|
513 |
-
raise UninstallationError(
|
514 |
-
"Cannot uninstall {!r}. It is a distutils installed project "
|
515 |
-
"and thus we cannot accurately determine which files belong "
|
516 |
-
"to it which would lead to only a partial uninstall.".format(
|
517 |
-
dist.raw_name,
|
518 |
-
)
|
519 |
-
)
|
520 |
-
|
521 |
-
elif dist.installed_as_egg:
|
522 |
-
# package installed by easy_install
|
523 |
-
# We cannot match on dist.egg_name because it can slightly vary
|
524 |
-
# i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg
|
525 |
-
paths_to_remove.add(dist_location)
|
526 |
-
easy_install_egg = os.path.split(dist_location)[1]
|
527 |
-
easy_install_pth = os.path.join(
|
528 |
-
os.path.dirname(dist_location),
|
529 |
-
"easy-install.pth",
|
530 |
-
)
|
531 |
-
paths_to_remove.add_pth(easy_install_pth, "./" + easy_install_egg)
|
532 |
-
|
533 |
-
elif dist.installed_with_dist_info:
|
534 |
-
for path in uninstallation_paths(dist):
|
535 |
-
paths_to_remove.add(path)
|
536 |
-
|
537 |
-
elif develop_egg_link:
|
538 |
-
# PEP 660 modern editable is handled in the ``.dist-info`` case
|
539 |
-
# above, so this only covers the setuptools-style editable.
|
540 |
-
with open(develop_egg_link) as fh:
|
541 |
-
link_pointer = os.path.normcase(fh.readline().strip())
|
542 |
-
normalized_link_pointer = paths_to_remove._normalize_path_cached(
|
543 |
-
link_pointer
|
544 |
-
)
|
545 |
-
assert os.path.samefile(
|
546 |
-
normalized_link_pointer, normalized_dist_location
|
547 |
-
), (
|
548 |
-
f"Egg-link {develop_egg_link} (to {link_pointer}) does not match "
|
549 |
-
f"installed location of {dist.raw_name} (at {dist_location})"
|
550 |
-
)
|
551 |
-
paths_to_remove.add(develop_egg_link)
|
552 |
-
easy_install_pth = os.path.join(
|
553 |
-
os.path.dirname(develop_egg_link), "easy-install.pth"
|
554 |
-
)
|
555 |
-
paths_to_remove.add_pth(easy_install_pth, dist_location)
|
556 |
-
|
557 |
-
else:
|
558 |
-
logger.debug(
|
559 |
-
"Not sure how to uninstall: %s - Check: %s",
|
560 |
-
dist,
|
561 |
-
dist_location,
|
562 |
-
)
|
563 |
-
|
564 |
-
if dist.in_usersite:
|
565 |
-
bin_dir = get_bin_user()
|
566 |
-
else:
|
567 |
-
bin_dir = get_bin_prefix()
|
568 |
-
|
569 |
-
# find distutils scripts= scripts
|
570 |
-
try:
|
571 |
-
for script in dist.iter_distutils_script_names():
|
572 |
-
paths_to_remove.add(os.path.join(bin_dir, script))
|
573 |
-
if WINDOWS:
|
574 |
-
paths_to_remove.add(os.path.join(bin_dir, f"{script}.bat"))
|
575 |
-
except (FileNotFoundError, NotADirectoryError):
|
576 |
-
pass
|
577 |
-
|
578 |
-
# find console_scripts and gui_scripts
|
579 |
-
def iter_scripts_to_remove(
|
580 |
-
dist: BaseDistribution,
|
581 |
-
bin_dir: str,
|
582 |
-
) -> Generator[str, None, None]:
|
583 |
-
for entry_point in dist.iter_entry_points():
|
584 |
-
if entry_point.group == "console_scripts":
|
585 |
-
yield from _script_names(bin_dir, entry_point.name, False)
|
586 |
-
elif entry_point.group == "gui_scripts":
|
587 |
-
yield from _script_names(bin_dir, entry_point.name, True)
|
588 |
-
|
589 |
-
for s in iter_scripts_to_remove(dist, bin_dir):
|
590 |
-
paths_to_remove.add(s)
|
591 |
-
|
592 |
-
return paths_to_remove
|
593 |
-
|
594 |
-
|
595 |
-
class UninstallPthEntries:
|
596 |
-
def __init__(self, pth_file: str) -> None:
|
597 |
-
self.file = pth_file
|
598 |
-
self.entries: Set[str] = set()
|
599 |
-
self._saved_lines: Optional[List[bytes]] = None
|
600 |
-
|
601 |
-
def add(self, entry: str) -> None:
|
602 |
-
entry = os.path.normcase(entry)
|
603 |
-
# On Windows, os.path.normcase converts the entry to use
|
604 |
-
# backslashes. This is correct for entries that describe absolute
|
605 |
-
# paths outside of site-packages, but all the others use forward
|
606 |
-
# slashes.
|
607 |
-
# os.path.splitdrive is used instead of os.path.isabs because isabs
|
608 |
-
# treats non-absolute paths with drive letter markings like c:foo\bar
|
609 |
-
# as absolute paths. It also does not recognize UNC paths if they don't
|
610 |
-
# have more than "\\sever\share". Valid examples: "\\server\share\" or
|
611 |
-
# "\\server\share\folder".
|
612 |
-
if WINDOWS and not os.path.splitdrive(entry)[0]:
|
613 |
-
entry = entry.replace("\\", "/")
|
614 |
-
self.entries.add(entry)
|
615 |
-
|
616 |
-
def remove(self) -> None:
|
617 |
-
logger.verbose("Removing pth entries from %s:", self.file)
|
618 |
-
|
619 |
-
# If the file doesn't exist, log a warning and return
|
620 |
-
if not os.path.isfile(self.file):
|
621 |
-
logger.warning("Cannot remove entries from nonexistent file %s", self.file)
|
622 |
-
return
|
623 |
-
with open(self.file, "rb") as fh:
|
624 |
-
# windows uses '\r\n' with py3k, but uses '\n' with py2.x
|
625 |
-
lines = fh.readlines()
|
626 |
-
self._saved_lines = lines
|
627 |
-
if any(b"\r\n" in line for line in lines):
|
628 |
-
endline = "\r\n"
|
629 |
-
else:
|
630 |
-
endline = "\n"
|
631 |
-
# handle missing trailing newline
|
632 |
-
if lines and not lines[-1].endswith(endline.encode("utf-8")):
|
633 |
-
lines[-1] = lines[-1] + endline.encode("utf-8")
|
634 |
-
for entry in self.entries:
|
635 |
-
try:
|
636 |
-
logger.verbose("Removing entry: %s", entry)
|
637 |
-
lines.remove((entry + endline).encode("utf-8"))
|
638 |
-
except ValueError:
|
639 |
-
pass
|
640 |
-
with open(self.file, "wb") as fh:
|
641 |
-
fh.writelines(lines)
|
642 |
-
|
643 |
-
def rollback(self) -> bool:
|
644 |
-
if self._saved_lines is None:
|
645 |
-
logger.error("Cannot roll back changes to %s, none were made", self.file)
|
646 |
-
return False
|
647 |
-
logger.debug("Rolling %s back to previous state", self.file)
|
648 |
-
with open(self.file, "wb") as fh:
|
649 |
-
fh.writelines(self._saved_lines)
|
650 |
-
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Big-Web/MMSD/env/Lib/site-packages/pkg_resources/_vendor/packaging/utils.py
DELETED
@@ -1,136 +0,0 @@
|
|
1 |
-
# This file is dual licensed under the terms of the Apache License, Version
|
2 |
-
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
3 |
-
# for complete details.
|
4 |
-
|
5 |
-
import re
|
6 |
-
from typing import FrozenSet, NewType, Tuple, Union, cast
|
7 |
-
|
8 |
-
from .tags import Tag, parse_tag
|
9 |
-
from .version import InvalidVersion, Version
|
10 |
-
|
11 |
-
BuildTag = Union[Tuple[()], Tuple[int, str]]
|
12 |
-
NormalizedName = NewType("NormalizedName", str)
|
13 |
-
|
14 |
-
|
15 |
-
class InvalidWheelFilename(ValueError):
|
16 |
-
"""
|
17 |
-
An invalid wheel filename was found, users should refer to PEP 427.
|
18 |
-
"""
|
19 |
-
|
20 |
-
|
21 |
-
class InvalidSdistFilename(ValueError):
|
22 |
-
"""
|
23 |
-
An invalid sdist filename was found, users should refer to the packaging user guide.
|
24 |
-
"""
|
25 |
-
|
26 |
-
|
27 |
-
_canonicalize_regex = re.compile(r"[-_.]+")
|
28 |
-
# PEP 427: The build number must start with a digit.
|
29 |
-
_build_tag_regex = re.compile(r"(\d+)(.*)")
|
30 |
-
|
31 |
-
|
32 |
-
def canonicalize_name(name: str) -> NormalizedName:
|
33 |
-
# This is taken from PEP 503.
|
34 |
-
value = _canonicalize_regex.sub("-", name).lower()
|
35 |
-
return cast(NormalizedName, value)
|
36 |
-
|
37 |
-
|
38 |
-
def canonicalize_version(version: Union[Version, str]) -> str:
|
39 |
-
"""
|
40 |
-
This is very similar to Version.__str__, but has one subtle difference
|
41 |
-
with the way it handles the release segment.
|
42 |
-
"""
|
43 |
-
if isinstance(version, str):
|
44 |
-
try:
|
45 |
-
parsed = Version(version)
|
46 |
-
except InvalidVersion:
|
47 |
-
# Legacy versions cannot be normalized
|
48 |
-
return version
|
49 |
-
else:
|
50 |
-
parsed = version
|
51 |
-
|
52 |
-
parts = []
|
53 |
-
|
54 |
-
# Epoch
|
55 |
-
if parsed.epoch != 0:
|
56 |
-
parts.append(f"{parsed.epoch}!")
|
57 |
-
|
58 |
-
# Release segment
|
59 |
-
# NB: This strips trailing '.0's to normalize
|
60 |
-
parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in parsed.release)))
|
61 |
-
|
62 |
-
# Pre-release
|
63 |
-
if parsed.pre is not None:
|
64 |
-
parts.append("".join(str(x) for x in parsed.pre))
|
65 |
-
|
66 |
-
# Post-release
|
67 |
-
if parsed.post is not None:
|
68 |
-
parts.append(f".post{parsed.post}")
|
69 |
-
|
70 |
-
# Development release
|
71 |
-
if parsed.dev is not None:
|
72 |
-
parts.append(f".dev{parsed.dev}")
|
73 |
-
|
74 |
-
# Local version segment
|
75 |
-
if parsed.local is not None:
|
76 |
-
parts.append(f"+{parsed.local}")
|
77 |
-
|
78 |
-
return "".join(parts)
|
79 |
-
|
80 |
-
|
81 |
-
def parse_wheel_filename(
|
82 |
-
filename: str,
|
83 |
-
) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:
|
84 |
-
if not filename.endswith(".whl"):
|
85 |
-
raise InvalidWheelFilename(
|
86 |
-
f"Invalid wheel filename (extension must be '.whl'): {filename}"
|
87 |
-
)
|
88 |
-
|
89 |
-
filename = filename[:-4]
|
90 |
-
dashes = filename.count("-")
|
91 |
-
if dashes not in (4, 5):
|
92 |
-
raise InvalidWheelFilename(
|
93 |
-
f"Invalid wheel filename (wrong number of parts): {filename}"
|
94 |
-
)
|
95 |
-
|
96 |
-
parts = filename.split("-", dashes - 2)
|
97 |
-
name_part = parts[0]
|
98 |
-
# See PEP 427 for the rules on escaping the project name
|
99 |
-
if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None:
|
100 |
-
raise InvalidWheelFilename(f"Invalid project name: {filename}")
|
101 |
-
name = canonicalize_name(name_part)
|
102 |
-
version = Version(parts[1])
|
103 |
-
if dashes == 5:
|
104 |
-
build_part = parts[2]
|
105 |
-
build_match = _build_tag_regex.match(build_part)
|
106 |
-
if build_match is None:
|
107 |
-
raise InvalidWheelFilename(
|
108 |
-
f"Invalid build number: {build_part} in '{filename}'"
|
109 |
-
)
|
110 |
-
build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))
|
111 |
-
else:
|
112 |
-
build = ()
|
113 |
-
tags = parse_tag(parts[-1])
|
114 |
-
return (name, version, build, tags)
|
115 |
-
|
116 |
-
|
117 |
-
def parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:
|
118 |
-
if filename.endswith(".tar.gz"):
|
119 |
-
file_stem = filename[: -len(".tar.gz")]
|
120 |
-
elif filename.endswith(".zip"):
|
121 |
-
file_stem = filename[: -len(".zip")]
|
122 |
-
else:
|
123 |
-
raise InvalidSdistFilename(
|
124 |
-
f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):"
|
125 |
-
f" {filename}"
|
126 |
-
)
|
127 |
-
|
128 |
-
# We are requiring a PEP 440 version, which cannot contain dashes,
|
129 |
-
# so we split on the last dash.
|
130 |
-
name_part, sep, version_part = file_stem.rpartition("-")
|
131 |
-
if not sep:
|
132 |
-
raise InvalidSdistFilename(f"Invalid sdist filename: {filename}")
|
133 |
-
|
134 |
-
name = canonicalize_name(name_part)
|
135 |
-
version = Version(version_part)
|
136 |
-
return (name, version)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Big-Web/MMSD/env/Lib/site-packages/s3transfer/manager.py
DELETED
@@ -1,731 +0,0 @@
|
|
1 |
-
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License"). You
|
4 |
-
# may not use this file except in compliance with the License. A copy of
|
5 |
-
# the License is located at
|
6 |
-
#
|
7 |
-
# http://aws.amazon.com/apache2.0/
|
8 |
-
#
|
9 |
-
# or in the "license" file accompanying this file. This file is
|
10 |
-
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
|
11 |
-
# ANY KIND, either express or implied. See the License for the specific
|
12 |
-
# language governing permissions and limitations under the License.
|
13 |
-
import copy
|
14 |
-
import logging
|
15 |
-
import re
|
16 |
-
import threading
|
17 |
-
|
18 |
-
from s3transfer.bandwidth import BandwidthLimiter, LeakyBucket
|
19 |
-
from s3transfer.constants import ALLOWED_DOWNLOAD_ARGS, KB, MB
|
20 |
-
from s3transfer.copies import CopySubmissionTask
|
21 |
-
from s3transfer.delete import DeleteSubmissionTask
|
22 |
-
from s3transfer.download import DownloadSubmissionTask
|
23 |
-
from s3transfer.exceptions import CancelledError, FatalError
|
24 |
-
from s3transfer.futures import (
|
25 |
-
IN_MEMORY_DOWNLOAD_TAG,
|
26 |
-
IN_MEMORY_UPLOAD_TAG,
|
27 |
-
BoundedExecutor,
|
28 |
-
TransferCoordinator,
|
29 |
-
TransferFuture,
|
30 |
-
TransferMeta,
|
31 |
-
)
|
32 |
-
from s3transfer.upload import UploadSubmissionTask
|
33 |
-
from s3transfer.utils import (
|
34 |
-
CallArgs,
|
35 |
-
OSUtils,
|
36 |
-
SlidingWindowSemaphore,
|
37 |
-
TaskSemaphore,
|
38 |
-
get_callbacks,
|
39 |
-
signal_not_transferring,
|
40 |
-
signal_transferring,
|
41 |
-
)
|
42 |
-
|
43 |
-
logger = logging.getLogger(__name__)
|
44 |
-
|
45 |
-
|
46 |
-
class TransferConfig:
|
47 |
-
def __init__(
|
48 |
-
self,
|
49 |
-
multipart_threshold=8 * MB,
|
50 |
-
multipart_chunksize=8 * MB,
|
51 |
-
max_request_concurrency=10,
|
52 |
-
max_submission_concurrency=5,
|
53 |
-
max_request_queue_size=1000,
|
54 |
-
max_submission_queue_size=1000,
|
55 |
-
max_io_queue_size=1000,
|
56 |
-
io_chunksize=256 * KB,
|
57 |
-
num_download_attempts=5,
|
58 |
-
max_in_memory_upload_chunks=10,
|
59 |
-
max_in_memory_download_chunks=10,
|
60 |
-
max_bandwidth=None,
|
61 |
-
):
|
62 |
-
"""Configurations for the transfer manager
|
63 |
-
|
64 |
-
:param multipart_threshold: The threshold for which multipart
|
65 |
-
transfers occur.
|
66 |
-
|
67 |
-
:param max_request_concurrency: The maximum number of S3 API
|
68 |
-
transfer-related requests that can happen at a time.
|
69 |
-
|
70 |
-
:param max_submission_concurrency: The maximum number of threads
|
71 |
-
processing a call to a TransferManager method. Processing a
|
72 |
-
call usually entails determining which S3 API requests that need
|
73 |
-
to be enqueued, but does **not** entail making any of the
|
74 |
-
S3 API data transferring requests needed to perform the transfer.
|
75 |
-
The threads controlled by ``max_request_concurrency`` is
|
76 |
-
responsible for that.
|
77 |
-
|
78 |
-
:param multipart_chunksize: The size of each transfer if a request
|
79 |
-
becomes a multipart transfer.
|
80 |
-
|
81 |
-
:param max_request_queue_size: The maximum amount of S3 API requests
|
82 |
-
that can be queued at a time.
|
83 |
-
|
84 |
-
:param max_submission_queue_size: The maximum amount of
|
85 |
-
TransferManager method calls that can be queued at a time.
|
86 |
-
|
87 |
-
:param max_io_queue_size: The maximum amount of read parts that
|
88 |
-
can be queued to be written to disk per download. The default
|
89 |
-
size for each elementin this queue is 8 KB.
|
90 |
-
|
91 |
-
:param io_chunksize: The max size of each chunk in the io queue.
|
92 |
-
Currently, this is size used when reading from the downloaded
|
93 |
-
stream as well.
|
94 |
-
|
95 |
-
:param num_download_attempts: The number of download attempts that
|
96 |
-
will be tried upon errors with downloading an object in S3. Note
|
97 |
-
that these retries account for errors that occur when streaming
|
98 |
-
down the data from s3 (i.e. socket errors and read timeouts that
|
99 |
-
occur after receiving an OK response from s3).
|
100 |
-
Other retryable exceptions such as throttling errors and 5xx errors
|
101 |
-
are already retried by botocore (this default is 5). The
|
102 |
-
``num_download_attempts`` does not take into account the
|
103 |
-
number of exceptions retried by botocore.
|
104 |
-
|
105 |
-
:param max_in_memory_upload_chunks: The number of chunks that can
|
106 |
-
be stored in memory at a time for all ongoing upload requests.
|
107 |
-
This pertains to chunks of data that need to be stored in memory
|
108 |
-
during an upload if the data is sourced from a file-like object.
|
109 |
-
The total maximum memory footprint due to a in-memory upload
|
110 |
-
chunks is roughly equal to:
|
111 |
-
|
112 |
-
max_in_memory_upload_chunks * multipart_chunksize
|
113 |
-
+ max_submission_concurrency * multipart_chunksize
|
114 |
-
|
115 |
-
``max_submission_concurrency`` has an affect on this value because
|
116 |
-
for each thread pulling data off of a file-like object, they may
|
117 |
-
be waiting with a single read chunk to be submitted for upload
|
118 |
-
because the ``max_in_memory_upload_chunks`` value has been reached
|
119 |
-
by the threads making the upload request.
|
120 |
-
|
121 |
-
:param max_in_memory_download_chunks: The number of chunks that can
|
122 |
-
be buffered in memory and **not** in the io queue at a time for all
|
123 |
-
ongoing download requests. This pertains specifically to file-like
|
124 |
-
objects that cannot be seeked. The total maximum memory footprint
|
125 |
-
due to a in-memory download chunks is roughly equal to:
|
126 |
-
|
127 |
-
max_in_memory_download_chunks * multipart_chunksize
|
128 |
-
|
129 |
-
:param max_bandwidth: The maximum bandwidth that will be consumed
|
130 |
-
in uploading and downloading file content. The value is in terms of
|
131 |
-
bytes per second.
|
132 |
-
"""
|
133 |
-
self.multipart_threshold = multipart_threshold
|
134 |
-
self.multipart_chunksize = multipart_chunksize
|
135 |
-
self.max_request_concurrency = max_request_concurrency
|
136 |
-
self.max_submission_concurrency = max_submission_concurrency
|
137 |
-
self.max_request_queue_size = max_request_queue_size
|
138 |
-
self.max_submission_queue_size = max_submission_queue_size
|
139 |
-
self.max_io_queue_size = max_io_queue_size
|
140 |
-
self.io_chunksize = io_chunksize
|
141 |
-
self.num_download_attempts = num_download_attempts
|
142 |
-
self.max_in_memory_upload_chunks = max_in_memory_upload_chunks
|
143 |
-
self.max_in_memory_download_chunks = max_in_memory_download_chunks
|
144 |
-
self.max_bandwidth = max_bandwidth
|
145 |
-
self._validate_attrs_are_nonzero()
|
146 |
-
|
147 |
-
def _validate_attrs_are_nonzero(self):
|
148 |
-
for attr, attr_val in self.__dict__.items():
|
149 |
-
if attr_val is not None and attr_val <= 0:
|
150 |
-
raise ValueError(
|
151 |
-
'Provided parameter %s of value %s must be greater than '
|
152 |
-
'0.' % (attr, attr_val)
|
153 |
-
)
|
154 |
-
|
155 |
-
|
156 |
-
class TransferManager:
|
157 |
-
ALLOWED_DOWNLOAD_ARGS = ALLOWED_DOWNLOAD_ARGS
|
158 |
-
|
159 |
-
ALLOWED_UPLOAD_ARGS = [
|
160 |
-
'ACL',
|
161 |
-
'CacheControl',
|
162 |
-
'ChecksumAlgorithm',
|
163 |
-
'ContentDisposition',
|
164 |
-
'ContentEncoding',
|
165 |
-
'ContentLanguage',
|
166 |
-
'ContentType',
|
167 |
-
'ExpectedBucketOwner',
|
168 |
-
'Expires',
|
169 |
-
'GrantFullControl',
|
170 |
-
'GrantRead',
|
171 |
-
'GrantReadACP',
|
172 |
-
'GrantWriteACP',
|
173 |
-
'Metadata',
|
174 |
-
'ObjectLockLegalHoldStatus',
|
175 |
-
'ObjectLockMode',
|
176 |
-
'ObjectLockRetainUntilDate',
|
177 |
-
'RequestPayer',
|
178 |
-
'ServerSideEncryption',
|
179 |
-
'StorageClass',
|
180 |
-
'SSECustomerAlgorithm',
|
181 |
-
'SSECustomerKey',
|
182 |
-
'SSECustomerKeyMD5',
|
183 |
-
'SSEKMSKeyId',
|
184 |
-
'SSEKMSEncryptionContext',
|
185 |
-
'Tagging',
|
186 |
-
'WebsiteRedirectLocation',
|
187 |
-
]
|
188 |
-
|
189 |
-
ALLOWED_COPY_ARGS = ALLOWED_UPLOAD_ARGS + [
|
190 |
-
'CopySourceIfMatch',
|
191 |
-
'CopySourceIfModifiedSince',
|
192 |
-
'CopySourceIfNoneMatch',
|
193 |
-
'CopySourceIfUnmodifiedSince',
|
194 |
-
'CopySourceSSECustomerAlgorithm',
|
195 |
-
'CopySourceSSECustomerKey',
|
196 |
-
'CopySourceSSECustomerKeyMD5',
|
197 |
-
'MetadataDirective',
|
198 |
-
'TaggingDirective',
|
199 |
-
]
|
200 |
-
|
201 |
-
ALLOWED_DELETE_ARGS = [
|
202 |
-
'MFA',
|
203 |
-
'VersionId',
|
204 |
-
'RequestPayer',
|
205 |
-
'ExpectedBucketOwner',
|
206 |
-
]
|
207 |
-
|
208 |
-
VALIDATE_SUPPORTED_BUCKET_VALUES = True
|
209 |
-
|
210 |
-
_UNSUPPORTED_BUCKET_PATTERNS = {
|
211 |
-
'S3 Object Lambda': re.compile(
|
212 |
-
r'^arn:(aws).*:s3-object-lambda:[a-z\-0-9]+:[0-9]{12}:'
|
213 |
-
r'accesspoint[/:][a-zA-Z0-9\-]{1,63}'
|
214 |
-
),
|
215 |
-
}
|
216 |
-
|
217 |
-
def __init__(self, client, config=None, osutil=None, executor_cls=None):
|
218 |
-
"""A transfer manager interface for Amazon S3
|
219 |
-
|
220 |
-
:param client: Client to be used by the manager
|
221 |
-
:param config: TransferConfig to associate specific configurations
|
222 |
-
:param osutil: OSUtils object to use for os-related behavior when
|
223 |
-
using with transfer manager.
|
224 |
-
|
225 |
-
:type executor_cls: s3transfer.futures.BaseExecutor
|
226 |
-
:param executor_cls: The class of executor to use with the transfer
|
227 |
-
manager. By default, concurrent.futures.ThreadPoolExecutor is used.
|
228 |
-
"""
|
229 |
-
self._client = client
|
230 |
-
self._config = config
|
231 |
-
if config is None:
|
232 |
-
self._config = TransferConfig()
|
233 |
-
self._osutil = osutil
|
234 |
-
if osutil is None:
|
235 |
-
self._osutil = OSUtils()
|
236 |
-
self._coordinator_controller = TransferCoordinatorController()
|
237 |
-
# A counter to create unique id's for each transfer submitted.
|
238 |
-
self._id_counter = 0
|
239 |
-
|
240 |
-
# The executor responsible for making S3 API transfer requests
|
241 |
-
self._request_executor = BoundedExecutor(
|
242 |
-
max_size=self._config.max_request_queue_size,
|
243 |
-
max_num_threads=self._config.max_request_concurrency,
|
244 |
-
tag_semaphores={
|
245 |
-
IN_MEMORY_UPLOAD_TAG: TaskSemaphore(
|
246 |
-
self._config.max_in_memory_upload_chunks
|
247 |
-
),
|
248 |
-
IN_MEMORY_DOWNLOAD_TAG: SlidingWindowSemaphore(
|
249 |
-
self._config.max_in_memory_download_chunks
|
250 |
-
),
|
251 |
-
},
|
252 |
-
executor_cls=executor_cls,
|
253 |
-
)
|
254 |
-
|
255 |
-
# The executor responsible for submitting the necessary tasks to
|
256 |
-
# perform the desired transfer
|
257 |
-
self._submission_executor = BoundedExecutor(
|
258 |
-
max_size=self._config.max_submission_queue_size,
|
259 |
-
max_num_threads=self._config.max_submission_concurrency,
|
260 |
-
executor_cls=executor_cls,
|
261 |
-
)
|
262 |
-
|
263 |
-
# There is one thread available for writing to disk. It will handle
|
264 |
-
# downloads for all files.
|
265 |
-
self._io_executor = BoundedExecutor(
|
266 |
-
max_size=self._config.max_io_queue_size,
|
267 |
-
max_num_threads=1,
|
268 |
-
executor_cls=executor_cls,
|
269 |
-
)
|
270 |
-
|
271 |
-
# The component responsible for limiting bandwidth usage if it
|
272 |
-
# is configured.
|
273 |
-
self._bandwidth_limiter = None
|
274 |
-
if self._config.max_bandwidth is not None:
|
275 |
-
logger.debug(
|
276 |
-
'Setting max_bandwidth to %s', self._config.max_bandwidth
|
277 |
-
)
|
278 |
-
leaky_bucket = LeakyBucket(self._config.max_bandwidth)
|
279 |
-
self._bandwidth_limiter = BandwidthLimiter(leaky_bucket)
|
280 |
-
|
281 |
-
self._register_handlers()
|
282 |
-
|
283 |
-
@property
|
284 |
-
def client(self):
|
285 |
-
return self._client
|
286 |
-
|
287 |
-
@property
|
288 |
-
def config(self):
|
289 |
-
return self._config
|
290 |
-
|
291 |
-
def upload(self, fileobj, bucket, key, extra_args=None, subscribers=None):
|
292 |
-
"""Uploads a file to S3
|
293 |
-
|
294 |
-
:type fileobj: str or seekable file-like object
|
295 |
-
:param fileobj: The name of a file to upload or a seekable file-like
|
296 |
-
object to upload. It is recommended to use a filename because
|
297 |
-
file-like objects may result in higher memory usage.
|
298 |
-
|
299 |
-
:type bucket: str
|
300 |
-
:param bucket: The name of the bucket to upload to
|
301 |
-
|
302 |
-
:type key: str
|
303 |
-
:param key: The name of the key to upload to
|
304 |
-
|
305 |
-
:type extra_args: dict
|
306 |
-
:param extra_args: Extra arguments that may be passed to the
|
307 |
-
client operation
|
308 |
-
|
309 |
-
:type subscribers: list(s3transfer.subscribers.BaseSubscriber)
|
310 |
-
:param subscribers: The list of subscribers to be invoked in the
|
311 |
-
order provided based on the event emit during the process of
|
312 |
-
the transfer request.
|
313 |
-
|
314 |
-
:rtype: s3transfer.futures.TransferFuture
|
315 |
-
:returns: Transfer future representing the upload
|
316 |
-
"""
|
317 |
-
if extra_args is None:
|
318 |
-
extra_args = {}
|
319 |
-
if subscribers is None:
|
320 |
-
subscribers = []
|
321 |
-
self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS)
|
322 |
-
self._validate_if_bucket_supported(bucket)
|
323 |
-
call_args = CallArgs(
|
324 |
-
fileobj=fileobj,
|
325 |
-
bucket=bucket,
|
326 |
-
key=key,
|
327 |
-
extra_args=extra_args,
|
328 |
-
subscribers=subscribers,
|
329 |
-
)
|
330 |
-
extra_main_kwargs = {}
|
331 |
-
if self._bandwidth_limiter:
|
332 |
-
extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter
|
333 |
-
return self._submit_transfer(
|
334 |
-
call_args, UploadSubmissionTask, extra_main_kwargs
|
335 |
-
)
|
336 |
-
|
337 |
-
def download(
|
338 |
-
self, bucket, key, fileobj, extra_args=None, subscribers=None
|
339 |
-
):
|
340 |
-
"""Downloads a file from S3
|
341 |
-
|
342 |
-
:type bucket: str
|
343 |
-
:param bucket: The name of the bucket to download from
|
344 |
-
|
345 |
-
:type key: str
|
346 |
-
:param key: The name of the key to download from
|
347 |
-
|
348 |
-
:type fileobj: str or seekable file-like object
|
349 |
-
:param fileobj: The name of a file to download or a seekable file-like
|
350 |
-
object to download. It is recommended to use a filename because
|
351 |
-
file-like objects may result in higher memory usage.
|
352 |
-
|
353 |
-
:type extra_args: dict
|
354 |
-
:param extra_args: Extra arguments that may be passed to the
|
355 |
-
client operation
|
356 |
-
|
357 |
-
:type subscribers: list(s3transfer.subscribers.BaseSubscriber)
|
358 |
-
:param subscribers: The list of subscribers to be invoked in the
|
359 |
-
order provided based on the event emit during the process of
|
360 |
-
the transfer request.
|
361 |
-
|
362 |
-
:rtype: s3transfer.futures.TransferFuture
|
363 |
-
:returns: Transfer future representing the download
|
364 |
-
"""
|
365 |
-
if extra_args is None:
|
366 |
-
extra_args = {}
|
367 |
-
if subscribers is None:
|
368 |
-
subscribers = []
|
369 |
-
self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS)
|
370 |
-
self._validate_if_bucket_supported(bucket)
|
371 |
-
call_args = CallArgs(
|
372 |
-
bucket=bucket,
|
373 |
-
key=key,
|
374 |
-
fileobj=fileobj,
|
375 |
-
extra_args=extra_args,
|
376 |
-
subscribers=subscribers,
|
377 |
-
)
|
378 |
-
extra_main_kwargs = {'io_executor': self._io_executor}
|
379 |
-
if self._bandwidth_limiter:
|
380 |
-
extra_main_kwargs['bandwidth_limiter'] = self._bandwidth_limiter
|
381 |
-
return self._submit_transfer(
|
382 |
-
call_args, DownloadSubmissionTask, extra_main_kwargs
|
383 |
-
)
|
384 |
-
|
385 |
-
def copy(
|
386 |
-
self,
|
387 |
-
copy_source,
|
388 |
-
bucket,
|
389 |
-
key,
|
390 |
-
extra_args=None,
|
391 |
-
subscribers=None,
|
392 |
-
source_client=None,
|
393 |
-
):
|
394 |
-
"""Copies a file in S3
|
395 |
-
|
396 |
-
:type copy_source: dict
|
397 |
-
:param copy_source: The name of the source bucket, key name of the
|
398 |
-
source object, and optional version ID of the source object. The
|
399 |
-
dictionary format is:
|
400 |
-
``{'Bucket': 'bucket', 'Key': 'key', 'VersionId': 'id'}``. Note
|
401 |
-
that the ``VersionId`` key is optional and may be omitted.
|
402 |
-
|
403 |
-
:type bucket: str
|
404 |
-
:param bucket: The name of the bucket to copy to
|
405 |
-
|
406 |
-
:type key: str
|
407 |
-
:param key: The name of the key to copy to
|
408 |
-
|
409 |
-
:type extra_args: dict
|
410 |
-
:param extra_args: Extra arguments that may be passed to the
|
411 |
-
client operation
|
412 |
-
|
413 |
-
:type subscribers: a list of subscribers
|
414 |
-
:param subscribers: The list of subscribers to be invoked in the
|
415 |
-
order provided based on the event emit during the process of
|
416 |
-
the transfer request.
|
417 |
-
|
418 |
-
:type source_client: botocore or boto3 Client
|
419 |
-
:param source_client: The client to be used for operation that
|
420 |
-
may happen at the source object. For example, this client is
|
421 |
-
used for the head_object that determines the size of the copy.
|
422 |
-
If no client is provided, the transfer manager's client is used
|
423 |
-
as the client for the source object.
|
424 |
-
|
425 |
-
:rtype: s3transfer.futures.TransferFuture
|
426 |
-
:returns: Transfer future representing the copy
|
427 |
-
"""
|
428 |
-
if extra_args is None:
|
429 |
-
extra_args = {}
|
430 |
-
if subscribers is None:
|
431 |
-
subscribers = []
|
432 |
-
if source_client is None:
|
433 |
-
source_client = self._client
|
434 |
-
self._validate_all_known_args(extra_args, self.ALLOWED_COPY_ARGS)
|
435 |
-
if isinstance(copy_source, dict):
|
436 |
-
self._validate_if_bucket_supported(copy_source.get('Bucket'))
|
437 |
-
self._validate_if_bucket_supported(bucket)
|
438 |
-
call_args = CallArgs(
|
439 |
-
copy_source=copy_source,
|
440 |
-
bucket=bucket,
|
441 |
-
key=key,
|
442 |
-
extra_args=extra_args,
|
443 |
-
subscribers=subscribers,
|
444 |
-
source_client=source_client,
|
445 |
-
)
|
446 |
-
return self._submit_transfer(call_args, CopySubmissionTask)
|
447 |
-
|
448 |
-
def delete(self, bucket, key, extra_args=None, subscribers=None):
|
449 |
-
"""Delete an S3 object.
|
450 |
-
|
451 |
-
:type bucket: str
|
452 |
-
:param bucket: The name of the bucket.
|
453 |
-
|
454 |
-
:type key: str
|
455 |
-
:param key: The name of the S3 object to delete.
|
456 |
-
|
457 |
-
:type extra_args: dict
|
458 |
-
:param extra_args: Extra arguments that may be passed to the
|
459 |
-
DeleteObject call.
|
460 |
-
|
461 |
-
:type subscribers: list
|
462 |
-
:param subscribers: A list of subscribers to be invoked during the
|
463 |
-
process of the transfer request. Note that the ``on_progress``
|
464 |
-
callback is not invoked during object deletion.
|
465 |
-
|
466 |
-
:rtype: s3transfer.futures.TransferFuture
|
467 |
-
:return: Transfer future representing the deletion.
|
468 |
-
|
469 |
-
"""
|
470 |
-
if extra_args is None:
|
471 |
-
extra_args = {}
|
472 |
-
if subscribers is None:
|
473 |
-
subscribers = []
|
474 |
-
self._validate_all_known_args(extra_args, self.ALLOWED_DELETE_ARGS)
|
475 |
-
self._validate_if_bucket_supported(bucket)
|
476 |
-
call_args = CallArgs(
|
477 |
-
bucket=bucket,
|
478 |
-
key=key,
|
479 |
-
extra_args=extra_args,
|
480 |
-
subscribers=subscribers,
|
481 |
-
)
|
482 |
-
return self._submit_transfer(call_args, DeleteSubmissionTask)
|
483 |
-
|
484 |
-
def _validate_if_bucket_supported(self, bucket):
|
485 |
-
# s3 high level operations don't support some resources
|
486 |
-
# (eg. S3 Object Lambda) only direct API calls are available
|
487 |
-
# for such resources
|
488 |
-
if self.VALIDATE_SUPPORTED_BUCKET_VALUES:
|
489 |
-
for resource, pattern in self._UNSUPPORTED_BUCKET_PATTERNS.items():
|
490 |
-
match = pattern.match(bucket)
|
491 |
-
if match:
|
492 |
-
raise ValueError(
|
493 |
-
'TransferManager methods do not support %s '
|
494 |
-
'resource. Use direct client calls instead.' % resource
|
495 |
-
)
|
496 |
-
|
497 |
-
def _validate_all_known_args(self, actual, allowed):
|
498 |
-
for kwarg in actual:
|
499 |
-
if kwarg not in allowed:
|
500 |
-
raise ValueError(
|
501 |
-
"Invalid extra_args key '%s', "
|
502 |
-
"must be one of: %s" % (kwarg, ', '.join(allowed))
|
503 |
-
)
|
504 |
-
|
505 |
-
def _submit_transfer(
|
506 |
-
self, call_args, submission_task_cls, extra_main_kwargs=None
|
507 |
-
):
|
508 |
-
if not extra_main_kwargs:
|
509 |
-
extra_main_kwargs = {}
|
510 |
-
|
511 |
-
# Create a TransferFuture to return back to the user
|
512 |
-
transfer_future, components = self._get_future_with_components(
|
513 |
-
call_args
|
514 |
-
)
|
515 |
-
|
516 |
-
# Add any provided done callbacks to the created transfer future
|
517 |
-
# to be invoked on the transfer future being complete.
|
518 |
-
for callback in get_callbacks(transfer_future, 'done'):
|
519 |
-
components['coordinator'].add_done_callback(callback)
|
520 |
-
|
521 |
-
# Get the main kwargs needed to instantiate the submission task
|
522 |
-
main_kwargs = self._get_submission_task_main_kwargs(
|
523 |
-
transfer_future, extra_main_kwargs
|
524 |
-
)
|
525 |
-
|
526 |
-
# Submit a SubmissionTask that will submit all of the necessary
|
527 |
-
# tasks needed to complete the S3 transfer.
|
528 |
-
self._submission_executor.submit(
|
529 |
-
submission_task_cls(
|
530 |
-
transfer_coordinator=components['coordinator'],
|
531 |
-
main_kwargs=main_kwargs,
|
532 |
-
)
|
533 |
-
)
|
534 |
-
|
535 |
-
# Increment the unique id counter for future transfer requests
|
536 |
-
self._id_counter += 1
|
537 |
-
|
538 |
-
return transfer_future
|
539 |
-
|
540 |
-
def _get_future_with_components(self, call_args):
|
541 |
-
transfer_id = self._id_counter
|
542 |
-
# Creates a new transfer future along with its components
|
543 |
-
transfer_coordinator = TransferCoordinator(transfer_id=transfer_id)
|
544 |
-
# Track the transfer coordinator for transfers to manage.
|
545 |
-
self._coordinator_controller.add_transfer_coordinator(
|
546 |
-
transfer_coordinator
|
547 |
-
)
|
548 |
-
# Also make sure that the transfer coordinator is removed once
|
549 |
-
# the transfer completes so it does not stick around in memory.
|
550 |
-
transfer_coordinator.add_done_callback(
|
551 |
-
self._coordinator_controller.remove_transfer_coordinator,
|
552 |
-
transfer_coordinator,
|
553 |
-
)
|
554 |
-
components = {
|
555 |
-
'meta': TransferMeta(call_args, transfer_id=transfer_id),
|
556 |
-
'coordinator': transfer_coordinator,
|
557 |
-
}
|
558 |
-
transfer_future = TransferFuture(**components)
|
559 |
-
return transfer_future, components
|
560 |
-
|
561 |
-
def _get_submission_task_main_kwargs(
|
562 |
-
self, transfer_future, extra_main_kwargs
|
563 |
-
):
|
564 |
-
main_kwargs = {
|
565 |
-
'client': self._client,
|
566 |
-
'config': self._config,
|
567 |
-
'osutil': self._osutil,
|
568 |
-
'request_executor': self._request_executor,
|
569 |
-
'transfer_future': transfer_future,
|
570 |
-
}
|
571 |
-
main_kwargs.update(extra_main_kwargs)
|
572 |
-
return main_kwargs
|
573 |
-
|
574 |
-
def _register_handlers(self):
|
575 |
-
# Register handlers to enable/disable callbacks on uploads.
|
576 |
-
event_name = 'request-created.s3'
|
577 |
-
self._client.meta.events.register_first(
|
578 |
-
event_name,
|
579 |
-
signal_not_transferring,
|
580 |
-
unique_id='s3upload-not-transferring',
|
581 |
-
)
|
582 |
-
self._client.meta.events.register_last(
|
583 |
-
event_name, signal_transferring, unique_id='s3upload-transferring'
|
584 |
-
)
|
585 |
-
|
586 |
-
def __enter__(self):
|
587 |
-
return self
|
588 |
-
|
589 |
-
def __exit__(self, exc_type, exc_value, *args):
|
590 |
-
cancel = False
|
591 |
-
cancel_msg = ''
|
592 |
-
cancel_exc_type = FatalError
|
593 |
-
# If a exception was raised in the context handler, signal to cancel
|
594 |
-
# all of the inprogress futures in the shutdown.
|
595 |
-
if exc_type:
|
596 |
-
cancel = True
|
597 |
-
cancel_msg = str(exc_value)
|
598 |
-
if not cancel_msg:
|
599 |
-
cancel_msg = repr(exc_value)
|
600 |
-
# If it was a KeyboardInterrupt, the cancellation was initiated
|
601 |
-
# by the user.
|
602 |
-
if isinstance(exc_value, KeyboardInterrupt):
|
603 |
-
cancel_exc_type = CancelledError
|
604 |
-
self._shutdown(cancel, cancel_msg, cancel_exc_type)
|
605 |
-
|
606 |
-
def shutdown(self, cancel=False, cancel_msg=''):
|
607 |
-
"""Shutdown the TransferManager
|
608 |
-
|
609 |
-
It will wait till all transfers complete before it completely shuts
|
610 |
-
down.
|
611 |
-
|
612 |
-
:type cancel: boolean
|
613 |
-
:param cancel: If True, calls TransferFuture.cancel() for
|
614 |
-
all in-progress in transfers. This is useful if you want the
|
615 |
-
shutdown to happen quicker.
|
616 |
-
|
617 |
-
:type cancel_msg: str
|
618 |
-
:param cancel_msg: The message to specify if canceling all in-progress
|
619 |
-
transfers.
|
620 |
-
"""
|
621 |
-
self._shutdown(cancel, cancel, cancel_msg)
|
622 |
-
|
623 |
-
def _shutdown(self, cancel, cancel_msg, exc_type=CancelledError):
|
624 |
-
if cancel:
|
625 |
-
# Cancel all in-flight transfers if requested, before waiting
|
626 |
-
# for them to complete.
|
627 |
-
self._coordinator_controller.cancel(cancel_msg, exc_type)
|
628 |
-
try:
|
629 |
-
# Wait until there are no more in-progress transfers. This is
|
630 |
-
# wrapped in a try statement because this can be interrupted
|
631 |
-
# with a KeyboardInterrupt that needs to be caught.
|
632 |
-
self._coordinator_controller.wait()
|
633 |
-
except KeyboardInterrupt:
|
634 |
-
# If not errors were raised in the try block, the cancel should
|
635 |
-
# have no coordinators it needs to run cancel on. If there was
|
636 |
-
# an error raised in the try statement we want to cancel all of
|
637 |
-
# the inflight transfers before shutting down to speed that
|
638 |
-
# process up.
|
639 |
-
self._coordinator_controller.cancel('KeyboardInterrupt()')
|
640 |
-
raise
|
641 |
-
finally:
|
642 |
-
# Shutdown all of the executors.
|
643 |
-
self._submission_executor.shutdown()
|
644 |
-
self._request_executor.shutdown()
|
645 |
-
self._io_executor.shutdown()
|
646 |
-
|
647 |
-
|
648 |
-
class TransferCoordinatorController:
|
649 |
-
def __init__(self):
|
650 |
-
"""Abstraction to control all transfer coordinators
|
651 |
-
|
652 |
-
This abstraction allows the manager to wait for inprogress transfers
|
653 |
-
to complete and cancel all inprogress transfers.
|
654 |
-
"""
|
655 |
-
self._lock = threading.Lock()
|
656 |
-
self._tracked_transfer_coordinators = set()
|
657 |
-
|
658 |
-
@property
|
659 |
-
def tracked_transfer_coordinators(self):
|
660 |
-
"""The set of transfer coordinators being tracked"""
|
661 |
-
with self._lock:
|
662 |
-
# We return a copy because the set is mutable and if you were to
|
663 |
-
# iterate over the set, it may be changing in length due to
|
664 |
-
# additions and removals of transfer coordinators.
|
665 |
-
return copy.copy(self._tracked_transfer_coordinators)
|
666 |
-
|
667 |
-
def add_transfer_coordinator(self, transfer_coordinator):
|
668 |
-
"""Adds a transfer coordinator of a transfer to be canceled if needed
|
669 |
-
|
670 |
-
:type transfer_coordinator: s3transfer.futures.TransferCoordinator
|
671 |
-
:param transfer_coordinator: The transfer coordinator for the
|
672 |
-
particular transfer
|
673 |
-
"""
|
674 |
-
with self._lock:
|
675 |
-
self._tracked_transfer_coordinators.add(transfer_coordinator)
|
676 |
-
|
677 |
-
def remove_transfer_coordinator(self, transfer_coordinator):
|
678 |
-
"""Remove a transfer coordinator from cancellation consideration
|
679 |
-
|
680 |
-
Typically, this method is invoked by the transfer coordinator itself
|
681 |
-
to remove its self when it completes its transfer.
|
682 |
-
|
683 |
-
:type transfer_coordinator: s3transfer.futures.TransferCoordinator
|
684 |
-
:param transfer_coordinator: The transfer coordinator for the
|
685 |
-
particular transfer
|
686 |
-
"""
|
687 |
-
with self._lock:
|
688 |
-
self._tracked_transfer_coordinators.remove(transfer_coordinator)
|
689 |
-
|
690 |
-
def cancel(self, msg='', exc_type=CancelledError):
|
691 |
-
"""Cancels all inprogress transfers
|
692 |
-
|
693 |
-
This cancels the inprogress transfers by calling cancel() on all
|
694 |
-
tracked transfer coordinators.
|
695 |
-
|
696 |
-
:param msg: The message to pass on to each transfer coordinator that
|
697 |
-
gets cancelled.
|
698 |
-
|
699 |
-
:param exc_type: The type of exception to set for the cancellation
|
700 |
-
"""
|
701 |
-
for transfer_coordinator in self.tracked_transfer_coordinators:
|
702 |
-
transfer_coordinator.cancel(msg, exc_type)
|
703 |
-
|
704 |
-
def wait(self):
|
705 |
-
"""Wait until there are no more inprogress transfers
|
706 |
-
|
707 |
-
This will not stop when failures are encountered and not propagate any
|
708 |
-
of these errors from failed transfers, but it can be interrupted with
|
709 |
-
a KeyboardInterrupt.
|
710 |
-
"""
|
711 |
-
try:
|
712 |
-
transfer_coordinator = None
|
713 |
-
for transfer_coordinator in self.tracked_transfer_coordinators:
|
714 |
-
transfer_coordinator.result()
|
715 |
-
except KeyboardInterrupt:
|
716 |
-
logger.debug('Received KeyboardInterrupt in wait()')
|
717 |
-
# If Keyboard interrupt is raised while waiting for
|
718 |
-
# the result, then exit out of the wait and raise the
|
719 |
-
# exception
|
720 |
-
if transfer_coordinator:
|
721 |
-
logger.debug(
|
722 |
-
'On KeyboardInterrupt was waiting for %s',
|
723 |
-
transfer_coordinator,
|
724 |
-
)
|
725 |
-
raise
|
726 |
-
except Exception:
|
727 |
-
# A general exception could have been thrown because
|
728 |
-
# of result(). We just want to ignore this and continue
|
729 |
-
# because we at least know that the transfer coordinator
|
730 |
-
# has completed.
|
731 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/Big-Web/MMSD/env/Lib/site-packages/urllib3/contrib/pyopenssl.py
DELETED
@@ -1,518 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
TLS with SNI_-support for Python 2. Follow these instructions if you would
|
3 |
-
like to verify TLS certificates in Python 2. Note, the default libraries do
|
4 |
-
*not* do certificate checking; you need to do additional work to validate
|
5 |
-
certificates yourself.
|
6 |
-
|
7 |
-
This needs the following packages installed:
|
8 |
-
|
9 |
-
* `pyOpenSSL`_ (tested with 16.0.0)
|
10 |
-
* `cryptography`_ (minimum 1.3.4, from pyopenssl)
|
11 |
-
* `idna`_ (minimum 2.0, from cryptography)
|
12 |
-
|
13 |
-
However, pyopenssl depends on cryptography, which depends on idna, so while we
|
14 |
-
use all three directly here we end up having relatively few packages required.
|
15 |
-
|
16 |
-
You can install them with the following command:
|
17 |
-
|
18 |
-
.. code-block:: bash
|
19 |
-
|
20 |
-
$ python -m pip install pyopenssl cryptography idna
|
21 |
-
|
22 |
-
To activate certificate checking, call
|
23 |
-
:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code
|
24 |
-
before you begin making HTTP requests. This can be done in a ``sitecustomize``
|
25 |
-
module, or at any other time before your application begins using ``urllib3``,
|
26 |
-
like this:
|
27 |
-
|
28 |
-
.. code-block:: python
|
29 |
-
|
30 |
-
try:
|
31 |
-
import urllib3.contrib.pyopenssl
|
32 |
-
urllib3.contrib.pyopenssl.inject_into_urllib3()
|
33 |
-
except ImportError:
|
34 |
-
pass
|
35 |
-
|
36 |
-
Now you can use :mod:`urllib3` as you normally would, and it will support SNI
|
37 |
-
when the required modules are installed.
|
38 |
-
|
39 |
-
Activating this module also has the positive side effect of disabling SSL/TLS
|
40 |
-
compression in Python 2 (see `CRIME attack`_).
|
41 |
-
|
42 |
-
.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication
|
43 |
-
.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)
|
44 |
-
.. _pyopenssl: https://www.pyopenssl.org
|
45 |
-
.. _cryptography: https://cryptography.io
|
46 |
-
.. _idna: https://github.com/kjd/idna
|
47 |
-
"""
|
48 |
-
from __future__ import absolute_import
|
49 |
-
|
50 |
-
import OpenSSL.crypto
|
51 |
-
import OpenSSL.SSL
|
52 |
-
from cryptography import x509
|
53 |
-
from cryptography.hazmat.backends.openssl import backend as openssl_backend
|
54 |
-
|
55 |
-
try:
|
56 |
-
from cryptography.x509 import UnsupportedExtension
|
57 |
-
except ImportError:
|
58 |
-
# UnsupportedExtension is gone in cryptography >= 2.1.0
|
59 |
-
class UnsupportedExtension(Exception):
|
60 |
-
pass
|
61 |
-
|
62 |
-
|
63 |
-
from io import BytesIO
|
64 |
-
from socket import error as SocketError
|
65 |
-
from socket import timeout
|
66 |
-
|
67 |
-
try: # Platform-specific: Python 2
|
68 |
-
from socket import _fileobject
|
69 |
-
except ImportError: # Platform-specific: Python 3
|
70 |
-
_fileobject = None
|
71 |
-
from ..packages.backports.makefile import backport_makefile
|
72 |
-
|
73 |
-
import logging
|
74 |
-
import ssl
|
75 |
-
import sys
|
76 |
-
import warnings
|
77 |
-
|
78 |
-
from .. import util
|
79 |
-
from ..packages import six
|
80 |
-
from ..util.ssl_ import PROTOCOL_TLS_CLIENT
|
81 |
-
|
82 |
-
warnings.warn(
|
83 |
-
"'urllib3.contrib.pyopenssl' module is deprecated and will be removed "
|
84 |
-
"in a future release of urllib3 2.x. Read more in this issue: "
|
85 |
-
"https://github.com/urllib3/urllib3/issues/2680",
|
86 |
-
category=DeprecationWarning,
|
87 |
-
stacklevel=2,
|
88 |
-
)
|
89 |
-
|
90 |
-
__all__ = ["inject_into_urllib3", "extract_from_urllib3"]
|
91 |
-
|
92 |
-
# SNI always works.
|
93 |
-
HAS_SNI = True
|
94 |
-
|
95 |
-
# Map from urllib3 to PyOpenSSL compatible parameter-values.
|
96 |
-
_openssl_versions = {
|
97 |
-
util.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD,
|
98 |
-
PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD,
|
99 |
-
ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
|
100 |
-
}
|
101 |
-
|
102 |
-
if hasattr(ssl, "PROTOCOL_SSLv3") and hasattr(OpenSSL.SSL, "SSLv3_METHOD"):
|
103 |
-
_openssl_versions[ssl.PROTOCOL_SSLv3] = OpenSSL.SSL.SSLv3_METHOD
|
104 |
-
|
105 |
-
if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"):
|
106 |
-
_openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD
|
107 |
-
|
108 |
-
if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"):
|
109 |
-
_openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD
|
110 |
-
|
111 |
-
|
112 |
-
_stdlib_to_openssl_verify = {
|
113 |
-
ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
|
114 |
-
ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
|
115 |
-
ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER
|
116 |
-
+ OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
|
117 |
-
}
|
118 |
-
_openssl_to_stdlib_verify = dict((v, k) for k, v in _stdlib_to_openssl_verify.items())
|
119 |
-
|
120 |
-
# OpenSSL will only write 16K at a time
|
121 |
-
SSL_WRITE_BLOCKSIZE = 16384
|
122 |
-
|
123 |
-
orig_util_HAS_SNI = util.HAS_SNI
|
124 |
-
orig_util_SSLContext = util.ssl_.SSLContext
|
125 |
-
|
126 |
-
|
127 |
-
log = logging.getLogger(__name__)
|
128 |
-
|
129 |
-
|
130 |
-
def inject_into_urllib3():
|
131 |
-
"Monkey-patch urllib3 with PyOpenSSL-backed SSL-support."
|
132 |
-
|
133 |
-
_validate_dependencies_met()
|
134 |
-
|
135 |
-
util.SSLContext = PyOpenSSLContext
|
136 |
-
util.ssl_.SSLContext = PyOpenSSLContext
|
137 |
-
util.HAS_SNI = HAS_SNI
|
138 |
-
util.ssl_.HAS_SNI = HAS_SNI
|
139 |
-
util.IS_PYOPENSSL = True
|
140 |
-
util.ssl_.IS_PYOPENSSL = True
|
141 |
-
|
142 |
-
|
143 |
-
def extract_from_urllib3():
|
144 |
-
"Undo monkey-patching by :func:`inject_into_urllib3`."
|
145 |
-
|
146 |
-
util.SSLContext = orig_util_SSLContext
|
147 |
-
util.ssl_.SSLContext = orig_util_SSLContext
|
148 |
-
util.HAS_SNI = orig_util_HAS_SNI
|
149 |
-
util.ssl_.HAS_SNI = orig_util_HAS_SNI
|
150 |
-
util.IS_PYOPENSSL = False
|
151 |
-
util.ssl_.IS_PYOPENSSL = False
|
152 |
-
|
153 |
-
|
154 |
-
def _validate_dependencies_met():
|
155 |
-
"""
|
156 |
-
Verifies that PyOpenSSL's package-level dependencies have been met.
|
157 |
-
Throws `ImportError` if they are not met.
|
158 |
-
"""
|
159 |
-
# Method added in `cryptography==1.1`; not available in older versions
|
160 |
-
from cryptography.x509.extensions import Extensions
|
161 |
-
|
162 |
-
if getattr(Extensions, "get_extension_for_class", None) is None:
|
163 |
-
raise ImportError(
|
164 |
-
"'cryptography' module missing required functionality. "
|
165 |
-
"Try upgrading to v1.3.4 or newer."
|
166 |
-
)
|
167 |
-
|
168 |
-
# pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
|
169 |
-
# attribute is only present on those versions.
|
170 |
-
from OpenSSL.crypto import X509
|
171 |
-
|
172 |
-
x509 = X509()
|
173 |
-
if getattr(x509, "_x509", None) is None:
|
174 |
-
raise ImportError(
|
175 |
-
"'pyOpenSSL' module missing required functionality. "
|
176 |
-
"Try upgrading to v0.14 or newer."
|
177 |
-
)
|
178 |
-
|
179 |
-
|
180 |
-
def _dnsname_to_stdlib(name):
|
181 |
-
"""
|
182 |
-
Converts a dNSName SubjectAlternativeName field to the form used by the
|
183 |
-
standard library on the given Python version.
|
184 |
-
|
185 |
-
Cryptography produces a dNSName as a unicode string that was idna-decoded
|
186 |
-
from ASCII bytes. We need to idna-encode that string to get it back, and
|
187 |
-
then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
|
188 |
-
uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
|
189 |
-
|
190 |
-
If the name cannot be idna-encoded then we return None signalling that
|
191 |
-
the name given should be skipped.
|
192 |
-
"""
|
193 |
-
|
194 |
-
def idna_encode(name):
|
195 |
-
"""
|
196 |
-
Borrowed wholesale from the Python Cryptography Project. It turns out
|
197 |
-
that we can't just safely call `idna.encode`: it can explode for
|
198 |
-
wildcard names. This avoids that problem.
|
199 |
-
"""
|
200 |
-
import idna
|
201 |
-
|
202 |
-
try:
|
203 |
-
for prefix in [u"*.", u"."]:
|
204 |
-
if name.startswith(prefix):
|
205 |
-
name = name[len(prefix) :]
|
206 |
-
return prefix.encode("ascii") + idna.encode(name)
|
207 |
-
return idna.encode(name)
|
208 |
-
except idna.core.IDNAError:
|
209 |
-
return None
|
210 |
-
|
211 |
-
# Don't send IPv6 addresses through the IDNA encoder.
|
212 |
-
if ":" in name:
|
213 |
-
return name
|
214 |
-
|
215 |
-
name = idna_encode(name)
|
216 |
-
if name is None:
|
217 |
-
return None
|
218 |
-
elif sys.version_info >= (3, 0):
|
219 |
-
name = name.decode("utf-8")
|
220 |
-
return name
|
221 |
-
|
222 |
-
|
223 |
-
def get_subj_alt_name(peer_cert):
|
224 |
-
"""
|
225 |
-
Given an PyOpenSSL certificate, provides all the subject alternative names.
|
226 |
-
"""
|
227 |
-
# Pass the cert to cryptography, which has much better APIs for this.
|
228 |
-
if hasattr(peer_cert, "to_cryptography"):
|
229 |
-
cert = peer_cert.to_cryptography()
|
230 |
-
else:
|
231 |
-
der = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, peer_cert)
|
232 |
-
cert = x509.load_der_x509_certificate(der, openssl_backend)
|
233 |
-
|
234 |
-
# We want to find the SAN extension. Ask Cryptography to locate it (it's
|
235 |
-
# faster than looping in Python)
|
236 |
-
try:
|
237 |
-
ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
|
238 |
-
except x509.ExtensionNotFound:
|
239 |
-
# No such extension, return the empty list.
|
240 |
-
return []
|
241 |
-
except (
|
242 |
-
x509.DuplicateExtension,
|
243 |
-
UnsupportedExtension,
|
244 |
-
x509.UnsupportedGeneralNameType,
|
245 |
-
UnicodeError,
|
246 |
-
) as e:
|
247 |
-
# A problem has been found with the quality of the certificate. Assume
|
248 |
-
# no SAN field is present.
|
249 |
-
log.warning(
|
250 |
-
"A problem was encountered with the certificate that prevented "
|
251 |
-
"urllib3 from finding the SubjectAlternativeName field. This can "
|
252 |
-
"affect certificate validation. The error was %s",
|
253 |
-
e,
|
254 |
-
)
|
255 |
-
return []
|
256 |
-
|
257 |
-
# We want to return dNSName and iPAddress fields. We need to cast the IPs
|
258 |
-
# back to strings because the match_hostname function wants them as
|
259 |
-
# strings.
|
260 |
-
# Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
|
261 |
-
# decoded. This is pretty frustrating, but that's what the standard library
|
262 |
-
# does with certificates, and so we need to attempt to do the same.
|
263 |
-
# We also want to skip over names which cannot be idna encoded.
|
264 |
-
names = [
|
265 |
-
("DNS", name)
|
266 |
-
for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
|
267 |
-
if name is not None
|
268 |
-
]
|
269 |
-
names.extend(
|
270 |
-
("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress)
|
271 |
-
)
|
272 |
-
|
273 |
-
return names
|
274 |
-
|
275 |
-
|
276 |
-
class WrappedSocket(object):
|
277 |
-
"""API-compatibility wrapper for Python OpenSSL's Connection-class.
|
278 |
-
|
279 |
-
Note: _makefile_refs, _drop() and _reuse() are needed for the garbage
|
280 |
-
collector of pypy.
|
281 |
-
"""
|
282 |
-
|
283 |
-
def __init__(self, connection, socket, suppress_ragged_eofs=True):
|
284 |
-
self.connection = connection
|
285 |
-
self.socket = socket
|
286 |
-
self.suppress_ragged_eofs = suppress_ragged_eofs
|
287 |
-
self._makefile_refs = 0
|
288 |
-
self._closed = False
|
289 |
-
|
290 |
-
def fileno(self):
|
291 |
-
return self.socket.fileno()
|
292 |
-
|
293 |
-
# Copy-pasted from Python 3.5 source code
|
294 |
-
def _decref_socketios(self):
|
295 |
-
if self._makefile_refs > 0:
|
296 |
-
self._makefile_refs -= 1
|
297 |
-
if self._closed:
|
298 |
-
self.close()
|
299 |
-
|
300 |
-
def recv(self, *args, **kwargs):
|
301 |
-
try:
|
302 |
-
data = self.connection.recv(*args, **kwargs)
|
303 |
-
except OpenSSL.SSL.SysCallError as e:
|
304 |
-
if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
|
305 |
-
return b""
|
306 |
-
else:
|
307 |
-
raise SocketError(str(e))
|
308 |
-
except OpenSSL.SSL.ZeroReturnError:
|
309 |
-
if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
|
310 |
-
return b""
|
311 |
-
else:
|
312 |
-
raise
|
313 |
-
except OpenSSL.SSL.WantReadError:
|
314 |
-
if not util.wait_for_read(self.socket, self.socket.gettimeout()):
|
315 |
-
raise timeout("The read operation timed out")
|
316 |
-
else:
|
317 |
-
return self.recv(*args, **kwargs)
|
318 |
-
|
319 |
-
# TLS 1.3 post-handshake authentication
|
320 |
-
except OpenSSL.SSL.Error as e:
|
321 |
-
raise ssl.SSLError("read error: %r" % e)
|
322 |
-
else:
|
323 |
-
return data
|
324 |
-
|
325 |
-
def recv_into(self, *args, **kwargs):
|
326 |
-
try:
|
327 |
-
return self.connection.recv_into(*args, **kwargs)
|
328 |
-
except OpenSSL.SSL.SysCallError as e:
|
329 |
-
if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):
|
330 |
-
return 0
|
331 |
-
else:
|
332 |
-
raise SocketError(str(e))
|
333 |
-
except OpenSSL.SSL.ZeroReturnError:
|
334 |
-
if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
|
335 |
-
return 0
|
336 |
-
else:
|
337 |
-
raise
|
338 |
-
except OpenSSL.SSL.WantReadError:
|
339 |
-
if not util.wait_for_read(self.socket, self.socket.gettimeout()):
|
340 |
-
raise timeout("The read operation timed out")
|
341 |
-
else:
|
342 |
-
return self.recv_into(*args, **kwargs)
|
343 |
-
|
344 |
-
# TLS 1.3 post-handshake authentication
|
345 |
-
except OpenSSL.SSL.Error as e:
|
346 |
-
raise ssl.SSLError("read error: %r" % e)
|
347 |
-
|
348 |
-
def settimeout(self, timeout):
|
349 |
-
return self.socket.settimeout(timeout)
|
350 |
-
|
351 |
-
def _send_until_done(self, data):
|
352 |
-
while True:
|
353 |
-
try:
|
354 |
-
return self.connection.send(data)
|
355 |
-
except OpenSSL.SSL.WantWriteError:
|
356 |
-
if not util.wait_for_write(self.socket, self.socket.gettimeout()):
|
357 |
-
raise timeout()
|
358 |
-
continue
|
359 |
-
except OpenSSL.SSL.SysCallError as e:
|
360 |
-
raise SocketError(str(e))
|
361 |
-
|
362 |
-
def sendall(self, data):
|
363 |
-
total_sent = 0
|
364 |
-
while total_sent < len(data):
|
365 |
-
sent = self._send_until_done(
|
366 |
-
data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]
|
367 |
-
)
|
368 |
-
total_sent += sent
|
369 |
-
|
370 |
-
def shutdown(self):
|
371 |
-
# FIXME rethrow compatible exceptions should we ever use this
|
372 |
-
self.connection.shutdown()
|
373 |
-
|
374 |
-
def close(self):
|
375 |
-
if self._makefile_refs < 1:
|
376 |
-
try:
|
377 |
-
self._closed = True
|
378 |
-
return self.connection.close()
|
379 |
-
except OpenSSL.SSL.Error:
|
380 |
-
return
|
381 |
-
else:
|
382 |
-
self._makefile_refs -= 1
|
383 |
-
|
384 |
-
def getpeercert(self, binary_form=False):
|
385 |
-
x509 = self.connection.get_peer_certificate()
|
386 |
-
|
387 |
-
if not x509:
|
388 |
-
return x509
|
389 |
-
|
390 |
-
if binary_form:
|
391 |
-
return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)
|
392 |
-
|
393 |
-
return {
|
394 |
-
"subject": ((("commonName", x509.get_subject().CN),),),
|
395 |
-
"subjectAltName": get_subj_alt_name(x509),
|
396 |
-
}
|
397 |
-
|
398 |
-
def version(self):
|
399 |
-
return self.connection.get_protocol_version_name()
|
400 |
-
|
401 |
-
def _reuse(self):
|
402 |
-
self._makefile_refs += 1
|
403 |
-
|
404 |
-
def _drop(self):
|
405 |
-
if self._makefile_refs < 1:
|
406 |
-
self.close()
|
407 |
-
else:
|
408 |
-
self._makefile_refs -= 1
|
409 |
-
|
410 |
-
|
411 |
-
if _fileobject: # Platform-specific: Python 2
|
412 |
-
|
413 |
-
def makefile(self, mode, bufsize=-1):
|
414 |
-
self._makefile_refs += 1
|
415 |
-
return _fileobject(self, mode, bufsize, close=True)
|
416 |
-
|
417 |
-
else: # Platform-specific: Python 3
|
418 |
-
makefile = backport_makefile
|
419 |
-
|
420 |
-
WrappedSocket.makefile = makefile
|
421 |
-
|
422 |
-
|
423 |
-
class PyOpenSSLContext(object):
|
424 |
-
"""
|
425 |
-
I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible
|
426 |
-
for translating the interface of the standard library ``SSLContext`` object
|
427 |
-
to calls into PyOpenSSL.
|
428 |
-
"""
|
429 |
-
|
430 |
-
def __init__(self, protocol):
|
431 |
-
self.protocol = _openssl_versions[protocol]
|
432 |
-
self._ctx = OpenSSL.SSL.Context(self.protocol)
|
433 |
-
self._options = 0
|
434 |
-
self.check_hostname = False
|
435 |
-
|
436 |
-
@property
|
437 |
-
def options(self):
|
438 |
-
return self._options
|
439 |
-
|
440 |
-
@options.setter
|
441 |
-
def options(self, value):
|
442 |
-
self._options = value
|
443 |
-
self._ctx.set_options(value)
|
444 |
-
|
445 |
-
@property
|
446 |
-
def verify_mode(self):
|
447 |
-
return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
|
448 |
-
|
449 |
-
@verify_mode.setter
|
450 |
-
def verify_mode(self, value):
|
451 |
-
self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback)
|
452 |
-
|
453 |
-
def set_default_verify_paths(self):
|
454 |
-
self._ctx.set_default_verify_paths()
|
455 |
-
|
456 |
-
def set_ciphers(self, ciphers):
|
457 |
-
if isinstance(ciphers, six.text_type):
|
458 |
-
ciphers = ciphers.encode("utf-8")
|
459 |
-
self._ctx.set_cipher_list(ciphers)
|
460 |
-
|
461 |
-
def load_verify_locations(self, cafile=None, capath=None, cadata=None):
|
462 |
-
if cafile is not None:
|
463 |
-
cafile = cafile.encode("utf-8")
|
464 |
-
if capath is not None:
|
465 |
-
capath = capath.encode("utf-8")
|
466 |
-
try:
|
467 |
-
self._ctx.load_verify_locations(cafile, capath)
|
468 |
-
if cadata is not None:
|
469 |
-
self._ctx.load_verify_locations(BytesIO(cadata))
|
470 |
-
except OpenSSL.SSL.Error as e:
|
471 |
-
raise ssl.SSLError("unable to load trusted certificates: %r" % e)
|
472 |
-
|
473 |
-
def load_cert_chain(self, certfile, keyfile=None, password=None):
|
474 |
-
self._ctx.use_certificate_chain_file(certfile)
|
475 |
-
if password is not None:
|
476 |
-
if not isinstance(password, six.binary_type):
|
477 |
-
password = password.encode("utf-8")
|
478 |
-
self._ctx.set_passwd_cb(lambda *_: password)
|
479 |
-
self._ctx.use_privatekey_file(keyfile or certfile)
|
480 |
-
|
481 |
-
def set_alpn_protocols(self, protocols):
|
482 |
-
protocols = [six.ensure_binary(p) for p in protocols]
|
483 |
-
return self._ctx.set_alpn_protos(protocols)
|
484 |
-
|
485 |
-
def wrap_socket(
|
486 |
-
self,
|
487 |
-
sock,
|
488 |
-
server_side=False,
|
489 |
-
do_handshake_on_connect=True,
|
490 |
-
suppress_ragged_eofs=True,
|
491 |
-
server_hostname=None,
|
492 |
-
):
|
493 |
-
cnx = OpenSSL.SSL.Connection(self._ctx, sock)
|
494 |
-
|
495 |
-
if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3
|
496 |
-
server_hostname = server_hostname.encode("utf-8")
|
497 |
-
|
498 |
-
if server_hostname is not None:
|
499 |
-
cnx.set_tlsext_host_name(server_hostname)
|
500 |
-
|
501 |
-
cnx.set_connect_state()
|
502 |
-
|
503 |
-
while True:
|
504 |
-
try:
|
505 |
-
cnx.do_handshake()
|
506 |
-
except OpenSSL.SSL.WantReadError:
|
507 |
-
if not util.wait_for_read(sock, sock.gettimeout()):
|
508 |
-
raise timeout("select timed out")
|
509 |
-
continue
|
510 |
-
except OpenSSL.SSL.Error as e:
|
511 |
-
raise ssl.SSLError("bad handshake: %r" % e)
|
512 |
-
break
|
513 |
-
|
514 |
-
return WrappedSocket(cnx, sock)
|
515 |
-
|
516 |
-
|
517 |
-
def _verify_callback(cnx, x509, err_no, err_depth, return_code):
|
518 |
-
return err_no == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CC123123/blip2_t/app.py
DELETED
@@ -1,282 +0,0 @@
|
|
1 |
-
from io import BytesIO
|
2 |
-
|
3 |
-
import string
|
4 |
-
import gradio as gr
|
5 |
-
import requests
|
6 |
-
from utils import Endpoint, get_token
|
7 |
-
|
8 |
-
|
9 |
-
def encode_image(image):
|
10 |
-
buffered = BytesIO()
|
11 |
-
image.save(buffered, format="JPEG")
|
12 |
-
buffered.seek(0)
|
13 |
-
|
14 |
-
return buffered
|
15 |
-
|
16 |
-
|
17 |
-
def query_chat_api(
|
18 |
-
image, prompt, decoding_method, temperature, len_penalty, repetition_penalty
|
19 |
-
):
|
20 |
-
|
21 |
-
url = endpoint.url
|
22 |
-
url = url + "/api/generate"
|
23 |
-
|
24 |
-
headers = {
|
25 |
-
"User-Agent": "BLIP-2 HuggingFace Space",
|
26 |
-
"Auth-Token": get_token(),
|
27 |
-
}
|
28 |
-
|
29 |
-
data = {
|
30 |
-
"prompt": prompt,
|
31 |
-
"use_nucleus_sampling": decoding_method == "Nucleus sampling",
|
32 |
-
"temperature": temperature,
|
33 |
-
"length_penalty": len_penalty,
|
34 |
-
"repetition_penalty": repetition_penalty,
|
35 |
-
}
|
36 |
-
|
37 |
-
image = encode_image(image)
|
38 |
-
files = {"image": image}
|
39 |
-
|
40 |
-
response = requests.post(url, data=data, files=files, headers=headers)
|
41 |
-
|
42 |
-
if response.status_code == 200:
|
43 |
-
return response.json()
|
44 |
-
else:
|
45 |
-
return "Error: " + response.text
|
46 |
-
|
47 |
-
|
48 |
-
def query_caption_api(
|
49 |
-
image, decoding_method, temperature, len_penalty, repetition_penalty
|
50 |
-
):
|
51 |
-
|
52 |
-
url = endpoint.url
|
53 |
-
url = url + "/api/caption"
|
54 |
-
|
55 |
-
headers = {
|
56 |
-
"User-Agent": "BLIP-2 HuggingFace Space",
|
57 |
-
"Auth-Token": get_token(),
|
58 |
-
}
|
59 |
-
|
60 |
-
data = {
|
61 |
-
"use_nucleus_sampling": decoding_method == "Nucleus sampling",
|
62 |
-
"temperature": temperature,
|
63 |
-
"length_penalty": len_penalty,
|
64 |
-
"repetition_penalty": repetition_penalty,
|
65 |
-
}
|
66 |
-
|
67 |
-
image = encode_image(image)
|
68 |
-
files = {"image": image}
|
69 |
-
|
70 |
-
response = requests.post(url, data=data, files=files, headers=headers)
|
71 |
-
|
72 |
-
if response.status_code == 200:
|
73 |
-
return response.json()
|
74 |
-
else:
|
75 |
-
return "Error: " + response.text
|
76 |
-
|
77 |
-
|
78 |
-
def postprocess_output(output):
|
79 |
-
# if last character is not a punctuation, add a full stop
|
80 |
-
if not output[0][-1] in string.punctuation:
|
81 |
-
output[0] += "."
|
82 |
-
|
83 |
-
return output
|
84 |
-
|
85 |
-
|
86 |
-
def inference_chat(
|
87 |
-
image,
|
88 |
-
text_input,
|
89 |
-
decoding_method,
|
90 |
-
temperature,
|
91 |
-
length_penalty,
|
92 |
-
repetition_penalty,
|
93 |
-
history=[],
|
94 |
-
):
|
95 |
-
text_input = text_input
|
96 |
-
history.append(text_input)
|
97 |
-
|
98 |
-
prompt = " ".join(history)
|
99 |
-
|
100 |
-
output = query_chat_api(
|
101 |
-
image, prompt, decoding_method, temperature, length_penalty, repetition_penalty
|
102 |
-
)
|
103 |
-
output = postprocess_output(output)
|
104 |
-
history += output
|
105 |
-
|
106 |
-
chat = [
|
107 |
-
(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)
|
108 |
-
] # convert to tuples of list
|
109 |
-
|
110 |
-
return {chatbot: chat, state: history}
|
111 |
-
|
112 |
-
|
113 |
-
def inference_caption(
|
114 |
-
image,
|
115 |
-
decoding_method,
|
116 |
-
temperature,
|
117 |
-
length_penalty,
|
118 |
-
repetition_penalty,
|
119 |
-
):
|
120 |
-
output = query_caption_api(
|
121 |
-
image, decoding_method, temperature, length_penalty, repetition_penalty
|
122 |
-
)
|
123 |
-
|
124 |
-
return output[0]
|
125 |
-
|
126 |
-
|
127 |
-
title = """<h1 align="center">BLIP-2</h1>"""
|
128 |
-
description = """Gradio demo for BLIP-2, image-to-text generation from Salesforce Research. To use it, simply upload your image, or click one of the examples to load them.
|
129 |
-
<br> <strong>Disclaimer</strong>: This is a research prototype and is not intended for production use. No data including but not restricted to text and images is collected."""
|
130 |
-
article = """<strong>Paper</strong>: <a href='https://arxiv.org/abs/2301.12597' target='_blank'>BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models</a>
|
131 |
-
<br> <strong>Code</strong>: BLIP2 is now integrated into GitHub repo: <a href='https://github.com/salesforce/LAVIS' target='_blank'>LAVIS: a One-stop Library for Language and Vision</a>
|
132 |
-
<br> <strong>🤗 `transformers` integration</strong>: You can now use `transformers` to use our BLIP-2 models! Check out the <a href='https://huggingface.co/docs/transformers/main/en/model_doc/blip-2' target='_blank'> official docs </a>
|
133 |
-
<p> <strong>Project Page</strong>: <a href='https://github.com/salesforce/LAVIS/tree/main/projects/blip2' target='_blank'> BLIP2 on LAVIS</a>
|
134 |
-
<br> <strong>Description</strong>: Captioning results from <strong>BLIP2_OPT_6.7B</strong>. Chat results from <strong>BLIP2_FlanT5xxl</strong>.
|
135 |
-
"""
|
136 |
-
|
137 |
-
endpoint = Endpoint()
|
138 |
-
|
139 |
-
examples = [
|
140 |
-
["house.png", "How could someone get out of the house?"],
|
141 |
-
["flower.jpg", "Question: What is this flower and where is it's origin? Answer:"],
|
142 |
-
["pizza.jpg", "What are steps to cook it?"],
|
143 |
-
["sunset.jpg", "Here is a romantic message going along the photo:"],
|
144 |
-
["forbidden_city.webp", "In what dynasties was this place built?"],
|
145 |
-
]
|
146 |
-
|
147 |
-
with gr.Blocks(
|
148 |
-
css="""
|
149 |
-
.message.svelte-w6rprc.svelte-w6rprc.svelte-w6rprc {font-size: 20px; margin-top: 20px}
|
150 |
-
#component-21 > div.wrap.svelte-w6rprc {height: 600px;}
|
151 |
-
"""
|
152 |
-
) as iface:
|
153 |
-
state = gr.State([])
|
154 |
-
|
155 |
-
gr.Markdown(title)
|
156 |
-
gr.Markdown(description)
|
157 |
-
gr.Markdown(article)
|
158 |
-
|
159 |
-
with gr.Row():
|
160 |
-
with gr.Column(scale=1):
|
161 |
-
image_input = gr.Image(type="pil")
|
162 |
-
|
163 |
-
# with gr.Row():
|
164 |
-
sampling = gr.Radio(
|
165 |
-
choices=["Beam search", "Nucleus sampling"],
|
166 |
-
value="Beam search",
|
167 |
-
label="Text Decoding Method",
|
168 |
-
interactive=True,
|
169 |
-
)
|
170 |
-
|
171 |
-
temperature = gr.Slider(
|
172 |
-
minimum=0.5,
|
173 |
-
maximum=1.0,
|
174 |
-
value=1.0,
|
175 |
-
step=0.1,
|
176 |
-
interactive=True,
|
177 |
-
label="Temperature (used with nucleus sampling)",
|
178 |
-
)
|
179 |
-
|
180 |
-
len_penalty = gr.Slider(
|
181 |
-
minimum=-1.0,
|
182 |
-
maximum=2.0,
|
183 |
-
value=1.0,
|
184 |
-
step=0.2,
|
185 |
-
interactive=True,
|
186 |
-
label="Length Penalty (set to larger for longer sequence, used with beam search)",
|
187 |
-
)
|
188 |
-
|
189 |
-
rep_penalty = gr.Slider(
|
190 |
-
minimum=1.0,
|
191 |
-
maximum=5.0,
|
192 |
-
value=1.5,
|
193 |
-
step=0.5,
|
194 |
-
interactive=True,
|
195 |
-
label="Repeat Penalty (larger value prevents repetition)",
|
196 |
-
)
|
197 |
-
|
198 |
-
with gr.Column(scale=1.8):
|
199 |
-
|
200 |
-
with gr.Column():
|
201 |
-
caption_output = gr.Textbox(lines=1, label="Caption Output")
|
202 |
-
caption_button = gr.Button(
|
203 |
-
value="Caption it!", interactive=True, variant="primary"
|
204 |
-
)
|
205 |
-
caption_button.click(
|
206 |
-
inference_caption,
|
207 |
-
[
|
208 |
-
image_input,
|
209 |
-
sampling,
|
210 |
-
temperature,
|
211 |
-
len_penalty,
|
212 |
-
rep_penalty,
|
213 |
-
],
|
214 |
-
[caption_output],
|
215 |
-
)
|
216 |
-
|
217 |
-
gr.Markdown("""Trying prompting your input for chat; e.g. example prompt for QA, \"Question: {} Answer:\" Use proper punctuation (e.g., question mark).""")
|
218 |
-
with gr.Row():
|
219 |
-
with gr.Column(
|
220 |
-
scale=1.5,
|
221 |
-
):
|
222 |
-
chatbot = gr.Chatbot(
|
223 |
-
label="Chat Output (from FlanT5)",
|
224 |
-
)
|
225 |
-
|
226 |
-
# with gr.Row():
|
227 |
-
with gr.Column(scale=1):
|
228 |
-
chat_input = gr.Textbox(lines=1, label="Chat Input")
|
229 |
-
chat_input.submit(
|
230 |
-
inference_chat,
|
231 |
-
[
|
232 |
-
image_input,
|
233 |
-
chat_input,
|
234 |
-
sampling,
|
235 |
-
temperature,
|
236 |
-
len_penalty,
|
237 |
-
rep_penalty,
|
238 |
-
state,
|
239 |
-
],
|
240 |
-
[chatbot, state],
|
241 |
-
)
|
242 |
-
|
243 |
-
with gr.Row():
|
244 |
-
clear_button = gr.Button(value="Clear", interactive=True)
|
245 |
-
clear_button.click(
|
246 |
-
lambda: ("", [], []),
|
247 |
-
[],
|
248 |
-
[chat_input, chatbot, state],
|
249 |
-
queue=False,
|
250 |
-
)
|
251 |
-
|
252 |
-
submit_button = gr.Button(
|
253 |
-
value="Submit", interactive=True, variant="primary"
|
254 |
-
)
|
255 |
-
submit_button.click(
|
256 |
-
inference_chat,
|
257 |
-
[
|
258 |
-
image_input,
|
259 |
-
chat_input,
|
260 |
-
sampling,
|
261 |
-
temperature,
|
262 |
-
len_penalty,
|
263 |
-
rep_penalty,
|
264 |
-
state,
|
265 |
-
],
|
266 |
-
[chatbot, state],
|
267 |
-
)
|
268 |
-
|
269 |
-
image_input.change(
|
270 |
-
lambda: ("", "", []),
|
271 |
-
[],
|
272 |
-
[chatbot, caption_output, state],
|
273 |
-
queue=False,
|
274 |
-
)
|
275 |
-
|
276 |
-
examples = gr.Examples(
|
277 |
-
examples=examples,
|
278 |
-
inputs=[image_input, chat_input],
|
279 |
-
)
|
280 |
-
|
281 |
-
iface.queue(concurrency_count=1, api_open=False, max_size=10)
|
282 |
-
iface.launch(enable_queue=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/tests/test_box2box_transform.py
DELETED
@@ -1,64 +0,0 @@
|
|
1 |
-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
2 |
-
import logging
|
3 |
-
import unittest
|
4 |
-
import torch
|
5 |
-
|
6 |
-
from detectron2.modeling.box_regression import Box2BoxTransform, Box2BoxTransformRotated
|
7 |
-
|
8 |
-
logger = logging.getLogger(__name__)
|
9 |
-
|
10 |
-
|
11 |
-
def random_boxes(mean_box, stdev, N):
|
12 |
-
return torch.rand(N, 4) * stdev + torch.tensor(mean_box, dtype=torch.float)
|
13 |
-
|
14 |
-
|
15 |
-
class TestBox2BoxTransform(unittest.TestCase):
|
16 |
-
def test_reconstruction(self):
|
17 |
-
weights = (5, 5, 10, 10)
|
18 |
-
b2b_tfm = Box2BoxTransform(weights=weights)
|
19 |
-
src_boxes = random_boxes([10, 10, 20, 20], 1, 10)
|
20 |
-
dst_boxes = random_boxes([10, 10, 20, 20], 1, 10)
|
21 |
-
|
22 |
-
devices = [torch.device("cpu")]
|
23 |
-
if torch.cuda.is_available():
|
24 |
-
devices.append(torch.device("cuda"))
|
25 |
-
for device in devices:
|
26 |
-
src_boxes = src_boxes.to(device=device)
|
27 |
-
dst_boxes = dst_boxes.to(device=device)
|
28 |
-
deltas = b2b_tfm.get_deltas(src_boxes, dst_boxes)
|
29 |
-
dst_boxes_reconstructed = b2b_tfm.apply_deltas(deltas, src_boxes)
|
30 |
-
assert torch.allclose(dst_boxes, dst_boxes_reconstructed)
|
31 |
-
|
32 |
-
|
33 |
-
def random_rotated_boxes(mean_box, std_length, std_angle, N):
|
34 |
-
return torch.cat(
|
35 |
-
[torch.rand(N, 4) * std_length, torch.rand(N, 1) * std_angle], dim=1
|
36 |
-
) + torch.tensor(mean_box, dtype=torch.float)
|
37 |
-
|
38 |
-
|
39 |
-
class TestBox2BoxTransformRotated(unittest.TestCase):
|
40 |
-
def test_reconstruction(self):
|
41 |
-
weights = (5, 5, 10, 10, 1)
|
42 |
-
b2b_transform = Box2BoxTransformRotated(weights=weights)
|
43 |
-
src_boxes = random_rotated_boxes([10, 10, 20, 20, -30], 5, 60.0, 10)
|
44 |
-
dst_boxes = random_rotated_boxes([10, 10, 20, 20, -30], 5, 60.0, 10)
|
45 |
-
|
46 |
-
devices = [torch.device("cpu")]
|
47 |
-
if torch.cuda.is_available():
|
48 |
-
devices.append(torch.device("cuda"))
|
49 |
-
for device in devices:
|
50 |
-
src_boxes = src_boxes.to(device=device)
|
51 |
-
dst_boxes = dst_boxes.to(device=device)
|
52 |
-
deltas = b2b_transform.get_deltas(src_boxes, dst_boxes)
|
53 |
-
dst_boxes_reconstructed = b2b_transform.apply_deltas(deltas, src_boxes)
|
54 |
-
assert torch.allclose(dst_boxes[:, :4], dst_boxes_reconstructed[:, :4], atol=1e-5)
|
55 |
-
# angle difference has to be normalized
|
56 |
-
assert torch.allclose(
|
57 |
-
(dst_boxes[:, 4] - dst_boxes_reconstructed[:, 4] + 180.0) % 360.0 - 180.0,
|
58 |
-
torch.zeros_like(dst_boxes[:, 4]),
|
59 |
-
atol=1e-4,
|
60 |
-
)
|
61 |
-
|
62 |
-
|
63 |
-
if __name__ == "__main__":
|
64 |
-
unittest.main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/WALT/mmdet/models/roi_heads/scnet_roi_head.py
DELETED
@@ -1,582 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import torch.nn.functional as F
|
3 |
-
|
4 |
-
from mmdet.core import (bbox2result, bbox2roi, bbox_mapping, merge_aug_bboxes,
|
5 |
-
merge_aug_masks, multiclass_nms)
|
6 |
-
from ..builder import HEADS, build_head, build_roi_extractor
|
7 |
-
from .cascade_roi_head import CascadeRoIHead
|
8 |
-
|
9 |
-
|
10 |
-
@HEADS.register_module()
|
11 |
-
class SCNetRoIHead(CascadeRoIHead):
|
12 |
-
"""RoIHead for `SCNet <https://arxiv.org/abs/2012.10150>`_.
|
13 |
-
|
14 |
-
Args:
|
15 |
-
num_stages (int): number of cascade stages.
|
16 |
-
stage_loss_weights (list): loss weight of cascade stages.
|
17 |
-
semantic_roi_extractor (dict): config to init semantic roi extractor.
|
18 |
-
semantic_head (dict): config to init semantic head.
|
19 |
-
feat_relay_head (dict): config to init feature_relay_head.
|
20 |
-
glbctx_head (dict): config to init global context head.
|
21 |
-
"""
|
22 |
-
|
23 |
-
def __init__(self,
|
24 |
-
num_stages,
|
25 |
-
stage_loss_weights,
|
26 |
-
semantic_roi_extractor=None,
|
27 |
-
semantic_head=None,
|
28 |
-
feat_relay_head=None,
|
29 |
-
glbctx_head=None,
|
30 |
-
**kwargs):
|
31 |
-
super(SCNetRoIHead, self).__init__(num_stages, stage_loss_weights,
|
32 |
-
**kwargs)
|
33 |
-
assert self.with_bbox and self.with_mask
|
34 |
-
assert not self.with_shared_head # shared head is not supported
|
35 |
-
|
36 |
-
if semantic_head is not None:
|
37 |
-
self.semantic_roi_extractor = build_roi_extractor(
|
38 |
-
semantic_roi_extractor)
|
39 |
-
self.semantic_head = build_head(semantic_head)
|
40 |
-
|
41 |
-
if feat_relay_head is not None:
|
42 |
-
self.feat_relay_head = build_head(feat_relay_head)
|
43 |
-
|
44 |
-
if glbctx_head is not None:
|
45 |
-
self.glbctx_head = build_head(glbctx_head)
|
46 |
-
|
47 |
-
def init_mask_head(self, mask_roi_extractor, mask_head):
|
48 |
-
"""Initialize ``mask_head``"""
|
49 |
-
if mask_roi_extractor is not None:
|
50 |
-
self.mask_roi_extractor = build_roi_extractor(mask_roi_extractor)
|
51 |
-
self.mask_head = build_head(mask_head)
|
52 |
-
|
53 |
-
def init_weights(self, pretrained):
|
54 |
-
"""Initialize the weights in head.
|
55 |
-
|
56 |
-
Args:
|
57 |
-
pretrained (str, optional): Path to pre-trained weights.
|
58 |
-
Defaults to None.
|
59 |
-
"""
|
60 |
-
for i in range(self.num_stages):
|
61 |
-
if self.with_bbox:
|
62 |
-
self.bbox_roi_extractor[i].init_weights()
|
63 |
-
self.bbox_head[i].init_weights()
|
64 |
-
if self.with_mask:
|
65 |
-
self.mask_roi_extractor.init_weights()
|
66 |
-
self.mask_head.init_weights()
|
67 |
-
if self.with_semantic:
|
68 |
-
self.semantic_head.init_weights()
|
69 |
-
if self.with_glbctx:
|
70 |
-
self.glbctx_head.init_weights()
|
71 |
-
if self.with_feat_relay:
|
72 |
-
self.feat_relay_head.init_weights()
|
73 |
-
|
74 |
-
@property
|
75 |
-
def with_semantic(self):
|
76 |
-
"""bool: whether the head has semantic head"""
|
77 |
-
return hasattr(self,
|
78 |
-
'semantic_head') and self.semantic_head is not None
|
79 |
-
|
80 |
-
@property
|
81 |
-
def with_feat_relay(self):
|
82 |
-
"""bool: whether the head has feature relay head"""
|
83 |
-
return (hasattr(self, 'feat_relay_head')
|
84 |
-
and self.feat_relay_head is not None)
|
85 |
-
|
86 |
-
@property
|
87 |
-
def with_glbctx(self):
|
88 |
-
"""bool: whether the head has global context head"""
|
89 |
-
return hasattr(self, 'glbctx_head') and self.glbctx_head is not None
|
90 |
-
|
91 |
-
def _fuse_glbctx(self, roi_feats, glbctx_feat, rois):
|
92 |
-
"""Fuse global context feats with roi feats."""
|
93 |
-
assert roi_feats.size(0) == rois.size(0)
|
94 |
-
img_inds = torch.unique(rois[:, 0].cpu(), sorted=True).long()
|
95 |
-
fused_feats = torch.zeros_like(roi_feats)
|
96 |
-
for img_id in img_inds:
|
97 |
-
inds = (rois[:, 0] == img_id.item())
|
98 |
-
fused_feats[inds] = roi_feats[inds] + glbctx_feat[img_id]
|
99 |
-
return fused_feats
|
100 |
-
|
101 |
-
def _slice_pos_feats(self, feats, sampling_results):
|
102 |
-
"""Get features from pos rois."""
|
103 |
-
num_rois = [res.bboxes.size(0) for res in sampling_results]
|
104 |
-
num_pos_rois = [res.pos_bboxes.size(0) for res in sampling_results]
|
105 |
-
inds = torch.zeros(sum(num_rois), dtype=torch.bool)
|
106 |
-
start = 0
|
107 |
-
for i in range(len(num_rois)):
|
108 |
-
start = 0 if i == 0 else start + num_rois[i - 1]
|
109 |
-
stop = start + num_pos_rois[i]
|
110 |
-
inds[start:stop] = 1
|
111 |
-
sliced_feats = feats[inds]
|
112 |
-
return sliced_feats
|
113 |
-
|
114 |
-
def _bbox_forward(self,
|
115 |
-
stage,
|
116 |
-
x,
|
117 |
-
rois,
|
118 |
-
semantic_feat=None,
|
119 |
-
glbctx_feat=None):
|
120 |
-
"""Box head forward function used in both training and testing."""
|
121 |
-
bbox_roi_extractor = self.bbox_roi_extractor[stage]
|
122 |
-
bbox_head = self.bbox_head[stage]
|
123 |
-
bbox_feats = bbox_roi_extractor(
|
124 |
-
x[:len(bbox_roi_extractor.featmap_strides)], rois)
|
125 |
-
if self.with_semantic and semantic_feat is not None:
|
126 |
-
bbox_semantic_feat = self.semantic_roi_extractor([semantic_feat],
|
127 |
-
rois)
|
128 |
-
if bbox_semantic_feat.shape[-2:] != bbox_feats.shape[-2:]:
|
129 |
-
bbox_semantic_feat = F.adaptive_avg_pool2d(
|
130 |
-
bbox_semantic_feat, bbox_feats.shape[-2:])
|
131 |
-
bbox_feats += bbox_semantic_feat
|
132 |
-
if self.with_glbctx and glbctx_feat is not None:
|
133 |
-
bbox_feats = self._fuse_glbctx(bbox_feats, glbctx_feat, rois)
|
134 |
-
cls_score, bbox_pred, relayed_feat = bbox_head(
|
135 |
-
bbox_feats, return_shared_feat=True)
|
136 |
-
|
137 |
-
bbox_results = dict(
|
138 |
-
cls_score=cls_score,
|
139 |
-
bbox_pred=bbox_pred,
|
140 |
-
relayed_feat=relayed_feat)
|
141 |
-
return bbox_results
|
142 |
-
|
143 |
-
def _mask_forward(self,
|
144 |
-
x,
|
145 |
-
rois,
|
146 |
-
semantic_feat=None,
|
147 |
-
glbctx_feat=None,
|
148 |
-
relayed_feat=None):
|
149 |
-
"""Mask head forward function used in both training and testing."""
|
150 |
-
mask_feats = self.mask_roi_extractor(
|
151 |
-
x[:self.mask_roi_extractor.num_inputs], rois)
|
152 |
-
if self.with_semantic and semantic_feat is not None:
|
153 |
-
mask_semantic_feat = self.semantic_roi_extractor([semantic_feat],
|
154 |
-
rois)
|
155 |
-
if mask_semantic_feat.shape[-2:] != mask_feats.shape[-2:]:
|
156 |
-
mask_semantic_feat = F.adaptive_avg_pool2d(
|
157 |
-
mask_semantic_feat, mask_feats.shape[-2:])
|
158 |
-
mask_feats += mask_semantic_feat
|
159 |
-
if self.with_glbctx and glbctx_feat is not None:
|
160 |
-
mask_feats = self._fuse_glbctx(mask_feats, glbctx_feat, rois)
|
161 |
-
if self.with_feat_relay and relayed_feat is not None:
|
162 |
-
mask_feats = mask_feats + relayed_feat
|
163 |
-
mask_pred = self.mask_head(mask_feats)
|
164 |
-
mask_results = dict(mask_pred=mask_pred)
|
165 |
-
|
166 |
-
return mask_results
|
167 |
-
|
168 |
-
def _bbox_forward_train(self,
|
169 |
-
stage,
|
170 |
-
x,
|
171 |
-
sampling_results,
|
172 |
-
gt_bboxes,
|
173 |
-
gt_labels,
|
174 |
-
rcnn_train_cfg,
|
175 |
-
semantic_feat=None,
|
176 |
-
glbctx_feat=None):
|
177 |
-
"""Run forward function and calculate loss for box head in training."""
|
178 |
-
bbox_head = self.bbox_head[stage]
|
179 |
-
rois = bbox2roi([res.bboxes for res in sampling_results])
|
180 |
-
bbox_results = self._bbox_forward(
|
181 |
-
stage,
|
182 |
-
x,
|
183 |
-
rois,
|
184 |
-
semantic_feat=semantic_feat,
|
185 |
-
glbctx_feat=glbctx_feat)
|
186 |
-
|
187 |
-
bbox_targets = bbox_head.get_targets(sampling_results, gt_bboxes,
|
188 |
-
gt_labels, rcnn_train_cfg)
|
189 |
-
loss_bbox = bbox_head.loss(bbox_results['cls_score'],
|
190 |
-
bbox_results['bbox_pred'], rois,
|
191 |
-
*bbox_targets)
|
192 |
-
|
193 |
-
bbox_results.update(
|
194 |
-
loss_bbox=loss_bbox, rois=rois, bbox_targets=bbox_targets)
|
195 |
-
return bbox_results
|
196 |
-
|
197 |
-
def _mask_forward_train(self,
|
198 |
-
x,
|
199 |
-
sampling_results,
|
200 |
-
gt_masks,
|
201 |
-
rcnn_train_cfg,
|
202 |
-
semantic_feat=None,
|
203 |
-
glbctx_feat=None,
|
204 |
-
relayed_feat=None):
|
205 |
-
"""Run forward function and calculate loss for mask head in
|
206 |
-
training."""
|
207 |
-
pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])
|
208 |
-
mask_results = self._mask_forward(
|
209 |
-
x,
|
210 |
-
pos_rois,
|
211 |
-
semantic_feat=semantic_feat,
|
212 |
-
glbctx_feat=glbctx_feat,
|
213 |
-
relayed_feat=relayed_feat)
|
214 |
-
|
215 |
-
mask_targets = self.mask_head.get_targets(sampling_results, gt_masks,
|
216 |
-
rcnn_train_cfg)
|
217 |
-
pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])
|
218 |
-
loss_mask = self.mask_head.loss(mask_results['mask_pred'],
|
219 |
-
mask_targets, pos_labels)
|
220 |
-
|
221 |
-
mask_results = loss_mask
|
222 |
-
return mask_results
|
223 |
-
|
224 |
-
def forward_train(self,
|
225 |
-
x,
|
226 |
-
img_metas,
|
227 |
-
proposal_list,
|
228 |
-
gt_bboxes,
|
229 |
-
gt_labels,
|
230 |
-
gt_bboxes_ignore=None,
|
231 |
-
gt_masks=None,
|
232 |
-
gt_semantic_seg=None):
|
233 |
-
"""
|
234 |
-
Args:
|
235 |
-
x (list[Tensor]): list of multi-level img features.
|
236 |
-
|
237 |
-
img_metas (list[dict]): list of image info dict where each dict
|
238 |
-
has: 'img_shape', 'scale_factor', 'flip', and may also contain
|
239 |
-
'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.
|
240 |
-
For details on the values of these keys see
|
241 |
-
`mmdet/datasets/pipelines/formatting.py:Collect`.
|
242 |
-
|
243 |
-
proposal_list (list[Tensors]): list of region proposals.
|
244 |
-
|
245 |
-
gt_bboxes (list[Tensor]): Ground truth bboxes for each image with
|
246 |
-
shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.
|
247 |
-
|
248 |
-
gt_labels (list[Tensor]): class indices corresponding to each box
|
249 |
-
|
250 |
-
gt_bboxes_ignore (None, list[Tensor]): specify which bounding
|
251 |
-
boxes can be ignored when computing the loss.
|
252 |
-
|
253 |
-
gt_masks (None, Tensor) : true segmentation masks for each box
|
254 |
-
used if the architecture supports a segmentation task.
|
255 |
-
|
256 |
-
gt_semantic_seg (None, list[Tensor]): semantic segmentation masks
|
257 |
-
used if the architecture supports semantic segmentation task.
|
258 |
-
|
259 |
-
Returns:
|
260 |
-
dict[str, Tensor]: a dictionary of loss components
|
261 |
-
"""
|
262 |
-
losses = dict()
|
263 |
-
|
264 |
-
# semantic segmentation branch
|
265 |
-
if self.with_semantic:
|
266 |
-
semantic_pred, semantic_feat = self.semantic_head(x)
|
267 |
-
loss_seg = self.semantic_head.loss(semantic_pred, gt_semantic_seg)
|
268 |
-
losses['loss_semantic_seg'] = loss_seg
|
269 |
-
else:
|
270 |
-
semantic_feat = None
|
271 |
-
|
272 |
-
# global context branch
|
273 |
-
if self.with_glbctx:
|
274 |
-
mc_pred, glbctx_feat = self.glbctx_head(x)
|
275 |
-
loss_glbctx = self.glbctx_head.loss(mc_pred, gt_labels)
|
276 |
-
losses['loss_glbctx'] = loss_glbctx
|
277 |
-
else:
|
278 |
-
glbctx_feat = None
|
279 |
-
|
280 |
-
for i in range(self.num_stages):
|
281 |
-
self.current_stage = i
|
282 |
-
rcnn_train_cfg = self.train_cfg[i]
|
283 |
-
lw = self.stage_loss_weights[i]
|
284 |
-
|
285 |
-
# assign gts and sample proposals
|
286 |
-
sampling_results = []
|
287 |
-
bbox_assigner = self.bbox_assigner[i]
|
288 |
-
bbox_sampler = self.bbox_sampler[i]
|
289 |
-
num_imgs = len(img_metas)
|
290 |
-
if gt_bboxes_ignore is None:
|
291 |
-
gt_bboxes_ignore = [None for _ in range(num_imgs)]
|
292 |
-
|
293 |
-
for j in range(num_imgs):
|
294 |
-
assign_result = bbox_assigner.assign(proposal_list[j],
|
295 |
-
gt_bboxes[j],
|
296 |
-
gt_bboxes_ignore[j],
|
297 |
-
gt_labels[j])
|
298 |
-
sampling_result = bbox_sampler.sample(
|
299 |
-
assign_result,
|
300 |
-
proposal_list[j],
|
301 |
-
gt_bboxes[j],
|
302 |
-
gt_labels[j],
|
303 |
-
feats=[lvl_feat[j][None] for lvl_feat in x])
|
304 |
-
sampling_results.append(sampling_result)
|
305 |
-
|
306 |
-
bbox_results = \
|
307 |
-
self._bbox_forward_train(
|
308 |
-
i, x, sampling_results, gt_bboxes, gt_labels,
|
309 |
-
rcnn_train_cfg, semantic_feat, glbctx_feat)
|
310 |
-
roi_labels = bbox_results['bbox_targets'][0]
|
311 |
-
|
312 |
-
for name, value in bbox_results['loss_bbox'].items():
|
313 |
-
losses[f's{i}.{name}'] = (
|
314 |
-
value * lw if 'loss' in name else value)
|
315 |
-
|
316 |
-
# refine boxes
|
317 |
-
if i < self.num_stages - 1:
|
318 |
-
pos_is_gts = [res.pos_is_gt for res in sampling_results]
|
319 |
-
with torch.no_grad():
|
320 |
-
proposal_list = self.bbox_head[i].refine_bboxes(
|
321 |
-
bbox_results['rois'], roi_labels,
|
322 |
-
bbox_results['bbox_pred'], pos_is_gts, img_metas)
|
323 |
-
|
324 |
-
if self.with_feat_relay:
|
325 |
-
relayed_feat = self._slice_pos_feats(bbox_results['relayed_feat'],
|
326 |
-
sampling_results)
|
327 |
-
relayed_feat = self.feat_relay_head(relayed_feat)
|
328 |
-
else:
|
329 |
-
relayed_feat = None
|
330 |
-
|
331 |
-
mask_results = self._mask_forward_train(x, sampling_results, gt_masks,
|
332 |
-
rcnn_train_cfg, semantic_feat,
|
333 |
-
glbctx_feat, relayed_feat)
|
334 |
-
mask_lw = sum(self.stage_loss_weights)
|
335 |
-
losses['loss_mask'] = mask_lw * mask_results['loss_mask']
|
336 |
-
|
337 |
-
return losses
|
338 |
-
|
339 |
-
def simple_test(self, x, proposal_list, img_metas, rescale=False):
|
340 |
-
"""Test without augmentation."""
|
341 |
-
if self.with_semantic:
|
342 |
-
_, semantic_feat = self.semantic_head(x)
|
343 |
-
else:
|
344 |
-
semantic_feat = None
|
345 |
-
|
346 |
-
if self.with_glbctx:
|
347 |
-
mc_pred, glbctx_feat = self.glbctx_head(x)
|
348 |
-
else:
|
349 |
-
glbctx_feat = None
|
350 |
-
|
351 |
-
num_imgs = len(proposal_list)
|
352 |
-
img_shapes = tuple(meta['img_shape'] for meta in img_metas)
|
353 |
-
ori_shapes = tuple(meta['ori_shape'] for meta in img_metas)
|
354 |
-
scale_factors = tuple(meta['scale_factor'] for meta in img_metas)
|
355 |
-
|
356 |
-
# "ms" in variable names means multi-stage
|
357 |
-
ms_scores = []
|
358 |
-
rcnn_test_cfg = self.test_cfg
|
359 |
-
|
360 |
-
rois = bbox2roi(proposal_list)
|
361 |
-
for i in range(self.num_stages):
|
362 |
-
bbox_head = self.bbox_head[i]
|
363 |
-
bbox_results = self._bbox_forward(
|
364 |
-
i,
|
365 |
-
x,
|
366 |
-
rois,
|
367 |
-
semantic_feat=semantic_feat,
|
368 |
-
glbctx_feat=glbctx_feat)
|
369 |
-
# split batch bbox prediction back to each image
|
370 |
-
cls_score = bbox_results['cls_score']
|
371 |
-
bbox_pred = bbox_results['bbox_pred']
|
372 |
-
num_proposals_per_img = tuple(len(p) for p in proposal_list)
|
373 |
-
rois = rois.split(num_proposals_per_img, 0)
|
374 |
-
cls_score = cls_score.split(num_proposals_per_img, 0)
|
375 |
-
bbox_pred = bbox_pred.split(num_proposals_per_img, 0)
|
376 |
-
ms_scores.append(cls_score)
|
377 |
-
|
378 |
-
if i < self.num_stages - 1:
|
379 |
-
bbox_label = [s[:, :-1].argmax(dim=1) for s in cls_score]
|
380 |
-
rois = torch.cat([
|
381 |
-
bbox_head.regress_by_class(rois[i], bbox_label[i],
|
382 |
-
bbox_pred[i], img_metas[i])
|
383 |
-
for i in range(num_imgs)
|
384 |
-
])
|
385 |
-
|
386 |
-
# average scores of each image by stages
|
387 |
-
cls_score = [
|
388 |
-
sum([score[i] for score in ms_scores]) / float(len(ms_scores))
|
389 |
-
for i in range(num_imgs)
|
390 |
-
]
|
391 |
-
|
392 |
-
# apply bbox post-processing to each image individually
|
393 |
-
det_bboxes = []
|
394 |
-
det_labels = []
|
395 |
-
for i in range(num_imgs):
|
396 |
-
det_bbox, det_label = self.bbox_head[-1].get_bboxes(
|
397 |
-
rois[i],
|
398 |
-
cls_score[i],
|
399 |
-
bbox_pred[i],
|
400 |
-
img_shapes[i],
|
401 |
-
scale_factors[i],
|
402 |
-
rescale=rescale,
|
403 |
-
cfg=rcnn_test_cfg)
|
404 |
-
det_bboxes.append(det_bbox)
|
405 |
-
det_labels.append(det_label)
|
406 |
-
det_bbox_results = [
|
407 |
-
bbox2result(det_bboxes[i], det_labels[i],
|
408 |
-
self.bbox_head[-1].num_classes)
|
409 |
-
for i in range(num_imgs)
|
410 |
-
]
|
411 |
-
|
412 |
-
if self.with_mask:
|
413 |
-
if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):
|
414 |
-
mask_classes = self.mask_head.num_classes
|
415 |
-
det_segm_results = [[[] for _ in range(mask_classes)]
|
416 |
-
for _ in range(num_imgs)]
|
417 |
-
else:
|
418 |
-
if rescale and not isinstance(scale_factors[0], float):
|
419 |
-
scale_factors = [
|
420 |
-
torch.from_numpy(scale_factor).to(det_bboxes[0].device)
|
421 |
-
for scale_factor in scale_factors
|
422 |
-
]
|
423 |
-
_bboxes = [
|
424 |
-
det_bboxes[i][:, :4] *
|
425 |
-
scale_factors[i] if rescale else det_bboxes[i]
|
426 |
-
for i in range(num_imgs)
|
427 |
-
]
|
428 |
-
mask_rois = bbox2roi(_bboxes)
|
429 |
-
|
430 |
-
# get relay feature on mask_rois
|
431 |
-
bbox_results = self._bbox_forward(
|
432 |
-
-1,
|
433 |
-
x,
|
434 |
-
mask_rois,
|
435 |
-
semantic_feat=semantic_feat,
|
436 |
-
glbctx_feat=glbctx_feat)
|
437 |
-
relayed_feat = bbox_results['relayed_feat']
|
438 |
-
relayed_feat = self.feat_relay_head(relayed_feat)
|
439 |
-
|
440 |
-
mask_results = self._mask_forward(
|
441 |
-
x,
|
442 |
-
mask_rois,
|
443 |
-
semantic_feat=semantic_feat,
|
444 |
-
glbctx_feat=glbctx_feat,
|
445 |
-
relayed_feat=relayed_feat)
|
446 |
-
mask_pred = mask_results['mask_pred']
|
447 |
-
|
448 |
-
# split batch mask prediction back to each image
|
449 |
-
num_bbox_per_img = tuple(len(_bbox) for _bbox in _bboxes)
|
450 |
-
mask_preds = mask_pred.split(num_bbox_per_img, 0)
|
451 |
-
|
452 |
-
# apply mask post-processing to each image individually
|
453 |
-
det_segm_results = []
|
454 |
-
for i in range(num_imgs):
|
455 |
-
if det_bboxes[i].shape[0] == 0:
|
456 |
-
det_segm_results.append(
|
457 |
-
[[] for _ in range(self.mask_head.num_classes)])
|
458 |
-
else:
|
459 |
-
segm_result = self.mask_head.get_seg_masks(
|
460 |
-
mask_preds[i], _bboxes[i], det_labels[i],
|
461 |
-
self.test_cfg, ori_shapes[i], scale_factors[i],
|
462 |
-
rescale)
|
463 |
-
det_segm_results.append(segm_result)
|
464 |
-
|
465 |
-
# return results
|
466 |
-
if self.with_mask:
|
467 |
-
return list(zip(det_bbox_results, det_segm_results))
|
468 |
-
else:
|
469 |
-
return det_bbox_results
|
470 |
-
|
471 |
-
def aug_test(self, img_feats, proposal_list, img_metas, rescale=False):
|
472 |
-
if self.with_semantic:
|
473 |
-
semantic_feats = [
|
474 |
-
self.semantic_head(feat)[1] for feat in img_feats
|
475 |
-
]
|
476 |
-
else:
|
477 |
-
semantic_feats = [None] * len(img_metas)
|
478 |
-
|
479 |
-
if self.with_glbctx:
|
480 |
-
glbctx_feats = [self.glbctx_head(feat)[1] for feat in img_feats]
|
481 |
-
else:
|
482 |
-
glbctx_feats = [None] * len(img_metas)
|
483 |
-
|
484 |
-
rcnn_test_cfg = self.test_cfg
|
485 |
-
aug_bboxes = []
|
486 |
-
aug_scores = []
|
487 |
-
for x, img_meta, semantic_feat, glbctx_feat in zip(
|
488 |
-
img_feats, img_metas, semantic_feats, glbctx_feats):
|
489 |
-
# only one image in the batch
|
490 |
-
img_shape = img_meta[0]['img_shape']
|
491 |
-
scale_factor = img_meta[0]['scale_factor']
|
492 |
-
flip = img_meta[0]['flip']
|
493 |
-
|
494 |
-
proposals = bbox_mapping(proposal_list[0][:, :4], img_shape,
|
495 |
-
scale_factor, flip)
|
496 |
-
# "ms" in variable names means multi-stage
|
497 |
-
ms_scores = []
|
498 |
-
|
499 |
-
rois = bbox2roi([proposals])
|
500 |
-
for i in range(self.num_stages):
|
501 |
-
bbox_head = self.bbox_head[i]
|
502 |
-
bbox_results = self._bbox_forward(
|
503 |
-
i,
|
504 |
-
x,
|
505 |
-
rois,
|
506 |
-
semantic_feat=semantic_feat,
|
507 |
-
glbctx_feat=glbctx_feat)
|
508 |
-
ms_scores.append(bbox_results['cls_score'])
|
509 |
-
if i < self.num_stages - 1:
|
510 |
-
bbox_label = bbox_results['cls_score'].argmax(dim=1)
|
511 |
-
rois = bbox_head.regress_by_class(
|
512 |
-
rois, bbox_label, bbox_results['bbox_pred'],
|
513 |
-
img_meta[0])
|
514 |
-
|
515 |
-
cls_score = sum(ms_scores) / float(len(ms_scores))
|
516 |
-
bboxes, scores = self.bbox_head[-1].get_bboxes(
|
517 |
-
rois,
|
518 |
-
cls_score,
|
519 |
-
bbox_results['bbox_pred'],
|
520 |
-
img_shape,
|
521 |
-
scale_factor,
|
522 |
-
rescale=False,
|
523 |
-
cfg=None)
|
524 |
-
aug_bboxes.append(bboxes)
|
525 |
-
aug_scores.append(scores)
|
526 |
-
|
527 |
-
# after merging, bboxes will be rescaled to the original image size
|
528 |
-
merged_bboxes, merged_scores = merge_aug_bboxes(
|
529 |
-
aug_bboxes, aug_scores, img_metas, rcnn_test_cfg)
|
530 |
-
det_bboxes, det_labels = multiclass_nms(merged_bboxes, merged_scores,
|
531 |
-
rcnn_test_cfg.score_thr,
|
532 |
-
rcnn_test_cfg.nms,
|
533 |
-
rcnn_test_cfg.max_per_img)
|
534 |
-
|
535 |
-
det_bbox_results = bbox2result(det_bboxes, det_labels,
|
536 |
-
self.bbox_head[-1].num_classes)
|
537 |
-
|
538 |
-
if self.with_mask:
|
539 |
-
if det_bboxes.shape[0] == 0:
|
540 |
-
det_segm_results = [[]
|
541 |
-
for _ in range(self.mask_head.num_classes)]
|
542 |
-
else:
|
543 |
-
aug_masks = []
|
544 |
-
for x, img_meta, semantic_feat, glbctx_feat in zip(
|
545 |
-
img_feats, img_metas, semantic_feats, glbctx_feats):
|
546 |
-
img_shape = img_meta[0]['img_shape']
|
547 |
-
scale_factor = img_meta[0]['scale_factor']
|
548 |
-
flip = img_meta[0]['flip']
|
549 |
-
_bboxes = bbox_mapping(det_bboxes[:, :4], img_shape,
|
550 |
-
scale_factor, flip)
|
551 |
-
mask_rois = bbox2roi([_bboxes])
|
552 |
-
# get relay feature on mask_rois
|
553 |
-
bbox_results = self._bbox_forward(
|
554 |
-
-1,
|
555 |
-
x,
|
556 |
-
mask_rois,
|
557 |
-
semantic_feat=semantic_feat,
|
558 |
-
glbctx_feat=glbctx_feat)
|
559 |
-
relayed_feat = bbox_results['relayed_feat']
|
560 |
-
relayed_feat = self.feat_relay_head(relayed_feat)
|
561 |
-
mask_results = self._mask_forward(
|
562 |
-
x,
|
563 |
-
mask_rois,
|
564 |
-
semantic_feat=semantic_feat,
|
565 |
-
glbctx_feat=glbctx_feat,
|
566 |
-
relayed_feat=relayed_feat)
|
567 |
-
mask_pred = mask_results['mask_pred']
|
568 |
-
aug_masks.append(mask_pred.sigmoid().cpu().numpy())
|
569 |
-
merged_masks = merge_aug_masks(aug_masks, img_metas,
|
570 |
-
self.test_cfg)
|
571 |
-
ori_shape = img_metas[0][0]['ori_shape']
|
572 |
-
det_segm_results = self.mask_head.get_seg_masks(
|
573 |
-
merged_masks,
|
574 |
-
det_bboxes,
|
575 |
-
det_labels,
|
576 |
-
rcnn_test_cfg,
|
577 |
-
ori_shape,
|
578 |
-
scale_factor=1.0,
|
579 |
-
rescale=False)
|
580 |
-
return [(det_bbox_results, det_segm_results)]
|
581 |
-
else:
|
582 |
-
return [det_bbox_results]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/lama-example/models/ade20k/segm_lib/nn/modules/tests/test_sync_batchnorm.py
DELETED
@@ -1,111 +0,0 @@
|
|
1 |
-
# -*- coding: utf-8 -*-
|
2 |
-
# File : test_sync_batchnorm.py
|
3 |
-
# Author : Jiayuan Mao
|
4 |
-
# Email : [email protected]
|
5 |
-
# Date : 27/01/2018
|
6 |
-
#
|
7 |
-
# This file is part of Synchronized-BatchNorm-PyTorch.
|
8 |
-
|
9 |
-
import unittest
|
10 |
-
|
11 |
-
import torch
|
12 |
-
import torch.nn as nn
|
13 |
-
from torch.autograd import Variable
|
14 |
-
|
15 |
-
from sync_batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, DataParallelWithCallback
|
16 |
-
from sync_batchnorm.unittest import TorchTestCase
|
17 |
-
|
18 |
-
|
19 |
-
def handy_var(a, unbias=True):
|
20 |
-
n = a.size(0)
|
21 |
-
asum = a.sum(dim=0)
|
22 |
-
as_sum = (a ** 2).sum(dim=0) # a square sum
|
23 |
-
sumvar = as_sum - asum * asum / n
|
24 |
-
if unbias:
|
25 |
-
return sumvar / (n - 1)
|
26 |
-
else:
|
27 |
-
return sumvar / n
|
28 |
-
|
29 |
-
|
30 |
-
def _find_bn(module):
|
31 |
-
for m in module.modules():
|
32 |
-
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, SynchronizedBatchNorm1d, SynchronizedBatchNorm2d)):
|
33 |
-
return m
|
34 |
-
|
35 |
-
|
36 |
-
class SyncTestCase(TorchTestCase):
|
37 |
-
def _syncParameters(self, bn1, bn2):
|
38 |
-
bn1.reset_parameters()
|
39 |
-
bn2.reset_parameters()
|
40 |
-
if bn1.affine and bn2.affine:
|
41 |
-
bn2.weight.data.copy_(bn1.weight.data)
|
42 |
-
bn2.bias.data.copy_(bn1.bias.data)
|
43 |
-
|
44 |
-
def _checkBatchNormResult(self, bn1, bn2, input, is_train, cuda=False):
|
45 |
-
"""Check the forward and backward for the customized batch normalization."""
|
46 |
-
bn1.train(mode=is_train)
|
47 |
-
bn2.train(mode=is_train)
|
48 |
-
|
49 |
-
if cuda:
|
50 |
-
input = input.cuda()
|
51 |
-
|
52 |
-
self._syncParameters(_find_bn(bn1), _find_bn(bn2))
|
53 |
-
|
54 |
-
input1 = Variable(input, requires_grad=True)
|
55 |
-
output1 = bn1(input1)
|
56 |
-
output1.sum().backward()
|
57 |
-
input2 = Variable(input, requires_grad=True)
|
58 |
-
output2 = bn2(input2)
|
59 |
-
output2.sum().backward()
|
60 |
-
|
61 |
-
self.assertTensorClose(input1.data, input2.data)
|
62 |
-
self.assertTensorClose(output1.data, output2.data)
|
63 |
-
self.assertTensorClose(input1.grad, input2.grad)
|
64 |
-
self.assertTensorClose(_find_bn(bn1).running_mean, _find_bn(bn2).running_mean)
|
65 |
-
self.assertTensorClose(_find_bn(bn1).running_var, _find_bn(bn2).running_var)
|
66 |
-
|
67 |
-
def testSyncBatchNormNormalTrain(self):
|
68 |
-
bn = nn.BatchNorm1d(10)
|
69 |
-
sync_bn = SynchronizedBatchNorm1d(10)
|
70 |
-
|
71 |
-
self._checkBatchNormResult(bn, sync_bn, torch.rand(16, 10), True)
|
72 |
-
|
73 |
-
def testSyncBatchNormNormalEval(self):
|
74 |
-
bn = nn.BatchNorm1d(10)
|
75 |
-
sync_bn = SynchronizedBatchNorm1d(10)
|
76 |
-
|
77 |
-
self._checkBatchNormResult(bn, sync_bn, torch.rand(16, 10), False)
|
78 |
-
|
79 |
-
def testSyncBatchNormSyncTrain(self):
|
80 |
-
bn = nn.BatchNorm1d(10, eps=1e-5, affine=False)
|
81 |
-
sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
|
82 |
-
sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
|
83 |
-
|
84 |
-
bn.cuda()
|
85 |
-
sync_bn.cuda()
|
86 |
-
|
87 |
-
self._checkBatchNormResult(bn, sync_bn, torch.rand(16, 10), True, cuda=True)
|
88 |
-
|
89 |
-
def testSyncBatchNormSyncEval(self):
|
90 |
-
bn = nn.BatchNorm1d(10, eps=1e-5, affine=False)
|
91 |
-
sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
|
92 |
-
sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
|
93 |
-
|
94 |
-
bn.cuda()
|
95 |
-
sync_bn.cuda()
|
96 |
-
|
97 |
-
self._checkBatchNormResult(bn, sync_bn, torch.rand(16, 10), False, cuda=True)
|
98 |
-
|
99 |
-
def testSyncBatchNorm2DSyncTrain(self):
|
100 |
-
bn = nn.BatchNorm2d(10)
|
101 |
-
sync_bn = SynchronizedBatchNorm2d(10)
|
102 |
-
sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
|
103 |
-
|
104 |
-
bn.cuda()
|
105 |
-
sync_bn.cuda()
|
106 |
-
|
107 |
-
self._checkBatchNormResult(bn, sync_bn, torch.rand(16, 10, 16, 16), True, cuda=True)
|
108 |
-
|
109 |
-
|
110 |
-
if __name__ == '__main__':
|
111 |
-
unittest.main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CVPR/lama-example/models/ade20k/segm_lib/utils/__init__.py
DELETED
@@ -1 +0,0 @@
|
|
1 |
-
from .th import *
|
|
|
|
spaces/CikeyQI/Yunzai/Yunzai/lib/renderer/loader.js
DELETED
@@ -1,56 +0,0 @@
|
|
1 |
-
import fs from 'node:fs'
|
2 |
-
import yaml from 'yaml'
|
3 |
-
import lodash from 'lodash'
|
4 |
-
import cfg from '../config/config.js'
|
5 |
-
import { Data } from '#miao'
|
6 |
-
import Renderer from './Renderer.js'
|
7 |
-
|
8 |
-
/** 全局变量 Renderer */
|
9 |
-
global.Renderer = Renderer
|
10 |
-
|
11 |
-
/**
|
12 |
-
* 加载渲染器
|
13 |
-
*/
|
14 |
-
class RendererLoader {
|
15 |
-
constructor() {
|
16 |
-
this.renderers = new Map()
|
17 |
-
this.dir = './renderers'
|
18 |
-
// TODO 渲染器热加载
|
19 |
-
this.watcher = {}
|
20 |
-
}
|
21 |
-
|
22 |
-
static async init() {
|
23 |
-
const render = new RendererLoader()
|
24 |
-
await render.load()
|
25 |
-
return render
|
26 |
-
}
|
27 |
-
|
28 |
-
async load() {
|
29 |
-
const subFolders = fs.readdirSync(this.dir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory())
|
30 |
-
for (let subFolder of subFolders) {
|
31 |
-
let name = subFolder.name
|
32 |
-
try {
|
33 |
-
const rendererFn = await Data.importDefault(`${this.dir}/${name}/index.js`)
|
34 |
-
let configFile = `${this.dir}/${name}/config.yaml`
|
35 |
-
let rendererCfg = fs.existsSync(configFile) ? yaml.parse(fs.readFileSync(configFile, 'utf8')) : {}
|
36 |
-
let renderer = rendererFn(rendererCfg)
|
37 |
-
if (!renderer.id || !renderer.type || !renderer.render || !lodash.isFunction(renderer.render)) {
|
38 |
-
logger.warn('渲染后端 ' + (renderer.id || subFolder.name) + ' 不可用')
|
39 |
-
}
|
40 |
-
this.renderers.set(renderer.id, renderer)
|
41 |
-
logger.info(`加载渲染后端 ${renderer.id}`)
|
42 |
-
} catch (err) {
|
43 |
-
logger.error(`渲染后端 ${name} 加载失败`)
|
44 |
-
logger.error(err)
|
45 |
-
}
|
46 |
-
}
|
47 |
-
}
|
48 |
-
|
49 |
-
getRenderer(name = cfg.renderer?.name || 'puppeteer') {
|
50 |
-
// TODO 渲染器降级
|
51 |
-
return this.renderers.get(name)
|
52 |
-
}
|
53 |
-
}
|
54 |
-
|
55 |
-
|
56 |
-
export default await RendererLoader.init()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spaces/CjangCjengh/Shanghainese-TTS/attentions.py
DELETED
@@ -1,300 +0,0 @@
|
|
1 |
-
import math
|
2 |
-
import torch
|
3 |
-
from torch import nn
|
4 |
-
from torch.nn import functional as F
|
5 |
-
|
6 |
-
import commons
|
7 |
-
from modules import LayerNorm
|
8 |
-
|
9 |
-
|
10 |
-
class Encoder(nn.Module):
|
11 |
-
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., window_size=4, **kwargs):
|
12 |
-
super().__init__()
|
13 |
-
self.hidden_channels = hidden_channels
|
14 |
-
self.filter_channels = filter_channels
|
15 |
-
self.n_heads = n_heads
|
16 |
-
self.n_layers = n_layers
|
17 |
-
self.kernel_size = kernel_size
|
18 |
-
self.p_dropout = p_dropout
|
19 |
-
self.window_size = window_size
|
20 |
-
|
21 |
-
self.drop = nn.Dropout(p_dropout)
|
22 |
-
self.attn_layers = nn.ModuleList()
|
23 |
-
self.norm_layers_1 = nn.ModuleList()
|
24 |
-
self.ffn_layers = nn.ModuleList()
|
25 |
-
self.norm_layers_2 = nn.ModuleList()
|
26 |
-
for i in range(self.n_layers):
|
27 |
-
self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, window_size=window_size))
|
28 |
-
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
29 |
-
self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout))
|
30 |
-
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
31 |
-
|
32 |
-
def forward(self, x, x_mask):
|
33 |
-
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
34 |
-
x = x * x_mask
|
35 |
-
for i in range(self.n_layers):
|
36 |
-
y = self.attn_layers[i](x, x, attn_mask)
|
37 |
-
y = self.drop(y)
|
38 |
-
x = self.norm_layers_1[i](x + y)
|
39 |
-
|
40 |
-
y = self.ffn_layers[i](x, x_mask)
|
41 |
-
y = self.drop(y)
|
42 |
-
x = self.norm_layers_2[i](x + y)
|
43 |
-
x = x * x_mask
|
44 |
-
return x
|
45 |
-
|
46 |
-
|
47 |
-
class Decoder(nn.Module):
|
48 |
-
def __init__(self, hidden_channels, filter_channels, n_heads, n_layers, kernel_size=1, p_dropout=0., proximal_bias=False, proximal_init=True, **kwargs):
|
49 |
-
super().__init__()
|
50 |
-
self.hidden_channels = hidden_channels
|
51 |
-
self.filter_channels = filter_channels
|
52 |
-
self.n_heads = n_heads
|
53 |
-
self.n_layers = n_layers
|
54 |
-
self.kernel_size = kernel_size
|
55 |
-
self.p_dropout = p_dropout
|
56 |
-
self.proximal_bias = proximal_bias
|
57 |
-
self.proximal_init = proximal_init
|
58 |
-
|
59 |
-
self.drop = nn.Dropout(p_dropout)
|
60 |
-
self.self_attn_layers = nn.ModuleList()
|
61 |
-
self.norm_layers_0 = nn.ModuleList()
|
62 |
-
self.encdec_attn_layers = nn.ModuleList()
|
63 |
-
self.norm_layers_1 = nn.ModuleList()
|
64 |
-
self.ffn_layers = nn.ModuleList()
|
65 |
-
self.norm_layers_2 = nn.ModuleList()
|
66 |
-
for i in range(self.n_layers):
|
67 |
-
self.self_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout, proximal_bias=proximal_bias, proximal_init=proximal_init))
|
68 |
-
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
69 |
-
self.encdec_attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
|
70 |
-
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
71 |
-
self.ffn_layers.append(FFN(hidden_channels, hidden_channels, filter_channels, kernel_size, p_dropout=p_dropout, causal=True))
|
72 |
-
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
73 |
-
|
74 |
-
def forward(self, x, x_mask, h, h_mask):
|
75 |
-
"""
|
76 |
-
x: decoder input
|
77 |
-
h: encoder output
|
78 |
-
"""
|
79 |
-
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtype)
|
80 |
-
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
81 |
-
x = x * x_mask
|
82 |
-
for i in range(self.n_layers):
|
83 |
-
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
84 |
-
y = self.drop(y)
|
85 |
-
x = self.norm_layers_0[i](x + y)
|
86 |
-
|
87 |
-
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
88 |
-
y = self.drop(y)
|
89 |
-
x = self.norm_layers_1[i](x + y)
|
90 |
-
|
91 |
-
y = self.ffn_layers[i](x, x_mask)
|
92 |
-
y = self.drop(y)
|
93 |
-
x = self.norm_layers_2[i](x + y)
|
94 |
-
x = x * x_mask
|
95 |
-
return x
|
96 |
-
|
97 |
-
|
98 |
-
class MultiHeadAttention(nn.Module):
|
99 |
-
def __init__(self, channels, out_channels, n_heads, p_dropout=0., window_size=None, heads_share=True, block_length=None, proximal_bias=False, proximal_init=False):
|
100 |
-
super().__init__()
|
101 |
-
assert channels % n_heads == 0
|
102 |
-
|
103 |
-
self.channels = channels
|
104 |
-
self.out_channels = out_channels
|
105 |
-
self.n_heads = n_heads
|
106 |
-
self.p_dropout = p_dropout
|
107 |
-
self.window_size = window_size
|
108 |
-
self.heads_share = heads_share
|
109 |
-
self.block_length = block_length
|
110 |
-
self.proximal_bias = proximal_bias
|
111 |
-
self.proximal_init = proximal_init
|
112 |
-
self.attn = None
|
113 |
-
|
114 |
-
self.k_channels = channels // n_heads
|
115 |
-
self.conv_q = nn.Conv1d(channels, channels, 1)
|
116 |
-
self.conv_k = nn.Conv1d(channels, channels, 1)
|
117 |
-
self.conv_v = nn.Conv1d(channels, channels, 1)
|
118 |
-
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
119 |
-
self.drop = nn.Dropout(p_dropout)
|
120 |
-
|
121 |
-
if window_size is not None:
|
122 |
-
n_heads_rel = 1 if heads_share else n_heads
|
123 |
-
rel_stddev = self.k_channels**-0.5
|
124 |
-
self.emb_rel_k = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
125 |
-
self.emb_rel_v = nn.Parameter(torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels) * rel_stddev)
|
126 |
-
|
127 |
-
nn.init.xavier_uniform_(self.conv_q.weight)
|
128 |
-
nn.init.xavier_uniform_(self.conv_k.weight)
|
129 |
-
nn.init.xavier_uniform_(self.conv_v.weight)
|
130 |
-
if proximal_init:
|
131 |
-
with torch.no_grad():
|
132 |
-
self.conv_k.weight.copy_(self.conv_q.weight)
|
133 |
-
self.conv_k.bias.copy_(self.conv_q.bias)
|
134 |
-
|
135 |
-
def forward(self, x, c, attn_mask=None):
|
136 |
-
q = self.conv_q(x)
|
137 |
-
k = self.conv_k(c)
|
138 |
-
v = self.conv_v(c)
|
139 |
-
|
140 |
-
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
141 |
-
|
142 |
-
x = self.conv_o(x)
|
143 |
-
return x
|
144 |
-
|
145 |
-
def attention(self, query, key, value, mask=None):
|
146 |
-
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
147 |
-
b, d, t_s, t_t = (*key.size(), query.size(2))
|
148 |
-
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
149 |
-
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
150 |
-
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
151 |
-
|
152 |
-
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
153 |
-
if self.window_size is not None:
|
154 |
-
assert t_s == t_t, "Relative attention is only available for self-attention."
|
155 |
-
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
156 |
-
rel_logits = self._matmul_with_relative_keys(query /math.sqrt(self.k_channels), key_relative_embeddings)
|
157 |
-
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
158 |
-
scores = scores + scores_local
|
159 |
-
if self.proximal_bias:
|
160 |
-
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
161 |
-
scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
|
162 |
-
if mask is not None:
|
163 |
-
scores = scores.masked_fill(mask == 0, -1e4)
|
164 |
-
if self.block_length is not None:
|
165 |
-
assert t_s == t_t, "Local attention is only available for self-attention."
|
166 |
-
block_mask = torch.ones_like(scores).triu(-self.block_length).tril(self.block_length)
|
167 |
-
scores = scores.masked_fill(block_mask == 0, -1e4)
|
168 |
-
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
169 |
-
p_attn = self.drop(p_attn)
|
170 |
-
output = torch.matmul(p_attn, value)
|
171 |
-
if self.window_size is not None:
|
172 |
-
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
173 |
-
value_relative_embeddings = self._get_relative_embeddings(self.emb_rel_v, t_s)
|
174 |
-
output = output + self._matmul_with_relative_values(relative_weights, value_relative_embeddings)
|
175 |
-
output = output.transpose(2, 3).contiguous().view(b, d, t_t) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
176 |
-
return output, p_attn
|
177 |
-
|
178 |
-
def _matmul_with_relative_values(self, x, y):
|
179 |
-
"""
|
180 |
-
x: [b, h, l, m]
|
181 |
-
y: [h or 1, m, d]
|
182 |
-
ret: [b, h, l, d]
|
183 |
-
"""
|
184 |
-
ret = torch.matmul(x, y.unsqueeze(0))
|
185 |
-
return ret
|
186 |
-
|
187 |
-
def _matmul_with_relative_keys(self, x, y):
|
188 |
-
"""
|
189 |
-
x: [b, h, l, d]
|
190 |
-
y: [h or 1, m, d]
|
191 |
-
ret: [b, h, l, m]
|
192 |
-
"""
|
193 |
-
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
194 |
-
return ret
|
195 |
-
|
196 |
-
def _get_relative_embeddings(self, relative_embeddings, length):
|
197 |
-
max_relative_position = 2 * self.window_size + 1
|
198 |
-
# Pad first before slice to avoid using cond ops.
|
199 |
-
pad_length = max(length - (self.window_size + 1), 0)
|
200 |
-
slice_start_position = max((self.window_size + 1) - length, 0)
|
201 |
-
slice_end_position = slice_start_position + 2 * length - 1
|
202 |
-
if pad_length > 0:
|
203 |
-
padded_relative_embeddings = F.pad(
|
204 |
-
relative_embeddings,
|
205 |
-
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]))
|
206 |
-
else:
|
207 |
-
padded_relative_embeddings = relative_embeddings
|
208 |
-
used_relative_embeddings = padded_relative_embeddings[:,slice_start_position:slice_end_position]
|
209 |
-
return used_relative_embeddings
|
210 |
-
|
211 |
-
def _relative_position_to_absolute_position(self, x):
|
212 |
-
"""
|
213 |
-
x: [b, h, l, 2*l-1]
|
214 |
-
ret: [b, h, l, l]
|
215 |
-
"""
|
216 |
-
batch, heads, length, _ = x.size()
|
217 |
-
# Concat columns of pad to shift from relative to absolute indexing.
|
218 |
-
x = F.pad(x, commons.convert_pad_shape([[0,0],[0,0],[0,0],[0,1]]))
|
219 |
-
|
220 |
-
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
221 |
-
x_flat = x.view([batch, heads, length * 2 * length])
|
222 |
-
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0,0],[0,0],[0,length-1]]))
|
223 |
-
|
224 |
-
# Reshape and slice out the padded elements.
|
225 |
-
x_final = x_flat.view([batch, heads, length+1, 2*length-1])[:, :, :length, length-1:]
|
226 |
-
return x_final
|
227 |
-
|
228 |
-
def _absolute_position_to_relative_position(self, x):
|
229 |
-
"""
|
230 |
-
x: [b, h, l, l]
|
231 |
-
ret: [b, h, l, 2*l-1]
|
232 |
-
"""
|
233 |
-
batch, heads, length, _ = x.size()
|
234 |
-
# padd along column
|
235 |
-
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length-1]]))
|
236 |
-
x_flat = x.view([batch, heads, length**2 + length*(length -1)])
|
237 |
-
# add 0's in the beginning that will skew the elements after reshape
|
238 |
-
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
239 |
-
x_final = x_flat.view([batch, heads, length, 2*length])[:,:,:,1:]
|
240 |
-
return x_final
|
241 |
-
|
242 |
-
def _attention_bias_proximal(self, length):
|
243 |
-
"""Bias for self-attention to encourage attention to close positions.
|
244 |
-
Args:
|
245 |
-
length: an integer scalar.
|
246 |
-
Returns:
|
247 |
-
a Tensor with shape [1, 1, length, length]
|
248 |
-
"""
|
249 |
-
r = torch.arange(length, dtype=torch.float32)
|
250 |
-
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
251 |
-
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
252 |
-
|
253 |
-
|
254 |
-
class FFN(nn.Module):
|
255 |
-
def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0., activation=None, causal=False):
|
256 |
-
super().__init__()
|
257 |
-
self.in_channels = in_channels
|
258 |
-
self.out_channels = out_channels
|
259 |
-
self.filter_channels = filter_channels
|
260 |
-
self.kernel_size = kernel_size
|
261 |
-
self.p_dropout = p_dropout
|
262 |
-
self.activation = activation
|
263 |
-
self.causal = causal
|
264 |
-
|
265 |
-
if causal:
|
266 |
-
self.padding = self._causal_padding
|
267 |
-
else:
|
268 |
-
self.padding = self._same_padding
|
269 |
-
|
270 |
-
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
271 |
-
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
272 |
-
self.drop = nn.Dropout(p_dropout)
|
273 |
-
|
274 |
-
def forward(self, x, x_mask):
|
275 |
-
x = self.conv_1(self.padding(x * x_mask))
|
276 |
-
if self.activation == "gelu":
|
277 |
-
x = x * torch.sigmoid(1.702 * x)
|
278 |
-
else:
|
279 |
-
x = torch.relu(x)
|
280 |
-
x = self.drop(x)
|
281 |
-
x = self.conv_2(self.padding(x * x_mask))
|
282 |
-
return x * x_mask
|
283 |
-
|
284 |
-
def _causal_padding(self, x):
|
285 |
-
if self.kernel_size == 1:
|
286 |
-
return x
|
287 |
-
pad_l = self.kernel_size - 1
|
288 |
-
pad_r = 0
|
289 |
-
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
290 |
-
x = F.pad(x, commons.convert_pad_shape(padding))
|
291 |
-
return x
|
292 |
-
|
293 |
-
def _same_padding(self, x):
|
294 |
-
if self.kernel_size == 1:
|
295 |
-
return x
|
296 |
-
pad_l = (self.kernel_size - 1) // 2
|
297 |
-
pad_r = self.kernel_size // 2
|
298 |
-
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
299 |
-
x = F.pad(x, commons.convert_pad_shape(padding))
|
300 |
-
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|