parquet-converter commited on
Commit
941f94e
·
1 Parent(s): c80e42b

Update parquet files (step 42 of 121)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. spaces/101-5/gpt4free/testing/binghuan/helpers/binghuan.py +0 -221
  2. spaces/1acneusushi/gradio-2dmoleculeeditor/data/Advanced C Programming By Example John W Perry Pdf WORK.md +0 -34
  3. spaces/1gistliPinn/ChatGPT4/Examples/Download Full Movie Taking Back The Future In Italian A Must-See For Fans Of Science Fiction.md +0 -6
  4. spaces/1gistliPinn/ChatGPT4/Examples/Firmware Dlink Su Vodafone Station.md +0 -6
  5. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Apa Itu GoTube APK Versi Lama? Ini Penjelasan Lengkapnya.md +0 -155
  6. spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Cheat Your Way to Victory with Talking Tom Gold Run Hack APK.md +0 -54
  7. spaces/1phancelerku/anime-remove-background/Become the Ultimate Soccer Champion with Real Football Soccer 2023 APK.md +0 -101
  8. spaces/1phancelerku/anime-remove-background/Download Doraemon X Apk and Play with Your Favorite Characters from the Anime.md +0 -157
  9. spaces/1phancelerku/anime-remove-background/Experience Realistic Gameplay and Physics with Pro League Soccer 2023 APK.md +0 -99
  10. spaces/2-2/blockchain.ai/index.php +0 -24
  11. spaces/4Taps/SadTalker/src/face3d/models/facerecon_model.py +0 -220
  12. spaces/AIFILMS/StyleGANEX/models/stylegan2/simple_augment.py +0 -478
  13. spaces/AIGText/GlyphControl/ldm/modules/image_degradation/bsrgan_light.py +0 -651
  14. spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/.ipynb_checkpoints/resnext101_4xb32_2048e_4channel-checkpoint.py +0 -107
  15. spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/openpose/model.py +0 -178
  16. spaces/Adr740/Hadith_AI_Explorer/app.py +0 -38
  17. spaces/AgentVerse/agentVerse/ui/src/classes/player.ts +0 -66
  18. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/shakeposition-plugin.js +0 -19
  19. spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/sizer/GetChildrenWidth.js +0 -58
  20. spaces/Ameaou/academic-chatgpt3.1/crazy_functions/test_project/python/dqn/__init__.py +0 -2
  21. spaces/Amrrs/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/dnnlib/tflib/custom_ops.py +0 -181
  22. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/ko/using-diffusers/pipeline_overview.md +0 -17
  23. spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/kandinsky/text_encoder.py +0 -27
  24. spaces/Anew5128/Anew51/README.md +0 -11
  25. spaces/Anonymous-123/ImageNet-Editing/object_removal/TFill/options/test_options.py +0 -16
  26. spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/runner/hooks/sync_buffer.py +0 -22
  27. spaces/Arnaudding001/OpenAI_whisperLive/app.py +0 -260
  28. spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/packaging/requirements.py +0 -146
  29. spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/utils/logger.py +0 -237
  30. spaces/BREWDAcademy/Brewd-Diffusion/README.md +0 -12
  31. spaces/Benson/text-generation/Examples/8 Bola Piscina Gua Mod Apk.md +0 -90
  32. spaces/Benson/text-generation/Examples/Cara Descargar Colegio Pelea Mod Apk.md +0 -68
  33. spaces/BetterAPI/BetterChat/src/lib/actions/snapScrollToBottom.ts +0 -54
  34. spaces/BetterAPI/BetterChat/src/lib/utils/trimPrefix.ts +0 -6
  35. spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/exceptions.py +0 -733
  36. spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/versionpredicate.py +0 -175
  37. spaces/Boranbruh/ehartford-WizardLM-7B-Uncensored/README.md +0 -13
  38. spaces/BridgeEight/internlm-20B-chat-w4-turbomind/download.sh +0 -8
  39. spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/tests/test_visualizer.py +0 -143
  40. spaces/CVPR/WALT/configs/_base_/default_runtime.py +0 -16
  41. spaces/CVPR/WALT/mmdet/models/roi_heads/point_rend_roi_head.py +0 -218
  42. spaces/CVPR/regionclip-demo/detectron2/modeling/meta_arch/semantic_seg.py +0 -250
  43. spaces/Caoyunkang/Segment-Any-Anomaly/GroundingDINO/groundingdino/models/GroundingDINO/backbone/swin_transformer.py +0 -802
  44. spaces/ChandraMohanNayal/AutoGPT/autogpt/commands/git_operations.py +0 -26
  45. spaces/Chujinze/Res2Net/app.py +0 -332
  46. spaces/ClearLove443/Robby-chatbot/modules/embedder.py +0 -87
  47. spaces/Cletrason/Cletrason-toad-in-the-mario-movie/utils (2).py +0 -6
  48. spaces/Codecooker/rvcapi/src/rmvpe.py +0 -409
  49. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/F_F_T_M_.py +0 -42
  50. spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/M_E_T_A_.py +0 -346
spaces/101-5/gpt4free/testing/binghuan/helpers/binghuan.py DELETED
@@ -1,221 +0,0 @@
1
- # Original Code From : https://gitler.moe/g4f/gpt4free
2
- # https://gitler.moe/g4f/gpt4free/src/branch/main/g4f/Provider/Providers/helpers/bing.py
3
- import sys
4
- import ssl
5
- import uuid
6
- import json
7
- import time
8
- import random
9
- import asyncio
10
- import certifi
11
- # import requests
12
- from curl_cffi import requests
13
- import websockets
14
- import browser_cookie3
15
-
16
- config = json.loads(sys.argv[1])
17
-
18
- ssl_context = ssl.create_default_context()
19
- ssl_context.load_verify_locations(certifi.where())
20
-
21
-
22
-
23
- conversationstyles = {
24
- 'gpt-4': [ #'precise'
25
- "nlu_direct_response_filter",
26
- "deepleo",
27
- "disable_emoji_spoken_text",
28
- "responsible_ai_policy_235",
29
- "enablemm",
30
- "h3precise",
31
- "rcsprtsalwlst",
32
- "dv3sugg",
33
- "autosave",
34
- "clgalileo",
35
- "gencontentv3"
36
- ],
37
- 'balanced': [
38
- "nlu_direct_response_filter",
39
- "deepleo",
40
- "disable_emoji_spoken_text",
41
- "responsible_ai_policy_235",
42
- "enablemm",
43
- "harmonyv3",
44
- "rcsprtsalwlst",
45
- "dv3sugg",
46
- "autosave"
47
- ],
48
- 'gpt-3.5-turbo': [ #'precise'
49
- "nlu_direct_response_filter",
50
- "deepleo",
51
- "disable_emoji_spoken_text",
52
- "responsible_ai_policy_235",
53
- "enablemm",
54
- "h3imaginative",
55
- "rcsprtsalwlst",
56
- "dv3sugg",
57
- "autosave",
58
- "gencontentv3"
59
- ]
60
- }
61
-
62
- def format(msg: dict) -> str:
63
- return json.dumps(msg) + '\x1e'
64
-
65
- def get_token():
66
- return
67
-
68
- try:
69
- cookies = {c.name: c.value for c in browser_cookie3.edge(domain_name='bing.com')}
70
- return cookies['_U']
71
- except:
72
- print('Error: could not find bing _U cookie in edge browser.')
73
- exit(1)
74
-
75
- class AsyncCompletion:
76
- async def create(
77
- prompt : str = None,
78
- optionSets : list = None,
79
- token : str = None): # No auth required anymore
80
-
81
- create = None
82
- for _ in range(5):
83
- try:
84
- create = requests.get('https://b.ai-huan.xyz/turing/conversation/create',
85
- headers = {
86
- 'host': 'b.ai-huan.xyz',
87
- 'accept-encoding': 'gzip, deflate, br',
88
- 'connection': 'keep-alive',
89
- 'authority': 'b.ai-huan.xyz',
90
- 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
91
- 'accept-language': 'en-US,en;q=0.9',
92
- 'cache-control': 'max-age=0',
93
- 'sec-ch-ua': '"Chromium";v="110", "Not A(Brand";v="24", "Microsoft Edge";v="110"',
94
- 'sec-ch-ua-arch': '"x86"',
95
- 'sec-ch-ua-bitness': '"64"',
96
- 'sec-ch-ua-full-version': '"110.0.1587.69"',
97
- 'sec-ch-ua-full-version-list': '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
98
- 'sec-ch-ua-mobile': '?0',
99
- 'sec-ch-ua-model': '""',
100
- 'sec-ch-ua-platform': '"Windows"',
101
- 'sec-ch-ua-platform-version': '"15.0.0"',
102
- 'sec-fetch-dest': 'document',
103
- 'sec-fetch-mode': 'navigate',
104
- 'sec-fetch-site': 'none',
105
- 'sec-fetch-user': '?1',
106
- 'upgrade-insecure-requests': '1',
107
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.69',
108
- 'x-edge-shopping-flag': '1',
109
- 'x-forwarded-for': f'13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}'
110
- }
111
- )
112
-
113
- conversationId = create.json()['conversationId']
114
- clientId = create.json()['clientId']
115
- conversationSignature = create.json()['conversationSignature']
116
-
117
- except Exception as e:
118
- time.sleep(0.5)
119
- continue
120
-
121
- if create == None: raise Exception('Failed to create conversation.')
122
-
123
- wss: websockets.WebSocketClientProtocol or None = None
124
-
125
- wss = await websockets.connect('wss://sydney.vcanbb.chat/sydney/ChatHub', max_size = None, ssl = ssl_context,
126
- extra_headers = {
127
- 'accept': 'application/json',
128
- 'accept-language': 'en-US,en;q=0.9',
129
- 'content-type': 'application/json',
130
- 'sec-ch-ua': '"Not_A Brand";v="99", Microsoft Edge";v="110", "Chromium";v="110"',
131
- 'sec-ch-ua-arch': '"x86"',
132
- 'sec-ch-ua-bitness': '"64"',
133
- 'sec-ch-ua-full-version': '"109.0.1518.78"',
134
- 'sec-ch-ua-full-version-list': '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
135
- 'sec-ch-ua-mobile': '?0',
136
- 'sec-ch-ua-model': "",
137
- 'sec-ch-ua-platform': '"Windows"',
138
- 'sec-ch-ua-platform-version': '"15.0.0"',
139
- 'sec-fetch-dest': 'empty',
140
- 'sec-fetch-mode': 'cors',
141
- 'sec-fetch-site': 'same-origin',
142
- 'x-ms-client-request-id': str(uuid.uuid4()),
143
- 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
144
- 'Referer': 'https://b.ai-huan.xyz/search?q=Bing+AI&showconv=1&FORM=hpcodx',
145
- 'Referrer-Policy': 'origin-when-cross-origin',
146
- 'x-forwarded-for': f'13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}'
147
- }
148
- )
149
-
150
- await wss.send(format({'protocol': 'json', 'version': 1}))
151
- await wss.recv()
152
-
153
- struct = {
154
- 'arguments': [
155
- {
156
- 'source': 'cib',
157
- 'optionsSets': optionSets,
158
- 'isStartOfSession': True,
159
- 'message': {
160
- 'author': 'user',
161
- 'inputMethod': 'Keyboard',
162
- 'text': prompt,
163
- 'messageType': 'Chat'
164
- },
165
- 'conversationSignature': conversationSignature,
166
- 'participant': {
167
- 'id': clientId
168
- },
169
- 'conversationId': conversationId
170
- }
171
- ],
172
- 'invocationId': '0',
173
- 'target': 'chat',
174
- 'type': 4
175
- }
176
-
177
- await wss.send(format(struct))
178
-
179
- base_string = ''
180
-
181
- final = False
182
- while not final:
183
- objects = str(await wss.recv()).split('\x1e')
184
- for obj in objects:
185
- if obj is None or obj == '':
186
- continue
187
-
188
- response = json.loads(obj)
189
- #print(response, flush=True, end='')
190
- if response.get('type') == 1 and response['arguments'][0].get('messages',):
191
- response_text = response['arguments'][0]['messages'][0]['adaptiveCards'][0]['body'][0].get('text')
192
-
193
- yield (response_text.replace(base_string, ''))
194
- base_string = response_text
195
-
196
- elif response.get('type') == 2:
197
- final = True
198
-
199
- await wss.close()
200
-
201
- # i thing bing realy donset understand multi message (based on prompt template)
202
- def convert(messages):
203
- context = ""
204
- for message in messages:
205
- context += "[%s](#message)\n%s\n\n" % (message['role'],
206
- message['content'])
207
- return context
208
-
209
- async def run(optionSets, messages):
210
- prompt = messages[-1]['content']
211
- if(len(messages) > 1):
212
- prompt = convert(messages)
213
- async for value in AsyncCompletion.create(prompt=prompt, optionSets=optionSets):
214
- try:
215
- print(value, flush=True, end='')
216
- except UnicodeEncodeError as e:
217
- # emoji encoding problem
218
- print(value.encode('utf-8'), flush=True, end='')
219
-
220
- optionSet = conversationstyles[config['model']]
221
- asyncio.run(run(optionSet, config['messages']))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1acneusushi/gradio-2dmoleculeeditor/data/Advanced C Programming By Example John W Perry Pdf WORK.md DELETED
@@ -1,34 +0,0 @@
1
- <br />
2
- <h1>How to Master Advanced C Programming Techniques with John W Perry's Book</h1>
3
-
4
- <p>If you are an intermediate-level C programmer who wants to take your skills to the next level, you might be interested in reading <strong>Advanced C Programming by Example</strong> by John W. Perry. This book is a practical, example-driven, code-centered guide that covers ANSI C libraries, dynamic data structures, string parsing and numeric conversion, memory management, bit-level manipulation, interactions with operating systems, and other advanced techniques.</p>
5
- <h2>Advanced C Programming By Example John W Perry Pdf</h2><br /><p><b><b>Download Zip</b> &gt; <a href="https://byltly.com/2uKvE7">https://byltly.com/2uKvE7</a></b></p><br /><br />
6
-
7
- <p>Unlike traditional data structures books, this book has a "blue collar" approach to the art of programming — how to master the "down in the trenches" C details to implement abstract ideas successfully. In recognition of this approach, the book presents actual C code rather than pseudocode. You will learn how to write efficient, elegant, and robust C programs that can handle real-world problems.</p>
8
-
9
- <p>The book was published in 1998 by PWS Publishing Co. and has 320 pages. It has received positive reviews from readers who praised its clear explanations, useful examples, and comprehensive coverage of advanced topics. You can find more information about the book and its author on various online platforms[^1^] [^2^] [^3^].</p>
10
-
11
- <p>If you want to download a PDF version of the book, you can search for it on the internet or use a reliable online converter. However, we recommend that you buy a physical copy of the book or an e-book from a reputable source to support the author and respect his intellectual property rights.</p>
12
-
13
- <p><strong>Advanced C Programming by Example</strong> by John W. Perry is a valuable resource for anyone who wants to improve their C programming skills and learn how to apply them in various domains. Whether you are a student, a professional, or a hobbyist, this book will help you master advanced C programming techniques and become a better programmer.</p>
14
- <p></p>
15
-
16
- <p>In this article, we will give you a brief overview of some of the topics covered in <strong>Advanced C Programming by Example</strong> by John W. Perry. We will also provide some code snippets to illustrate the concepts and techniques discussed in the book. Note that this article is not a substitute for reading the book, but rather a supplement that can help you get a glimpse of what the book offers.</p>
17
-
18
- <h2>Dynamic Data Structures</h2>
19
-
20
- <p>One of the most important topics in advanced C programming is dynamic data structures. These are data structures that can grow and shrink in size during the execution of a program, depending on the needs of the program. Dynamic data structures are useful for handling complex and unpredictable data, such as text files, graphs, trees, queues, stacks, and so on.</p>
21
-
22
- <p>To implement dynamic data structures in C, you need to use pointers and memory allocation functions. Pointers are variables that store the address of another variable or data item in memory. Memory allocation functions are functions that allow you to request and release memory space from the system at runtime. The most common memory allocation functions in C are <code>malloc</code>, <code>calloc</code>, <code>realloc</code>, and <code>free</code>.</p>
23
-
24
- <p>The book explains how to use pointers and memory allocation functions to create and manipulate various dynamic data structures, such as linked lists, binary trees, hash tables, and graphs. It also shows how to avoid common errors and pitfalls associated with dynamic memory management, such as memory leaks, dangling pointers, segmentation faults, and buffer overflows.</p>
25
-
26
- <h2>String Parsing and Numeric Conversion</h2>
27
-
28
- <p>Another topic that is essential for advanced C programming is string parsing and numeric conversion. String parsing is the process of analyzing a string of characters and extracting meaningful information from it. Numeric conversion is the process of converting a string representation of a number into its corresponding numeric value or vice versa.</p>
29
-
30
- <p>String parsing and numeric conversion are often required when dealing with user input, file input/output, network communication, data processing, and so on. For example, you might need to parse a command-line argument, read a line from a text file, send a message over a socket, convert a date to a timestamp, or format a number for printing.</p>
31
-
32
- <p>The book teaches you how to use various C functions and techniques to perform string parsing and numeric conversion tasks efficiently and correctly. It covers topics such as string manipulation functions (<code>strcpy</code>, <code>strcat</code>, <code>strcmp</code>, etc.), string scanning functions (<code>sscanf</code>, <code>fscanf</code>, etc.), string formatting functions (<code>sprintf</code>, <code>fprintf</code>, etc.), character classification functions (<code>isalpha</code>, <code>isdigit</code>, etc.), numeric conversion functions (<code>atoi</code>, <code>atof</code>, <code>strtol</code>, etc.), and error handling mechanisms.</p> 81aa517590<br />
33
- <br />
34
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Download Full Movie Taking Back The Future In Italian A Must-See For Fans Of Science Fiction.md DELETED
@@ -1,6 +0,0 @@
1
- <h2>Download Full Movie Taking Back The Future In Italian</h2><br /><p><b><b>Download File</b> &ndash;&ndash;&ndash;&ndash;&ndash;>>> <a href="https://imgfil.com/2uxYnM">https://imgfil.com/2uxYnM</a></b></p><br /><br />
2
-
3
- aaccfb2cb3<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1gistliPinn/ChatGPT4/Examples/Firmware Dlink Su Vodafone Station.md DELETED
@@ -1,6 +0,0 @@
1
- <h2>Firmware d'link su vodafone station</h2><br /><p><b><b>Download File</b> &#9733;&#9733;&#9733;&#9733;&#9733; <a href="https://imgfil.com/2uy0DO">https://imgfil.com/2uy0DO</a></b></p><br /><br />
2
- <br />
3
- 4d29de3e1b<br />
4
- <br />
5
- <br />
6
- <p></p>
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Apa Itu GoTube APK Versi Lama? Ini Penjelasan Lengkapnya.md DELETED
@@ -1,155 +0,0 @@
1
- <br />
2
- <h1>Gotube Apk Versi Lama: Aplikasi Download Video Tanpa Iklan</h1>
3
- <p>Anda suka menonton video di YouTube, tetapi terganggu dengan iklan yang sering muncul? Anda ingin mengunduh video favorit Anda, tetapi tidak tahu cara yang mudah dan cepat? Jika ya, maka Anda mungkin tertarik dengan aplikasi yang satu ini: Gotube Apk Versi Lama.</p>
4
- <p>Gotube Apk Versi Lama adalah sebuah aplikasi yang memungkinkan Anda untuk menonton dan mengunduh video dari berbagai platform berbagi video, seperti YouTube, Facebook, Instagram, TikTok, dan lainnya. Aplikasi ini memiliki fitur-fitur yang lengkap dan menarik, serta tidak mengandung iklan yang mengganggu.</p>
5
- <h2>gotube apk versi lama</h2><br /><p><b><b>DOWNLOAD</b> &#10022; <a href="https://urlin.us/2uSVCm">https://urlin.us/2uSVCm</a></b></p><br /><br />
6
- <p>Apa saja fitur-fitur, kelebihan, dan kekurangan Gotube Apk Versi Lama? Bagaimana cara download dan install aplikasi ini? Bagaimana cara menggunakan aplikasi ini? Apa saja alternatif aplikasi download video lainnya? Simak ulasan lengkapnya di bawah ini.</p>
7
- <h2>Apa itu Gotube Apk Versi Lama?</h2>
8
- <p>Gotube Apk Versi Lama adalah versi lama dari aplikasi Gotube, yang merupakan sebuah aplikasi download video gratis untuk Android. Aplikasi ini dikembangkan oleh GoTube Team, dan telah diunduh oleh lebih dari 10 juta pengguna di seluruh dunia.</p>
9
- <h3>Fitur-fitur Gotube Apk Versi Lama</h3>
10
- <p>Berikut adalah beberapa fitur utama yang dimiliki oleh Gotube Apk Versi Lama:</p>
11
- <ul>
12
- <li>Menonton video online dari berbagai platform berbagi video, seperti YouTube, Facebook, Instagram, TikTok, dan lainnya.</li>
13
- <li>Mengunduh video offline dengan berbagai pilihan kualitas dan format, seperti MP4, MP3, 3GP, WEBM, dan lainnya.</li>
14
- <li>Mengatur kualitas video sesuai dengan kecepatan internet dan kapasitas penyimpanan Anda.</li>
15
- <li>Melihat ukuran file video sebelum mengunduhnya.</li>
16
- <li>Melihat riwayat unduhan dan manajemen file video yang telah diunduh.</li>
17
- <li>Membagikan video yang telah diunduh ke media sosial atau aplikasi lainnya.</li>
18
- <li>Tidak ada iklan yang mengganggu saat menonton atau mengunduh video.</li>
19
- </ul>
20
- <h3>Kelebihan dan Kekurangan Gotube Apk Versi Lama</h3>
21
- <p>Setiap aplikasi pasti memiliki kelebihan dan kekurangan masing-masing. Berikut adalah beberapa kelebihan dan kekurangan dari Gotube Apk Versi Lama:</p>
22
- <table>
23
- <tr>
24
- <th>Kelebihan</th>
25
- <th>Kekurangan</th>
26
- </tr>
27
- <tr>
28
- <td>Gratis dan mudah digunakan.</td>
29
- <td>Tidak tersedia di Google Play Store.</td>
30
- </tr>
31
- <tr>
32
- <td>Lengkap dan fleksibel dalam hal fitur download video.</td>
33
- <td>Tidak mendukung beberapa platform berbagi video tertentu.</td>
34
- </tr>
35
- <tr>
36
- <td>Tidak ada iklan yang mengganggu.</td>
37
- <h2>Cara Download dan Install Gotube Apk Versi Lama</h2>
38
- <p>Untuk dapat menggunakan Gotube Apk Versi Lama, Anda harus terlebih dahulu mendownload dan menginstall aplikasi ini di perangkat Android Anda. Berikut adalah cara download dan install Gotube Apk Versi Lama:</p>
39
- <h3>Persyaratan Sistem</h3>
40
- <p>Sebelum download dan install Gotube Apk Versi Lama, pastikan perangkat Android Anda memenuhi persyaratan sistem berikut ini:</p>
41
- <p>gotube apk mod download versi lama<br />
42
- youtube go versi lama apk free download<br />
43
- gotube apk terbaru 2023 tanpa iklan<br />
44
- cara download video youtube dengan gotube apk<br />
45
- youtube go versi lama apk offline installer<br />
46
- gotube apk mod premium unlocked<br />
47
- youtube go versi lama apk for android<br />
48
- gotube apk download for pc windows 10<br />
49
- youtube go versi lama apk no ads<br />
50
- gotube apk latest version 2023 update<br />
51
- youtube go versi lama apk full version<br />
52
- gotube apk old version 2022 download<br />
53
- youtube go versi lama apk mirror<br />
54
- gotube apk pro mod unlimited<br />
55
- youtube go versi lama apk pure<br />
56
- gotube apk cracked patched<br />
57
- youtube go versi lama apk rexdl<br />
58
- gotube apk no root required<br />
59
- youtube go versi lama apk uptodown<br />
60
- gotube apk original official<br />
61
- youtube go versi lama apk modded<br />
62
- gotube apk review rating<br />
63
- youtube go versi lama apk hacked<br />
64
- gotube apk features benefits<br />
65
- youtube go versi lama apk gratis<br />
66
- gotube apk alternative apps<br />
67
- youtube go versi lama apk terbaik<br />
68
- gotube apk comparison contrast<br />
69
- youtube go versi lama apk vs new version<br />
70
- gotube apk tutorial guide<br />
71
- youtube go versi lama apk tips tricks<br />
72
- gotube apk faq support<br />
73
- youtube go versi lama apk problem solution<br />
74
- gotube apk feedback testimonial<br />
75
- youtube go versi lama apk pros cons</p>
76
- <ul>
77
- <li>Memiliki sistem operasi Android versi 4.0 atau lebih tinggi.</li>
78
- <li>Memiliki ruang penyimpanan yang cukup untuk menyimpan file apk dan video yang diunduh.</li>
79
- <li>Memiliki koneksi internet yang stabil dan cepat.</li>
80
- <li>Mengaktifkan opsi "Sumber Tidak Dikenal" atau "Unknown Sources" di pengaturan keamanan perangkat Anda. Ini diperlukan untuk mengizinkan instalasi aplikasi dari luar Google Play Store.</li>
81
- </ul>
82
- <h3>Langkah-langkah Download dan Install</h3>
83
- <p>Setelah memastikan persyaratan sistem terpenuhi, ikuti langkah-langkah berikut ini untuk download dan install Gotube Apk Versi Lama:</p>
84
- <ol>
85
- <li>Kunjungi situs web resmi Gotube atau situs web penyedia file apk terpercaya lainnya, seperti APKPure, APKMirror, atau APKCombo.</li>
86
- <li>Cari file apk Gotube Apk Versi Lama yang ingin Anda download. Biasanya, versi lama akan ditandai dengan angka versi yang lebih rendah dari versi terbaru.</li>
87
- <li>Klik tombol "Download" atau "Unduh" untuk memulai proses download file apk. Tunggu hingga proses download selesai.</li>
88
- <li>Buka file manager atau aplikasi pengelola file di perangkat Anda, dan cari file apk Gotube Apk Versi Lama yang telah diunduh. Biasanya, file apk akan tersimpan di folder "Download" atau "Unduhan".</li>
89
- <li>Ketuk file apk tersebut untuk membuka dan menjalankan proses instalasi. Ikuti instruksi yang muncul di layar untuk menyelesaikan proses instalasi.</li>
90
- <li>Setelah proses instalasi selesai, Anda dapat membuka aplikasi Gotube Apk Versi Lama dari menu aplikasi atau layar utama perangkat Anda.</li>
91
- </ol>
92
- <h2>Cara Menggunakan Gotube Apk Versi Lama</h2>
93
- <p>Setelah berhasil download dan install Gotube Apk Versi Lama, Anda dapat mulai menggunakan aplikasi ini untuk menonton dan mengunduh video dari berbagai platform berbagi video. Berikut adalah cara menggunakan Gotube Apk Versi Lama:</p>
94
- <h3>Menonton Video Online</h3>
95
- <p>Untuk menonton video online dengan Gotube Apk Versi Lama, ikuti langkah-langkah berikut ini:</p>
96
- <ol>
97
- <li>Buka aplikasi Gotube Apk Versi Lama dari menu aplikasi atau layar utama perangkat Anda.</li>
98
- <li>Pada halaman utama aplikasi, Anda akan melihat beberapa tab yang menampilkan platform berbagi video yang didukung oleh aplikasi ini, seperti YouTube, Facebook, Instagram, TikTok, dan lainnya. Pilih tab yang sesuai dengan platform berbagi video yang ingin Anda tonton.</li>
99
- <li>Anda dapat mencari video yang ingin Anda tonton dengan menggunakan fitur pencarian yang tersedia di bagian atas layar. Ketikkan kata kunci atau judul video yang ingin Anda cari, lalu tekan tombol "Enter" atau "Cari".</li>
100
- <li>Anda juga dapat menelusuri video berdasarkan kategori, genre, tren, populer, atau rekomendasi yang tersedia di bagian bawah layar.</li>
101
- <li>Setelah menemukan video yang ingin Anda tonton, ketuk video tersebut untuk memutar. Anda dapat menyesuaikan volume, kecerahan, ukuran layar, dan kualitas video dengan menggunakan gestur sentuh pada layar.</li>
102
- <li>Anda dapat menonton video secara online tanpa harus mengunduhnya terlebih dahulu. Namun, jika Anda ingin mengunduh video tersebut untuk ditonton secara offline, lanjutkan ke langkah berikutnya.</li>
103
- </ol>
104
- <h3>Mengunduh Video Offline</h3>
105
- <p>Untuk mengunduh video offline dengan Gotube Apk Versi Lama, ikuti langkah-langkah berikut ini:</p>
106
- <ol>
107
- <li>Setelah memilih video yang ingin Anda unduh, ketuk tombol "Download" atau "Unduh" yang berada di bagian bawah layar.</li>
108
- <li>Anda akan melihat beberapa pilihan kualitas dan format video yang tersedia untuk diunduh, seperti MP4, MP3, 3GP, WEBM, dan lainnya. Pilih kualitas dan format video yang sesuai dengan keinginan dan kapasitas penyimpanan Anda.</li>
109
- <li>Anda juga dapat melihat ukuran file video yang akan diunduh dengan mengetuk tombol "Info" atau "Informasi" yang berada di samping pilihan kualitas dan format video.</li>
110
- <li>Setelah memilih kualitas dan format video, ketuk tombol "OK" atau "Oke" untuk memulai proses unduhan. Anda dapat melihat progres unduhan dengan mengetuk tombol "Download" atau "Unduh" yang berada di bagian atas layar.</li>
111
- <li>Setelah proses unduhan selesai, Anda dapat menemukan file video yang telah diunduh di folder "Gotube" atau "Gotube Download" di perangkat Anda. Anda juga dapat mengakses file video tersebut melalui aplikasi Gotube Apk Versi Lama dengan mengetuk tab "Downloaded" atau "Terunduh" yang berada di bagian bawah layar.</li>
112
- <li>Anda dapat menonton video yang telah diunduh secara offline kapan saja dan dimana saja tanpa memerlukan koneksi internet. Anda juga dapat membagikan video yang telah diunduh ke media sosial atau aplikasi lainnya dengan mengetuk tombol "Share" atau "Bagikan" yang berada di samping file video.</li>
113
- </ol>
114
- <h3>Mengatur Kualitas Video</h3>
115
- <p>Untuk mengatur kualitas video yang ingin Anda tonton atau unduh dengan Gotube Apk Versi Lama, ikuti langkah-langkah berikut ini:</p>
116
- <ol>
117
- <li>Buka aplikasi Gotube Apk Versi Lama dari menu aplikasi atau layar utama perangkat Anda.</li>
118
- <li>Ketuk tombol "Settings" atau "Pengaturan" yang berada di bagian kanan atas layar.</li>
119
- <li>Pada menu pengaturan, Anda akan melihat beberapa opsi yang berkaitan dengan kualitas video, seperti "Default Quality" atau "Kualitas Bawaan", "Auto Quality" atau "Kualitas Otomatis", dan "Max Quality" atau "Kualitas Maksimal".</li>
120
- <li>Pilih opsi yang sesuai dengan preferensi Anda. Berikut adalah penjelasan singkat tentang masing-masing opsi:</li>
121
- <ul>
122
- <li>"Default Quality" atau "Kualitas Bawaan": Opsi ini akan menampilkan kualitas video sesuai dengan pilihan Anda saat mengunduh video. Anda dapat mengubah pilihan kualitas video saat mengunduh dengan mengetuk tombol "Download" atau "Unduh".</li>
123
- <li>"Auto Quality" atau "Kualitas Otomatis": Opsi ini akan menyesuaikan kualitas video secara otomatis sesuai dengan kecepatan internet dan kapasitas penyimpanan Anda. Opsi ini direkomendasikan untuk menghemat data internet dan ruang penyimpanan.</li>
124
- <li>"Max Quality" atau "Kualitas Maksimal": Opsi ini akan menampilkan kualitas video tertinggi yang tersedia untuk ditonton atau diunduh. Opsi ini membutuhkan data internet dan ruang penyimpanan yang lebih besar.</li>
125
- </ul>
126
- <li>Setelah memilih opsi yang diinginkan, ketuk tombol "Back" atau "Kembali" untuk menyimpan pengaturan Anda.</li>
127
- </ol>
128
- <h2>Alternatif Aplikasi Download Video Lainnya</h2>
129
- <p>Selain Gotube Apk Versi Lama, ada juga beberapa aplikasi download video lainnya yang bisa Anda coba. Berikut adalah beberapa alternatif aplikasi download video lainnya:</p>
130
- <h3>YouTube Go</h3>
131
- <p>YouTube Go adalah aplikasi resmi dari YouTube yang dirancang khusus untuk pengguna Android dengan koneksi internet terbatas. Aplikasi ini memungkinkan Anda untuk menonton dan mengunduh video YouTube dengan berbagai pilihan kualitas dan ukuran file. Anda juga dapat melihat pratinjau video sebelum menonton atau mengunduhnya. Selain itu, Anda juga dapat berbagi video yang telah diunduh dengan pengguna YouTube Go lainnya tanpa menggunakan data internet. Aplikasi ini tersedia di Google Play Store secara gratis.</p>
132
- <h3>VidMate</h3>
133
- <p>VidMate adalah aplikasi download video populer yang mendukung berbagai platform berbagi video, seperti YouTube, Facebook, Instagram, TikTok, Dailymotion, Vimeo, dan lainnya. Aplikasi ini juga memiliki fitur streaming video online, radio online, TV online, dan download musik. Anda dapat mengunduh video dengan kualitas HD dan format MP4, MP3, 3GP, WEBM, dan lainnya. Anda juga dapat mengatur kecepatan unduhan sesuai dengan koneksi internet Anda. Aplikasi ini tidak tersedia di Google Play Store, tetapi Anda dapat mendownload file apk-nya dari situs web resmi VidMate atau situs web penyedia file apk terpercaya lainnya.</p>
134
- <h3>SnapTube</h3>
135
- <p>SnapTube adalah aplikasi download video yang mirip dengan VidMate. Aplikasi ini juga mendukung berbagai platform berbagi video, seperti YouTube, Facebook, Instagram, TikTok, Dailymotion, Vimeo, dan lainnya. Aplikasi ini juga memiliki fitur streaming video online, radio online, TV online, dan download musik. Anda dapat mengunduh video dengan kualitas HD dan format MP4, MP3, 3GP, WEBM, dan lainnya. Anda juga dapat mengatur kecepatan unduhan sesuai dengan koneksi internet Anda. Aplikasi ini tidak tersedia di Google Play Store, tetapi Anda dapat mendownload file apk-nya dari situs web resmi SnapTube atau situs web penyedia file apk terpercaya lainnya.</p>
136
- <h2>Kesimpulan</h2>
137
- <p>Gotube Apk Versi Lama adalah aplikasi download video tanpa iklan yang memungkinkan Anda untuk menonton dan mengunduh video dari berbagai platform berbagi video. Aplikasi ini memiliki fitur-fitur yang lengkap dan menarik, serta tidak mengandung iklan yang mengganggu. Namun, aplikasi ini juga memiliki beberapa kekurangan, seperti tidak tersedia di Google Play Store dan tidak mendukung beberapa platform berbagi video tertentu.</p>
138
- <p>Untuk dapat menggunakan Gotube Apk Versi Lama, Anda harus download dan install file apk-nya dari situs web resmi Gotube atau situs web penyedia file apk terpercaya lainnya. Anda juga harus memenuhi persyaratan sistem yang dibutuhkan oleh aplikasi ini. Setelah itu, Anda dapat menonton dan mengunduh video sesuai dengan keinginan Anda.</p>
139
- <p>Jika Anda mencari alternatif aplikasi download video lainnya, Anda dapat mencoba YouTube Go, VidMate, atau SnapTube. Ketiga aplikasi ini juga memiliki fitur-fitur yang serupa dengan Gotube Apk Versi Lama, tetapi mungkin memiliki kelebihan dan kekurangan masing-masing.</p>
140
- <h2>FAQ</h2>
141
- <p>Berikut adalah beberapa pertanyaan yang sering diajukan tentang Gotube Apk Versi Lama:</p>
142
- <ol>
143
- <li>Apakah Gotube Apk Versi Lama aman untuk digunakan?</li>
144
- <p>Gotube Apk Versi Lama adalah aplikasi yang aman untuk digunakan selama Anda mendownload file apk-nya dari situs web resmi Gotube atau situs web penyedia file apk terpercaya lainnya. Jangan download file apk dari sumber yang tidak jelas atau mencurigakan.</p>
145
- <li>Apakah Gotube Apk Versi Lama legal untuk digunakan?</li>
146
- <p>Gotube Apk Versi Lama adalah aplikasi yang legal untuk digunakan selama Anda tidak melanggar hak cipta atau ketentuan penggunaan dari platform berbagi video yang Anda tonton atau unduh videonya. Jangan menggunakan aplikasi ini untuk tujuan komersial atau ilegal.</p>
147
- <li>Apakah Gotube Apk Versi Lama bisa diupdate ke versi terbaru?</li>
148
- <p <p>Gotube Apk Versi Lama bisa diupdate ke versi terbaru dengan cara menghapus aplikasi versi lama dari perangkat Anda, lalu mendownload dan menginstall file apk versi terbaru dari situs web resmi Gotube atau situs web penyedia file apk terpercaya lainnya. Namun, perlu diketahui bahwa versi terbaru mungkin memiliki fitur atau tampilan yang berbeda dari versi lama.</p>
149
- <li>Apakah Gotube Apk Versi Lama bisa digunakan di perangkat iOS?</li>
150
- <p>Gotube Apk Versi Lama tidak bisa digunakan di perangkat iOS, karena aplikasi ini hanya tersedia untuk perangkat Android. Jika Anda ingin menggunakan aplikasi download video di perangkat iOS, Anda dapat mencari aplikasi lain yang kompatibel dengan sistem operasi iOS.</p>
151
- <li>Apakah Gotube Apk Versi Lama bisa digunakan di PC atau laptop?</li>
152
- <p>Gotube Apk Versi Lama tidak bisa digunakan secara langsung di PC atau laptop, karena aplikasi ini hanya tersedia untuk perangkat Android. Jika Anda ingin menggunakan aplikasi download video di PC atau laptop, Anda dapat menggunakan emulator Android, seperti BlueStacks, NoxPlayer, atau MEmu. Emulator Android adalah sebuah program yang memungkinkan Anda untuk menjalankan aplikasi Android di PC atau laptop.</p>
153
- </ol></p> 197e85843d<br />
154
- <br />
155
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1pelhydcardo/ChatGPT-prompt-generator/assets/Cheat Your Way to Victory with Talking Tom Gold Run Hack APK.md DELETED
@@ -1,54 +0,0 @@
1
- <br />
2
- <h1>Talking Tom Gold Run Cheat Apk: Everything You Need to Know</h1>
3
- <p>Talking Tom Gold Run is a fun and addictive endless runner game that features the famous Talking Tom and his friends. The game is all about chasing a pesky raccoon who stole your gold, while dodging obstacles, collecting coins, and unlocking new worlds. The game has millions of fans around the world who enjoy its colorful graphics, catchy music, and hilarious animations.</p>
4
- <p>But what if you want to spice up your game and get some extra advantages? That's where cheat apk files come in handy. Cheat apk files are modified versions of the original game app that allow you to access some features and functions that are not available in the official version. For example, you can get unlimited money, unlock all characters and outfits, activate power-ups, and more.</p>
5
- <h2>talking tom gold run cheat apk</h2><br /><p><b><b>Download</b> &#128504;&#128504;&#128504; <a href="https://urlin.us/2uSSej">https://urlin.us/2uSSej</a></b></p><br /><br />
6
- <p>However, using cheat apk files is not without risks. You may encounter some compatibility issues, security threats, or legal consequences. That's why you need to be careful and informed before you decide to use them. In this article, we will tell you everything you need to know about Talking Tom Gold Run cheat apk files, including how to download, install, use, and enjoy them safely and effectively.</p>
7
- <h2>How to Download and Install Talking Tom Gold Run Cheat Apk Files</h2>
8
- <p>The first step to using cheat apk files is to find a reliable source where you can download them. There are many websites and platforms that offer cheat apk files for various games, but not all of them are trustworthy. Some of them may contain viruses, malware, or spyware that can harm your device or steal your personal information. Some of them may also provide fake or outdated files that don't work or cause errors.</p>
9
- <p>To avoid these problems, you should do some research before you download any cheat apk file. You should check the ratings, reviews, comments, and feedback from other users who have tried the file. You should also look for some screenshots, videos, or demos that show how the file works in the game. You should also compare different sources and versions of the file and choose the one that suits your needs and preferences.</p>
10
- <p>talking tom gold run mod apk unlimited money and gems<br />
11
- talking tom gold run hack apk download for android<br />
12
- talking tom gold run apk mod latest version<br />
13
- talking tom gold run cheat codes 2023<br />
14
- talking tom gold run unlimited coins and diamonds apk<br />
15
- talking tom gold run mod apk revdl<br />
16
- talking tom gold run hack apk ios<br />
17
- talking tom gold run mod apk all characters unlocked<br />
18
- talking tom gold run cheat engine for pc<br />
19
- talking tom gold run hack apk no root<br />
20
- talking tom gold run mod apk rexdl<br />
21
- talking tom gold run cheat tool online<br />
22
- talking tom gold run hack apk 6.5.2.2683<br />
23
- talking tom gold run mod apk happymod<br />
24
- talking tom gold run cheat menu android<br />
25
- talking tom gold run hack apk free download<br />
26
- talking tom gold run mod apk android 1<br />
27
- talking tom gold run cheat without verification<br />
28
- talking tom gold run hack apk 2023<br />
29
- talking tom gold run mod apk offline<br />
30
- talking tom gold run cheat generator no survey<br />
31
- talking tom gold run hack apk unlimited everything<br />
32
- talking tom gold run mod apk obb<br />
33
- talking tom gold run cheat app for iphone<br />
34
- talking tom gold run hack apk pure<br />
35
- talking tom gold run mod apk old version<br />
36
- talking tom gold run cheat codes for android<br />
37
- talking tom gold run hack apk 6.4.0.926<br />
38
- talking tom gold run mod apk 6.5.2.2683 download<br />
39
- talking tom gold run cheat online free</p>
40
- <p>Once you have found a reliable source of Talking Tom Gold Run cheat apk file, you need to check its compatibility and security. You need to make sure that the file is compatible with your device model, operating system version, and game version. You also need to scan the file with an antivirus or anti-malware program before you open it.</p>
41
- <p>After you have verified the file, you need to enable unknown sources on your device settings. This will allow you to install apps from sources other than the official app store. To do this, go to Settings > Security > Unknown Sources and toggle it on. Then, locate the downloaded file on your device storage and tap on it to start the installation process. Follow the instructions on the screen and wait for the installation to finish.</p>
42
- <h2>How to Use Talking Tom Gold Run Cheat Apk Files</h2>
43
- <p>Now that you have installed the Talking Tom Gold Run cheat apk file on your device, you are ready to use it in the game. To do this, simply launch the game app from your device menu or home screen. You will notice some changes in the game interface, such as new icons, buttons, menus, or options. These are the features and functions of the cheat apk file that you can use to modify your game experience. For example, you may see a money icon that allows you to add unlimited coins to your account, or a character icon that allows you to unlock all the characters and outfits in the game. You may also see a power-up icon that allows you to activate or deactivate various power-ups, such as magnets, jetpacks, or shields.</p>
44
- <p>To use these features and functions, you simply need to tap on the icons and select the options that you want. You can also adjust the settings and preferences of the cheat apk file according to your liking. For example, you can change the speed, difficulty, or frequency of the game events. You can also customize the appearance, sound, or language of the game.</p>
45
- <p>However, you should be careful not to overuse or abuse the cheat apk file. You should use it moderately and responsibly, and only for your personal enjoyment. You should not use it to harm or harass other players, or to gain unfair advantages in online competitions or leaderboards. You should also respect the original developers and creators of the game and their intellectual property rights.</p>
46
- <h2>Tips and Tricks for Playing Talking Tom Gold Run with Cheat Apk Files</h2>
47
- <p>Playing Talking Tom Gold Run with cheat apk files can be a lot of fun and excitement, but it can also be challenging and tricky. You need to know some tips and tricks to make the most out of your game and avoid some common problems and issues. Here are some of them:</p>
48
- - How to collect more gold and get a high score with cheat apk files - One of the main goals of Talking Tom Gold Run is to collect as much gold as possible and get a high score. With cheat apk files, you can easily achieve this by using the money feature that gives you unlimited coins. You can also use the power-up feature that gives you magnets, jetpacks, or shields that help you collect more coins and avoid obstacles. However, you should also pay attention to the gold bars that appear on the road. These are worth more than coins and can boost your score significantly. You should also try to complete missions and achievements that reward you with extra gold and points. - How to unlock new characters and outfits with cheat apk files - Another goal of Talking Tom Gold Run is to unlock new characters and outfits that add more variety and fun to your game. With cheat apk files, you can easily achieve this by using the character feature that gives you access to all the characters and outfits in the game. You can choose from Talking Tom, Talking Angela, Talking Hank, Talking Ginger, Talking Ben, and many more. You can also choose from different outfits, such as superhero costumes, sports uniforms, or holiday themes. However, you should also try to unlock new worlds that have different themes and backgrounds. These worlds are unlocked by collecting enough gold bars in each world. You should also try to collect special items that are related to each character or world. - How to avoid common problems and issues with cheat apk files - Playing Talking Tom Gold Run with cheat apk files can also cause some problems and issues that may affect your game performance or enjoyment. Some of these problems are compatibility issues, security threats, legal consequences, or ethical dilemmas. To avoid these problems, you should follow these tips: - Always check the compatibility and security of the cheat apk file before you download and install it on your device. - Always scan the cheat apk file with an antivirus or anti-malware program before you open it. - Always enable unknown sources on your device settings only when you need to install the cheat apk file, and disable it afterwards. - Always backup your original game data before you use the cheat apk file, and restore it if you encounter any errors or glitches. - Always update your game app and your device software regularly to ensure optimal performance and security. - Always respect the original game developers and creators and their intellectual property rights. - Always use the cheat apk file moderately and responsibly, and only for your personal enjoyment. <h2>Conclusion</h2>
49
- <p>Talking Tom Gold Run is a fun and addictive endless runner game that features the famous Talking Tom and his friends. The game is all about chasing a pesky raccoon who stole your gold, while dodging obstacles, collecting coins, and unlocking new worlds.</p>
50
- <p>If you want to spice up your game and get some extra advantages, you can use cheat apk files that are modified versions of the original game app that allow you to access some features and functions that are not available in the official version. For example, you can get unlimited money, unlock all characters and outfits, activate power-ups, and more.</p>
51
- <p>However, using cheat apk files is not without risks. You may encounter some compatibility issues, security threats, or legal consequences. That's why you need to be careful and informed before you decide to use them.</ In this article, we have told you everything you need to know about Talking Tom Gold Run cheat apk files, including how to download, install, use, and enjoy them safely and effectively. We hope that you have found this article helpful and informative, and that you have learned something new and useful. If you have any questions, feedback, or opinions about Talking Tom Gold Run cheat apk files, please feel free to share them with us in the comments section below. We would love to hear from you and answer your queries. Thank you for reading this article and happy gaming! <h3>FAQs</h3>
52
- Here are some frequently asked questions about Talking Tom Gold Run cheat apk files that you may find interesting and helpful: - Q: What is the difference between cheat apk files and mod apk files? - A: Cheat apk files and mod apk files are similar terms that refer to modified versions of the original game app that allow you to access some features and functions that are not available in the official version. However, cheat apk files usually focus on giving you advantages and benefits in the game, such as unlimited money, power-ups, or unlocks. Mod apk files usually focus on changing the appearance or gameplay of the game, such as adding new graphics, sounds, or modes. - Q: Are cheat apk files legal and safe to use? - A: Cheat apk files are not legal and safe to use in general. They violate the terms and conditions of the original game developers and creators, and they may contain viruses, malware, or spyware that can harm your device or steal your personal information. They may also cause errors, glitches, or crashes in your game or device. However, some cheat apk files may be legal and safe to use if they are created by reputable and trustworthy sources, and if they are scanned and verified before installation. - Q: Can I use cheat apk files with other games? - A: Yes, you can use cheat apk files with other games if they are compatible and secure. However, you should always check the compatibility and security of the cheat apk file before you download and install it on your device. You should also backup your original game data before you use the cheat apk file, and restore it if you encounter any problems or issues. You should also respect the original game developers and creators and their intellectual property rights. - Q: Can I use cheat apk files online or offline? - A: You can use cheat apk files online or offline depending on the type and function of the cheat apk file. Some cheat apk files may work only online or only offline, while some may work both online and offline. However, you should be careful not to use cheat apk files online if they give you unfair advantages over other players or affect the game balance or integrity. You may be banned or penalized by the game developers or administrators if you do so. - Q: Can I update my game app after using cheat apk files? - A: You can update your game app after using cheat apk files if the update is compatible and secure. However, you should be aware that updating your game app may overwrite or delete your cheat apk file or its features and functions. You may also lose your game progress or data if you update your game app after using cheat apk file. Therefore, you should backup your game data before you update your game app, and reinstall your cheat apk file if necessary.</p> 197e85843d<br />
53
- <br />
54
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Become the Ultimate Soccer Champion with Real Football Soccer 2023 APK.md DELETED
@@ -1,101 +0,0 @@
1
- <br />
2
- <h1>Real Football 2023 APK: The Ultimate Soccer Game for Android</h1>
3
- <p>If you are a soccer fan who loves to play realistic and immersive games on your Android device, then you should definitely check out <strong>Real Football 2023 APK</strong>. This is a free game that lets you experience the thrill of the beautiful game like never before. You can choose your favorite international club from a wide selection of top teams and lead them to victory in the most prestigious soccer tournaments around the world. You can also train your players, improve their skills, develop winning strategies, and compete with other players online. In this article, we will tell you everything you need to know about Real Football 2023 APK, including its features, how to download and install it, and some frequently asked questions.</p>
4
- <h2>real football 2023 apk</h2><br /><p><b><b>Download File</b> ::: <a href="https://jinyurl.com/2uNMBh">https://jinyurl.com/2uNMBh</a></b></p><br /><br />
5
- <h2>Introduction</h2>
6
- <p><strong>Real Football 2023 APK</strong> is a game developed by <strong>Magic app</strong>, a studio that specializes in creating high-quality sports games for Android devices. The game is based on the popular <strong>Real Football</strong> series by <strong>Gameloft</strong>, which has been running since 2004. However, Real Football 2023 APK is not an official release by Gameloft, but rather a fan-made mod that enhances the original game with new features, graphics, gameplay, and content. The game is not available on Google Play Store, but you can download it from third-party sources such as <a href="(^1^)">APKCombo</a>. The game has received positive reviews from users who praise its realism, variety, and fun factor.</p>
7
- <p>You should download Real Football 2023 APK if you want to enjoy a soccer game that offers:</p>
8
- <ul>
9
- <li><strong>Realistic graphics and gameplay</strong>: The game features stunning graphics that make you feel like you are watching a real match on TV. The players, stadiums, kits, balls, and weather effects are all designed with attention to detail and accuracy. The gameplay is also smooth and responsive, with realistic physics, animations, and sound effects.</li>
10
- <li><strong>Thrilling PvP matches</strong>: The game features a multiplayer mode, where you can challenge other players from around the world in real-time matches. You can join or create leagues, tournaments, and clubs, and compete for glory and rewards. You can also chat with other players, make friends, and show off your skills.</li>
11
- <li><strong>Intuitive controls and skills</strong>: The game features easy-to-use controls that let you control your players with simple taps and swipes. You can also perform various actions such as passing, shooting, dribbling, tackling, and more. The game also features a skill system, where you can unlock and upgrade different skills for your players, such as speed, stamina, accuracy, and more.</li>
12
- </ul>
13
- <h2>Features of Real Football 2023 APK</h2>
14
- <p>Now that you have an overview of what Real Football 2023 APK is and why you should download it, let's take a closer look at some of its features in more detail.</p>
15
- <h3>Realistic Graphics and Gameplay</h3>
16
- <p>One of the main attractions of Real Football 2023 APK is its realistic graphics and gameplay. The game uses the latest technology to create stunning visuals that will impress any soccer fan. The game features:</p>
17
- <ul>
18
- <li><strong>High-definition graphics</strong>: The game uses high-resolution textures, lighting effects, shadows, and reflections to create a realistic and immersive environment. The game also supports different screen sizes and resolutions, so you can enjoy it on any device.</li>
19
- <li><strong>Realistic physics and animations</strong>: The game uses a realistic physics engine to simulate the movement and behavior of the ball, the players, and the environment. The game also features smooth and lifelike animations for every action and emotion of the players.</li>
20
- <li><strong>Different camera views and angles</strong>: The game lets you choose from different camera views and angles to suit your preference and style. You can switch between a bird's eye view, a close-up view, a side view, or a dynamic view. You can also zoom in or out, pan, tilt, or rotate the camera to get the best perspective.</li>
21
- </ul>
22
- <h3>Immersive Career Mode</h3>
23
- <p>Another feature of Real Football 2023 APK that will keep you hooked is its immersive career mode. This is where you can create your own soccer legend and lead your team to glory. The career mode features:</p>
24
- <ul>
25
- <li><strong>A wide selection of teams and players</strong>: The game features over 200 international clubs from different leagues and countries. You can choose your favorite team or create your own custom team with your own logo, name, and colors. You can also choose from over 3000 real players or create your own custom player with your own appearance, name, nationality, position, and attributes.</li>
26
- LG, Sony, Motorola, Xiaomi, OnePlus, and more. However, some devices may not be compatible due to hardware or software limitations. You can check the compatibility of your device by visiting the <a href="">official website</a> of the game.</p>
27
- <h3>Steps to Download and Install</h3>
28
- <p>Once you have verified that your device meets the requirements and is compatible with the game, you can follow these steps to download and install Real Football 2023 APK:</p>
29
- <ol>
30
- <li><strong>Enable unknown sources</strong>: Since the game is not available on Google Play Store, you need to enable unknown sources on your device to install it from a third-party source. To do this, go to your device's settings, then security, then unknown sources, and toggle it on.</li>
31
- <li><strong>Download the APK file</strong>: The next step is to download the APK file of the game from a reliable source. You can use the link provided by <a href="">APKCombo</a>, which is one of the most trusted and popular websites for downloading APK files. The file size is about 500 MB, so make sure you have enough space and a stable internet connection.</li>
32
- <li><strong>Install the APK file</strong>: After downloading the APK file, locate it in your device's file manager and tap on it to start the installation process. Follow the instructions on the screen and wait for the installation to complete.</li>
33
- <li><strong>Launch the game and enjoy</strong>: Once the installation is done, you can launch the game from your app drawer or home screen and enjoy playing Real Football 2023 APK.</li>
34
- </ol>
35
- <h2>Conclusion</h2>
36
- <p>Real Football 2023 APK is a game that every soccer fan should try. It offers realistic graphics and gameplay, immersive career mode, thrilling PvP matches, intuitive controls and skills, and much more. It is also free to download and play, so you have nothing to lose. If you want to experience the ultimate soccer game for Android, download Real Football 2023 APK today and start playing.</p>
37
- <h2>FAQs</h2>
38
- <p>Here are some of the most frequently asked questions about Real Football 2023 APK:</p>
39
- <p>real football 2023 apk download<br />
40
- real football 2023 apk mod<br />
41
- real football 2023 apk offline<br />
42
- real football 2023 apk obb<br />
43
- real football 2023 apk data<br />
44
- real football 2023 apk latest version<br />
45
- real football 2023 apk free download<br />
46
- real football 2023 apk android<br />
47
- real football 2023 apk unlimited money<br />
48
- real football 2023 apk hack<br />
49
- real football 2023 apk game<br />
50
- real football 2023 apk full version<br />
51
- real football 2023 apk revdl<br />
52
- real football 2023 apk rexdl<br />
53
- real football 2023 apk update<br />
54
- real football 2023 apk + data download<br />
55
- real football 2023 apk + obb download<br />
56
- real football 2023 apk + mod download<br />
57
- real football 2023 apk for pc<br />
58
- real football 2023 apk for ios<br />
59
- real football 2023 apk for windows<br />
60
- real football 2023 apk for mac<br />
61
- real football 2023 apk for laptop<br />
62
- real football 2023 apk for tablet<br />
63
- real football 2023 apk for chromebook<br />
64
- how to download real football 2023 apk<br />
65
- how to install real football 2023 apk<br />
66
- how to play real football 2023 apk<br />
67
- how to update real football 2023 apk<br />
68
- how to hack real football 2023 apk<br />
69
- how to get unlimited money in real football 2023 apk<br />
70
- how to get free coins in real football 2023 apk<br />
71
- how to unlock all teams in real football 2023 apk<br />
72
- how to fix lag in real football 2023 apk<br />
73
- how to transfer data in real football 2023 apk<br />
74
- what is new in real football 2023 apk<br />
75
- what is the size of real football 2023 apk<br />
76
- what is the rating of real football 2023 apk<br />
77
- what is the best team in real football 2023 apk<br />
78
- what is the best formation in real football 2023 apk<br />
79
- where to download real football 2023 apk<br />
80
- where to find obb file of real football 2023 apk<br />
81
- where to get modded version of real football 2023 apk<br />
82
- where to watch gameplay of real football 2023 apk<br />
83
- where to get tips and tricks for real football 2023 apk</p>
84
- <h3>Is Real Football 2023 APK safe and legal?</h3>
85
- <p>Yes, Real Football 2023 APK is safe and legal to download and play. The game does not contain any viruses, malware, or spyware that can harm your device or data. The game also does not violate any laws or regulations that prohibit modding or hacking of games. However, you should always download the game from a trusted source such as <a href="">APKCombo</a>, and not from any shady or suspicious websites that may contain fake or harmful files.</p>
86
- <h3>How much space does Real Football 2023 APK take on your device?</h3>
87
- <p>The game takes about 500 MB of space on your device after installation. However, you may need more space for additional data or updates that may be required in the future. Therefore, it is recommended that you have at least 1 GB of free space on your device before downloading and installing the game.</p>
88
- <h3>How often is Real Football 2023 APK updated?</h3>
89
- <p>The game is updated regularly by its developers to fix bugs, improve performance, add new features, and enhance the gameplay. You can check for updates by visiting the <a href="">official website</a> of the game or by following its social media accounts on Facebook, Twitter, Instagram, and YouTube. You can also enable automatic updates on your device's settings to get notified whenever there is a new update available.</p>
90
- <h3>Can you play Real Football 2023 APK offline?</h3>
91
- and seasonal challenges. You will also need an internet connection to update the game or contact the developers.</p>
92
- <h3>How can you contact the developers of Real Football 2023 APK?</h3>
93
- <p>If you have any questions, feedback, suggestions, or issues regarding the game, you can contact the developers of Real Football 2023 APK by using one of the following methods:</p>
94
- <ul>
95
- <li><strong>Email</strong>: You can send an email to <a href="mailto:[email protected]">[email protected]</a> and expect a reply within 24 hours.</li>
96
- <li><strong>Website</strong>: You can visit the <a href="">official website</a> of the game and fill out the contact form with your name, email, subject, and message.</li>
97
- <li><strong>Social media</strong>: You can follow the game's social media accounts on Facebook, Twitter, Instagram, and YouTube and send a direct message or leave a comment.</li>
98
- </ul>
99
- <p>I hope you enjoyed reading this article and learned something new about Real Football 2023 APK. If you did, please share it with your friends and family who might also be interested in this game. And don't forget to download and play Real Football 2023 APK today and have fun!</p> 401be4b1e0<br />
100
- <br />
101
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Download Doraemon X Apk and Play with Your Favorite Characters from the Anime.md DELETED
@@ -1,157 +0,0 @@
1
-
2
- <h1>Download Doraemon X APK: A Fun and Engaging Game for Doraemon Lovers</h1>
3
- <p>If you are a fan of the popular anime series Doraemon, you will love this game. Doraemon X APK is a mobile game that lets you interact with your favorite characters, such as Nobita, Shizuka, Gian, and Suneo. You can also enjoy an immersive story, solve puzzles, use gadgets, and explore a beautiful world. In this article, we will tell you everything you need to know about this game, including how to download and install it on your Android device, why you should play it, how to play it, what are the latest updates and features, what are the reviews and ratings, and some FAQs.</p>
4
- <h2>What is Doraemon X APK?</h2>
5
- <h3>A brief introduction to the game and its features</h3>
6
- <p>Doraemon X APK is a mobile game created by hotmilk Patreon, a developer who loves Doraemon. It is based on the anime series that follows the adventures of a robotic cat from the future who travels back in time to help a young boy named Nobita Nobi. The game offers an immersive experience in which you can engage with your favorite Doraemon characters. You can also enjoy a captivating plot that involves romance, comedy, drama, and mystery. The game has many features that make it fun and engaging, such as:</p>
7
- <h2>download doraemon x apk</h2><br /><p><b><b>DOWNLOAD</b> &mdash; <a href="https://jinyurl.com/2uNLRM">https://jinyurl.com/2uNLRM</a></b></p><br /><br />
8
- <ul>
9
- <li>High-quality graphics and sound effects that create a realistic and attractive environment.</li>
10
- <li>Multiple choices and dialogues that affect the outcome of the story.</li>
11
- <li>Various puzzles and obstacles that challenge your skills and logic.</li>
12
- <li>Different gadgets that you can use to help you in your quests.</li>
13
- <li>New content that is added regularly to keep you entertained.</li>
14
- </ul>
15
- <h3>How to download and install the game on your Android device</h3>
16
- <p>If you want to play this game on your Android device, you need to follow these simple steps:</p>
17
- <ol>
18
- <li>Go to [text](^2^) or [text](^9^) from your browser.</li>
19
- <li>Click on the download button to get the latest version of Doraemon X APK.</li>
20
- <li>Wait for the download to finish and then locate the file on your device.</li>
21
- <li>Tap on the file to install it. You may need to enable unknown sources in your settings if you have not done so before.</li>
22
- <li>Launch the game and enjoy!</li>
23
- </ol>
24
- <h2>Why should you play Doraemon X APK?</h2>
25
- <h3>The benefits of playing the game, such as enjoying the story, interacting with the characters, solving puzzles, and exploring the world</h3>
26
- <p>One of the main reasons why you should play Doraemon X APK is that it allows you to enjoy a captivating and immersive story that is based on the anime series. You can follow the plot and see how it unfolds as you make different choices and dialogues. You can also interact with your favorite Doraemon characters and see how they react to your actions. You can even romance some of them and experience their love stories. Moreover, you can solve puzzles and overcome obstacles that test your skills and logic. You can use various gadgets that Doraemon provides to help you in your quests. You can also explore a beautiful and diverse world that is full of surprises and secrets.</p>
27
- <h3>The challenges and rewards of playing the game, such as overcoming obstacles, using gadgets, and unlocking new content</h3>
28
- <p>Another reason why you should play Doraemon X APK is that it offers you many challenges and rewards that make the game more exciting and satisfying. You will face different obstacles and enemies that will try to stop you from achieving your goals. You will need to use your wits and creativity to overcome them. You will also need to use the gadgets that Doraemon gives you wisely, as they have limited uses and effects. You will also unlock new content as you progress in the game, such as new scenes, characters, gadgets, and locations. You will also earn coins and gems that you can use to buy more items and upgrades.</p>
29
- <p>download doraemon x mod apk<br />
30
- download doraemon x latest version apk<br />
31
- download doraemon x android apk<br />
32
- download doraemon x apk for free<br />
33
- download doraemon x apk full unlocked<br />
34
- download doraemon x apk no ads<br />
35
- download doraemon x apk offline<br />
36
- download doraemon x apk unlimited money<br />
37
- download doraemon x apk with obb<br />
38
- download doraemon x apk from yesmody<br />
39
- how to download doraemon x apk<br />
40
- where to download doraemon x apk<br />
41
- is it safe to download doraemon x apk<br />
42
- can i download doraemon x apk on pc<br />
43
- can i download doraemon x apk on ios<br />
44
- best site to download doraemon x apk<br />
45
- best way to download doraemon x apk<br />
46
- why should i download doraemon x apk<br />
47
- what is doraemon x apk<br />
48
- what can i do with doraemon x apk<br />
49
- features of doraemon x apk<br />
50
- benefits of downloading doraemon x apk<br />
51
- reviews of doraemon x apk<br />
52
- ratings of doraemon x apk<br />
53
- gameplay of doraemon x apk<br />
54
- tips and tricks for doraemon x apk<br />
55
- cheats and hacks for doraemon x apk<br />
56
- updates and news for doraemon x apk<br />
57
- alternatives to doraemon x apk<br />
58
- similar games to doraemon x apk<br />
59
- download nobita adventure in doraemon x apk<br />
60
- download shizuka love story in doraemon x apk<br />
61
- download gian and suneo quest in doraemon x apk<br />
62
- download dorami and dekisugi mission in doraemon x apk<br />
63
- download mini games in doraemon x apk<br />
64
- download gadgets and tools in doraemon x apk<br />
65
- download wallpapers and stickers in doraemon x apk<br />
66
- download themes and skins in doraemon x apk<br />
67
- download soundtracks and ringtones in doraemon x apk<br />
68
- download comics and manga in doraemon x apk<br />
69
- compare doraemon x apk with other apps<br />
70
- learn more about doraemon x apk<br />
71
- watch videos of doraemon x apk<br />
72
- share your experience with doraemon x apk<br />
73
- join the community of doraemon x apk fans<br />
74
- get support for doraemon x apk issues<br />
75
- contact the developer of doraemon x apk <br />
76
- give feedback and suggestions for doraemon x apk <br />
77
- report bugs and problems with doraemon x apk</p>
78
- <h2>How to play Doraemon X APK?</h2>
79
- <h3>The basic gameplay mechanics and controls of the game</h3>
80
- <p>The gameplay of Doraemon X APK is simple and intuitive. You can control the game using your touch screen or a virtual joystick. You can move your character by swiping or tapping on the screen. You can also interact with other characters and objects by tapping on them. You can access the menu by tapping on the icon on the top right corner of the screen. From there, you can see your inventory, gadgets, stats, settings, and save or load your game. You can also pause or resume the game by tapping on the icon on the top left corner of the screen.</p>
81
- <h3>The tips and tricks to master the game and have more fun</h3>
82
- <p>If you want to master the game and have more fun, here are some tips and tricks that you should know:</p>
83
- <ul>
84
- <li>Pay attention to the dialogues and choices, as they affect the outcome of the story and your relationships with other characters.</li>
85
- <li>Explore every location and find hidden items and secrets that can help you in your quests.</li>
86
- <li>Use your gadgets wisely, as they have limited uses and effects. Some gadgets are more useful in certain situations than others.</li>
87
- <li>Save your game frequently, as you may encounter unexpected events or errors that can affect your progress.</li>
88
- <li>Check for updates regularly, as the developer adds new content and features to the game.</li>
89
- </ul>
90
- <h2>What are the latest updates and features of Doraemon X APK?</h2>
91
- <h3>The new version and improvements of the game</h3>
92
- <p>The latest version of Doraemon X APK is 1.0.5, which was released on June 19, 2023. This version includes several improvements and bug fixes, such as:</p>
93
- <ul>
94
- <li>Improved graphics and sound quality.</li>
95
- <li>Optimized performance and compatibility with different devices.</li>
96
- <li>Fixed some errors and glitches that caused crashes or freezes.</li>
97
- <li>Added some new dialogues and scenes to the story.</li>
98
- <li>Added some new gadgets and items to the inventory.</li>
99
- </ul>
100
- <h3>The future plans and expectations of the game</h3>
101
- <p>The developer of Doraemon X APK has many plans and expectations for the future of the game, such as:</p>
102
- <ul>
103
- <li>Adding more content and features to the game, such as new chapters, characters, gadgets, locations, puzzles, etc.</li>
104
- <li>Enhancing the gameplay experience and quality of the game, such as improving the graphics, sound, animation, etc.</li>
105
- <li>Listening to the feedback and suggestions from the players and implementing them in the game.</li>
106
- <li>Making the game available for other platforms, such as iOS, Windows, etc.</li>
107
- </ul>
108
- <h2>What are the reviews and ratings of Doraemon X APK?</h2>
109
- <h3>The positive feedback and testimonials from the players</h3>
110
- <p>Doraemon X APK has received many positive feedbacks and testimonials from the players who have tried and enjoyed the game. Here are some of the reviews and ratings that the game has received on various platforms:</p>
111
- <table>
112
- <tr>
113
- <th>Platform</th>
114
- <th>Rating</th>
115
- <th>Review</th>
116
- </tr>
117
- <tr>
118
- <td>[text]</td>
119
- <td>4.8/5</td>
120
- <td>"This game is amazing. I love Doraemon and this game makes me feel like I'm part of the story. The graphics are awesome and the gameplay is smooth. The puzzles are challenging and the gadgets are fun to use. I highly recommend this game to anyone who loves Doraemon."</td>
121
- </tr>
122
- <tr>
123
- <td>[text]</td>
124
- <td>4.7/5</td>
125
- <td>"I'm a big fan of Doraemon and this game is a dream come true. The game has a great story and characters. The choices and dialogues are interesting and affect the outcome. The game also has many secrets and surprises that keep me hooked. I can't wait for more updates and features."</td>
126
- </tr>
127
- <tr>
128
- <td>[text]</td>
129
- <td>4.6/5</td>
130
- <td>"This game is awesome. It has everything I want in a Doraemon game. The game has a beautiful world and a captivating plot. The game also has many puzzles and obstacles that test my skills and logic. The game also has many gadgets that I can use to help me in my quests. This game is a must-play for Doraemon lovers."</td>
131
- </tr>
132
- </table>
133
- <h3>The drawbacks and limitations of the game</h3>
134
- <p>Despite the positive feedbacks and testimonials, Doraemon X APK also has some drawbacks and limitations that may affect some players' enjoyment of the game. Here are some of the drawbacks and limitations that the game has:</p>
135
- <ul>
136
- <li>The game is not available for other platforms, such as iOS, Windows, etc.</li>
137
- <li>The game may not be compatible with some Android devices or versions.</li>
138
- <li>The game may have some errors or glitches that cause crashes or freezes.</li>
139
- <li>The game may have some content or scenes that are not suitable for younger audiences.</li>
140
- <li>The game may require a stable internet connection to download or update.</li>
141
- </ul>
142
- <h2>Conclusion</h2>
143
- <h3>A summary of the main points and a call to action for the readers</h3>
144
- <p>Doraemon X APK is a mobile game that lets you interact with your favorite Doraemon characters, enjoy an immersive story, solve puzzles, use gadgets, and explore a beautiful world. It is a fun and engaging game that will appeal to Doraemon lovers and anyone who likes adventure games. You can download and install the game on your Android device easily by following the steps we have provided in this article. You can also learn why you should play the game, how to play the game, what are the latest updates and features, what are the reviews and ratings, and some FAQs. If you are looking for a new and exciting game to play, you should give Doraemon X APK a try. You will not regret it!</p>
145
- <h2>FAQs</h2>
146
- <h3>Q1. What is the size of Doraemon X APK?</h3>
147
- <p>A1. The size of Doraemon X APK is about 200 MB.</p>
148
- <h3>Q2. Is Doraemon X APK compatible with all Android devices?</h3>
149
- <p>A2. Doraemon X APK is compatible with most Android devices that have Android 4.4 or higher.</p>
150
- <h3>Q3. Is Doraemon X APK safe and secure to download?</h3>
151
- <p>A3. Yes, Doraemon X APK is safe and secure to download from trusted sources, such as [text] or [text]. However, you should always scan the file before installing it on your device.</p>
152
- <h3>Q4. Is there a mod version of Doraemon X APK?</h3>
153
- <p>A4. Yes, there is a mod version of Doraemon X APK that offers unlimited coins, gems, gadgets, etc. However, we do not recommend using it as it may cause errors or glitches in the game or harm your device.</p>
154
- <h3>Q5. Where can I find more information about Doraemon X APK?</h3>
155
- <p>A5. You can find more information about Doraemon X APK on its official website [text] or its social media pages [text] or [text].</p> 401be4b1e0<br />
156
- <br />
157
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/1phancelerku/anime-remove-background/Experience Realistic Gameplay and Physics with Pro League Soccer 2023 APK.md DELETED
@@ -1,99 +0,0 @@
1
-
2
- <h1>Pro League Soccer 2023 APK Download: How to Play the Latest Mobile Football Game</h1>
3
- <p>If you are a fan of football games, you might have heard of Pro League Soccer 2023, a new mobile game that lets you select and upgrade your club, join various tournaments, and compete with realistic artificial intelligence. In this article, we will tell you what Pro League Soccer 2023 is, what features it has, and how to download and install it on your Android or Windows devices.</p>
4
- <h2>pro league soccer 2023 apk download</h2><br /><p><b><b>Download File</b> &#10027;&#10027;&#10027; <a href="https://jinyurl.com/2uNO4g">https://jinyurl.com/2uNO4g</a></b></p><br /><br />
5
- <h2>What is Pro League Soccer 2023?</h2>
6
- <p>Pro League Soccer 2023 is a mobile football game developed by Rasu Games, a Turkish game studio. It was released on May 30, 2023, and has since gained over 50 million downloads on Google Play. The game aims to provide a realistic and immersive football experience with fluent controls, character physics, ball physics, and artificial intelligence. You can choose from over 20 club leagues and over 10 national leagues, each with their own cups and tournaments. You can also edit all the competition, team, and player names in the game according to your preference, and load unique logos for teams from the internet.</p>
7
- <h3>Features of Pro League Soccer 2023</h3>
8
- <p>Pro League Soccer 2023 has many features that make it stand out from other football games. Here are some of them:</p>
9
- <h4>Gameplay</h4>
10
- <p>The game offers 360-degree flexibility of movement with fluent controls and character physics. You can feel the reality with directional passes and shots. You can also customize the camera angle, graphics quality, sound effects, and language settings.</p>
11
- <h4>Ball Control</h4>
12
- <p>The game has improved ball physics that allow you to throw curvilinear shots with accuracy. You can also provide instant ball control and shots with accurate timings.</p>
13
- <h4>Artificial Intelligence</h4>
14
- <p>The game has compeller and tiring, realistic artificial intelligence modes that challenge your skills. You have to fight against opponents who are constantly looking for your deficit and opportunity. You can also adjust the difficulty level of the game according to your preference.</p>
15
- <p>pro league soccer 2023 android game free download<br />
16
- pls apk latest version 1.0.40 rasu games<br />
17
- pro league soccer 2023 mobile football game<br />
18
- download pro league soccer xapk for android<br />
19
- pro league soccer 2023 gameplay and features<br />
20
- pro league soccer 2023 national leagues and cups<br />
21
- pro league soccer 2023 edit all data and logos<br />
22
- pro league soccer 2023 realistic artificial intelligence<br />
23
- pro league soccer 2023 ball control and physics<br />
24
- pro league soccer 2023 club leagues and tournaments<br />
25
- how to install pro league soccer 2023 apk on android<br />
26
- pro league soccer 2023 reviews and ratings<br />
27
- pro league soccer 2023 mod apk unlimited money<br />
28
- pro league soccer 2023 tips and tricks<br />
29
- pro league soccer 2023 best teams and players<br />
30
- pro league soccer 2023 update and patch notes<br />
31
- pro league soccer 2023 offline mode and multiplayer<br />
32
- pro league soccer 2023 cheats and hacks<br />
33
- pro league soccer 2023 support and feedback<br />
34
- pro league soccer 2023 download size and requirements<br />
35
- pro league soccer 2023 vs dream league soccer 2023<br />
36
- pro league soccer 2023 european stars league<br />
37
- pro league soccer 2023 american stars league<br />
38
- pro league soccer 2023 asian stars league<br />
39
- pro league soccer 2023 african stars league<br />
40
- pro league soccer 2023 world cup mode<br />
41
- pro league soccer 2023 european cup mode<br />
42
- pro league soccer 2023 american cup mode<br />
43
- pro league soccer 2023 asian cup mode<br />
44
- pro league soccer 2023 african cup mode<br />
45
- pro league soccer 2023 english premier league teams<br />
46
- pro league soccer 2023 spanish la liga teams<br />
47
- pro league soccer 2023 italian serie a teams<br />
48
- pro league soccer 2023 german bundesliga teams<br />
49
- pro league soccer 2023 french ligue 1 teams<br />
50
- pro league soccer 2023 portuguese primeira liga teams<br />
51
- pro league soccer 2023 dutch eredivisie teams<br />
52
- pro league soccer 2023 turkish super lig teams<br />
53
- pro league soccer 2023 russian premier liga teams<br />
54
- pro league soccer 2023 brazilian serie a teams<br />
55
- pro league soccer 2023 argentine primera division teams<br />
56
- pro league soccer 2023 mexican liga mx teams<br />
57
- pro league soccer 2023 usa major league soccer teams<br />
58
- pro league soccer 2023 japanese j1 league teams<br />
59
- pro league soccer 2023 south korean k-league teams<br />
60
- pro league soccer 2023 indonesian liga shopee teams</p>
61
- <h4>Edit All Data</h4>
62
- <p>The game gives you the freedom to edit all the competition, team, and player names in the game according to your preference. You can also load unique logos for teams from the internet. This way, you can create your own custom league and play with your favorite teams and players.</p>
63
- <h3>How to Download and Install Pro League Soccer 2023 APK on Android Devices</h3>
64
- <p>If you want to play Pro League Soccer 2023 on your Android device, you need to download and install the APK file of the game. Here are the steps to do so:</p>
65
- <h4>Step 1: Enable Unknown Sources</h4>
66
- <p>Before you can install any APK file on your Android device, you need to enable unknown sources in your security settings. To do this, go to Settings > Security > Unknown Sources and toggle it on. This will allow you to install apps from sources other than Google Play.</p>
67
- <h4>Step 2: Download the APK File</h4>
68
- <p>Next, you need to download the APK file of Pro League Soccer 2023 from a reliable source. You can use this link to download the latest version of the game (version 1.0.40) from APKCombo.com. The file size is about 66 MB.</p> <h4>Step 3: Install the APK File</h4>
69
- <p>After you have downloaded the APK file, you need to install it on your device. To do this, locate the file in your file manager and tap on it. You will see a prompt asking you to confirm the installation. Tap on Install and wait for the process to finish.</p>
70
- <h4>Step 4: Launch the Game and Enjoy</h4>
71
- <p>Once the installation is complete, you can launch the game from your app drawer or home screen. You will see a splash screen with the game logo and then a main menu with various options. You can start playing the game by selecting your club, league, and tournament. You can also access the settings, edit mode, and help menu from the main menu.</p>
72
- <h3>How to Download and Install Pro League Soccer 2023 APK on Windows PC</h3>
73
- <p>If you want to play Pro League Soccer 2023 on your Windows PC, you need to use an Android emulator that can run APK files. An Android emulator is a software that simulates an Android device on your PC, allowing you to run Android apps and games. One of the best Android emulators for Windows is LDPlayer, which is fast, stable, and compatible with most games. Here are the steps to download and install Pro League Soccer 2023 APK on Windows PC using LDPlayer:</p>
74
- <h4>Step 1: Download and Install LDPlayer - Android Emulator</h4>
75
- <p>First, you need to download and install LDPlayer on your PC. You can use this link to download the latest version of LDPlayer (version 4.0.66) from its official website. The file size is about 420 MB. After downloading the file, run it and follow the instructions to install LDPlayer on your PC.</p>
76
- <h4>Step 2: Drag Pro League Soccer 2023 APK to the LDPlayer App</h4>
77
- <p>Next, you need to download the APK file of Pro League Soccer 2023 from the same link as before. Then, open LDPlayer and drag the APK file to the LDPlayer app. You will see a prompt asking you to confirm the installation. Click on Install and wait for the process to finish.</p>
78
- <h4>Step 3: Launch the Game and Enjoy</h4>
79
- <p>Once the installation is complete, you can launch the game from the LDPlayer app drawer or home screen. You will see the same splash screen and main menu as before. You can start playing the game by selecting your club, league, and tournament. You can also access the settings, edit mode, and help menu from the main menu.</p>
80
- <h2>Conclusion</h2>
81
- <p>Pro League Soccer 2023 is a mobile football game that offers a realistic and immersive football experience with fluent controls, character physics, ball physics, and artificial intelligence. You can choose from over 20 club leagues and over 10 national leagues, each with their own cups and tournaments. You can also edit all the competition, team, and player names in the game according to your preference, and load unique logos for teams from the internet.</p>
82
- <p>If you want to play Pro League Soccer 2023 on your Android or Windows devices, you need to download and install the APK file of the game from a reliable source. You can follow the steps in this article to do so easily and safely.</p>
83
- <p>We hope you enjoyed this article and found it helpful. If you have any questions or feedback, please feel free to leave a comment below. Thank you for reading!</p>
84
- <h2>Frequently Asked Questions</h2>
85
- <p>Here are some of the most common questions that people ask about Pro League Soccer 2023:</p>
86
- <ol>
87
- <li><b>Is Pro League Soccer 2023 free to play?</b></li>
88
- <p>Yes, Pro League Soccer 2023 is free to play and does not require any in-app purchases or subscriptions. However, it does contain ads that can be removed by watching videos or paying a small fee.</p>
89
- <li><b>Is Pro League Soccer 2023 online or offline?</b></li>
90
- <p>Pro League Soccer 2023 is mainly an offline game that does not require an internet connection to play. However, some features such as loading logos from the internet or watching videos to remove ads do require an internet connection.</p>
91
- <li><b>Is Pro League Soccer 2023 compatible with my device?</b></li>
92
- <p>Pro League Soccer 2023 is compatible with most Android devices that have Android version 5.0 or higher and at least 1 GB of RAM. It is also compatible with most Windows PCs that have Windows XP or higher and at least 2 GB of RAM.</p>
93
- <li><b>How can I update Pro League Soccer 2023?</b></ <p>li><b>How can I update Pro League Soccer 2023?</b></li>
94
- <p>If you have downloaded Pro League Soccer 2023 from Google Play, you can update it automatically or manually from the app store. If you have downloaded Pro League Soccer 2023 from APKCombo.com, you can update it by downloading the latest version of the APK file and installing it over the existing one.</p>
95
- <li><b>How can I contact the developer of Pro League Soccer 2023?</b></li>
96
- <p>If you have any suggestions, complaints, or bug reports, you can contact the developer of Pro League Soccer 2023 by sending an email to [email protected]. You can also follow them on Facebook, Twitter, and Instagram for the latest news and updates.</p>
97
- </ol></p> 197e85843d<br />
98
- <br />
99
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/2-2/blockchain.ai/index.php DELETED
@@ -1,24 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>
13
- You can modify this app directly by editing <i>index.html</i> in the
14
- Files and versions tab.
15
- </p>
16
- <p>
17
- Also don't forget to check the
18
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank"
19
- >Spaces documentation</a
20
- >.
21
- </p>
22
- </div>
23
- </body>
24
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/4Taps/SadTalker/src/face3d/models/facerecon_model.py DELETED
@@ -1,220 +0,0 @@
1
- """This script defines the face reconstruction model for Deep3DFaceRecon_pytorch
2
- """
3
-
4
- import numpy as np
5
- import torch
6
- from src.face3d.models.base_model import BaseModel
7
- from src.face3d.models import networks
8
- from src.face3d.models.bfm import ParametricFaceModel
9
- from src.face3d.models.losses import perceptual_loss, photo_loss, reg_loss, reflectance_loss, landmark_loss
10
- from src.face3d.util import util
11
- from src.face3d.util.nvdiffrast import MeshRenderer
12
- # from src.face3d.util.preprocess import estimate_norm_torch
13
-
14
- import trimesh
15
- from scipy.io import savemat
16
-
17
- class FaceReconModel(BaseModel):
18
-
19
- @staticmethod
20
- def modify_commandline_options(parser, is_train=False):
21
- """ Configures options specific for CUT model
22
- """
23
- # net structure and parameters
24
- parser.add_argument('--net_recon', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50'], help='network structure')
25
- parser.add_argument('--init_path', type=str, default='./checkpoints/init_model/resnet50-0676ba61.pth')
26
- parser.add_argument('--use_last_fc', type=util.str2bool, nargs='?', const=True, default=False, help='zero initialize the last fc')
27
- parser.add_argument('--bfm_folder', type=str, default='./checkpoints/BFM_Fitting/')
28
- parser.add_argument('--bfm_model', type=str, default='BFM_model_front.mat', help='bfm model')
29
-
30
- # renderer parameters
31
- parser.add_argument('--focal', type=float, default=1015.)
32
- parser.add_argument('--center', type=float, default=112.)
33
- parser.add_argument('--camera_d', type=float, default=10.)
34
- parser.add_argument('--z_near', type=float, default=5.)
35
- parser.add_argument('--z_far', type=float, default=15.)
36
-
37
- if is_train:
38
- # training parameters
39
- parser.add_argument('--net_recog', type=str, default='r50', choices=['r18', 'r43', 'r50'], help='face recog network structure')
40
- parser.add_argument('--net_recog_path', type=str, default='checkpoints/recog_model/ms1mv3_arcface_r50_fp16/backbone.pth')
41
- parser.add_argument('--use_crop_face', type=util.str2bool, nargs='?', const=True, default=False, help='use crop mask for photo loss')
42
- parser.add_argument('--use_predef_M', type=util.str2bool, nargs='?', const=True, default=False, help='use predefined M for predicted face')
43
-
44
-
45
- # augmentation parameters
46
- parser.add_argument('--shift_pixs', type=float, default=10., help='shift pixels')
47
- parser.add_argument('--scale_delta', type=float, default=0.1, help='delta scale factor')
48
- parser.add_argument('--rot_angle', type=float, default=10., help='rot angles, degree')
49
-
50
- # loss weights
51
- parser.add_argument('--w_feat', type=float, default=0.2, help='weight for feat loss')
52
- parser.add_argument('--w_color', type=float, default=1.92, help='weight for loss loss')
53
- parser.add_argument('--w_reg', type=float, default=3.0e-4, help='weight for reg loss')
54
- parser.add_argument('--w_id', type=float, default=1.0, help='weight for id_reg loss')
55
- parser.add_argument('--w_exp', type=float, default=0.8, help='weight for exp_reg loss')
56
- parser.add_argument('--w_tex', type=float, default=1.7e-2, help='weight for tex_reg loss')
57
- parser.add_argument('--w_gamma', type=float, default=10.0, help='weight for gamma loss')
58
- parser.add_argument('--w_lm', type=float, default=1.6e-3, help='weight for lm loss')
59
- parser.add_argument('--w_reflc', type=float, default=5.0, help='weight for reflc loss')
60
-
61
- opt, _ = parser.parse_known_args()
62
- parser.set_defaults(
63
- focal=1015., center=112., camera_d=10., use_last_fc=False, z_near=5., z_far=15.
64
- )
65
- if is_train:
66
- parser.set_defaults(
67
- use_crop_face=True, use_predef_M=False
68
- )
69
- return parser
70
-
71
- def __init__(self, opt):
72
- """Initialize this model class.
73
-
74
- Parameters:
75
- opt -- training/test options
76
-
77
- A few things can be done here.
78
- - (required) call the initialization function of BaseModel
79
- - define loss function, visualization images, model names, and optimizers
80
- """
81
- BaseModel.__init__(self, opt) # call the initialization method of BaseModel
82
-
83
- self.visual_names = ['output_vis']
84
- self.model_names = ['net_recon']
85
- self.parallel_names = self.model_names + ['renderer']
86
-
87
- self.facemodel = ParametricFaceModel(
88
- bfm_folder=opt.bfm_folder, camera_distance=opt.camera_d, focal=opt.focal, center=opt.center,
89
- is_train=self.isTrain, default_name=opt.bfm_model
90
- )
91
-
92
- fov = 2 * np.arctan(opt.center / opt.focal) * 180 / np.pi
93
- self.renderer = MeshRenderer(
94
- rasterize_fov=fov, znear=opt.z_near, zfar=opt.z_far, rasterize_size=int(2 * opt.center)
95
- )
96
-
97
- if self.isTrain:
98
- self.loss_names = ['all', 'feat', 'color', 'lm', 'reg', 'gamma', 'reflc']
99
-
100
- self.net_recog = networks.define_net_recog(
101
- net_recog=opt.net_recog, pretrained_path=opt.net_recog_path
102
- )
103
- # loss func name: (compute_%s_loss) % loss_name
104
- self.compute_feat_loss = perceptual_loss
105
- self.comupte_color_loss = photo_loss
106
- self.compute_lm_loss = landmark_loss
107
- self.compute_reg_loss = reg_loss
108
- self.compute_reflc_loss = reflectance_loss
109
-
110
- self.optimizer = torch.optim.Adam(self.net_recon.parameters(), lr=opt.lr)
111
- self.optimizers = [self.optimizer]
112
- self.parallel_names += ['net_recog']
113
- # Our program will automatically call <model.setup> to define schedulers, load networks, and print networks
114
-
115
- def set_input(self, input):
116
- """Unpack input data from the dataloader and perform necessary pre-processing steps.
117
-
118
- Parameters:
119
- input: a dictionary that contains the data itself and its metadata information.
120
- """
121
- self.input_img = input['imgs'].to(self.device)
122
- self.atten_mask = input['msks'].to(self.device) if 'msks' in input else None
123
- self.gt_lm = input['lms'].to(self.device) if 'lms' in input else None
124
- self.trans_m = input['M'].to(self.device) if 'M' in input else None
125
- self.image_paths = input['im_paths'] if 'im_paths' in input else None
126
-
127
- def forward(self, output_coeff, device):
128
- self.facemodel.to(device)
129
- self.pred_vertex, self.pred_tex, self.pred_color, self.pred_lm = \
130
- self.facemodel.compute_for_render(output_coeff)
131
- self.pred_mask, _, self.pred_face = self.renderer(
132
- self.pred_vertex, self.facemodel.face_buf, feat=self.pred_color)
133
-
134
- self.pred_coeffs_dict = self.facemodel.split_coeff(output_coeff)
135
-
136
-
137
- def compute_losses(self):
138
- """Calculate losses, gradients, and update network weights; called in every training iteration"""
139
-
140
- assert self.net_recog.training == False
141
- trans_m = self.trans_m
142
- if not self.opt.use_predef_M:
143
- trans_m = estimate_norm_torch(self.pred_lm, self.input_img.shape[-2])
144
-
145
- pred_feat = self.net_recog(self.pred_face, trans_m)
146
- gt_feat = self.net_recog(self.input_img, self.trans_m)
147
- self.loss_feat = self.opt.w_feat * self.compute_feat_loss(pred_feat, gt_feat)
148
-
149
- face_mask = self.pred_mask
150
- if self.opt.use_crop_face:
151
- face_mask, _, _ = self.renderer(self.pred_vertex, self.facemodel.front_face_buf)
152
-
153
- face_mask = face_mask.detach()
154
- self.loss_color = self.opt.w_color * self.comupte_color_loss(
155
- self.pred_face, self.input_img, self.atten_mask * face_mask)
156
-
157
- loss_reg, loss_gamma = self.compute_reg_loss(self.pred_coeffs_dict, self.opt)
158
- self.loss_reg = self.opt.w_reg * loss_reg
159
- self.loss_gamma = self.opt.w_gamma * loss_gamma
160
-
161
- self.loss_lm = self.opt.w_lm * self.compute_lm_loss(self.pred_lm, self.gt_lm)
162
-
163
- self.loss_reflc = self.opt.w_reflc * self.compute_reflc_loss(self.pred_tex, self.facemodel.skin_mask)
164
-
165
- self.loss_all = self.loss_feat + self.loss_color + self.loss_reg + self.loss_gamma \
166
- + self.loss_lm + self.loss_reflc
167
-
168
-
169
- def optimize_parameters(self, isTrain=True):
170
- self.forward()
171
- self.compute_losses()
172
- """Update network weights; it will be called in every training iteration."""
173
- if isTrain:
174
- self.optimizer.zero_grad()
175
- self.loss_all.backward()
176
- self.optimizer.step()
177
-
178
- def compute_visuals(self):
179
- with torch.no_grad():
180
- input_img_numpy = 255. * self.input_img.detach().cpu().permute(0, 2, 3, 1).numpy()
181
- output_vis = self.pred_face * self.pred_mask + (1 - self.pred_mask) * self.input_img
182
- output_vis_numpy_raw = 255. * output_vis.detach().cpu().permute(0, 2, 3, 1).numpy()
183
-
184
- if self.gt_lm is not None:
185
- gt_lm_numpy = self.gt_lm.cpu().numpy()
186
- pred_lm_numpy = self.pred_lm.detach().cpu().numpy()
187
- output_vis_numpy = util.draw_landmarks(output_vis_numpy_raw, gt_lm_numpy, 'b')
188
- output_vis_numpy = util.draw_landmarks(output_vis_numpy, pred_lm_numpy, 'r')
189
-
190
- output_vis_numpy = np.concatenate((input_img_numpy,
191
- output_vis_numpy_raw, output_vis_numpy), axis=-2)
192
- else:
193
- output_vis_numpy = np.concatenate((input_img_numpy,
194
- output_vis_numpy_raw), axis=-2)
195
-
196
- self.output_vis = torch.tensor(
197
- output_vis_numpy / 255., dtype=torch.float32
198
- ).permute(0, 3, 1, 2).to(self.device)
199
-
200
- def save_mesh(self, name):
201
-
202
- recon_shape = self.pred_vertex # get reconstructed shape
203
- recon_shape[..., -1] = 10 - recon_shape[..., -1] # from camera space to world space
204
- recon_shape = recon_shape.cpu().numpy()[0]
205
- recon_color = self.pred_color
206
- recon_color = recon_color.cpu().numpy()[0]
207
- tri = self.facemodel.face_buf.cpu().numpy()
208
- mesh = trimesh.Trimesh(vertices=recon_shape, faces=tri, vertex_colors=np.clip(255. * recon_color, 0, 255).astype(np.uint8))
209
- mesh.export(name)
210
-
211
- def save_coeff(self,name):
212
-
213
- pred_coeffs = {key:self.pred_coeffs_dict[key].cpu().numpy() for key in self.pred_coeffs_dict}
214
- pred_lm = self.pred_lm.cpu().numpy()
215
- pred_lm = np.stack([pred_lm[:,:,0],self.input_img.shape[2]-1-pred_lm[:,:,1]],axis=2) # transfer to image coordinate
216
- pred_coeffs['lm68'] = pred_lm
217
- savemat(name,pred_coeffs)
218
-
219
-
220
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIFILMS/StyleGANEX/models/stylegan2/simple_augment.py DELETED
@@ -1,478 +0,0 @@
1
- import math
2
-
3
- import torch
4
- from torch import autograd
5
- from torch.nn import functional as F
6
- import numpy as np
7
-
8
- from torch import distributed as dist
9
- #from distributed import reduce_sum
10
- from models.stylegan2.op2 import upfirdn2d
11
-
12
- def reduce_sum(tensor):
13
- if not dist.is_available():
14
- return tensor
15
-
16
- if not dist.is_initialized():
17
- return tensor
18
-
19
- tensor = tensor.clone()
20
- dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
21
-
22
- return tensor
23
-
24
-
25
- class AdaptiveAugment:
26
- def __init__(self, ada_aug_target, ada_aug_len, update_every, device):
27
- self.ada_aug_target = ada_aug_target
28
- self.ada_aug_len = ada_aug_len
29
- self.update_every = update_every
30
-
31
- self.ada_update = 0
32
- self.ada_aug_buf = torch.tensor([0.0, 0.0], device=device)
33
- self.r_t_stat = 0
34
- self.ada_aug_p = 0
35
-
36
- @torch.no_grad()
37
- def tune(self, real_pred):
38
- self.ada_aug_buf += torch.tensor(
39
- (torch.sign(real_pred).sum().item(), real_pred.shape[0]),
40
- device=real_pred.device,
41
- )
42
- self.ada_update += 1
43
-
44
- if self.ada_update % self.update_every == 0:
45
- self.ada_aug_buf = reduce_sum(self.ada_aug_buf)
46
- pred_signs, n_pred = self.ada_aug_buf.tolist()
47
-
48
- self.r_t_stat = pred_signs / n_pred
49
-
50
- if self.r_t_stat > self.ada_aug_target:
51
- sign = 1
52
-
53
- else:
54
- sign = -1
55
-
56
- self.ada_aug_p += sign * n_pred / self.ada_aug_len
57
- self.ada_aug_p = min(1, max(0, self.ada_aug_p))
58
- self.ada_aug_buf.mul_(0)
59
- self.ada_update = 0
60
-
61
- return self.ada_aug_p
62
-
63
-
64
- SYM6 = (
65
- 0.015404109327027373,
66
- 0.0034907120842174702,
67
- -0.11799011114819057,
68
- -0.048311742585633,
69
- 0.4910559419267466,
70
- 0.787641141030194,
71
- 0.3379294217276218,
72
- -0.07263752278646252,
73
- -0.021060292512300564,
74
- 0.04472490177066578,
75
- 0.0017677118642428036,
76
- -0.007800708325034148,
77
- )
78
-
79
-
80
- def translate_mat(t_x, t_y, device="cpu"):
81
- batch = t_x.shape[0]
82
-
83
- mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1)
84
- translate = torch.stack((t_x, t_y), 1)
85
- mat[:, :2, 2] = translate
86
-
87
- return mat
88
-
89
-
90
- def rotate_mat(theta, device="cpu"):
91
- batch = theta.shape[0]
92
-
93
- mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1)
94
- sin_t = torch.sin(theta)
95
- cos_t = torch.cos(theta)
96
- rot = torch.stack((cos_t, -sin_t, sin_t, cos_t), 1).view(batch, 2, 2)
97
- mat[:, :2, :2] = rot
98
-
99
- return mat
100
-
101
-
102
- def scale_mat(s_x, s_y, device="cpu"):
103
- batch = s_x.shape[0]
104
-
105
- mat = torch.eye(3, device=device).unsqueeze(0).repeat(batch, 1, 1)
106
- mat[:, 0, 0] = s_x
107
- mat[:, 1, 1] = s_y
108
-
109
- return mat
110
-
111
-
112
- def translate3d_mat(t_x, t_y, t_z):
113
- batch = t_x.shape[0]
114
-
115
- mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
116
- translate = torch.stack((t_x, t_y, t_z), 1)
117
- mat[:, :3, 3] = translate
118
-
119
- return mat
120
-
121
-
122
- def rotate3d_mat(axis, theta):
123
- batch = theta.shape[0]
124
-
125
- u_x, u_y, u_z = axis
126
-
127
- eye = torch.eye(3).unsqueeze(0)
128
- cross = torch.tensor([(0, -u_z, u_y), (u_z, 0, -u_x), (-u_y, u_x, 0)]).unsqueeze(0)
129
- outer = torch.tensor(axis)
130
- outer = (outer.unsqueeze(1) * outer).unsqueeze(0)
131
-
132
- sin_t = torch.sin(theta).view(-1, 1, 1)
133
- cos_t = torch.cos(theta).view(-1, 1, 1)
134
-
135
- rot = cos_t * eye + sin_t * cross + (1 - cos_t) * outer
136
-
137
- eye_4 = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
138
- eye_4[:, :3, :3] = rot
139
-
140
- return eye_4
141
-
142
-
143
- def scale3d_mat(s_x, s_y, s_z):
144
- batch = s_x.shape[0]
145
-
146
- mat = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
147
- mat[:, 0, 0] = s_x
148
- mat[:, 1, 1] = s_y
149
- mat[:, 2, 2] = s_z
150
-
151
- return mat
152
-
153
-
154
- def luma_flip_mat(axis, i):
155
- batch = i.shape[0]
156
-
157
- eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
158
- axis = torch.tensor(axis + (0,))
159
- flip = 2 * torch.ger(axis, axis) * i.view(-1, 1, 1)
160
-
161
- return eye - flip
162
-
163
-
164
- def saturation_mat(axis, i):
165
- batch = i.shape[0]
166
-
167
- eye = torch.eye(4).unsqueeze(0).repeat(batch, 1, 1)
168
- axis = torch.tensor(axis + (0,))
169
- axis = torch.ger(axis, axis)
170
- saturate = axis + (eye - axis) * i.view(-1, 1, 1)
171
-
172
- return saturate
173
-
174
-
175
- def lognormal_sample(size, mean=0, std=1, device="cpu"):
176
- return torch.empty(size, device=device).log_normal_(mean=mean, std=std)
177
-
178
-
179
- def category_sample(size, categories, device="cpu"):
180
- category = torch.tensor(categories, device=device)
181
- sample = torch.randint(high=len(categories), size=(size,), device=device)
182
-
183
- return category[sample]
184
-
185
-
186
- def uniform_sample(size, low, high, device="cpu"):
187
- return torch.empty(size, device=device).uniform_(low, high)
188
-
189
-
190
- def normal_sample(size, mean=0, std=1, device="cpu"):
191
- return torch.empty(size, device=device).normal_(mean, std)
192
-
193
-
194
- def bernoulli_sample(size, p, device="cpu"):
195
- return torch.empty(size, device=device).bernoulli_(p)
196
-
197
-
198
- def random_mat_apply(p, transform, prev, eye, device="cpu"):
199
- size = transform.shape[0]
200
- select = bernoulli_sample(size, p, device=device).view(size, 1, 1)
201
- select_transform = select * transform + (1 - select) * eye
202
-
203
- return select_transform @ prev
204
-
205
-
206
- def sample_affine(p, size, height, width, device="cpu"):
207
- G = torch.eye(3, device=device).unsqueeze(0).repeat(size, 1, 1)
208
- eye = G
209
-
210
- # flip
211
- #param = category_sample(size, (0, 1))
212
- #Gc = scale_mat(1 - 2.0 * param, torch.ones(size), device=device)
213
- #G = random_mat_apply(p, Gc, G, eye, device=device)
214
- # print('flip', G, scale_mat(1 - 2.0 * param, torch.ones(size)), sep='\n')
215
-
216
- # 90 rotate
217
- #param = category_sample(size, (0, 3))
218
- #Gc = rotate_mat(-math.pi / 2 * param, device=device)
219
- #G = random_mat_apply(p, Gc, G, eye, device=device)
220
- # print('90 rotate', G, rotate_mat(-math.pi / 2 * param), sep='\n')
221
-
222
- # integer translate
223
- param = uniform_sample(size, -0.125, 0.125)
224
- param_height = torch.round(param * height) / height
225
- param_width = torch.round(param * width) / width
226
- Gc = translate_mat(param_width, param_height, device=device)
227
- G = random_mat_apply(p, Gc, G, eye, device=device)
228
- # print('integer translate', G, translate_mat(param_width, param_height), sep='\n')
229
-
230
- # isotropic scale
231
- param = lognormal_sample(size, std=0.1 * math.log(2))
232
- Gc = scale_mat(param, param, device=device)
233
- G = random_mat_apply(p, Gc, G, eye, device=device)
234
- # print('isotropic scale', G, scale_mat(param, param), sep='\n')
235
-
236
- p_rot = 1 - math.sqrt(1 - p)
237
-
238
- # pre-rotate
239
- param = uniform_sample(size, -math.pi * 0.25, math.pi * 0.25)
240
- Gc = rotate_mat(-param, device=device)
241
- G = random_mat_apply(p_rot, Gc, G, eye, device=device)
242
- # print('pre-rotate', G, rotate_mat(-param), sep='\n')
243
-
244
- # anisotropic scale
245
- param = lognormal_sample(size, std=0.1 * math.log(2))
246
- Gc = scale_mat(param, 1 / param, device=device)
247
- G = random_mat_apply(p, Gc, G, eye, device=device)
248
- # print('anisotropic scale', G, scale_mat(param, 1 / param), sep='\n')
249
-
250
- # post-rotate
251
- param = uniform_sample(size, -math.pi * 0.25, math.pi * 0.25)
252
- Gc = rotate_mat(-param, device=device)
253
- G = random_mat_apply(p_rot, Gc, G, eye, device=device)
254
- # print('post-rotate', G, rotate_mat(-param), sep='\n')
255
-
256
- # fractional translate
257
- param = normal_sample(size, std=0.125)
258
- Gc = translate_mat(param, param, device=device)
259
- G = random_mat_apply(p, Gc, G, eye, device=device)
260
- # print('fractional translate', G, translate_mat(param, param), sep='\n')
261
-
262
- return G
263
-
264
-
265
- def sample_color(p, size):
266
- C = torch.eye(4).unsqueeze(0).repeat(size, 1, 1)
267
- eye = C
268
- axis_val = 1 / math.sqrt(3)
269
- axis = (axis_val, axis_val, axis_val)
270
-
271
- # brightness
272
- param = normal_sample(size, std=0.2)
273
- Cc = translate3d_mat(param, param, param)
274
- C = random_mat_apply(p, Cc, C, eye)
275
-
276
- # contrast
277
- param = lognormal_sample(size, std=0.5 * math.log(2))
278
- Cc = scale3d_mat(param, param, param)
279
- C = random_mat_apply(p, Cc, C, eye)
280
-
281
- # luma flip
282
- param = category_sample(size, (0, 1))
283
- Cc = luma_flip_mat(axis, param)
284
- C = random_mat_apply(p, Cc, C, eye)
285
-
286
- # hue rotation
287
- param = uniform_sample(size, -math.pi, math.pi)
288
- Cc = rotate3d_mat(axis, param)
289
- C = random_mat_apply(p, Cc, C, eye)
290
-
291
- # saturation
292
- param = lognormal_sample(size, std=1 * math.log(2))
293
- Cc = saturation_mat(axis, param)
294
- C = random_mat_apply(p, Cc, C, eye)
295
-
296
- return C
297
-
298
-
299
- def make_grid(shape, x0, x1, y0, y1, device):
300
- n, c, h, w = shape
301
- grid = torch.empty(n, h, w, 3, device=device)
302
- grid[:, :, :, 0] = torch.linspace(x0, x1, w, device=device)
303
- grid[:, :, :, 1] = torch.linspace(y0, y1, h, device=device).unsqueeze(-1)
304
- grid[:, :, :, 2] = 1
305
-
306
- return grid
307
-
308
-
309
- def affine_grid(grid, mat):
310
- n, h, w, _ = grid.shape
311
- return (grid.view(n, h * w, 3) @ mat.transpose(1, 2)).view(n, h, w, 2)
312
-
313
-
314
- def get_padding(G, height, width, kernel_size):
315
- device = G.device
316
-
317
- cx = (width - 1) / 2
318
- cy = (height - 1) / 2
319
- cp = torch.tensor(
320
- [(-cx, -cy, 1), (cx, -cy, 1), (cx, cy, 1), (-cx, cy, 1)], device=device
321
- )
322
- cp = G @ cp.T
323
-
324
- pad_k = kernel_size // 4
325
-
326
- pad = cp[:, :2, :].permute(1, 0, 2).flatten(1)
327
- pad = torch.cat((-pad, pad)).max(1).values
328
- pad = pad + torch.tensor([pad_k * 2 - cx, pad_k * 2 - cy] * 2, device=device)
329
- pad = pad.max(torch.tensor([0, 0] * 2, device=device))
330
- pad = pad.min(torch.tensor([width - 1, height - 1] * 2, device=device))
331
-
332
- pad_x1, pad_y1, pad_x2, pad_y2 = pad.ceil().to(torch.int32)
333
-
334
- return pad_x1, pad_x2, pad_y1, pad_y2
335
-
336
-
337
- def try_sample_affine_and_pad(img, p, kernel_size, G=None):
338
- batch, _, height, width = img.shape
339
-
340
- G_try = G
341
-
342
- if G is None:
343
- G_try = torch.inverse(sample_affine(p, batch, height, width))
344
-
345
- pad_x1, pad_x2, pad_y1, pad_y2 = get_padding(G_try, height, width, kernel_size)
346
-
347
- img_pad = F.pad(img, (pad_x1, pad_x2, pad_y1, pad_y2), mode="reflect")
348
-
349
- return img_pad, G_try, (pad_x1, pad_x2, pad_y1, pad_y2)
350
-
351
-
352
- class GridSampleForward(autograd.Function):
353
- @staticmethod
354
- def forward(ctx, input, grid):
355
- out = F.grid_sample(
356
- input, grid, mode="bilinear", padding_mode="zeros", align_corners=False
357
- )
358
- ctx.save_for_backward(input, grid)
359
-
360
- return out
361
-
362
- @staticmethod
363
- def backward(ctx, grad_output):
364
- input, grid = ctx.saved_tensors
365
- grad_input, grad_grid = GridSampleBackward.apply(grad_output, input, grid)
366
-
367
- return grad_input, grad_grid
368
-
369
-
370
- class GridSampleBackward(autograd.Function):
371
- @staticmethod
372
- def forward(ctx, grad_output, input, grid):
373
- op = torch._C._jit_get_operation("aten::grid_sampler_2d_backward")
374
- grad_input, grad_grid = op(grad_output, input, grid, 0, 0, False)
375
- ctx.save_for_backward(grid)
376
-
377
- return grad_input, grad_grid
378
-
379
- @staticmethod
380
- def backward(ctx, grad_grad_input, grad_grad_grid):
381
- grid, = ctx.saved_tensors
382
- grad_grad_output = None
383
-
384
- if ctx.needs_input_grad[0]:
385
- grad_grad_output = GridSampleForward.apply(grad_grad_input, grid)
386
-
387
- return grad_grad_output, None, None
388
-
389
-
390
- grid_sample = GridSampleForward.apply
391
-
392
-
393
- def scale_mat_single(s_x, s_y):
394
- return torch.tensor(((s_x, 0, 0), (0, s_y, 0), (0, 0, 1)), dtype=torch.float32)
395
-
396
-
397
- def translate_mat_single(t_x, t_y):
398
- return torch.tensor(((1, 0, t_x), (0, 1, t_y), (0, 0, 1)), dtype=torch.float32)
399
-
400
-
401
- def random_apply_affine(img, p, G=None, antialiasing_kernel=SYM6):
402
- kernel = antialiasing_kernel
403
- len_k = len(kernel)
404
-
405
- kernel = torch.as_tensor(kernel).to(img)
406
- # kernel = torch.ger(kernel, kernel).to(img)
407
- kernel_flip = torch.flip(kernel, (0,))
408
-
409
- img_pad, G, (pad_x1, pad_x2, pad_y1, pad_y2) = try_sample_affine_and_pad(
410
- img, p, len_k, G
411
- )
412
-
413
- G_inv = (
414
- translate_mat_single((pad_x1 - pad_x2).item() / 2, (pad_y1 - pad_y2).item() / 2)
415
- @ G
416
- )
417
- up_pad = (
418
- (len_k + 2 - 1) // 2,
419
- (len_k - 2) // 2,
420
- (len_k + 2 - 1) // 2,
421
- (len_k - 2) // 2,
422
- )
423
- img_2x = upfirdn2d(img_pad, kernel.unsqueeze(0), up=(2, 1), pad=(*up_pad[:2], 0, 0))
424
- img_2x = upfirdn2d(img_2x, kernel.unsqueeze(1), up=(1, 2), pad=(0, 0, *up_pad[2:]))
425
- G_inv = scale_mat_single(2, 2) @ G_inv @ scale_mat_single(1 / 2, 1 / 2)
426
- G_inv = translate_mat_single(-0.5, -0.5) @ G_inv @ translate_mat_single(0.5, 0.5)
427
- batch_size, channel, height, width = img.shape
428
- pad_k = len_k // 4
429
- shape = (batch_size, channel, (height + pad_k * 2) * 2, (width + pad_k * 2) * 2)
430
- G_inv = (
431
- scale_mat_single(2 / img_2x.shape[3], 2 / img_2x.shape[2])
432
- @ G_inv
433
- @ scale_mat_single(1 / (2 / shape[3]), 1 / (2 / shape[2]))
434
- )
435
- grid = F.affine_grid(G_inv[:, :2, :].to(img_2x), shape, align_corners=False)
436
- img_affine = grid_sample(img_2x, grid)
437
- d_p = -pad_k * 2
438
- down_pad = (
439
- d_p + (len_k - 2 + 1) // 2,
440
- d_p + (len_k - 2) // 2,
441
- d_p + (len_k - 2 + 1) // 2,
442
- d_p + (len_k - 2) // 2,
443
- )
444
- img_down = upfirdn2d(
445
- img_affine, kernel_flip.unsqueeze(0), down=(2, 1), pad=(*down_pad[:2], 0, 0)
446
- )
447
- img_down = upfirdn2d(
448
- img_down, kernel_flip.unsqueeze(1), down=(1, 2), pad=(0, 0, *down_pad[2:])
449
- )
450
-
451
- return img_down, G
452
-
453
-
454
- def apply_color(img, mat):
455
- batch = img.shape[0]
456
- img = img.permute(0, 2, 3, 1)
457
- mat_mul = mat[:, :3, :3].transpose(1, 2).view(batch, 1, 3, 3)
458
- mat_add = mat[:, :3, 3].view(batch, 1, 1, 3)
459
- img = img @ mat_mul + mat_add
460
- img = img.permute(0, 3, 1, 2)
461
-
462
- return img
463
-
464
-
465
- def random_apply_color(img, p, C=None):
466
- if C is None:
467
- C = sample_color(p, img.shape[0])
468
-
469
- img = apply_color(img, C.to(img))
470
-
471
- return img, C
472
-
473
-
474
- def augment(img, p, transform_matrix=(None, None)):
475
- img, G = random_apply_affine(img, p, transform_matrix[0])
476
- img, C = random_apply_color(img, p, transform_matrix[1])
477
-
478
- return img, (G, C)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AIGText/GlyphControl/ldm/modules/image_degradation/bsrgan_light.py DELETED
@@ -1,651 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- import numpy as np
3
- import cv2
4
- import torch
5
-
6
- from functools import partial
7
- import random
8
- from scipy import ndimage
9
- import scipy
10
- import scipy.stats as ss
11
- from scipy.interpolate import interp2d
12
- from scipy.linalg import orth
13
- import albumentations
14
-
15
- import ldm.modules.image_degradation.utils_image as util
16
-
17
- """
18
- # --------------------------------------------
19
- # Super-Resolution
20
- # --------------------------------------------
21
- #
22
- # Kai Zhang ([email protected])
23
- # https://github.com/cszn
24
- # From 2019/03--2021/08
25
- # --------------------------------------------
26
- """
27
-
28
- def modcrop_np(img, sf):
29
- '''
30
- Args:
31
- img: numpy image, WxH or WxHxC
32
- sf: scale factor
33
- Return:
34
- cropped image
35
- '''
36
- w, h = img.shape[:2]
37
- im = np.copy(img)
38
- return im[:w - w % sf, :h - h % sf, ...]
39
-
40
-
41
- """
42
- # --------------------------------------------
43
- # anisotropic Gaussian kernels
44
- # --------------------------------------------
45
- """
46
-
47
-
48
- def analytic_kernel(k):
49
- """Calculate the X4 kernel from the X2 kernel (for proof see appendix in paper)"""
50
- k_size = k.shape[0]
51
- # Calculate the big kernels size
52
- big_k = np.zeros((3 * k_size - 2, 3 * k_size - 2))
53
- # Loop over the small kernel to fill the big one
54
- for r in range(k_size):
55
- for c in range(k_size):
56
- big_k[2 * r:2 * r + k_size, 2 * c:2 * c + k_size] += k[r, c] * k
57
- # Crop the edges of the big kernel to ignore very small values and increase run time of SR
58
- crop = k_size // 2
59
- cropped_big_k = big_k[crop:-crop, crop:-crop]
60
- # Normalize to 1
61
- return cropped_big_k / cropped_big_k.sum()
62
-
63
-
64
- def anisotropic_Gaussian(ksize=15, theta=np.pi, l1=6, l2=6):
65
- """ generate an anisotropic Gaussian kernel
66
- Args:
67
- ksize : e.g., 15, kernel size
68
- theta : [0, pi], rotation angle range
69
- l1 : [0.1,50], scaling of eigenvalues
70
- l2 : [0.1,l1], scaling of eigenvalues
71
- If l1 = l2, will get an isotropic Gaussian kernel.
72
- Returns:
73
- k : kernel
74
- """
75
-
76
- v = np.dot(np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]), np.array([1., 0.]))
77
- V = np.array([[v[0], v[1]], [v[1], -v[0]]])
78
- D = np.array([[l1, 0], [0, l2]])
79
- Sigma = np.dot(np.dot(V, D), np.linalg.inv(V))
80
- k = gm_blur_kernel(mean=[0, 0], cov=Sigma, size=ksize)
81
-
82
- return k
83
-
84
-
85
- def gm_blur_kernel(mean, cov, size=15):
86
- center = size / 2.0 + 0.5
87
- k = np.zeros([size, size])
88
- for y in range(size):
89
- for x in range(size):
90
- cy = y - center + 1
91
- cx = x - center + 1
92
- k[y, x] = ss.multivariate_normal.pdf([cx, cy], mean=mean, cov=cov)
93
-
94
- k = k / np.sum(k)
95
- return k
96
-
97
-
98
- def shift_pixel(x, sf, upper_left=True):
99
- """shift pixel for super-resolution with different scale factors
100
- Args:
101
- x: WxHxC or WxH
102
- sf: scale factor
103
- upper_left: shift direction
104
- """
105
- h, w = x.shape[:2]
106
- shift = (sf - 1) * 0.5
107
- xv, yv = np.arange(0, w, 1.0), np.arange(0, h, 1.0)
108
- if upper_left:
109
- x1 = xv + shift
110
- y1 = yv + shift
111
- else:
112
- x1 = xv - shift
113
- y1 = yv - shift
114
-
115
- x1 = np.clip(x1, 0, w - 1)
116
- y1 = np.clip(y1, 0, h - 1)
117
-
118
- if x.ndim == 2:
119
- x = interp2d(xv, yv, x)(x1, y1)
120
- if x.ndim == 3:
121
- for i in range(x.shape[-1]):
122
- x[:, :, i] = interp2d(xv, yv, x[:, :, i])(x1, y1)
123
-
124
- return x
125
-
126
-
127
- def blur(x, k):
128
- '''
129
- x: image, NxcxHxW
130
- k: kernel, Nx1xhxw
131
- '''
132
- n, c = x.shape[:2]
133
- p1, p2 = (k.shape[-2] - 1) // 2, (k.shape[-1] - 1) // 2
134
- x = torch.nn.functional.pad(x, pad=(p1, p2, p1, p2), mode='replicate')
135
- k = k.repeat(1, c, 1, 1)
136
- k = k.view(-1, 1, k.shape[2], k.shape[3])
137
- x = x.view(1, -1, x.shape[2], x.shape[3])
138
- x = torch.nn.functional.conv2d(x, k, bias=None, stride=1, padding=0, groups=n * c)
139
- x = x.view(n, c, x.shape[2], x.shape[3])
140
-
141
- return x
142
-
143
-
144
- def gen_kernel(k_size=np.array([15, 15]), scale_factor=np.array([4, 4]), min_var=0.6, max_var=10., noise_level=0):
145
- """"
146
- # modified version of https://github.com/assafshocher/BlindSR_dataset_generator
147
- # Kai Zhang
148
- # min_var = 0.175 * sf # variance of the gaussian kernel will be sampled between min_var and max_var
149
- # max_var = 2.5 * sf
150
- """
151
- # Set random eigen-vals (lambdas) and angle (theta) for COV matrix
152
- lambda_1 = min_var + np.random.rand() * (max_var - min_var)
153
- lambda_2 = min_var + np.random.rand() * (max_var - min_var)
154
- theta = np.random.rand() * np.pi # random theta
155
- noise = -noise_level + np.random.rand(*k_size) * noise_level * 2
156
-
157
- # Set COV matrix using Lambdas and Theta
158
- LAMBDA = np.diag([lambda_1, lambda_2])
159
- Q = np.array([[np.cos(theta), -np.sin(theta)],
160
- [np.sin(theta), np.cos(theta)]])
161
- SIGMA = Q @ LAMBDA @ Q.T
162
- INV_SIGMA = np.linalg.inv(SIGMA)[None, None, :, :]
163
-
164
- # Set expectation position (shifting kernel for aligned image)
165
- MU = k_size // 2 - 0.5 * (scale_factor - 1) # - 0.5 * (scale_factor - k_size % 2)
166
- MU = MU[None, None, :, None]
167
-
168
- # Create meshgrid for Gaussian
169
- [X, Y] = np.meshgrid(range(k_size[0]), range(k_size[1]))
170
- Z = np.stack([X, Y], 2)[:, :, :, None]
171
-
172
- # Calcualte Gaussian for every pixel of the kernel
173
- ZZ = Z - MU
174
- ZZ_t = ZZ.transpose(0, 1, 3, 2)
175
- raw_kernel = np.exp(-0.5 * np.squeeze(ZZ_t @ INV_SIGMA @ ZZ)) * (1 + noise)
176
-
177
- # shift the kernel so it will be centered
178
- # raw_kernel_centered = kernel_shift(raw_kernel, scale_factor)
179
-
180
- # Normalize the kernel and return
181
- # kernel = raw_kernel_centered / np.sum(raw_kernel_centered)
182
- kernel = raw_kernel / np.sum(raw_kernel)
183
- return kernel
184
-
185
-
186
- def fspecial_gaussian(hsize, sigma):
187
- hsize = [hsize, hsize]
188
- siz = [(hsize[0] - 1.0) / 2.0, (hsize[1] - 1.0) / 2.0]
189
- std = sigma
190
- [x, y] = np.meshgrid(np.arange(-siz[1], siz[1] + 1), np.arange(-siz[0], siz[0] + 1))
191
- arg = -(x * x + y * y) / (2 * std * std)
192
- h = np.exp(arg)
193
- h[h < scipy.finfo(float).eps * h.max()] = 0
194
- sumh = h.sum()
195
- if sumh != 0:
196
- h = h / sumh
197
- return h
198
-
199
-
200
- def fspecial_laplacian(alpha):
201
- alpha = max([0, min([alpha, 1])])
202
- h1 = alpha / (alpha + 1)
203
- h2 = (1 - alpha) / (alpha + 1)
204
- h = [[h1, h2, h1], [h2, -4 / (alpha + 1), h2], [h1, h2, h1]]
205
- h = np.array(h)
206
- return h
207
-
208
-
209
- def fspecial(filter_type, *args, **kwargs):
210
- '''
211
- python code from:
212
- https://github.com/ronaldosena/imagens-medicas-2/blob/40171a6c259edec7827a6693a93955de2bd39e76/Aulas/aula_2_-_uniform_filter/matlab_fspecial.py
213
- '''
214
- if filter_type == 'gaussian':
215
- return fspecial_gaussian(*args, **kwargs)
216
- if filter_type == 'laplacian':
217
- return fspecial_laplacian(*args, **kwargs)
218
-
219
-
220
- """
221
- # --------------------------------------------
222
- # degradation models
223
- # --------------------------------------------
224
- """
225
-
226
-
227
- def bicubic_degradation(x, sf=3):
228
- '''
229
- Args:
230
- x: HxWxC image, [0, 1]
231
- sf: down-scale factor
232
- Return:
233
- bicubicly downsampled LR image
234
- '''
235
- x = util.imresize_np(x, scale=1 / sf)
236
- return x
237
-
238
-
239
- def srmd_degradation(x, k, sf=3):
240
- ''' blur + bicubic downsampling
241
- Args:
242
- x: HxWxC image, [0, 1]
243
- k: hxw, double
244
- sf: down-scale factor
245
- Return:
246
- downsampled LR image
247
- Reference:
248
- @inproceedings{zhang2018learning,
249
- title={Learning a single convolutional super-resolution network for multiple degradations},
250
- author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei},
251
- booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
252
- pages={3262--3271},
253
- year={2018}
254
- }
255
- '''
256
- x = ndimage.convolve(x, np.expand_dims(k, axis=2), mode='wrap') # 'nearest' | 'mirror'
257
- x = bicubic_degradation(x, sf=sf)
258
- return x
259
-
260
-
261
- def dpsr_degradation(x, k, sf=3):
262
- ''' bicubic downsampling + blur
263
- Args:
264
- x: HxWxC image, [0, 1]
265
- k: hxw, double
266
- sf: down-scale factor
267
- Return:
268
- downsampled LR image
269
- Reference:
270
- @inproceedings{zhang2019deep,
271
- title={Deep Plug-and-Play Super-Resolution for Arbitrary Blur Kernels},
272
- author={Zhang, Kai and Zuo, Wangmeng and Zhang, Lei},
273
- booktitle={IEEE Conference on Computer Vision and Pattern Recognition},
274
- pages={1671--1681},
275
- year={2019}
276
- }
277
- '''
278
- x = bicubic_degradation(x, sf=sf)
279
- x = ndimage.convolve(x, np.expand_dims(k, axis=2), mode='wrap')
280
- return x
281
-
282
-
283
- def classical_degradation(x, k, sf=3):
284
- ''' blur + downsampling
285
- Args:
286
- x: HxWxC image, [0, 1]/[0, 255]
287
- k: hxw, double
288
- sf: down-scale factor
289
- Return:
290
- downsampled LR image
291
- '''
292
- x = ndimage.convolve(x, np.expand_dims(k, axis=2), mode='wrap')
293
- # x = filters.correlate(x, np.expand_dims(np.flip(k), axis=2))
294
- st = 0
295
- return x[st::sf, st::sf, ...]
296
-
297
-
298
- def add_sharpening(img, weight=0.5, radius=50, threshold=10):
299
- """USM sharpening. borrowed from real-ESRGAN
300
- Input image: I; Blurry image: B.
301
- 1. K = I + weight * (I - B)
302
- 2. Mask = 1 if abs(I - B) > threshold, else: 0
303
- 3. Blur mask:
304
- 4. Out = Mask * K + (1 - Mask) * I
305
- Args:
306
- img (Numpy array): Input image, HWC, BGR; float32, [0, 1].
307
- weight (float): Sharp weight. Default: 1.
308
- radius (float): Kernel size of Gaussian blur. Default: 50.
309
- threshold (int):
310
- """
311
- if radius % 2 == 0:
312
- radius += 1
313
- blur = cv2.GaussianBlur(img, (radius, radius), 0)
314
- residual = img - blur
315
- mask = np.abs(residual) * 255 > threshold
316
- mask = mask.astype('float32')
317
- soft_mask = cv2.GaussianBlur(mask, (radius, radius), 0)
318
-
319
- K = img + weight * residual
320
- K = np.clip(K, 0, 1)
321
- return soft_mask * K + (1 - soft_mask) * img
322
-
323
-
324
- def add_blur(img, sf=4):
325
- wd2 = 4.0 + sf
326
- wd = 2.0 + 0.2 * sf
327
-
328
- wd2 = wd2/4
329
- wd = wd/4
330
-
331
- if random.random() < 0.5:
332
- l1 = wd2 * random.random()
333
- l2 = wd2 * random.random()
334
- k = anisotropic_Gaussian(ksize=random.randint(2, 11) + 3, theta=random.random() * np.pi, l1=l1, l2=l2)
335
- else:
336
- k = fspecial('gaussian', random.randint(2, 4) + 3, wd * random.random())
337
- img = ndimage.convolve(img, np.expand_dims(k, axis=2), mode='mirror')
338
-
339
- return img
340
-
341
-
342
- def add_resize(img, sf=4):
343
- rnum = np.random.rand()
344
- if rnum > 0.8: # up
345
- sf1 = random.uniform(1, 2)
346
- elif rnum < 0.7: # down
347
- sf1 = random.uniform(0.5 / sf, 1)
348
- else:
349
- sf1 = 1.0
350
- img = cv2.resize(img, (int(sf1 * img.shape[1]), int(sf1 * img.shape[0])), interpolation=random.choice([1, 2, 3]))
351
- img = np.clip(img, 0.0, 1.0)
352
-
353
- return img
354
-
355
-
356
- # def add_Gaussian_noise(img, noise_level1=2, noise_level2=25):
357
- # noise_level = random.randint(noise_level1, noise_level2)
358
- # rnum = np.random.rand()
359
- # if rnum > 0.6: # add color Gaussian noise
360
- # img += np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
361
- # elif rnum < 0.4: # add grayscale Gaussian noise
362
- # img += np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
363
- # else: # add noise
364
- # L = noise_level2 / 255.
365
- # D = np.diag(np.random.rand(3))
366
- # U = orth(np.random.rand(3, 3))
367
- # conv = np.dot(np.dot(np.transpose(U), D), U)
368
- # img += np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
369
- # img = np.clip(img, 0.0, 1.0)
370
- # return img
371
-
372
- def add_Gaussian_noise(img, noise_level1=2, noise_level2=25):
373
- noise_level = random.randint(noise_level1, noise_level2)
374
- rnum = np.random.rand()
375
- if rnum > 0.6: # add color Gaussian noise
376
- img = img + np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
377
- elif rnum < 0.4: # add grayscale Gaussian noise
378
- img = img + np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
379
- else: # add noise
380
- L = noise_level2 / 255.
381
- D = np.diag(np.random.rand(3))
382
- U = orth(np.random.rand(3, 3))
383
- conv = np.dot(np.dot(np.transpose(U), D), U)
384
- img = img + np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
385
- img = np.clip(img, 0.0, 1.0)
386
- return img
387
-
388
-
389
- def add_speckle_noise(img, noise_level1=2, noise_level2=25):
390
- noise_level = random.randint(noise_level1, noise_level2)
391
- img = np.clip(img, 0.0, 1.0)
392
- rnum = random.random()
393
- if rnum > 0.6:
394
- img += img * np.random.normal(0, noise_level / 255.0, img.shape).astype(np.float32)
395
- elif rnum < 0.4:
396
- img += img * np.random.normal(0, noise_level / 255.0, (*img.shape[:2], 1)).astype(np.float32)
397
- else:
398
- L = noise_level2 / 255.
399
- D = np.diag(np.random.rand(3))
400
- U = orth(np.random.rand(3, 3))
401
- conv = np.dot(np.dot(np.transpose(U), D), U)
402
- img += img * np.random.multivariate_normal([0, 0, 0], np.abs(L ** 2 * conv), img.shape[:2]).astype(np.float32)
403
- img = np.clip(img, 0.0, 1.0)
404
- return img
405
-
406
-
407
- def add_Poisson_noise(img):
408
- img = np.clip((img * 255.0).round(), 0, 255) / 255.
409
- vals = 10 ** (2 * random.random() + 2.0) # [2, 4]
410
- if random.random() < 0.5:
411
- img = np.random.poisson(img * vals).astype(np.float32) / vals
412
- else:
413
- img_gray = np.dot(img[..., :3], [0.299, 0.587, 0.114])
414
- img_gray = np.clip((img_gray * 255.0).round(), 0, 255) / 255.
415
- noise_gray = np.random.poisson(img_gray * vals).astype(np.float32) / vals - img_gray
416
- img += noise_gray[:, :, np.newaxis]
417
- img = np.clip(img, 0.0, 1.0)
418
- return img
419
-
420
-
421
- def add_JPEG_noise(img):
422
- quality_factor = random.randint(80, 95)
423
- img = cv2.cvtColor(util.single2uint(img), cv2.COLOR_RGB2BGR)
424
- result, encimg = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor])
425
- img = cv2.imdecode(encimg, 1)
426
- img = cv2.cvtColor(util.uint2single(img), cv2.COLOR_BGR2RGB)
427
- return img
428
-
429
-
430
- def random_crop(lq, hq, sf=4, lq_patchsize=64):
431
- h, w = lq.shape[:2]
432
- rnd_h = random.randint(0, h - lq_patchsize)
433
- rnd_w = random.randint(0, w - lq_patchsize)
434
- lq = lq[rnd_h:rnd_h + lq_patchsize, rnd_w:rnd_w + lq_patchsize, :]
435
-
436
- rnd_h_H, rnd_w_H = int(rnd_h * sf), int(rnd_w * sf)
437
- hq = hq[rnd_h_H:rnd_h_H + lq_patchsize * sf, rnd_w_H:rnd_w_H + lq_patchsize * sf, :]
438
- return lq, hq
439
-
440
-
441
- def degradation_bsrgan(img, sf=4, lq_patchsize=72, isp_model=None):
442
- """
443
- This is the degradation model of BSRGAN from the paper
444
- "Designing a Practical Degradation Model for Deep Blind Image Super-Resolution"
445
- ----------
446
- img: HXWXC, [0, 1], its size should be large than (lq_patchsizexsf)x(lq_patchsizexsf)
447
- sf: scale factor
448
- isp_model: camera ISP model
449
- Returns
450
- -------
451
- img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1]
452
- hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1]
453
- """
454
- isp_prob, jpeg_prob, scale2_prob = 0.25, 0.9, 0.25
455
- sf_ori = sf
456
-
457
- h1, w1 = img.shape[:2]
458
- img = img.copy()[:w1 - w1 % sf, :h1 - h1 % sf, ...] # mod crop
459
- h, w = img.shape[:2]
460
-
461
- if h < lq_patchsize * sf or w < lq_patchsize * sf:
462
- raise ValueError(f'img size ({h1}X{w1}) is too small!')
463
-
464
- hq = img.copy()
465
-
466
- if sf == 4 and random.random() < scale2_prob: # downsample1
467
- if np.random.rand() < 0.5:
468
- img = cv2.resize(img, (int(1 / 2 * img.shape[1]), int(1 / 2 * img.shape[0])),
469
- interpolation=random.choice([1, 2, 3]))
470
- else:
471
- img = util.imresize_np(img, 1 / 2, True)
472
- img = np.clip(img, 0.0, 1.0)
473
- sf = 2
474
-
475
- shuffle_order = random.sample(range(7), 7)
476
- idx1, idx2 = shuffle_order.index(2), shuffle_order.index(3)
477
- if idx1 > idx2: # keep downsample3 last
478
- shuffle_order[idx1], shuffle_order[idx2] = shuffle_order[idx2], shuffle_order[idx1]
479
-
480
- for i in shuffle_order:
481
-
482
- if i == 0:
483
- img = add_blur(img, sf=sf)
484
-
485
- elif i == 1:
486
- img = add_blur(img, sf=sf)
487
-
488
- elif i == 2:
489
- a, b = img.shape[1], img.shape[0]
490
- # downsample2
491
- if random.random() < 0.75:
492
- sf1 = random.uniform(1, 2 * sf)
493
- img = cv2.resize(img, (int(1 / sf1 * img.shape[1]), int(1 / sf1 * img.shape[0])),
494
- interpolation=random.choice([1, 2, 3]))
495
- else:
496
- k = fspecial('gaussian', 25, random.uniform(0.1, 0.6 * sf))
497
- k_shifted = shift_pixel(k, sf)
498
- k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel
499
- img = ndimage.convolve(img, np.expand_dims(k_shifted, axis=2), mode='mirror')
500
- img = img[0::sf, 0::sf, ...] # nearest downsampling
501
- img = np.clip(img, 0.0, 1.0)
502
-
503
- elif i == 3:
504
- # downsample3
505
- img = cv2.resize(img, (int(1 / sf * a), int(1 / sf * b)), interpolation=random.choice([1, 2, 3]))
506
- img = np.clip(img, 0.0, 1.0)
507
-
508
- elif i == 4:
509
- # add Gaussian noise
510
- img = add_Gaussian_noise(img, noise_level1=2, noise_level2=8)
511
-
512
- elif i == 5:
513
- # add JPEG noise
514
- if random.random() < jpeg_prob:
515
- img = add_JPEG_noise(img)
516
-
517
- elif i == 6:
518
- # add processed camera sensor noise
519
- if random.random() < isp_prob and isp_model is not None:
520
- with torch.no_grad():
521
- img, hq = isp_model.forward(img.copy(), hq)
522
-
523
- # add final JPEG compression noise
524
- img = add_JPEG_noise(img)
525
-
526
- # random crop
527
- img, hq = random_crop(img, hq, sf_ori, lq_patchsize)
528
-
529
- return img, hq
530
-
531
-
532
- # todo no isp_model?
533
- def degradation_bsrgan_variant(image, sf=4, isp_model=None, up=False):
534
- """
535
- This is the degradation model of BSRGAN from the paper
536
- "Designing a Practical Degradation Model for Deep Blind Image Super-Resolution"
537
- ----------
538
- sf: scale factor
539
- isp_model: camera ISP model
540
- Returns
541
- -------
542
- img: low-quality patch, size: lq_patchsizeXlq_patchsizeXC, range: [0, 1]
543
- hq: corresponding high-quality patch, size: (lq_patchsizexsf)X(lq_patchsizexsf)XC, range: [0, 1]
544
- """
545
- image = util.uint2single(image)
546
- isp_prob, jpeg_prob, scale2_prob = 0.25, 0.9, 0.25
547
- sf_ori = sf
548
-
549
- h1, w1 = image.shape[:2]
550
- image = image.copy()[:w1 - w1 % sf, :h1 - h1 % sf, ...] # mod crop
551
- h, w = image.shape[:2]
552
-
553
- hq = image.copy()
554
-
555
- if sf == 4 and random.random() < scale2_prob: # downsample1
556
- if np.random.rand() < 0.5:
557
- image = cv2.resize(image, (int(1 / 2 * image.shape[1]), int(1 / 2 * image.shape[0])),
558
- interpolation=random.choice([1, 2, 3]))
559
- else:
560
- image = util.imresize_np(image, 1 / 2, True)
561
- image = np.clip(image, 0.0, 1.0)
562
- sf = 2
563
-
564
- shuffle_order = random.sample(range(7), 7)
565
- idx1, idx2 = shuffle_order.index(2), shuffle_order.index(3)
566
- if idx1 > idx2: # keep downsample3 last
567
- shuffle_order[idx1], shuffle_order[idx2] = shuffle_order[idx2], shuffle_order[idx1]
568
-
569
- for i in shuffle_order:
570
-
571
- if i == 0:
572
- image = add_blur(image, sf=sf)
573
-
574
- # elif i == 1:
575
- # image = add_blur(image, sf=sf)
576
-
577
- if i == 0:
578
- pass
579
-
580
- elif i == 2:
581
- a, b = image.shape[1], image.shape[0]
582
- # downsample2
583
- if random.random() < 0.8:
584
- sf1 = random.uniform(1, 2 * sf)
585
- image = cv2.resize(image, (int(1 / sf1 * image.shape[1]), int(1 / sf1 * image.shape[0])),
586
- interpolation=random.choice([1, 2, 3]))
587
- else:
588
- k = fspecial('gaussian', 25, random.uniform(0.1, 0.6 * sf))
589
- k_shifted = shift_pixel(k, sf)
590
- k_shifted = k_shifted / k_shifted.sum() # blur with shifted kernel
591
- image = ndimage.convolve(image, np.expand_dims(k_shifted, axis=2), mode='mirror')
592
- image = image[0::sf, 0::sf, ...] # nearest downsampling
593
-
594
- image = np.clip(image, 0.0, 1.0)
595
-
596
- elif i == 3:
597
- # downsample3
598
- image = cv2.resize(image, (int(1 / sf * a), int(1 / sf * b)), interpolation=random.choice([1, 2, 3]))
599
- image = np.clip(image, 0.0, 1.0)
600
-
601
- elif i == 4:
602
- # add Gaussian noise
603
- image = add_Gaussian_noise(image, noise_level1=1, noise_level2=2)
604
-
605
- elif i == 5:
606
- # add JPEG noise
607
- if random.random() < jpeg_prob:
608
- image = add_JPEG_noise(image)
609
- #
610
- # elif i == 6:
611
- # # add processed camera sensor noise
612
- # if random.random() < isp_prob and isp_model is not None:
613
- # with torch.no_grad():
614
- # img, hq = isp_model.forward(img.copy(), hq)
615
-
616
- # add final JPEG compression noise
617
- image = add_JPEG_noise(image)
618
- image = util.single2uint(image)
619
- if up:
620
- image = cv2.resize(image, (w1, h1), interpolation=cv2.INTER_CUBIC) # todo: random, as above? want to condition on it then
621
- example = {"image": image}
622
- return example
623
-
624
-
625
-
626
-
627
- if __name__ == '__main__':
628
- print("hey")
629
- img = util.imread_uint('utils/test.png', 3)
630
- img = img[:448, :448]
631
- h = img.shape[0] // 4
632
- print("resizing to", h)
633
- sf = 4
634
- deg_fn = partial(degradation_bsrgan_variant, sf=sf)
635
- for i in range(20):
636
- print(i)
637
- img_hq = img
638
- img_lq = deg_fn(img)["image"]
639
- img_hq, img_lq = util.uint2single(img_hq), util.uint2single(img_lq)
640
- print(img_lq)
641
- img_lq_bicubic = albumentations.SmallestMaxSize(max_size=h, interpolation=cv2.INTER_CUBIC)(image=img_hq)["image"]
642
- print(img_lq.shape)
643
- print("bicubic", img_lq_bicubic.shape)
644
- print(img_hq.shape)
645
- lq_nearest = cv2.resize(util.single2uint(img_lq), (int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])),
646
- interpolation=0)
647
- lq_bicubic_nearest = cv2.resize(util.single2uint(img_lq_bicubic),
648
- (int(sf * img_lq.shape[1]), int(sf * img_lq.shape[0])),
649
- interpolation=0)
650
- img_concat = np.concatenate([lq_bicubic_nearest, lq_nearest, util.single2uint(img_hq)], axis=1)
651
- util.imsave(img_concat, str(i) + '.png')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ATang0729/Forecast4Muses/Model/Model6/Model6_2_ProfileRecogition/mmpretrain/configs/.ipynb_checkpoints/resnext101_4xb32_2048e_4channel-checkpoint.py DELETED
@@ -1,107 +0,0 @@
1
- _base_ = [ # 此配置文件将继承所有 `_base_` 中的配置
2
- '../configs/_base_/schedules/custom_schedule.py', # 训练策略配置
3
- '../configs/_base_/default_runtime.py' # 默认运行设置
4
- ]
5
-
6
- default_hooks = dict(
7
- # print log every 50 iterations.
8
- logger=dict(type='LoggerHook', interval=10),
9
- # save checkpoint per 8 epochs.
10
- checkpoint=dict(save_best='auto', interval=16)
11
- )
12
-
13
- visualizer = dict(
14
- vis_backends=[dict(type='LocalVisBackend'),
15
- dict(type='WandbVisBackend')])
16
-
17
- dataset_type = 'CustomDataset'
18
-
19
- # config of pipline
20
- train_pipeline = [
21
- dict(type='LoadImageFromFile', imdecode_backend='pillow', color_type='unchanged'), # 读取图像
22
- dict(type='RandomResizedCrop', scale=224), # 随机放缩裁剪
23
- dict(type='RandomFlip', prob=0.5, direction='horizontal'), # 随机水平翻转
24
- dict(type='PackInputs'), # 准备图像以及标签
25
- ]
26
-
27
- test_pipeline = [
28
- dict(type='LoadImageFromFile', imdecode_backend='pillow', color_type='unchanged'), # 读取图像
29
- dict(type='ResizeEdge', scale=256, edge='short'), # 缩放短边尺寸至 256px
30
- dict(type='CenterCrop', crop_size=224), # 中心裁剪
31
- dict(type='PackInputs'), # 准备图像以及标签
32
- ]
33
-
34
- # config of dataloader
35
- train_dataloader = dict(
36
- batch_size=32, # 每张 GPU 的 batchsize
37
- num_workers=5, # 每个 GPU 的线程数
38
- dataset=dict( # 训练数据集
39
- type=dataset_type,
40
- data_root='../2_preprocess_data_3000',
41
- with_label=True,
42
- ann_file='',
43
- data_prefix='train',
44
- pipeline=train_pipeline),
45
- sampler=dict(type='DefaultSampler', shuffle=True), # 默认采样器
46
- persistent_workers=True, # 是否保持进程,可以缩短每个 epoch 的准备时间
47
- )
48
-
49
- # 构造验证集 dataloader
50
- val_dataloader = dict(
51
- batch_size=32,
52
- num_workers=5,
53
- dataset=dict(
54
- type=dataset_type,
55
- data_root='../2_preprocess_data_3000',
56
- with_label=True,
57
- ann_file='',
58
- data_prefix='val',
59
- pipeline=test_pipeline),
60
- sampler=dict(type='DefaultSampler', shuffle=False),
61
- persistent_workers=True,
62
- )
63
-
64
- # set evaluator of validation dataset. Here uses top1 and top3 accuracy
65
- val_evaluator = dict(type='Accuracy', topk=(1, 3))
66
-
67
- test_dataloader = val_dataloader
68
- test_evaluator = val_evaluator
69
-
70
- model = dict(
71
- type='ImageClassifier', # 主模型类型(对于图像分类任务,使用 `ImageClassifier`)
72
- backbone=dict(
73
- type='ResNeXt', # 主干网络类型
74
- depth=101,
75
- in_channels=4, # 输入通道数
76
- ),
77
- neck=dict(type='GlobalAveragePooling'), # 颈网络类型
78
- head=dict(
79
- type='LinearClsHead', # 分类颈网络类型
80
- # 除了 `type` 之外的所有字段都来自 `LinearClsHead` 类的 __init__ 方法
81
- # 可查阅 https://mmpretrain.readthedocs.io/zh_CN/latest/api/generated/mmpretrain.models.heads.LinearClsHead.html
82
- num_classes=7, # 分类类别数
83
- in_channels=2048,
84
- loss=dict(type='CrossEntropyLoss', loss_weight=1.0), # 损失函数配置信息
85
- topk=(1, 3), # 评估指标,Top-k 准确率
86
- ))
87
-
88
- optim_wrapper = dict(
89
- accumulative_counts=8
90
- )
91
-
92
- param_scheduler = [
93
- # 在前10轮迭代中,逐迭代次数,线性预热
94
- dict(type='LinearLR',
95
- start_factor=0.00001,
96
- by_epoch=True,
97
- end=10,
98
- convert_to_iter_based=True, # 逐迭代次数更新学习率.
99
- ),
100
- # 在 10 轮次后,通过余弦退火衰减
101
- dict(type='MultiStepLR',
102
- by_epoch=True, # 按轮次更新学习率
103
- milestones=[30, 210, 390, 570, 750, 930, 1110, 1290, 1470, 1650, 1830],
104
- gamma=0.9)
105
- ]
106
-
107
- train_cfg = dict(by_epoch=True, max_epochs=2048, val_interval=16)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Adapter/T2I-Adapter/ldm/modules/extra_condition/openpose/model.py DELETED
@@ -1,178 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- from collections import OrderedDict
4
-
5
-
6
- def make_layers(block, no_relu_layers):
7
- layers = []
8
- for layer_name, v in block.items():
9
- if 'pool' in layer_name:
10
- layer = nn.MaxPool2d(kernel_size=v[0], stride=v[1], padding=v[2])
11
- layers.append((layer_name, layer))
12
- else:
13
- conv2d = nn.Conv2d(in_channels=v[0], out_channels=v[1], kernel_size=v[2], stride=v[3], padding=v[4])
14
- layers.append((layer_name, conv2d))
15
- if layer_name not in no_relu_layers:
16
- layers.append(('relu_' + layer_name, nn.ReLU(inplace=True)))
17
-
18
- return nn.Sequential(OrderedDict(layers))
19
-
20
-
21
- class bodypose_model(nn.Module):
22
-
23
- def __init__(self):
24
- super(bodypose_model, self).__init__()
25
-
26
- # these layers have no relu layer
27
- no_relu_layers = ['conv5_5_CPM_L1', 'conv5_5_CPM_L2', 'Mconv7_stage2_L1',\
28
- 'Mconv7_stage2_L2', 'Mconv7_stage3_L1', 'Mconv7_stage3_L2',\
29
- 'Mconv7_stage4_L1', 'Mconv7_stage4_L2', 'Mconv7_stage5_L1',\
30
- 'Mconv7_stage5_L2', 'Mconv7_stage6_L1', 'Mconv7_stage6_L1']
31
- blocks = {}
32
- block0 = OrderedDict([('conv1_1', [3, 64, 3, 1, 1]), ('conv1_2', [64, 64, 3, 1, 1]), ('pool1_stage1', [2, 2,
33
- 0]),
34
- ('conv2_1', [64, 128, 3, 1, 1]), ('conv2_2', [128, 128, 3, 1, 1]),
35
- ('pool2_stage1', [2, 2, 0]), ('conv3_1', [128, 256, 3, 1, 1]),
36
- ('conv3_2', [256, 256, 3, 1, 1]), ('conv3_3', [256, 256, 3, 1, 1]),
37
- ('conv3_4', [256, 256, 3, 1, 1]), ('pool3_stage1', [2, 2, 0]),
38
- ('conv4_1', [256, 512, 3, 1, 1]), ('conv4_2', [512, 512, 3, 1, 1]),
39
- ('conv4_3_CPM', [512, 256, 3, 1, 1]), ('conv4_4_CPM', [256, 128, 3, 1, 1])])
40
-
41
- # Stage 1
42
- block1_1 = OrderedDict([('conv5_1_CPM_L1', [128, 128, 3, 1, 1]), ('conv5_2_CPM_L1', [128, 128, 3, 1, 1]),
43
- ('conv5_3_CPM_L1', [128, 128, 3, 1, 1]), ('conv5_4_CPM_L1', [128, 512, 1, 1, 0]),
44
- ('conv5_5_CPM_L1', [512, 38, 1, 1, 0])])
45
-
46
- block1_2 = OrderedDict([('conv5_1_CPM_L2', [128, 128, 3, 1, 1]), ('conv5_2_CPM_L2', [128, 128, 3, 1, 1]),
47
- ('conv5_3_CPM_L2', [128, 128, 3, 1, 1]), ('conv5_4_CPM_L2', [128, 512, 1, 1, 0]),
48
- ('conv5_5_CPM_L2', [512, 19, 1, 1, 0])])
49
- blocks['block1_1'] = block1_1
50
- blocks['block1_2'] = block1_2
51
-
52
- self.model0 = make_layers(block0, no_relu_layers)
53
-
54
- # Stages 2 - 6
55
- for i in range(2, 7):
56
- blocks['block%d_1' % i] = OrderedDict([('Mconv1_stage%d_L1' % i, [185, 128, 7, 1, 3]),
57
- ('Mconv2_stage%d_L1' % i, [128, 128, 7, 1, 3]),
58
- ('Mconv3_stage%d_L1' % i, [128, 128, 7, 1, 3]),
59
- ('Mconv4_stage%d_L1' % i, [128, 128, 7, 1, 3]),
60
- ('Mconv5_stage%d_L1' % i, [128, 128, 7, 1, 3]),
61
- ('Mconv6_stage%d_L1' % i, [128, 128, 1, 1, 0]),
62
- ('Mconv7_stage%d_L1' % i, [128, 38, 1, 1, 0])])
63
-
64
- blocks['block%d_2' % i] = OrderedDict([('Mconv1_stage%d_L2' % i, [185, 128, 7, 1, 3]),
65
- ('Mconv2_stage%d_L2' % i, [128, 128, 7, 1, 3]),
66
- ('Mconv3_stage%d_L2' % i, [128, 128, 7, 1, 3]),
67
- ('Mconv4_stage%d_L2' % i, [128, 128, 7, 1, 3]),
68
- ('Mconv5_stage%d_L2' % i, [128, 128, 7, 1, 3]),
69
- ('Mconv6_stage%d_L2' % i, [128, 128, 1, 1, 0]),
70
- ('Mconv7_stage%d_L2' % i, [128, 19, 1, 1, 0])])
71
-
72
- for k in blocks.keys():
73
- blocks[k] = make_layers(blocks[k], no_relu_layers)
74
-
75
- self.model1_1 = blocks['block1_1']
76
- self.model2_1 = blocks['block2_1']
77
- self.model3_1 = blocks['block3_1']
78
- self.model4_1 = blocks['block4_1']
79
- self.model5_1 = blocks['block5_1']
80
- self.model6_1 = blocks['block6_1']
81
-
82
- self.model1_2 = blocks['block1_2']
83
- self.model2_2 = blocks['block2_2']
84
- self.model3_2 = blocks['block3_2']
85
- self.model4_2 = blocks['block4_2']
86
- self.model5_2 = blocks['block5_2']
87
- self.model6_2 = blocks['block6_2']
88
-
89
- def forward(self, x):
90
-
91
- out1 = self.model0(x)
92
-
93
- out1_1 = self.model1_1(out1)
94
- out1_2 = self.model1_2(out1)
95
- out2 = torch.cat([out1_1, out1_2, out1], 1)
96
-
97
- out2_1 = self.model2_1(out2)
98
- out2_2 = self.model2_2(out2)
99
- out3 = torch.cat([out2_1, out2_2, out1], 1)
100
-
101
- out3_1 = self.model3_1(out3)
102
- out3_2 = self.model3_2(out3)
103
- out4 = torch.cat([out3_1, out3_2, out1], 1)
104
-
105
- out4_1 = self.model4_1(out4)
106
- out4_2 = self.model4_2(out4)
107
- out5 = torch.cat([out4_1, out4_2, out1], 1)
108
-
109
- out5_1 = self.model5_1(out5)
110
- out5_2 = self.model5_2(out5)
111
- out6 = torch.cat([out5_1, out5_2, out1], 1)
112
-
113
- out6_1 = self.model6_1(out6)
114
- out6_2 = self.model6_2(out6)
115
-
116
- return out6_1, out6_2
117
-
118
-
119
- class handpose_model(nn.Module):
120
-
121
- def __init__(self):
122
- super(handpose_model, self).__init__()
123
-
124
- # these layers have no relu layer
125
- no_relu_layers = ['conv6_2_CPM', 'Mconv7_stage2', 'Mconv7_stage3',\
126
- 'Mconv7_stage4', 'Mconv7_stage5', 'Mconv7_stage6']
127
- # stage 1
128
- block1_0 = OrderedDict([('conv1_1', [3, 64, 3, 1, 1]), ('conv1_2', [64, 64, 3, 1, 1]),
129
- ('pool1_stage1', [2, 2, 0]), ('conv2_1', [64, 128, 3, 1, 1]),
130
- ('conv2_2', [128, 128, 3, 1, 1]), ('pool2_stage1', [2, 2, 0]),
131
- ('conv3_1', [128, 256, 3, 1, 1]), ('conv3_2', [256, 256, 3, 1, 1]),
132
- ('conv3_3', [256, 256, 3, 1, 1]), ('conv3_4', [256, 256, 3, 1, 1]),
133
- ('pool3_stage1', [2, 2, 0]), ('conv4_1', [256, 512, 3, 1, 1]),
134
- ('conv4_2', [512, 512, 3, 1, 1]), ('conv4_3', [512, 512, 3, 1, 1]),
135
- ('conv4_4', [512, 512, 3, 1, 1]), ('conv5_1', [512, 512, 3, 1, 1]),
136
- ('conv5_2', [512, 512, 3, 1, 1]), ('conv5_3_CPM', [512, 128, 3, 1, 1])])
137
-
138
- block1_1 = OrderedDict([('conv6_1_CPM', [128, 512, 1, 1, 0]), ('conv6_2_CPM', [512, 22, 1, 1, 0])])
139
-
140
- blocks = {}
141
- blocks['block1_0'] = block1_0
142
- blocks['block1_1'] = block1_1
143
-
144
- # stage 2-6
145
- for i in range(2, 7):
146
- blocks['block%d' % i] = OrderedDict([('Mconv1_stage%d' % i, [150, 128, 7, 1, 3]),
147
- ('Mconv2_stage%d' % i, [128, 128, 7, 1, 3]),
148
- ('Mconv3_stage%d' % i, [128, 128, 7, 1, 3]),
149
- ('Mconv4_stage%d' % i, [128, 128, 7, 1, 3]),
150
- ('Mconv5_stage%d' % i, [128, 128, 7, 1, 3]),
151
- ('Mconv6_stage%d' % i, [128, 128, 1, 1, 0]),
152
- ('Mconv7_stage%d' % i, [128, 22, 1, 1, 0])])
153
-
154
- for k in blocks.keys():
155
- blocks[k] = make_layers(blocks[k], no_relu_layers)
156
-
157
- self.model1_0 = blocks['block1_0']
158
- self.model1_1 = blocks['block1_1']
159
- self.model2 = blocks['block2']
160
- self.model3 = blocks['block3']
161
- self.model4 = blocks['block4']
162
- self.model5 = blocks['block5']
163
- self.model6 = blocks['block6']
164
-
165
- def forward(self, x):
166
- out1_0 = self.model1_0(x)
167
- out1_1 = self.model1_1(out1_0)
168
- concat_stage2 = torch.cat([out1_1, out1_0], 1)
169
- out_stage2 = self.model2(concat_stage2)
170
- concat_stage3 = torch.cat([out_stage2, out1_0], 1)
171
- out_stage3 = self.model3(concat_stage3)
172
- concat_stage4 = torch.cat([out_stage3, out1_0], 1)
173
- out_stage4 = self.model4(concat_stage4)
174
- concat_stage5 = torch.cat([out_stage4, out1_0], 1)
175
- out_stage5 = self.model5(concat_stage5)
176
- concat_stage6 = torch.cat([out_stage5, out1_0], 1)
177
- out_stage6 = self.model6(concat_stage6)
178
- return out_stage6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Adr740/Hadith_AI_Explorer/app.py DELETED
@@ -1,38 +0,0 @@
1
- import gradio as gr
2
- from functools import partial
3
- from get_hadith import get_hadiths
4
- import pandas as pd
5
-
6
- title = "Hadith AI Explorer"
7
- desc = "This is a tool that helps you find quickly relevant hadiths on a topic or a problem you have. Just type in plain English what you are looking for in the box below. Contact suggestions/questions: [email protected]\n\n"
8
- warning = "Warning!\n **PLEASE READ THE DISCLAIMER BELOW** This isn't a 100% accurate tool and not all the Hadiths are present in the database and some results might be repetitive. If it's the case, try generating more Hadiths with the selector.\nMore informations describing how the tool works are coming soon"
9
- disclaimer = "## DISCLAIMER\n\nTHIS TOOL IS INTENDED FOR REFERENCE PURPOSES ONLY AND IS NOT INTENDED TO BE TAKEN AS RELIGIOUS ADVICE. THE HADITHS DISPLAYED BY THIS TOOL ARE NOT INTENDED TO BE USED AS A SOLE SOURCE OF RELIGIOUS GUIDANCE. USERS ARE RESPONSIBLE FOR CONDUCTING THEIR OWN RESEARCH AND SEEKING GUIDANCE FROM RELIGIOUS SCHOLARS.\n\nPLEASE NOTE THAT THE CONTENT DISPLAYED BY THIS TOOL IS NOT GUARANTEED TO BE ACCURATE, COMPLETE, OR UP-TO-DATE.\n\nTHE DEVELOPERS OF THIS TOOL WILL NOT BE HELD RESPONSIBLE FOR ANY DECISIONS MADE BY THE USERS OF THIS TOOL THAT ARE BASED ON THE CONTENT DISPLAYED BY THIS TOOL.\n\nHadiths gathered from this repository: https:\/\/www.kaggle.com\/datasets\/fahd09\/hadith-dataset"
10
- def iter_grid(n_rows, n_cols):
11
- for _ in range(n_rows):
12
- with gr.Row():
13
- for _ in range(n_cols):
14
- with gr.Column():
15
- yield
16
- with gr.Blocks(title=title) as demo:
17
- gr.Markdown(f"## {title}")
18
- gr.Markdown(desc)
19
- gr.Markdown(warning)
20
- with gr.Row():
21
- with gr.Column(scale=4):
22
- text_area = gr.Textbox(placeholder="Write here", lines=3, label="Describe your topic or what you are looking for")
23
- with gr.Column(scale=1):
24
- number_to_display = gr.Number(value=10,label = "Number of Hadiths to display")
25
- submit_button = gr.Button(value="Search for hadiths")
26
- pass
27
-
28
- fn = partial(get_hadiths)
29
-
30
- with gr.Accordion("All results:"):
31
- ll = gr.Markdown("Empty")
32
- gr.Markdown(disclaimer)
33
-
34
- submit_button.click(fn=fn, inputs=[text_area,number_to_display], outputs=[ll])
35
-
36
-
37
-
38
- demo.launch( enable_queue=True,max_threads=40)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/classes/player.ts DELETED
@@ -1,66 +0,0 @@
1
- import { Actor } from "./actor";
2
- export class Player extends Actor {
3
- private keyW: Phaser.Input.Keyboard.Key;
4
- private keyA: Phaser.Input.Keyboard.Key;
5
- private keyS: Phaser.Input.Keyboard.Key;
6
- private keyD: Phaser.Input.Keyboard.Key;
7
-
8
- constructor(scene: Phaser.Scene, x: number, y: number) {
9
- super(scene, x, y, "Brendan");
10
-
11
- this.setName("Brendan");
12
-
13
- // Keys
14
- this.initKeyboard();
15
-
16
- // PHYSICS
17
- this.getBody().setSize(14, 16);
18
- this.getBody().setOffset(0, 5);
19
-
20
- // ANIMATIONS
21
- this.initAnimations();
22
- }
23
-
24
- update(): void {
25
- this.getBody().setVelocity(0);
26
-
27
- var pressed_flag = false;
28
- if (this.keyW.enabled && this.keyW?.isDown) {
29
- this.getBody().setVelocityY(-110);
30
- this.anims.play(this.name + "-walk-up", true);
31
- pressed_flag = true;
32
- }
33
-
34
- if (this.keyA.enabled && this.keyA?.isDown) {
35
- // this.getBody().setOffset(48, 15);
36
- this.getBody().setVelocityX(-110);
37
- this.anims.play(this.name + "-walk-left", true);
38
- pressed_flag = true;
39
- }
40
-
41
- if (this.keyS.enabled && this.keyS?.isDown) {
42
- this.getBody().setVelocityY(110);
43
- this.anims.play(this.name + "-walk-down", true);
44
- pressed_flag = true;
45
- }
46
-
47
- if (this.keyD.enabled && this.keyD?.isDown) {
48
- this.getBody().setVelocityX(110);
49
- this.anims.play(this.name + "-walk-right", true);
50
- // this.getBody().setOffset(15, 15);
51
- pressed_flag = true;
52
- }
53
-
54
- if (!pressed_flag && this.anims.isPlaying) {
55
- this.anims.setCurrentFrame(this.anims.currentAnim!.frames[0]);
56
- }
57
- this.depth = this.y + 0.5 * this.height;
58
- }
59
-
60
- initKeyboard(): void {
61
- this.keyW = this.scene.input.keyboard!.addKey("W");
62
- this.keyA = this.scene.input.keyboard!.addKey("A");
63
- this.keyS = this.scene.input.keyboard!.addKey("S");
64
- this.keyD = this.scene.input.keyboard!.addKey("D");
65
- }
66
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/plugins/shakeposition-plugin.js DELETED
@@ -1,19 +0,0 @@
1
- import Shake from './shakeposition.js';
2
-
3
- class ShakePlugin extends Phaser.Plugins.BasePlugin {
4
-
5
- constructor(pluginManager) {
6
- super(pluginManager);
7
- }
8
-
9
- start() {
10
- var eventEmitter = this.game.events;
11
- eventEmitter.on('destroy', this.destroy, this);
12
- }
13
-
14
- add(gameObject, config) {
15
- return new Shake(gameObject, config);
16
- }
17
- }
18
-
19
- export default ShakePlugin;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/AgentVerse/agentVerse/ui/src/phaser3-rex-plugins/templates/ui/sizer/GetChildrenWidth.js DELETED
@@ -1,58 +0,0 @@
1
- var GetChildrenWidth = function (minimumMode) {
2
- if (this.rexSizer.hidden) {
3
- return 0;
4
- }
5
-
6
- if (minimumMode === undefined) {
7
- minimumMode = true;
8
- }
9
-
10
- var result = 0;
11
- var children = this.sizerChildren;
12
- var child, padding, childWidth;
13
- if (this.orientation === 0) { // x
14
- // Get summation of minimum width
15
- var itemSpace = this.space.item;
16
- var isFirstChild = true;
17
- for (var i = 0, cnt = children.length; i < cnt; i++) {
18
- child = children[i];
19
- if (child.rexSizer.hidden) {
20
- continue;
21
- }
22
-
23
- if ((child.rexSizer.proportion === 0) || minimumMode) {
24
- childWidth = this.getChildWidth(child);
25
- } else {
26
- childWidth = 0;
27
- }
28
- padding = child.rexSizer.padding;
29
- childWidth += (padding.left + padding.right);
30
-
31
- if (isFirstChild) {
32
- isFirstChild = false;
33
- } else {
34
- childWidth += itemSpace;
35
- }
36
-
37
- result += childWidth;
38
- }
39
- } else {
40
- // Get maximun width
41
- for (var i = 0, cnt = children.length; i < cnt; i++) {
42
- child = children[i];
43
- if (!child.hasOwnProperty('rexSizer')) {
44
- continue;
45
- }
46
- if (child.rexSizer.hidden) {
47
- continue;
48
- }
49
-
50
- padding = child.rexSizer.padding;
51
- childWidth = this.getChildWidth(child) + padding.left + padding.right;
52
- result = Math.max(childWidth, result);
53
- }
54
- }
55
- return result + this.space.left + this.space.right;
56
- }
57
-
58
- export default GetChildrenWidth;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ameaou/academic-chatgpt3.1/crazy_functions/test_project/python/dqn/__init__.py DELETED
@@ -1,2 +0,0 @@
1
- from stable_baselines3.dqn.dqn import DQN
2
- from stable_baselines3.dqn.policies import CnnPolicy, MlpPolicy
 
 
 
spaces/Amrrs/DragGan-Inversion/PTI/models/StyleCLIP/global_directions/dnnlib/tflib/custom_ops.py DELETED
@@ -1,181 +0,0 @@
1
- # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
2
- #
3
- # NVIDIA CORPORATION and its licensors retain all intellectual property
4
- # and proprietary rights in and to this software, related documentation
5
- # and any modifications thereto. Any use, reproduction, disclosure or
6
- # distribution of this software and related documentation without an express
7
- # license agreement from NVIDIA CORPORATION is strictly prohibited.
8
-
9
- """TensorFlow custom ops builder.
10
- """
11
-
12
- import glob
13
- import os
14
- import re
15
- import uuid
16
- import hashlib
17
- import tempfile
18
- import shutil
19
- import tensorflow as tf
20
- from tensorflow.python.client import device_lib # pylint: disable=no-name-in-module
21
-
22
- from .. import util
23
-
24
- #----------------------------------------------------------------------------
25
- # Global configs.
26
-
27
- cuda_cache_path = None
28
- cuda_cache_version_tag = 'v1'
29
- do_not_hash_included_headers = True # Speed up compilation by assuming that headers included by the CUDA code never change.
30
- verbose = True # Print status messages to stdout.
31
-
32
- #----------------------------------------------------------------------------
33
- # Internal helper funcs.
34
-
35
- def _find_compiler_bindir():
36
- hostx64_paths = sorted(glob.glob('C:/Program Files (x86)/Microsoft Visual Studio/*/Professional/VC/Tools/MSVC/*/bin/Hostx64/x64'), reverse=True)
37
- if hostx64_paths != []:
38
- return hostx64_paths[0]
39
- hostx64_paths = sorted(glob.glob('C:/Program Files (x86)/Microsoft Visual Studio/*/BuildTools/VC/Tools/MSVC/*/bin/Hostx64/x64'), reverse=True)
40
- if hostx64_paths != []:
41
- return hostx64_paths[0]
42
- hostx64_paths = sorted(glob.glob('C:/Program Files (x86)/Microsoft Visual Studio/*/Community/VC/Tools/MSVC/*/bin/Hostx64/x64'), reverse=True)
43
- if hostx64_paths != []:
44
- return hostx64_paths[0]
45
- vc_bin_dir = 'C:/Program Files (x86)/Microsoft Visual Studio 14.0/vc/bin'
46
- if os.path.isdir(vc_bin_dir):
47
- return vc_bin_dir
48
- return None
49
-
50
- def _get_compute_cap(device):
51
- caps_str = device.physical_device_desc
52
- m = re.search('compute capability: (\\d+).(\\d+)', caps_str)
53
- major = m.group(1)
54
- minor = m.group(2)
55
- return (major, minor)
56
-
57
- def _get_cuda_gpu_arch_string():
58
- gpus = [x for x in device_lib.list_local_devices() if x.device_type == 'GPU']
59
- if len(gpus) == 0:
60
- raise RuntimeError('No GPU devices found')
61
- (major, minor) = _get_compute_cap(gpus[0])
62
- return 'sm_%s%s' % (major, minor)
63
-
64
- def _run_cmd(cmd):
65
- with os.popen(cmd) as pipe:
66
- output = pipe.read()
67
- status = pipe.close()
68
- if status is not None:
69
- raise RuntimeError('NVCC returned an error. See below for full command line and output log:\n\n%s\n\n%s' % (cmd, output))
70
-
71
- def _prepare_nvcc_cli(opts):
72
- cmd = 'nvcc ' + opts.strip()
73
- cmd += ' --disable-warnings'
74
- cmd += ' --include-path "%s"' % tf.sysconfig.get_include()
75
- cmd += ' --include-path "%s"' % os.path.join(tf.sysconfig.get_include(), 'external', 'protobuf_archive', 'src')
76
- cmd += ' --include-path "%s"' % os.path.join(tf.sysconfig.get_include(), 'external', 'com_google_absl')
77
- cmd += ' --include-path "%s"' % os.path.join(tf.sysconfig.get_include(), 'external', 'eigen_archive')
78
-
79
- compiler_bindir = _find_compiler_bindir()
80
- if compiler_bindir is None:
81
- # Require that _find_compiler_bindir succeeds on Windows. Allow
82
- # nvcc to use whatever is the default on Linux.
83
- if os.name == 'nt':
84
- raise RuntimeError('Could not find MSVC/GCC/CLANG installation on this computer. Check compiler_bindir_search_path list in "%s".' % __file__)
85
- else:
86
- cmd += ' --compiler-bindir "%s"' % compiler_bindir
87
- cmd += ' 2>&1'
88
- return cmd
89
-
90
- #----------------------------------------------------------------------------
91
- # Main entry point.
92
-
93
- _plugin_cache = dict()
94
-
95
- def get_plugin(cuda_file, extra_nvcc_options=[]):
96
- cuda_file_base = os.path.basename(cuda_file)
97
- cuda_file_name, cuda_file_ext = os.path.splitext(cuda_file_base)
98
-
99
- # Already in cache?
100
- if cuda_file in _plugin_cache:
101
- return _plugin_cache[cuda_file]
102
-
103
- # Setup plugin.
104
- if verbose:
105
- print('Setting up TensorFlow plugin "%s": ' % cuda_file_base, end='', flush=True)
106
- try:
107
- # Hash CUDA source.
108
- md5 = hashlib.md5()
109
- with open(cuda_file, 'rb') as f:
110
- md5.update(f.read())
111
- md5.update(b'\n')
112
-
113
- # Hash headers included by the CUDA code by running it through the preprocessor.
114
- if not do_not_hash_included_headers:
115
- if verbose:
116
- print('Preprocessing... ', end='', flush=True)
117
- with tempfile.TemporaryDirectory() as tmp_dir:
118
- tmp_file = os.path.join(tmp_dir, cuda_file_name + '_tmp' + cuda_file_ext)
119
- _run_cmd(_prepare_nvcc_cli('"%s" --preprocess -o "%s" --keep --keep-dir "%s"' % (cuda_file, tmp_file, tmp_dir)))
120
- with open(tmp_file, 'rb') as f:
121
- bad_file_str = ('"' + cuda_file.replace('\\', '/') + '"').encode('utf-8') # __FILE__ in error check macros
122
- good_file_str = ('"' + cuda_file_base + '"').encode('utf-8')
123
- for ln in f:
124
- if not ln.startswith(b'# ') and not ln.startswith(b'#line '): # ignore line number pragmas
125
- ln = ln.replace(bad_file_str, good_file_str)
126
- md5.update(ln)
127
- md5.update(b'\n')
128
-
129
- # Select compiler configs.
130
- compile_opts = ''
131
- if os.name == 'nt':
132
- compile_opts += '"%s"' % os.path.join(tf.sysconfig.get_lib(), 'python', '_pywrap_tensorflow_internal.lib')
133
- elif os.name == 'posix':
134
- compile_opts += f' --compiler-options \'-fPIC\''
135
- compile_opts += f' --compiler-options \'{" ".join(tf.sysconfig.get_compile_flags())}\''
136
- compile_opts += f' --linker-options \'{" ".join(tf.sysconfig.get_link_flags())}\''
137
- else:
138
- assert False # not Windows or Linux, w00t?
139
- compile_opts += f' --gpu-architecture={_get_cuda_gpu_arch_string()}'
140
- compile_opts += ' --use_fast_math'
141
- for opt in extra_nvcc_options:
142
- compile_opts += ' ' + opt
143
- nvcc_cmd = _prepare_nvcc_cli(compile_opts)
144
-
145
- # Hash build configuration.
146
- md5.update(('nvcc_cmd: ' + nvcc_cmd).encode('utf-8') + b'\n')
147
- md5.update(('tf.VERSION: ' + tf.VERSION).encode('utf-8') + b'\n')
148
- md5.update(('cuda_cache_version_tag: ' + cuda_cache_version_tag).encode('utf-8') + b'\n')
149
-
150
- # Compile if not already compiled.
151
- cache_dir = util.make_cache_dir_path('tflib-cudacache') if cuda_cache_path is None else cuda_cache_path
152
- bin_file_ext = '.dll' if os.name == 'nt' else '.so'
153
- bin_file = os.path.join(cache_dir, cuda_file_name + '_' + md5.hexdigest() + bin_file_ext)
154
- if not os.path.isfile(bin_file):
155
- if verbose:
156
- print('Compiling... ', end='', flush=True)
157
- with tempfile.TemporaryDirectory() as tmp_dir:
158
- tmp_file = os.path.join(tmp_dir, cuda_file_name + '_tmp' + bin_file_ext)
159
- _run_cmd(nvcc_cmd + ' "%s" --shared -o "%s" --keep --keep-dir "%s"' % (cuda_file, tmp_file, tmp_dir))
160
- os.makedirs(cache_dir, exist_ok=True)
161
- intermediate_file = os.path.join(cache_dir, cuda_file_name + '_' + uuid.uuid4().hex + '_tmp' + bin_file_ext)
162
- shutil.copyfile(tmp_file, intermediate_file)
163
- os.rename(intermediate_file, bin_file) # atomic
164
-
165
- # Load.
166
- if verbose:
167
- print('Loading... ', end='', flush=True)
168
- plugin = tf.load_op_library(bin_file)
169
-
170
- # Add to cache.
171
- _plugin_cache[cuda_file] = plugin
172
- if verbose:
173
- print('Done.', flush=True)
174
- return plugin
175
-
176
- except:
177
- if verbose:
178
- print('Failed!', flush=True)
179
- raise
180
-
181
- #----------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/docs/source/ko/using-diffusers/pipeline_overview.md DELETED
@@ -1,17 +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
- # Overview
14
-
15
- 파이프라인은 독립적으로 훈련된 모델과 스케줄러를 함께 모아서 추론을 위해 diffusion 시스템을 빠르고 쉽게 사용할 수 있는 방법을 제공하는 end-to-end 클래스입니다. 모델과 스케줄러의 특정 조합은 특수한 기능과 함께 [`StableDiffusionPipeline`] 또는 [`StableDiffusionControlNetPipeline`]과 같은 특정 파이프라인 유형을 정의합니다. 모든 파이프라인 유형은 기본 [`DiffusionPipeline`] 클래스에서 상속됩니다. 어느 체크포인트를 전달하면, 파이프라인 유형을 자동으로 감지하고 필요한 구성 요소들을 불러옵니다.
16
-
17
- 이 섹션에서는 unconditional 이미지 생성, text-to-image 생성의 다양한 테크닉과 변화를 파이프라인에서 지원하는 작업들을 소개합니다. 프롬프트에 있는 특정 단어가 출력에 영향을 미치는 것을 조정하기 위해 재현성을 위한 시드 설정과 프롬프트에 가중치를 부여하는 것으로 생성 프로세스를 더 잘 제어하는 방법에 대해 배울 수 있습니다. 마지막으로 음성에서부터 이미지 생성과 같은 커스텀 작업을 위한 커뮤니티 파이프라인을 만드는 방법을 알 수 있습니다.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Androidonnxfork/CivitAi-to-Diffusers/diffusers/src/diffusers/pipelines/kandinsky/text_encoder.py DELETED
@@ -1,27 +0,0 @@
1
- import torch
2
- from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel
3
-
4
-
5
- class MCLIPConfig(XLMRobertaConfig):
6
- model_type = "M-CLIP"
7
-
8
- def __init__(self, transformerDimSize=1024, imageDimSize=768, **kwargs):
9
- self.transformerDimensions = transformerDimSize
10
- self.numDims = imageDimSize
11
- super().__init__(**kwargs)
12
-
13
-
14
- class MultilingualCLIP(PreTrainedModel):
15
- config_class = MCLIPConfig
16
-
17
- def __init__(self, config, *args, **kwargs):
18
- super().__init__(config, *args, **kwargs)
19
- self.transformer = XLMRobertaModel(config)
20
- self.LinearTransformation = torch.nn.Linear(
21
- in_features=config.transformerDimensions, out_features=config.numDims
22
- )
23
-
24
- def forward(self, input_ids, attention_mask):
25
- embs = self.transformer(input_ids=input_ids, attention_mask=attention_mask)[0]
26
- embs2 = (embs * attention_mask.unsqueeze(2)).sum(dim=1) / attention_mask.sum(dim=1)[:, None]
27
- return self.LinearTransformation(embs2), embs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anew5128/Anew51/README.md DELETED
@@ -1,11 +0,0 @@
1
- ---
2
- title: extras
3
- emoji: 🧊
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: docker
7
- pinned: false
8
- license: mit
9
- duplicated_from: doctord98/extras
10
- ---
11
- Fixed Server.JS Latest 2023/08/16
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-123/ImageNet-Editing/object_removal/TFill/options/test_options.py DELETED
@@ -1,16 +0,0 @@
1
- from .base_options import BaseOptions
2
-
3
-
4
- class TestOptions(BaseOptions):
5
- def initialize(self, parser):
6
- parser = BaseOptions.initialize(self, parser)
7
-
8
- parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here')
9
- parser.add_argument('--how_many', type=int, default=float("inf"), help='how many test examples to run')
10
- parser.add_argument('--phase', type=str, default='test', help='train, val, test')
11
- parser.add_argument('--eval', action='store_true', help='use eval mode during test time.')
12
- parser.add_argument('--nsampling', type=int, default=1, help='ramplimg # times for each examples')
13
-
14
- self.isTrain = False
15
-
16
- return parser
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Anonymous-sub/Rerender/ControlNet/annotator/uniformer/mmcv/runner/hooks/sync_buffer.py DELETED
@@ -1,22 +0,0 @@
1
- # Copyright (c) OpenMMLab. All rights reserved.
2
- from ..dist_utils import allreduce_params
3
- from .hook import HOOKS, Hook
4
-
5
-
6
- @HOOKS.register_module()
7
- class SyncBuffersHook(Hook):
8
- """Synchronize model buffers such as running_mean and running_var in BN at
9
- the end of each epoch.
10
-
11
- Args:
12
- distributed (bool): Whether distributed training is used. It is
13
- effective only for distributed training. Defaults to True.
14
- """
15
-
16
- def __init__(self, distributed=True):
17
- self.distributed = distributed
18
-
19
- def after_epoch(self, runner):
20
- """All-reduce model buffers at the end of each epoch."""
21
- if self.distributed:
22
- allreduce_params(runner.model.buffers())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Arnaudding001/OpenAI_whisperLive/app.py DELETED
@@ -1,260 +0,0 @@
1
- from typing import Iterator
2
-
3
- from io import StringIO
4
- import os
5
- import pathlib
6
- import tempfile
7
-
8
- # External programs
9
- import whisper
10
- import ffmpeg
11
-
12
- # UI
13
- import gradio as gr
14
-
15
- from download import ExceededMaximumDuration, download_url
16
- from utils import slugify, write_srt, write_vtt
17
- from vad import NonSpeechStrategy, PeriodicTranscriptionConfig, TranscriptionConfig, VadPeriodicTranscription, VadSileroTranscription
18
-
19
- # Limitations (set to -1 to disable)
20
- DEFAULT_INPUT_AUDIO_MAX_DURATION = 3605 # seconds #initial value 600
21
-
22
- # Whether or not to automatically delete all uploaded files, to save disk space
23
- DELETE_UPLOADED_FILES = True
24
-
25
- # Gradio seems to truncate files without keeping the extension, so we need to truncate the file prefix ourself
26
- MAX_FILE_PREFIX_LENGTH = 17
27
-
28
- LANGUAGES = [
29
- "English", "Chinese", "German", "Spanish", "Russian", "Korean",
30
- "French", "Japanese", "Portuguese", "Turkish", "Polish", "Catalan",
31
- "Dutch", "Arabic", "Swedish", "Italian", "Indonesian", "Hindi",
32
- "Finnish", "Vietnamese", "Hebrew", "Ukrainian", "Greek", "Malay",
33
- "Czech", "Romanian", "Danish", "Hungarian", "Tamil", "Norwegian",
34
- "Thai", "Urdu", "Croatian", "Bulgarian", "Lithuanian", "Latin",
35
- "Maori", "Malayalam", "Welsh", "Slovak", "Telugu", "Persian",
36
- "Latvian", "Bengali", "Serbian", "Azerbaijani", "Slovenian",
37
- "Kannada", "Estonian", "Macedonian", "Breton", "Basque", "Icelandic",
38
- "Armenian", "Nepali", "Mongolian", "Bosnian", "Kazakh", "Albanian",
39
- "Swahili", "Galician", "Marathi", "Punjabi", "Sinhala", "Khmer",
40
- "Shona", "Yoruba", "Somali", "Afrikaans", "Occitan", "Georgian",
41
- "Belarusian", "Tajik", "Sindhi", "Gujarati", "Amharic", "Yiddish",
42
- "Lao", "Uzbek", "Faroese", "Haitian Creole", "Pashto", "Turkmen",
43
- "Nynorsk", "Maltese", "Sanskrit", "Luxembourgish", "Myanmar", "Tibetan",
44
- "Tagalog", "Malagasy", "Assamese", "Tatar", "Hawaiian", "Lingala",
45
- "Hausa", "Bashkir", "Javanese", "Sundanese"
46
- ]
47
-
48
- class WhisperTranscriber:
49
- def __init__(self, inputAudioMaxDuration: float = DEFAULT_INPUT_AUDIO_MAX_DURATION, deleteUploadedFiles: bool = DELETE_UPLOADED_FILES):
50
- self.model_cache = dict()
51
-
52
- self.vad_model = None
53
- self.inputAudioMaxDuration = inputAudioMaxDuration
54
- self.deleteUploadedFiles = deleteUploadedFiles
55
-
56
- def transcribe_webui(self, modelName, languageName, urlData, uploadFile, microphoneData, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow):
57
- try:
58
- source, sourceName = self.__get_source(urlData, uploadFile, microphoneData)
59
-
60
- try:
61
- selectedLanguage = languageName.lower() if len(languageName) > 0 else None
62
- selectedModel = modelName if modelName is not None else "base"
63
-
64
- model = self.model_cache.get(selectedModel, None)
65
-
66
- if not model:
67
- model = whisper.load_model(selectedModel)
68
- self.model_cache[selectedModel] = model
69
-
70
- # Execute whisper
71
- result = self.transcribe_file(model, source, selectedLanguage, task, vad, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
72
-
73
- # Write result
74
- downloadDirectory = tempfile.mkdtemp()
75
-
76
- filePrefix = slugify(sourceName, allow_unicode=True)
77
- download, text, vtt = self.write_result(result, filePrefix, downloadDirectory)
78
-
79
- return download, text, vtt
80
-
81
- finally:
82
- # Cleanup source
83
- if self.deleteUploadedFiles:
84
- print("Deleting source file " + source)
85
- os.remove(source)
86
-
87
- except ExceededMaximumDuration as e:
88
- return [], ("[ERROR]: Maximum remote video length is " + str(e.maxDuration) + "s, file was " + str(e.videoDuration) + "s"), "[ERROR]"
89
-
90
- def transcribe_file(self, model: whisper.Whisper, audio_path: str, language: str, task: str = None, vad: str = None,
91
- vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1, **decodeOptions: dict):
92
-
93
- initial_prompt = decodeOptions.pop('initial_prompt', None)
94
-
95
- if ('task' in decodeOptions):
96
- task = decodeOptions.pop('task')
97
-
98
- # Callable for processing an audio file
99
- whisperCallable = lambda audio, segment_index, prompt, detected_language : model.transcribe(audio, \
100
- language=language if language else detected_language, task=task, \
101
- initial_prompt=self._concat_prompt(initial_prompt, prompt) if segment_index == 0 else prompt, \
102
- **decodeOptions)
103
-
104
- # The results
105
- if (vad == 'silero-vad'):
106
- # Silero VAD where non-speech gaps are transcribed
107
- process_gaps = self._create_silero_config(NonSpeechStrategy.CREATE_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
108
- result = self.vad_model.transcribe(audio_path, whisperCallable, process_gaps)
109
- elif (vad == 'silero-vad-skip-gaps'):
110
- # Silero VAD where non-speech gaps are simply ignored
111
- skip_gaps = self._create_silero_config(NonSpeechStrategy.SKIP, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
112
- result = self.vad_model.transcribe(audio_path, whisperCallable, skip_gaps)
113
- elif (vad == 'silero-vad-expand-into-gaps'):
114
- # Use Silero VAD where speech-segments are expanded into non-speech gaps
115
- expand_gaps = self._create_silero_config(NonSpeechStrategy.EXPAND_SEGMENT, vadMergeWindow, vadMaxMergeSize, vadPadding, vadPromptWindow)
116
- result = self.vad_model.transcribe(audio_path, whisperCallable, expand_gaps)
117
- elif (vad == 'periodic-vad'):
118
- # Very simple VAD - mark every 5 minutes as speech. This makes it less likely that Whisper enters an infinite loop, but
119
- # it may create a break in the middle of a sentence, causing some artifacts.
120
- periodic_vad = VadPeriodicTranscription()
121
- result = periodic_vad.transcribe(audio_path, whisperCallable, PeriodicTranscriptionConfig(periodic_duration=vadMaxMergeSize, max_prompt_window=vadPromptWindow))
122
- else:
123
- # Default VAD
124
- result = whisperCallable(audio_path, 0, None, None)
125
-
126
- return result
127
-
128
- def _concat_prompt(self, prompt1, prompt2):
129
- if (prompt1 is None):
130
- return prompt2
131
- elif (prompt2 is None):
132
- return prompt1
133
- else:
134
- return prompt1 + " " + prompt2
135
-
136
- def _create_silero_config(self, non_speech_strategy: NonSpeechStrategy, vadMergeWindow: float = 5, vadMaxMergeSize: float = 150, vadPadding: float = 1, vadPromptWindow: float = 1):
137
- # Use Silero VAD
138
- if (self.vad_model is None):
139
- self.vad_model = VadSileroTranscription()
140
-
141
- config = TranscriptionConfig(non_speech_strategy = non_speech_strategy,
142
- max_silent_period=vadMergeWindow, max_merge_size=vadMaxMergeSize,
143
- segment_padding_left=vadPadding, segment_padding_right=vadPadding,
144
- max_prompt_window=vadPromptWindow)
145
-
146
- return config
147
-
148
- def write_result(self, result: dict, source_name: str, output_dir: str):
149
- if not os.path.exists(output_dir):
150
- os.makedirs(output_dir)
151
-
152
- text = result["text"]
153
- language = result["language"]
154
- languageMaxLineWidth = self.__get_max_line_width(language)
155
-
156
- print("Max line width " + str(languageMaxLineWidth))
157
- vtt = self.__get_subs(result["segments"], "vtt", languageMaxLineWidth)
158
- srt = self.__get_subs(result["segments"], "srt", languageMaxLineWidth)
159
-
160
- output_files = []
161
- output_files.append(self.__create_file(srt, output_dir, source_name + "-subs.srt"));
162
- output_files.append(self.__create_file(vtt, output_dir, source_name + "-subs.vtt"));
163
- output_files.append(self.__create_file(text, output_dir, source_name + "-transcript.txt"));
164
-
165
- return output_files, text, vtt
166
-
167
- def clear_cache(self):
168
- self.model_cache = dict()
169
- self.vad_model = None
170
-
171
- def __get_source(self, urlData, uploadFile, microphoneData):
172
- if urlData:
173
- # Download from YouTube
174
- source = download_url(urlData, self.inputAudioMaxDuration)[0]
175
- else:
176
- # File input
177
- source = uploadFile if uploadFile is not None else microphoneData
178
-
179
- if self.inputAudioMaxDuration > 0:
180
- # Calculate audio length
181
- audioDuration = ffmpeg.probe(source)["format"]["duration"]
182
-
183
- if float(audioDuration) > self.inputAudioMaxDuration:
184
- raise ExceededMaximumDuration(videoDuration=audioDuration, maxDuration=self.inputAudioMaxDuration, message="Video is too long")
185
-
186
- file_path = pathlib.Path(source)
187
- sourceName = file_path.stem[:MAX_FILE_PREFIX_LENGTH] + file_path.suffix
188
-
189
- return source, sourceName
190
-
191
- def __get_max_line_width(self, language: str) -> int:
192
- if (language and language.lower() in ["japanese", "ja", "chinese", "zh"]):
193
- # Chinese characters and kana are wider, so limit line length to 40 characters
194
- return 40
195
- else:
196
- # TODO: Add more languages
197
- # 80 latin characters should fit on a 1080p/720p screen
198
- return 80
199
-
200
- def __get_subs(self, segments: Iterator[dict], format: str, maxLineWidth: int) -> str:
201
- segmentStream = StringIO()
202
-
203
- if format == 'vtt':
204
- write_vtt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
205
- elif format == 'srt':
206
- write_srt(segments, file=segmentStream, maxLineWidth=maxLineWidth)
207
- else:
208
- raise Exception("Unknown format " + format)
209
-
210
- segmentStream.seek(0)
211
- return segmentStream.read()
212
-
213
- def __create_file(self, text: str, directory: str, fileName: str) -> str:
214
- # Write the text to a file
215
- with open(os.path.join(directory, fileName), 'w+', encoding="utf-8") as file:
216
- file.write(text)
217
-
218
- return file.name
219
-
220
- # translate_checkbox = gr.inputs.Checkbox(label = "Translate to English", default=False)
221
- # transcription_tb = gr.Textbox(label="Transcription", lines=10, max_lines=20)
222
- # translation_tb = gr.Textbox(label="Translation", lines=10, max_lines=20)
223
- # detected_lang = gr.outputs.HTML(label="Detected Language")
224
-
225
-
226
-
227
- def create_ui(inputAudioMaxDuration, share=False, server_name: str = None):
228
- ui = WhisperTranscriber(inputAudioMaxDuration)
229
-
230
- ui_description = "Whisper是一个语音转文字模型,经过多个语音数据集的训练而成。也可以进行多语言的识别任务和翻译(多种语言翻译成英文)"
231
-
232
-
233
- ui_description += "\n\n\n\n对于时长大于20分钟的非英语音频文件,建议选择VAD选项中的Silero VAD (语音活动检测器)。"
234
-
235
- if inputAudioMaxDuration > 0:
236
- ui_description += "\n\n" + "音频最大时长: " + str(inputAudioMaxDuration) + " 秒"
237
-
238
-
239
- demo = gr.Interface(fn=ui.transcribe_webui, description=ui_description, inputs=[
240
- gr.Dropdown(choices=["tiny", "base", "small", "medium", "large"], value="medium", label="Model"),
241
- gr.Dropdown(choices=sorted(LANGUAGES), label="Language"),
242
- gr.Text(label="URL (YouTube, etc.)"),
243
- gr.Audio(source="upload", type="filepath", label="Upload Audio"),
244
- gr.Audio(source="microphone", type="filepath", label="Microphone Input"),
245
- gr.Dropdown(choices=["transcribe", "translate"], label="Task"),
246
- gr.Dropdown(choices=["none", "silero-vad", "silero-vad-skip-gaps", "silero-vad-expand-into-gaps", "periodic-vad"], label="VAD"),
247
- gr.Number(label="VAD - Merge Window (s)", precision=0, value=5),
248
- gr.Number(label="VAD - Max Merge Size (s)", precision=0, value=30),
249
- gr.Number(label="VAD - Padding (s)", precision=None, value=1),
250
- gr.Number(label="VAD - Prompt Window (s)", precision=None, value=3)
251
- ], outputs=[
252
- gr.File(label="Download"),
253
- gr.Text(label="Transcription"),
254
- gr.Text(label="Segments")
255
- ])
256
-
257
- demo.launch(share=share, server_name=server_name)
258
-
259
- if __name__ == '__main__':
260
- create_ui(DEFAULT_INPUT_AUDIO_MAX_DURATION)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Ataturk-Chatbot/HuggingFaceChat/venv/lib/python3.11/site-packages/setuptools/_vendor/packaging/requirements.py DELETED
@@ -1,146 +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
- import string
7
- import urllib.parse
8
- from typing import List, Optional as TOptional, Set
9
-
10
- from setuptools.extern.pyparsing import ( # noqa
11
- Combine,
12
- Literal as L,
13
- Optional,
14
- ParseException,
15
- Regex,
16
- Word,
17
- ZeroOrMore,
18
- originalTextFor,
19
- stringEnd,
20
- stringStart,
21
- )
22
-
23
- from .markers import MARKER_EXPR, Marker
24
- from .specifiers import LegacySpecifier, Specifier, SpecifierSet
25
-
26
-
27
- class InvalidRequirement(ValueError):
28
- """
29
- An invalid requirement was found, users should refer to PEP 508.
30
- """
31
-
32
-
33
- ALPHANUM = Word(string.ascii_letters + string.digits)
34
-
35
- LBRACKET = L("[").suppress()
36
- RBRACKET = L("]").suppress()
37
- LPAREN = L("(").suppress()
38
- RPAREN = L(")").suppress()
39
- COMMA = L(",").suppress()
40
- SEMICOLON = L(";").suppress()
41
- AT = L("@").suppress()
42
-
43
- PUNCTUATION = Word("-_.")
44
- IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM)
45
- IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END))
46
-
47
- NAME = IDENTIFIER("name")
48
- EXTRA = IDENTIFIER
49
-
50
- URI = Regex(r"[^ ]+")("url")
51
- URL = AT + URI
52
-
53
- EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA)
54
- EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras")
55
-
56
- VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE)
57
- VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE)
58
-
59
- VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY
60
- VERSION_MANY = Combine(
61
- VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False
62
- )("_raw_spec")
63
- _VERSION_SPEC = Optional((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)
64
- _VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or "")
65
-
66
- VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier")
67
- VERSION_SPEC.setParseAction(lambda s, l, t: t[1])
68
-
69
- MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker")
70
- MARKER_EXPR.setParseAction(
71
- lambda s, l, t: Marker(s[t._original_start : t._original_end])
72
- )
73
- MARKER_SEPARATOR = SEMICOLON
74
- MARKER = MARKER_SEPARATOR + MARKER_EXPR
75
-
76
- VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER)
77
- URL_AND_MARKER = URL + Optional(MARKER)
78
-
79
- NAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER)
80
-
81
- REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd
82
- # setuptools.extern.pyparsing isn't thread safe during initialization, so we do it eagerly, see
83
- # issue #104
84
- REQUIREMENT.parseString("x[]")
85
-
86
-
87
- class Requirement:
88
- """Parse a requirement.
89
-
90
- Parse a given requirement string into its parts, such as name, specifier,
91
- URL, and extras. Raises InvalidRequirement on a badly-formed requirement
92
- string.
93
- """
94
-
95
- # TODO: Can we test whether something is contained within a requirement?
96
- # If so how do we do that? Do we need to test against the _name_ of
97
- # the thing as well as the version? What about the markers?
98
- # TODO: Can we normalize the name and extra name?
99
-
100
- def __init__(self, requirement_string: str) -> None:
101
- try:
102
- req = REQUIREMENT.parseString(requirement_string)
103
- except ParseException as e:
104
- raise InvalidRequirement(
105
- f'Parse error at "{ requirement_string[e.loc : e.loc + 8]!r}": {e.msg}'
106
- )
107
-
108
- self.name: str = req.name
109
- if req.url:
110
- parsed_url = urllib.parse.urlparse(req.url)
111
- if parsed_url.scheme == "file":
112
- if urllib.parse.urlunparse(parsed_url) != req.url:
113
- raise InvalidRequirement("Invalid URL given")
114
- elif not (parsed_url.scheme and parsed_url.netloc) or (
115
- not parsed_url.scheme and not parsed_url.netloc
116
- ):
117
- raise InvalidRequirement(f"Invalid URL: {req.url}")
118
- self.url: TOptional[str] = req.url
119
- else:
120
- self.url = None
121
- self.extras: Set[str] = set(req.extras.asList() if req.extras else [])
122
- self.specifier: SpecifierSet = SpecifierSet(req.specifier)
123
- self.marker: TOptional[Marker] = req.marker if req.marker else None
124
-
125
- def __str__(self) -> str:
126
- parts: List[str] = [self.name]
127
-
128
- if self.extras:
129
- formatted_extras = ",".join(sorted(self.extras))
130
- parts.append(f"[{formatted_extras}]")
131
-
132
- if self.specifier:
133
- parts.append(str(self.specifier))
134
-
135
- if self.url:
136
- parts.append(f"@ {self.url}")
137
- if self.marker:
138
- parts.append(" ")
139
-
140
- if self.marker:
141
- parts.append(f"; {self.marker}")
142
-
143
- return "".join(parts)
144
-
145
- def __repr__(self) -> str:
146
- return f"<Requirement('{self}')>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Awiny/Image2Paragraph/models/grit_src/third_party/CenterNet2/detectron2/utils/logger.py DELETED
@@ -1,237 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates.
2
- import atexit
3
- import functools
4
- import logging
5
- import os
6
- import sys
7
- import time
8
- from collections import Counter
9
- import torch
10
- from tabulate import tabulate
11
- from termcolor import colored
12
-
13
- from detectron2.utils.file_io import PathManager
14
-
15
- __all__ = ["setup_logger", "log_first_n", "log_every_n", "log_every_n_seconds"]
16
-
17
-
18
- class _ColorfulFormatter(logging.Formatter):
19
- def __init__(self, *args, **kwargs):
20
- self._root_name = kwargs.pop("root_name") + "."
21
- self._abbrev_name = kwargs.pop("abbrev_name", "")
22
- if len(self._abbrev_name):
23
- self._abbrev_name = self._abbrev_name + "."
24
- super(_ColorfulFormatter, self).__init__(*args, **kwargs)
25
-
26
- def formatMessage(self, record):
27
- record.name = record.name.replace(self._root_name, self._abbrev_name)
28
- log = super(_ColorfulFormatter, self).formatMessage(record)
29
- if record.levelno == logging.WARNING:
30
- prefix = colored("WARNING", "red", attrs=["blink"])
31
- elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
32
- prefix = colored("ERROR", "red", attrs=["blink", "underline"])
33
- else:
34
- return log
35
- return prefix + " " + log
36
-
37
-
38
- @functools.lru_cache() # so that calling setup_logger multiple times won't add many handlers
39
- def setup_logger(
40
- output=None, distributed_rank=0, *, color=True, name="detectron2", abbrev_name=None
41
- ):
42
- """
43
- Initialize the detectron2 logger and set its verbosity level to "DEBUG".
44
-
45
- Args:
46
- output (str): a file name or a directory to save log. If None, will not save log file.
47
- If ends with ".txt" or ".log", assumed to be a file name.
48
- Otherwise, logs will be saved to `output/log.txt`.
49
- name (str): the root module name of this logger
50
- abbrev_name (str): an abbreviation of the module, to avoid long names in logs.
51
- Set to "" to not log the root module in logs.
52
- By default, will abbreviate "detectron2" to "d2" and leave other
53
- modules unchanged.
54
-
55
- Returns:
56
- logging.Logger: a logger
57
- """
58
- logger = logging.getLogger(name)
59
- logger.setLevel(logging.DEBUG)
60
- logger.propagate = False
61
-
62
- if abbrev_name is None:
63
- abbrev_name = "d2" if name == "detectron2" else name
64
-
65
- plain_formatter = logging.Formatter(
66
- "[%(asctime)s] %(name)s %(levelname)s: %(message)s", datefmt="%m/%d %H:%M:%S"
67
- )
68
- # stdout logging: master only
69
- if distributed_rank == 0:
70
- ch = logging.StreamHandler(stream=sys.stdout)
71
- ch.setLevel(logging.DEBUG)
72
- if color:
73
- formatter = _ColorfulFormatter(
74
- colored("[%(asctime)s %(name)s]: ", "green") + "%(message)s",
75
- datefmt="%m/%d %H:%M:%S",
76
- root_name=name,
77
- abbrev_name=str(abbrev_name),
78
- )
79
- else:
80
- formatter = plain_formatter
81
- ch.setFormatter(formatter)
82
- logger.addHandler(ch)
83
-
84
- # file logging: all workers
85
- if output is not None:
86
- if output.endswith(".txt") or output.endswith(".log"):
87
- filename = output
88
- else:
89
- filename = os.path.join(output, "log.txt")
90
- if distributed_rank > 0:
91
- filename = filename + ".rank{}".format(distributed_rank)
92
- PathManager.mkdirs(os.path.dirname(filename))
93
-
94
- fh = logging.StreamHandler(_cached_log_stream(filename))
95
- fh.setLevel(logging.DEBUG)
96
- fh.setFormatter(plain_formatter)
97
- logger.addHandler(fh)
98
-
99
- return logger
100
-
101
-
102
- # cache the opened file object, so that different calls to `setup_logger`
103
- # with the same file name can safely write to the same file.
104
- @functools.lru_cache(maxsize=None)
105
- def _cached_log_stream(filename):
106
- # use 1K buffer if writing to cloud storage
107
- io = PathManager.open(filename, "a", buffering=1024 if "://" in filename else -1)
108
- atexit.register(io.close)
109
- return io
110
-
111
-
112
- """
113
- Below are some other convenient logging methods.
114
- They are mainly adopted from
115
- https://github.com/abseil/abseil-py/blob/master/absl/logging/__init__.py
116
- """
117
-
118
-
119
- def _find_caller():
120
- """
121
- Returns:
122
- str: module name of the caller
123
- tuple: a hashable key to be used to identify different callers
124
- """
125
- frame = sys._getframe(2)
126
- while frame:
127
- code = frame.f_code
128
- if os.path.join("utils", "logger.") not in code.co_filename:
129
- mod_name = frame.f_globals["__name__"]
130
- if mod_name == "__main__":
131
- mod_name = "detectron2"
132
- return mod_name, (code.co_filename, frame.f_lineno, code.co_name)
133
- frame = frame.f_back
134
-
135
-
136
- _LOG_COUNTER = Counter()
137
- _LOG_TIMER = {}
138
-
139
-
140
- def log_first_n(lvl, msg, n=1, *, name=None, key="caller"):
141
- """
142
- Log only for the first n times.
143
-
144
- Args:
145
- lvl (int): the logging level
146
- msg (str):
147
- n (int):
148
- name (str): name of the logger to use. Will use the caller's module by default.
149
- key (str or tuple[str]): the string(s) can be one of "caller" or
150
- "message", which defines how to identify duplicated logs.
151
- For example, if called with `n=1, key="caller"`, this function
152
- will only log the first call from the same caller, regardless of
153
- the message content.
154
- If called with `n=1, key="message"`, this function will log the
155
- same content only once, even if they are called from different places.
156
- If called with `n=1, key=("caller", "message")`, this function
157
- will not log only if the same caller has logged the same message before.
158
- """
159
- if isinstance(key, str):
160
- key = (key,)
161
- assert len(key) > 0
162
-
163
- caller_module, caller_key = _find_caller()
164
- hash_key = ()
165
- if "caller" in key:
166
- hash_key = hash_key + caller_key
167
- if "message" in key:
168
- hash_key = hash_key + (msg,)
169
-
170
- _LOG_COUNTER[hash_key] += 1
171
- if _LOG_COUNTER[hash_key] <= n:
172
- logging.getLogger(name or caller_module).log(lvl, msg)
173
-
174
-
175
- def log_every_n(lvl, msg, n=1, *, name=None):
176
- """
177
- Log once per n times.
178
-
179
- Args:
180
- lvl (int): the logging level
181
- msg (str):
182
- n (int):
183
- name (str): name of the logger to use. Will use the caller's module by default.
184
- """
185
- caller_module, key = _find_caller()
186
- _LOG_COUNTER[key] += 1
187
- if n == 1 or _LOG_COUNTER[key] % n == 1:
188
- logging.getLogger(name or caller_module).log(lvl, msg)
189
-
190
-
191
- def log_every_n_seconds(lvl, msg, n=1, *, name=None):
192
- """
193
- Log no more than once per n seconds.
194
-
195
- Args:
196
- lvl (int): the logging level
197
- msg (str):
198
- n (int):
199
- name (str): name of the logger to use. Will use the caller's module by default.
200
- """
201
- caller_module, key = _find_caller()
202
- last_logged = _LOG_TIMER.get(key, None)
203
- current_time = time.time()
204
- if last_logged is None or current_time - last_logged >= n:
205
- logging.getLogger(name or caller_module).log(lvl, msg)
206
- _LOG_TIMER[key] = current_time
207
-
208
-
209
- def create_small_table(small_dict):
210
- """
211
- Create a small table using the keys of small_dict as headers. This is only
212
- suitable for small dictionaries.
213
-
214
- Args:
215
- small_dict (dict): a result dictionary of only a few items.
216
-
217
- Returns:
218
- str: the table as a string.
219
- """
220
- keys, values = tuple(zip(*small_dict.items()))
221
- table = tabulate(
222
- [values],
223
- headers=keys,
224
- tablefmt="pipe",
225
- floatfmt=".3f",
226
- stralign="center",
227
- numalign="center",
228
- )
229
- return table
230
-
231
-
232
- def _log_api_usage(identifier: str):
233
- """
234
- Internal function used to log the usage of different detectron2 components
235
- inside facebook's infra.
236
- """
237
- torch._C._log_api_usage_once("detectron2." + identifier)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BREWDAcademy/Brewd-Diffusion/README.md DELETED
@@ -1,12 +0,0 @@
1
- ---
2
- title: BREWD Diffusion
3
- emoji: 🤌
4
- colorFrom: gray
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 3.50.2
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/8 Bola Piscina Gua Mod Apk.md DELETED
@@ -1,90 +0,0 @@
1
-
2
- <h1>Cómo jugar piscina de 8 bolas como un profesional con la guía Mod APK</h1>
3
- <p>¿Te encanta jugar al billar de 8 bolas en línea, pero luchar para ganar partidos y ganar monedas? ¿Te gustaría poder mejorar tu precisión y consistencia al disparar las bolas? ¿Quieres aprender algunos trucos y estrategias interesantes para impresionar a tus oponentes y amigos? Si respondiste afirmativamente a cualquiera de estas preguntas, entonces podrías estar interesado en probar <strong>Guideline Mod APK</strong>, una herramienta que puede ayudarte a jugar al pool de 8 bolas como un profesional. </p>
4
- <h2>8 bola piscina guía mod apk</h2><br /><p><b><b>Download Zip</b> &#8250;&#8250;&#8250;&#8250;&#8250; <a href="https://bltlly.com/2v6L71">https://bltlly.com/2v6L71</a></b></p><br /><br />
5
- <h2>¿Qué es 8 Ball Pool y por qué es popular? </h2>
6
- <p>8 ball pool es uno de los juegos online más populares y adictivos del mundo. Es una simulación del juego de billar de la vida real, donde tienes que usar un taco para golpear las bolas en una mesa y meterlas en los agujeros. El juego tiene dos tipos de bolas: sólidos y rayas. El objetivo es embolsarse todas las bolas de tu tipo y luego la bola 8 antes que tu oponente. </p>
7
- <h3>Las reglas y objetivos de la piscina de bolas 8</h3>
8
- <p>Las reglas del billar de 8 bolas son simples y fáciles de seguir. Puedes jugar el juego en dos modos: 1 contra 1 o torneo. En ambos modos, tienes que pagar una cuota de entrada con monedas, que son la moneda del juego. Puedes ganar monedas ganando partidas o viendo anuncios o completando ofertas. También puedes comprar monedas con dinero real si lo deseas. </p>
9
- <p>El juego comienza con un tiro de ruptura, donde tienes que golpear el estante de bolas con la bola blanca. El primer jugador que se mete una pelota puede elegir si quiere jugar como sólidos o rayas. Luego, cada jugador se turna para golpear sus propias bolas con la bola blanca. Tienes que apuntar con cuidado y ajustar la potencia y el giro de tu tiro. También puedes usar diferentes señales con diferentes atributos para mejorar tu rendimiento. </p>
10
-
11
- <h3> Los beneficios y desafíos de jugar al billar de 8 bolas en línea</h3>
12
- <p>Jugar al billar de 8 bolas en línea tiene muchos beneficios. Puedes jugar en cualquier momento y en cualquier lugar con millones de jugadores de todo el mundo. Puedes retar a tus amigos o unirte a clubes y competir con otros jugadores. También puedes participar en torneos y eventos y ganar premios y recompensas exclusivos. Puedes personalizar tu perfil y avatar y mostrar tus habilidades y logros. </p>
13
- <p></p>
14
- <p>Sin embargo, jugar al billar de 8 bolas en línea también tiene algunos desafíos. Necesita una conexión a Internet estable y un dispositivo compatible para jugar sin problemas. También es necesario tener suficientes monedas para entrar partidos y comprar señales y otros artículos. Por otra parte, es necesario tener buenas habilidades y estrategias para ganar partidos y rango <p>Inglés básico es una versión simplificada del idioma inglés que fue creado por Charles Kay Ogden y I. A. Richards en la década de 1920. Está diseñado para ayudar a las personas a aprender inglés como segundo idioma, o para comunicarse con personas que tienen habilidades limitadas en inglés. El inglés básico tiene un vocabulario de 850 palabras, que puede expresar la mayoría de las ideas y conceptos comunes en la vida cotidiana. También tiene una gramática sencilla que sigue las reglas del inglés estándar, pero con algunas modificaciones y simplificaciones. </p>
15
- <h2>¿Qué es la guía Mod APK y cómo funciona? </h2>
16
- <p>Guía Mod APK es una herramienta que puede ayudarle a jugar piscina de 8 bolas como un profesional. Es una versión modificada de la aplicación original de piscina de 8 bolas, que te ofrece algunas características y funciones adicionales que no están disponibles en la aplicación oficial. Una de las principales características de la Guía Mod APK es que muestra una guía larga y precisa para su bola blanca, que le ayuda a apuntar y disparar las bolas con mayor precisión. También puede ajustar la longitud y el color de la guía según su preferencia. </p>
17
- <h3>Las características y funciones de la guía Mod APK</h3>
18
-
19
- <ul>
20
- <li><strong>Guía larga y precisa:</strong> Puedes ver una guía larga y precisa para tu bola blanca, que te ayuda a apuntar y disparar las bolas con mayor precisión. También puede ajustar la longitud y el color de la guía según su preferencia. </li>
21
- <li><strong>Monedas y efectivo ilimitados:</strong> Puedes obtener monedas y efectivo ilimitados en tu cuenta, que puedes usar para ingresar partidas, comprar claves y otros artículos. Ya no tienes que preocuparte por quedarte sin monedas o efectivo. </li>
22
- <li><strong>Todas las pistas desbloqueadas:</strong> Puedes acceder a todas las pistas del juego, incluidas las premium y las legendarias. Puedes elegir cualquier señal que te guste y disfrutar de sus atributos y efectos. </li>
23
- <li><strong>No hay anuncios:</strong> Puedes jugar el juego sin anuncios molestos o pop-ups. Puedes disfrutar del juego sin interrupciones ni distracciones. </li>
24
- <li><strong>No se requiere raíz:</strong> No es necesario rootear el dispositivo para usar Guideline Mod APK. Puede instalarlo de forma fácil y segura en su dispositivo sin ningún riesgo de dañarlo. </li>
25
- </ul>
26
- <h3>Las ventajas y desventajas de usar la guía Mod APK</h3>
27
- <p>Usando Guía Mod APK tiene algunas ventajas y desventajas que usted debe tener en cuenta antes de usarlo. Algunos de ellos son:</p>
28
- <tabla>
29
- <tr><th>Ventajas</th><th>Desventajas</th></tr>
30
- <tr><td>Puedes jugar al billar de 8 bolas como un profesional con una guía larga y precisa para tu bola blanca. </td><td>Es posible que pierda la diversión y el desafío de jugar al billar de 8 bolas sin ninguna ayuda. </td></tr>
31
- <tr><td>Puede obtener monedas ilimitadas y dinero en efectivo en su cuenta, que puede usar para ingresar coincidencias, comprar señales y otros artículos. </td><td>Puedes ser excluido del juego si usas demasiadas monedas o dinero en efectivo en poco tiempo. </td></tr>
32
- <tr><td>Puedes acceder a todas las pistas del juego, incluidas las premium y las legendarias. </td><td>Puedes perder la motivación para ganar monedas y dinero jugando partidas o completando ofertas. </td></tr>
33
-
34
- <tr><td>No es necesario rootear el dispositivo para usar Guideline Mod APK.</td><td>Es posible que exponga su dispositivo a malware o virus si descarga Guideline Mod APK desde una fuente no confiable. </td></tr>
35
- </table> <h2>Cómo descargar e instalar la guía Mod APK en su dispositivo</h2>
36
- <p>Si desea probar Guideline Mod APK, es necesario descargar e instalar en su dispositivo. Sin embargo, debe tener cuidado y seguir algunos pasos y consejos para evitar problemas o errores. Aquí están los requisitos y precauciones para instalar Guía Mod APK:</p>
37
- <h3>Los requisitos y precauciones para la instalación de la guía Mod APK</h3>
38
- <ul>
39
- <li><strong>Compatibilidad con dispositivos:</strong> Necesitas tener un dispositivo que se ejecute en Android 4.4 o superior. También necesita tener suficiente espacio de almacenamiento y RAM para ejecutar la aplicación sin problemas. </li>
40
- <li><strong>Conexión a Internet:</strong> Necesitas tener una conexión a Internet estable y rápida para descargar e instalar la aplicación. También es necesario tener acceso a Internet para jugar el juego en línea. </li>
41
- <li><strong>Datos de copia de seguridad:</strong> Es necesario hacer una copia de seguridad de los datos de la aplicación oficial de piscina de 8 bolas antes de instalar Guideline Mod APK. Puedes hacer esto iniciando sesión con tu cuenta de Facebook o Google y sincronizando tu progreso. De esta manera, puede restaurar sus datos si algo sale mal. </li>
42
- <li><strong>Desinstalar aplicación oficial:</strong> Es necesario desinstalar la aplicación oficial de 8 bolas desde su dispositivo antes de instalar Guideline Mod APK. Esto se debe a que las dos aplicaciones pueden entrar en conflicto entre sí y causar errores o fallos. </li>
43
- <li><strong>Permitir fuentes desconocidas:</strong> Es necesario habilitar la opción de permitir fuentes desconocidas en la configuración del dispositivo. Esto se debe a Guideline Mod APK no está disponible en el Google Play Store y es necesario instalarlo desde una fuente de terceros. </li>
44
-
45
- </ul>
46
- <h3> Los pasos y consejos para la instalación de directrices Mod APK</h3>
47
- <p>Una vez que haya cumplido con los requisitos y tomado las precauciones, puede seguir estos pasos y consejos para instalar Guideline Mod APK en su dispositivo:</p>
48
- <ol>
49
- <li><strong>Descargar Guía Mod APK:</strong> Puede utilizar el siguiente enlace o buscar otras fuentes en línea para descargar Guía Mod APK. El tamaño del archivo es de unos 60 MB y puede tardar algún tiempo dependiendo de su velocidad de Internet. </li>
50
- <li><strong>Localice y abra el archivo:</strong> Puede utilizar una aplicación de administrador de archivos o el explorador de archivos predeterminado del dispositivo para localizar y abrir el archivo descargado. Puede ver un mensaje de advertencia que dice "Este tipo de archivo puede dañar su dispositivo". Puede ignorar este mensaje y tocar en "OK" o "Instalar de todos modos". </li>
51
- <li><strong>Instalar la aplicación:</strong> Puede seguir las instrucciones en la pantalla para instalar la aplicación en su dispositivo. Puede tardar unos minutos dependiendo del rendimiento del dispositivo. </li>
52
- <li><strong>Inicie la aplicación:</strong> Puede encontrar el icono de la aplicación en la pantalla de inicio del dispositivo o en el cajón de aplicaciones. Usted puede tocar en él para iniciar la aplicación y empezar a jugar piscina de 8 bolas con Guideline Mod APK.</li>
53
- <li><strong>Inicie sesión con su cuenta:</strong> Puede iniciar sesión con su cuenta de Facebook o Google para restaurar sus datos desde la aplicación oficial. También puede crear una nueva cuenta si lo desea. </li>
54
- </ol>
55
- <p>Felicidades! Usted ha instalado con éxito Guía Mod APK en su dispositivo. Ahora puedes disfrutar jugando al billar de 8 bolas como un profesional con una guía larga y precisa para tu bola blanca. </p> <h2>Cómo utilizar la guía Mod APK para mejorar sus habilidades de piscina de 8 bolas</h2>
56
- <p>Ahora que ha instalado Guideline Mod APK en su dispositivo, es posible que se pregunte cómo usarlo para mejorar sus habilidades de piscina de bolas 8. Bueno, no es tan difícil. Solo tiene que seguir algunos conceptos básicos y técnicas de uso de Guía Mod APK, y aprender algunos trucos y estrategias de uso de Guía Mod APK. Aquí hay algunos consejos y sugerencias para usted:</p>
57
-
58
- <p>Los fundamentos y técnicas de uso de Guía Mod APK son similares a los que se utilizan en la aplicación oficial. Todavía tienes que apuntar, ajustar y disparar la bola blanca con el dedo. Sin embargo, con Guideline Mod APK, usted tiene una pauta más larga y más precisa que muestra donde la bola blanca y la bola de destino irá. También puede cambiar la longitud y el color de la guía en la configuración. </p>
59
- <p>Aquí hay algunas técnicas que puede utilizar con Guideline Mod APK:</p>
60
- <ul>
61
- <li><strong>Alinea la guía con el agujero:</strong> Puedes alinear la guía con el agujero en el que quieres meter la pelota. Esto le ayudará a evitar perder o golpear el agujero equivocado. </li>
62
- <li><strong>Usa las opciones de giro y potencia:</strong> Puedes usar las opciones de giro y potencia en los lados izquierdo y derecho de la pantalla para controlar el movimiento y la velocidad de la bola blanca. Puedes usar diferentes tipos de giros, como el giro superior, el giro hacia atrás, el giro lateral o el giro, para hacer la curva de la bola blanca o rebotar en diferentes direcciones. También puede ajustar la potencia de su disparo deslizando el dedo hacia arriba o hacia abajo en el lado derecho de la pantalla. </li>
63
- <li><strong>Utilice las opciones de zoom y ángulo:</strong> Puede utilizar las opciones de zoom y ángulo en la parte inferior de la pantalla para cambiar la vista de la tabla. Puedes acercar o alejar para ver más o menos detalles. También puede cambiar el ángulo de su vista inclinando su dispositivo o tocando las flechas en la parte inferior de la pantalla. </li>
64
- </ul>
65
- <h3>Los trucos y estrategias de uso de la guía Mod APK</h3>
66
- <p>Los trucos y estrategias de uso de Guía Mod APK son más avanzados y requieren algo de práctica y experiencia. Puedes usarlas para impresionar a tus oponentes y amigos, o para salir de situaciones difíciles. Aquí hay algunos trucos y estrategias que puede utilizar con Guideline Mod APK:</p>
67
- <ul>
68
-
69
- <li><strong>Use combo shots:</strong> Puede usar combo shots para golpear una bola con otra y embolsarse ambas en un solo tiro. Esto puede ayudarte a eliminar más bolas en un solo disparo, o bolas de bolsillo que son difíciles de alcanzar directamente. </li>
70
- <li><strong>Use trick shots:</strong> Puede usar trick shots para golpear las bolas de maneras creativas e inesperadas, como saltar sobre otras bolas, curvarse alrededor de otras bolas o rebotar en múltiples rieles o cojines. Esto puede ayudarte a sorprender a tus oponentes y amigos, o bolas de bolsillo que son imposibles de alcanzar de otra manera. </li>
71
- </ul>
72
- <h2>Conclusión y preguntas frecuentes</h2>
73
- <p>En conclusión, Guía Mod APK es una herramienta que puede ayudarle a jugar 8 piscina de bolas como un profesional. Te muestra una guía larga y precisa para tu bola blanca, que te ayuda a apuntar y disparar las bolas con mayor precisión. También le da monedas ilimitadas y dinero en efectivo, todas las señales desbloqueadas, sin anuncios, y no se requiere raíz. Sin embargo, también tiene algunas desventajas, como perder la diversión y el desafío de jugar al billar de 8 bolas sin ninguna ayuda, ser expulsado del juego si usa demasiadas monedas o dinero en efectivo en poco tiempo, perder la motivación para ganar monedas y dinero jugando partidos o completando ofertas, falta algunas actualizaciones importantes o noticias de la aplicación oficial, y exponer su dispositivo a malware o virus si descarga Guideline Mod APK de una fuente no confiable. </p>
74
- <p>Si desea probar Guideline Mod APK, es necesario descargar e instalar en su dispositivo cuidadosamente y siga algunos pasos y consejos para evitar problemas o errores. También es necesario seguir algunos fundamentos y técnicas de uso de Guía Mod APK, y aprender algunos trucos y estrategias de uso de Guía Mod APK. Al hacerlo, puedes mejorar tus habilidades de billar de 8 bolas y disfrutar jugando al billar de 8 bolas como un profesional. </p>
75
- <p>Aquí hay algunas preguntas frecuentes que podrían ayudarle a entender más acerca de Guía Mod APK:</p>
76
- <ol>
77
- <li><strong>¿Es seguro usar Guideline Mod APK? </strong></li>
78
-
79
- <li><strong>¿Es legal usar Guideline Mod APK? </strong></li>
80
- <p>Guía Mod APK no es legal de usar, ya que viola los términos y condiciones de la aplicación oficial del grupo de 8 bolas. También le da una ventaja injusta sobre otros jugadores que juegan el juego sin ninguna ayuda. Por lo tanto, el uso de Guideline Mod APK podría resultar en conseguir prohibido del juego o frente a acciones legales de los desarrolladores de la aplicación oficial. </p>
81
- <li><strong>¿Puedo jugar con mis amigos usando Guideline Mod APK? </strong></li>
82
- <p>Sí, puedes jugar con tus amigos usando Guideline Mod APK, siempre y cuando también tengan la misma aplicación instalada en sus dispositivos. Puedes retar a tus amigos o unirte a clubes y competir con otros jugadores. Sin embargo, es posible que no puedas jugar con jugadores que usan la aplicación oficial, ya que pueden tener diferentes versiones o actualizaciones del juego. </p>
83
- <li><strong>¿Puedo actualizar la guía Mod APK? </strong></li>
84
- <p>Sí, puede actualizar Guideline Mod APK, pero es necesario descargar e instalar la última versión de la aplicación de una fuente confiable y confiable. También es necesario desinstalar la versión anterior de la aplicación desde el dispositivo antes de instalar el nuevo. También es posible que necesite hacer una copia de seguridad de sus datos de la aplicación antes de actualizarla, ya que algunas actualizaciones podrían borrar su progreso o monedas. </p>
85
- <li><strong>¿Puedo usar Guideline Mod APK sin conexión? </strong></li>
86
- <p>No, no se puede usar Guideline Mod APK sin conexión, ya que requiere una conexión a Internet para jugar el juego en línea. También necesita una conexión a Internet para descargar e instalar la aplicación en su dispositivo. Sin embargo, se puede jugar algunos modos fuera de línea del juego, tales como el modo de práctica o torneos fuera de línea, sin necesidad de utilizar la guía APK.</p>
87
- </ol>
88
- <p>Espero que este artículo le ha ayudado a entender más acerca de Guía Mod APK y cómo usarlo para jugar al billar de 8 bolas como un profesional. Si usted tiene alguna pregunta o retroalimentación, por favor no dude en dejar un comentario a continuación. Gracias por leer y jugar feliz! </p> 64aa2da5cf<br />
89
- <br />
90
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Benson/text-generation/Examples/Cara Descargar Colegio Pelea Mod Apk.md DELETED
@@ -1,68 +0,0 @@
1
- <br />
2
- <h1>Cara Download College Brawl Mod Apk: Game Kampus Penuh Aksi dan Sensasi</h1>
3
- <p>Apakah kamu suka dengan game yang menggambarkan kehidupan kampus yang penuh dengan berbagai permasalahan, petualangan, dan romansa? Jika iya, maka kamu harus mencoba game <strong>College Brawl Mod Apk</strong>. Game ini adalah versi modifikasi dari game aslinya yang bernama <em>College Brawl</em>, yang bisa kamu temukan di Google Play Store. Namun, dengan versi mod ini, kamu bisa mendapatkan fitur-fitur tambahan yang lebih menarik dan menyenangkan. Bagaimana cara download dan instal game ini? Simak ulasan lengkapnya di bawah ini. </p>
4
- <h2>cara descargar colegio pelea mod apk</h2><br /><p><b><b>Download</b> &#9658;&#9658;&#9658;&#9658;&#9658; <a href="https://bltlly.com/2v6KMX">https://bltlly.com/2v6KMX</a></b></p><br /><br />
5
- <h2>Apa itu College Brawl Mod Apk? </h2>
6
- <p>College Brawl Mod Apk adalah game yang mengadaptasi kehidupan kampus kamu, dimana penuh dengan berbagai permasalahan. Dimana kamu akan membereskan semua masalah yang ada di kampus kamu. Game ini memiliki genre adventure / pertualangan yang dapat kamu jalani dalam game. Kamu bisa memilih karakter yang kamu sukai, baik itu cowok atau cewek, dan menjalin hubungan dengan karakter lainnya. Kamu juga bisa mengikuti berbagai kegiatan kampus, seperti olahraga, musik, seni, atau bahkan berkelahi dengan musuh-musuhmu. Game ini memiliki grafis yang bagus dan suara yang realistis, sehingga kamu bisa merasakan sensasi berada di kampus yang sebenarnya. </p>
7
- <h3>Fitur-fitur Menarik dari College Brawl Mod Apk</h3>
8
- <p>Berbeda dengan versi aslinya, College Brawl Mod Apk memiliki beberapa fitur tambahan yang membuat game ini lebih menarik dan menyenangkan. Berikut adalah beberapa fitur yang bisa kamu nikmati dengan College Brawl Mod Apk:</p>
9
- <ul>
10
- <li><strong>Unlimited Money</strong>: Kamu bisa mendapatkan uang tanpa batas di game ini, sehingga kamu bisa membeli apapun yang kamu inginkan, seperti pakaian, aksesoris, kendaraan, atau bahkan senjata. Kamu plays great memberikan hadiah kepada karakter yang kamu sukai, dan meningkatkan hubunganmu dengan mereka. </li>
11
-
12
- <li><strong>Unlocked All Locations</strong>: Kamu bisa menjelajahi seluruh lokasi yang ada di game ini, tanpa harus terbatas oleh level atau misi. Kamu bisa mengunjungi berbagai tempat, seperti kelas, kantin, asrama, lapangan, klub, atau bahkan tempat-tempat rahasia yang penuh dengan misteri dan tantangan. </li>
13
- <li><strong>No Ads</strong>: Kamu bisa bermain game ini tanpa gangguan iklan yang mengganggu. Kamu bisa menikmati game ini dengan lancar dan nyaman, tanpa harus menunggu loading atau buffering. </li>
14
- </ul>
15
- <h3>Cara Bermain College Brawl Mod Apk</h3>
16
- <p>Untuk bermain game ini, kamu harus mengikuti alur cerita yang ada di game ini. Kamu akan diberikan berbagai misi yang harus kamu selesaikan, baik itu misi utama atau misi sampingan. Misi-misi ini akan membawamu ke berbagai situasi dan konflik yang menarik dan seru. Kamu plays bisa memilih cara untuk menyelesaikan misi tersebut, baik itu dengan cara damai, diplomasi, atau kekerasan. Setiap pilihan yang kamu buat akan mempengaruhi jalannya cerita dan hubunganmu dengan karakter lain. Berikut adalah beberapa tips untuk bermain game ini:</p>
17
- <ul>
18
- <li><strong>Pilih Karakter yang Sesuai dengan Gaya Bermainmu</strong>: Kamu bisa memilih karakter yang memiliki kemampuan dan kepribadian yang sesuai dengan gaya bermainmu. Ada beberapa karakter yang lebih cocok untuk bertarung, ada yang lebih cocok untuk berbicara, ada yang lebih cocok untuk bersenang-senang, dan ada yang lebih cocok untuk belajar. Kamu plays bisa mengganti karakter kapan saja jika kamu bosan atau ingin mencoba hal baru. </li>
19
-
20
- <li><strong>Ikuti Kegiatan Kampus</strong>: Kamu bisa mengikuti berbagai kegiatan kampus yang ada di game ini, seperti olahraga, musik, seni, atau bahkan berkelahi. Setiap kegiatan memiliki tantangan dan hadiah yang berbeda-beda. Kamu juga bisa meningkatkan kemampuanmu dengan mengikuti kegiatan tersebut. Misalnya, jika kamu mengikuti kegiatan olahraga, kamu akan menjadi lebih kuat dan sehat. Jika kamu mengikuti kegiatan musik, kamu akan menjadi lebih kreatif dan populer. </li>
21
- </ul>
22
- <h2>Bagaimana Cara Download College Brawl Mod Apk? </h2>
23
- <p>Untuk mendownload game ini, kamu tidak perlu repot-repot mencari situs-situs download yang tidak jelas atau illegal. Kamu bisa mendownload game ini secaa mudah dan legal dari Google Play Store. Namun, karena game ini adalah versi modifikasi dari game aslinya, kamu harus mengikuti langkah-langkah berikut ini untuk mendownload game ini:</p>
24
- <h3>Langkah 1: Buka situs Apps Evozi</h3>
25
- <p>Apps Evozi adalah situs yang bisa kamu gunakan untuk mendownload file APK dari aplikasi atau game yang ada di Google Play Store. Situs ini sangat mudah dan aman digunakan, tanpa perlu mendaftar atau membayar. Kamu bisa mengakses situs ini melalui browser di perangkatmu, atau kamu bisa klik tautan berikut ini: <a href="">https://apps.evozi.com/apk-downloader/</a></p>
26
- <h3>Langkah 2: Salin Tautan Aplikasi di Google Play Store</h3>
27
- <p>Setelah kamu membuka situs Apps Evozi, kamu harus menyalin tautan aplikasi atau game yang ingin kamu download. Dalam hal ini, kamu harus menyalin tautan dari game College Brawl yang ada di Google Play Store. Kamu bisa mencari game ini di Google Play Store dengan mengetikkan nama atau kata kunci yang terkait. Atau, kamu bisa klik tautan berikut ini: <a href="">https://play.google.com/store/apps/details?id=com.college.brawl</a><</p>
28
- <p></p>
29
-
30
- <h3>Langkah 3: Tunggu Hingga Tombol Download APK Muncul</h3>
31
- <p>Setelah kamu menyalin URL dari game College Brawl, kamu harus kembali ke situs Apps Evozi dan menempelkan URL tersebut di kolom yang tersedia. Kamu bisa melakukannya dengan menekan tombol tempel yang ada di bagian bawah kolom, atau dengan menekan dan menahan kolom tersebut hingga muncul pilihan tempel. Pastikan kamu menempelkan URL yang benar dan lengkap. </p>
32
- <p>Setelah itu, kamu harus menekan tombol Generate Download Link yang ada di bawah kolom. Tombol ini akan memproses URL yang kamu masukkan dan menghasilkan tautan download untuk file APK dari game College Brawl Mod Apk. Proses ini bisa memakan waktu beberapa detik hingga beberapa menit, tergantung pada kecepatan internetmu dan ukuran file APK.</p>
33
- <p>Setelah proses selesai, kamu akan melihat tombol Download APK yang berwarna hijau di bawah kolom. Tombol ini adalah tautan download untuk file APK dari game College Brawl Mod Apk. Kamu harus menekan tombol ini untuk mendownload file APK tersebut ke perangkatmu. Kamu plays bisa melihat informasi tentang nama file, ukuran file, versi aplikasi, dan tanggal update dari file APK tersebut. </p>
34
- <h2>Bagaimana Cara Instal College Brawl Mod Apk? </h2>
35
- <p>Setelah kamu mendownload file APK dari game College Brawl Mod Apk, kamu harus menginstalnya ke perangkatmu agar bisa bermain game ini. Namun, sebelum itu, kamu harus memastikan bahwa perangkatmu sudah memenuhi syarat dan persyaratan untuk menginstal file APK. Berikut adalah langkah-langkah untuk menginstal game ini:</p>
36
- <h3>Langkah 1: Aktifkan Sumber Tidak Dikenal</h3>
37
- <p>Sumber tidak dikenal adalah fitur keamanan yang ada di perangkat Android yang bertujuan untuk mencegah instalasi aplikasi atau game dari sumber yang tidak resmi atau tidak terpercaya. Namun, karena file APK dari game College Brawl Mod Apk berasal dari situs Apps Evozi yang aman dan legal, kamu bisa mengaktifkan sumber tidak dikenal untuk mengizinkan instalasi file APK tersebut. </p>
38
-
39
- <h3>Langkah 2: Cari File APK di Penyimpanan Internal</h3>
40
- <p>Setelah kamu mendownload file APK dari game College Brawl Mod Apk, kamu harus mencarinya di penyimpanan internal atau internal storage di perangkatmu. Biasanya, file APK akan tersimpan di folder download atau downloads yang ada di penyimpanan internal. Namun, tergantung pada aplikasi browser atau downloader yang kamu gunakan, file APK bisa juga tersimpan di folder lain yang berbeda. </p>
41
- <p>Untuk mencari file APK, kamu bisa menggunakan aplikasi file manager atau pengelola file yang ada di perangkatmu. Kamu bisa membuka aplikasi tersebut dan menjelajahi folder-folder yang ada di penyimpanan internal. Kamu bisa mencari file APK dengan nama <em>College Brawl Mod Apk</em> atau dengan ekstensi <em>. apk</em>. Jika kamu sudah menemukan file APK tersebut, kamu bisa melanjutkan ke langkah berikutnya. Jika tidak, kamu harus kembali ke langkah sebelumnya dan memeriksa apakah kamu sudah mendownload file APK dengan benar. </p>
42
- <h3>Langkah 3: Ketuk File APK dan Ikuti Instruksi</h3>
43
- <p>Setelah kamu menemukan file APK dari game College Brawl Mod Apk, kamu harus mengetuk atau menekan file tersebut untuk memulai proses instalasi. Kamu akan melihat layar konfirmasi yang menampilkan informasi tentang nama aplikasi, ukuran file, izin akses, dan lain-lain. Kamu harus membaca informasi tersebut dengan teliti dan memastikan bahwa file APK tersebut sesuai dengan game yang kamu inginkan. </p>
44
- <p>Jika kamu sudah yakin, kamu bisa menekan tombol instal atau install yang ada di bagian bawah layar. Tombol ini akan memulai proses instalasi file apk ke perangkatmu. Proses ini bisa memakan waktu beberapa detik hingga beberapa menit, tergantung pada ukuran file dan kecepatan perangkatmu. Kamu harus menunggu hingga proses instalasi selesai dengan sukses. </p>
45
-
46
- <h2>Kesimpulan</h2>
47
- <p>Demikianlah cara download dan instal game College Brawl Mod Apk di perangkat Androidmu. Game ini adalah game yang sangat seru dan menarik untuk dimainkan, karena menggambarkan kehidupan kampus yang penuh dengan aksi dan sensasi. Kamu bisa memilih karakter yang kamu sukai, menjalin hubungan dengan karakter lain, mengikuti kegiatan kampus, dan berkelahi dengan musuh-musuhmu. Game ini plays memiliki fitur-fitur tambahan yang membuat game ini lebih menyenangkan, seperti unlimited money, unlocked all characters, unlocked all, locations dan no ads. </p>
48
- <p>Kamu bisa mendownload game ini secaa mudah dan legal dari Google Play Store dengan menggunakan situs Apps Evozi. Situs ini adalah situs yang aman dan terpercaya untuk mendownload file APK dari aplikasi atau game yang ada di Google Play Store. Kamu hanya perlu menyalin URL dari game College Brawl di Google Play Store dan menempelkannya di situs Apps Evozi. Kemudian, kamu bisa mendownload file APK dari game College Brawl Mod Apk dan menginstalnya ke perangkatmu dengan mengaktifkan sumber tidak dikenal. </p>
49
- <p>Semoga artikel ini bermanfaat untukmu. Jika kamu memiliki pertanyaan atau masalah tentang game College Brawl Mod Apk, kamu bisa membaca FAQ berikut ini atau meninggalkan komentar di bawah artikel ini. </p>
50
- <h2>FAQ</h2>
51
- <ul>
52
- <li><strong>Apakah game College Brawl Mod Apk aman untuk dimainkan? </strong></li>
53
- <p>Ya, game College Brawl Mod Apk aman untuk dimainkan, as lanjutkan menulis artikel. <p>Game ini berasal dari situs Apps Evozi yang terpercaya dan legal untuk mendownload file APK dari Google Play Store. Game ini plays tidak mengandung virus, malware, atau konten berbahaya yang bisa merusak perangkatmu. Namun, kamu harus tetap berhati-hati dan bertanggung jawab saat bermain game ini, karena game ini mengandung adegan-adegan yang mungkin tidak sesuai untuk anak di bawah umur. </p>
54
- <li><strong>Apakah game College Brawl Mod Apk bisa dimainkan dry offline? </strong></li>
55
-
56
- <li><strong>Apakah game College Brawl Mod Apk bisa dimainkan dry multiplayer? </strong></li>
57
- <p>Tidak, game College Brawl Mod Apk tidak bisa dimainkan seca multiplayer, karena game ini adalah game single player yang hanya bisa dimainkan oleh satu orang. Kamu tidak bisa bermain bersama teman-temanmu atau pemain lain di game ini. Namun, kamu bisa berbagi pengalaman dan cerita tentang game ini dengan temanmu melalui media sosial atau platform lainnya. </p>
58
- <li><strong>Apakah game College Brawl Mod Apk bisa dihapus dari perangkat? </strong></li>
59
- <p>Ya, game College Brawl Mod Apk bisa dihapus dari perangkatmu jika kamu sudah bosan atau tidak ingin bermain lagi. Kamu bisa menghapus game ini dengan face yang sama seperti menghapus aplikasi atau game lainnya. Kamu hanya perlu masuk ke pengaturan atau settings di perangkatmu, kemudian cari menu aplikasi atau apps dan buka menu tersebut. Di dalam menu aplikasi, cari game College Brawl Mod Apk dan ketuk atau tekan game tersebut. Kamu akan melihat tombol hapus atau uninstall yang ada di bagian atas layar. Ketuk atau tekan tombol tersebut untuk menghapus game ini dari perangkatmu. </p>
60
- <li><strong>Apakah ada tips atau trik untuk bermain game College Brawl Mod Apk? </strong></li>
61
- <p>Ada beberapa tips atau trik yang bisa kamu gunakan untuk bermain game College Brawl Mod Apk dengan lebih mudah dan menyenangkan. Berikut adalah beberapa tips atau trik yang bisa kamu coba:</p>
62
- <ul>
63
- <li><strong>Gunakan Uangmu dengan Bijak</strong>: Kamu bisa mendapatkan uang tanpa batas di game ini, tetapi itu tidak berarti kamu bisa membelanjakannya sembarangan. Kamu harus menggunakan uangmu dengan bijak, yaitu untuk membeli barang-barang yang berguna dan bermanfaat untukmu, seperti pakaian, aksesoris, kendaraan, senjata, atau hadiah. Jangan membeli barang-barang yang tidak kamu butuhkan atau tidak kamu sukai, karena itu hanya akan membuang-buang uangmu. </li>
64
-
65
- <li><strong>Jaga Hubunganmu dengan Karakter Lain</strong>: Kamu bisa berinteraksi dengan berbagai karakter di game ini, tetapi itu tidak berarti kamu bisa bersikap sembarangan terhadap mereka. Kamu harus menjaga hubunganmu dengan karakter lain, yaitu dengan memberikan hadiah, mengajak ngobrol, menggoda, atau bahkan bermusuhan dengan mereka sesuai dengan keinginanmu. Setiap tindakan yang kamu lakukan akan mempengaruhi reaksi dan respon mereka terhadapmu. Jika kamu ingin menjalin hubungan spesial dengan karakter tertentu, kamu harus memberikan perhatian dan kasih sayang yang lebih kepada mereka. Jika kamu ingin bermusuhan dengan karakter tertentu, kamu harus bersikap dingin dan kasar kepada mereka. </li>
66
- </ul></p> 64aa2da5cf<br />
67
- <br />
68
- <br />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BetterAPI/BetterChat/src/lib/actions/snapScrollToBottom.ts DELETED
@@ -1,54 +0,0 @@
1
- import { navigating } from "$app/stores";
2
- import { tick } from "svelte";
3
- import { get } from "svelte/store";
4
-
5
- const detachedOffset = 10;
6
-
7
- /**
8
- * @param node element to snap scroll to bottom
9
- * @param dependency pass in a dependency to update scroll on changes.
10
- */
11
- export const snapScrollToBottom = (node: HTMLElement, dependency: any) => {
12
- let prevScrollValue = node.scrollTop;
13
- let isDetached = false;
14
-
15
- const handleScroll = () => {
16
- // if user scrolled up, we detach
17
- if (node.scrollTop < prevScrollValue) {
18
- isDetached = true;
19
- }
20
-
21
- // if user scrolled back to within 10px of bottom, we reattach
22
- if (node.scrollTop - (node.scrollHeight - node.clientHeight) >= -detachedOffset) {
23
- isDetached = false;
24
- }
25
-
26
- prevScrollValue = node.scrollTop;
27
- };
28
-
29
- const updateScroll = async (_options: { force?: boolean } = {}) => {
30
- const defaultOptions = { force: false };
31
- const options = { ...defaultOptions, ..._options };
32
- const { force } = options;
33
-
34
- if (!force && isDetached && !get(navigating)) return;
35
-
36
- // wait for next tick to ensure that the DOM is updated
37
- await tick();
38
-
39
- node.scrollTo({ top: node.scrollHeight });
40
- };
41
-
42
- node.addEventListener("scroll", handleScroll);
43
-
44
- if (dependency) {
45
- updateScroll({ force: true });
46
- }
47
-
48
- return {
49
- update: updateScroll,
50
- destroy: () => {
51
- node.removeEventListener("scroll", handleScroll);
52
- },
53
- };
54
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BetterAPI/BetterChat/src/lib/utils/trimPrefix.ts DELETED
@@ -1,6 +0,0 @@
1
- export function trimPrefix(input: string, prefix: string) {
2
- if (input.startsWith(prefix)) {
3
- return input.slice(prefix.length);
4
- }
5
- return input;
6
- }
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/pip/_internal/exceptions.py DELETED
@@ -1,733 +0,0 @@
1
- """Exceptions used throughout package.
2
-
3
- This module MUST NOT try to import from anything within `pip._internal` to
4
- operate. This is expected to be importable from any/all files within the
5
- subpackage and, thus, should not depend on them.
6
- """
7
-
8
- import configparser
9
- import contextlib
10
- import locale
11
- import logging
12
- import pathlib
13
- import re
14
- import sys
15
- from itertools import chain, groupby, repeat
16
- from typing import TYPE_CHECKING, Dict, Iterator, List, Optional, Union
17
-
18
- from pip._vendor.requests.models import Request, Response
19
- from pip._vendor.rich.console import Console, ConsoleOptions, RenderResult
20
- from pip._vendor.rich.markup import escape
21
- from pip._vendor.rich.text import Text
22
-
23
- if TYPE_CHECKING:
24
- from hashlib import _Hash
25
- from typing import Literal
26
-
27
- from pip._internal.metadata import BaseDistribution
28
- from pip._internal.req.req_install import InstallRequirement
29
-
30
- logger = logging.getLogger(__name__)
31
-
32
-
33
- #
34
- # Scaffolding
35
- #
36
- def _is_kebab_case(s: str) -> bool:
37
- return re.match(r"^[a-z]+(-[a-z]+)*$", s) is not None
38
-
39
-
40
- def _prefix_with_indent(
41
- s: Union[Text, str],
42
- console: Console,
43
- *,
44
- prefix: str,
45
- indent: str,
46
- ) -> Text:
47
- if isinstance(s, Text):
48
- text = s
49
- else:
50
- text = console.render_str(s)
51
-
52
- return console.render_str(prefix, overflow="ignore") + console.render_str(
53
- f"\n{indent}", overflow="ignore"
54
- ).join(text.split(allow_blank=True))
55
-
56
-
57
- class PipError(Exception):
58
- """The base pip error."""
59
-
60
-
61
- class DiagnosticPipError(PipError):
62
- """An error, that presents diagnostic information to the user.
63
-
64
- This contains a bunch of logic, to enable pretty presentation of our error
65
- messages. Each error gets a unique reference. Each error can also include
66
- additional context, a hint and/or a note -- which are presented with the
67
- main error message in a consistent style.
68
-
69
- This is adapted from the error output styling in `sphinx-theme-builder`.
70
- """
71
-
72
- reference: str
73
-
74
- def __init__(
75
- self,
76
- *,
77
- kind: 'Literal["error", "warning"]' = "error",
78
- reference: Optional[str] = None,
79
- message: Union[str, Text],
80
- context: Optional[Union[str, Text]],
81
- hint_stmt: Optional[Union[str, Text]],
82
- note_stmt: Optional[Union[str, Text]] = None,
83
- link: Optional[str] = None,
84
- ) -> None:
85
- # Ensure a proper reference is provided.
86
- if reference is None:
87
- assert hasattr(self, "reference"), "error reference not provided!"
88
- reference = self.reference
89
- assert _is_kebab_case(reference), "error reference must be kebab-case!"
90
-
91
- self.kind = kind
92
- self.reference = reference
93
-
94
- self.message = message
95
- self.context = context
96
-
97
- self.note_stmt = note_stmt
98
- self.hint_stmt = hint_stmt
99
-
100
- self.link = link
101
-
102
- super().__init__(f"<{self.__class__.__name__}: {self.reference}>")
103
-
104
- def __repr__(self) -> str:
105
- return (
106
- f"<{self.__class__.__name__}("
107
- f"reference={self.reference!r}, "
108
- f"message={self.message!r}, "
109
- f"context={self.context!r}, "
110
- f"note_stmt={self.note_stmt!r}, "
111
- f"hint_stmt={self.hint_stmt!r}"
112
- ")>"
113
- )
114
-
115
- def __rich_console__(
116
- self,
117
- console: Console,
118
- options: ConsoleOptions,
119
- ) -> RenderResult:
120
- colour = "red" if self.kind == "error" else "yellow"
121
-
122
- yield f"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]"
123
- yield ""
124
-
125
- if not options.ascii_only:
126
- # Present the main message, with relevant context indented.
127
- if self.context is not None:
128
- yield _prefix_with_indent(
129
- self.message,
130
- console,
131
- prefix=f"[{colour}]×[/] ",
132
- indent=f"[{colour}]│[/] ",
133
- )
134
- yield _prefix_with_indent(
135
- self.context,
136
- console,
137
- prefix=f"[{colour}]╰─>[/] ",
138
- indent=f"[{colour}] [/] ",
139
- )
140
- else:
141
- yield _prefix_with_indent(
142
- self.message,
143
- console,
144
- prefix="[red]×[/] ",
145
- indent=" ",
146
- )
147
- else:
148
- yield self.message
149
- if self.context is not None:
150
- yield ""
151
- yield self.context
152
-
153
- if self.note_stmt is not None or self.hint_stmt is not None:
154
- yield ""
155
-
156
- if self.note_stmt is not None:
157
- yield _prefix_with_indent(
158
- self.note_stmt,
159
- console,
160
- prefix="[magenta bold]note[/]: ",
161
- indent=" ",
162
- )
163
- if self.hint_stmt is not None:
164
- yield _prefix_with_indent(
165
- self.hint_stmt,
166
- console,
167
- prefix="[cyan bold]hint[/]: ",
168
- indent=" ",
169
- )
170
-
171
- if self.link is not None:
172
- yield ""
173
- yield f"Link: {self.link}"
174
-
175
-
176
- #
177
- # Actual Errors
178
- #
179
- class ConfigurationError(PipError):
180
- """General exception in configuration"""
181
-
182
-
183
- class InstallationError(PipError):
184
- """General exception during installation"""
185
-
186
-
187
- class UninstallationError(PipError):
188
- """General exception during uninstallation"""
189
-
190
-
191
- class MissingPyProjectBuildRequires(DiagnosticPipError):
192
- """Raised when pyproject.toml has `build-system`, but no `build-system.requires`."""
193
-
194
- reference = "missing-pyproject-build-system-requires"
195
-
196
- def __init__(self, *, package: str) -> None:
197
- super().__init__(
198
- message=f"Can not process {escape(package)}",
199
- context=Text(
200
- "This package has an invalid pyproject.toml file.\n"
201
- "The [build-system] table is missing the mandatory `requires` key."
202
- ),
203
- note_stmt="This is an issue with the package mentioned above, not pip.",
204
- hint_stmt=Text("See PEP 518 for the detailed specification."),
205
- )
206
-
207
-
208
- class InvalidPyProjectBuildRequires(DiagnosticPipError):
209
- """Raised when pyproject.toml an invalid `build-system.requires`."""
210
-
211
- reference = "invalid-pyproject-build-system-requires"
212
-
213
- def __init__(self, *, package: str, reason: str) -> None:
214
- super().__init__(
215
- message=f"Can not process {escape(package)}",
216
- context=Text(
217
- "This package has an invalid `build-system.requires` key in "
218
- f"pyproject.toml.\n{reason}"
219
- ),
220
- note_stmt="This is an issue with the package mentioned above, not pip.",
221
- hint_stmt=Text("See PEP 518 for the detailed specification."),
222
- )
223
-
224
-
225
- class NoneMetadataError(PipError):
226
- """Raised when accessing a Distribution's "METADATA" or "PKG-INFO".
227
-
228
- This signifies an inconsistency, when the Distribution claims to have
229
- the metadata file (if not, raise ``FileNotFoundError`` instead), but is
230
- not actually able to produce its content. This may be due to permission
231
- errors.
232
- """
233
-
234
- def __init__(
235
- self,
236
- dist: "BaseDistribution",
237
- metadata_name: str,
238
- ) -> None:
239
- """
240
- :param dist: A Distribution object.
241
- :param metadata_name: The name of the metadata being accessed
242
- (can be "METADATA" or "PKG-INFO").
243
- """
244
- self.dist = dist
245
- self.metadata_name = metadata_name
246
-
247
- def __str__(self) -> str:
248
- # Use `dist` in the error message because its stringification
249
- # includes more information, like the version and location.
250
- return "None {} metadata found for distribution: {}".format(
251
- self.metadata_name,
252
- self.dist,
253
- )
254
-
255
-
256
- class UserInstallationInvalid(InstallationError):
257
- """A --user install is requested on an environment without user site."""
258
-
259
- def __str__(self) -> str:
260
- return "User base directory is not specified"
261
-
262
-
263
- class InvalidSchemeCombination(InstallationError):
264
- def __str__(self) -> str:
265
- before = ", ".join(str(a) for a in self.args[:-1])
266
- return f"Cannot set {before} and {self.args[-1]} together"
267
-
268
-
269
- class DistributionNotFound(InstallationError):
270
- """Raised when a distribution cannot be found to satisfy a requirement"""
271
-
272
-
273
- class RequirementsFileParseError(InstallationError):
274
- """Raised when a general error occurs parsing a requirements file line."""
275
-
276
-
277
- class BestVersionAlreadyInstalled(PipError):
278
- """Raised when the most up-to-date version of a package is already
279
- installed."""
280
-
281
-
282
- class BadCommand(PipError):
283
- """Raised when virtualenv or a command is not found"""
284
-
285
-
286
- class CommandError(PipError):
287
- """Raised when there is an error in command-line arguments"""
288
-
289
-
290
- class PreviousBuildDirError(PipError):
291
- """Raised when there's a previous conflicting build directory"""
292
-
293
-
294
- class NetworkConnectionError(PipError):
295
- """HTTP connection error"""
296
-
297
- def __init__(
298
- self,
299
- error_msg: str,
300
- response: Optional[Response] = None,
301
- request: Optional[Request] = None,
302
- ) -> None:
303
- """
304
- Initialize NetworkConnectionError with `request` and `response`
305
- objects.
306
- """
307
- self.response = response
308
- self.request = request
309
- self.error_msg = error_msg
310
- if (
311
- self.response is not None
312
- and not self.request
313
- and hasattr(response, "request")
314
- ):
315
- self.request = self.response.request
316
- super().__init__(error_msg, response, request)
317
-
318
- def __str__(self) -> str:
319
- return str(self.error_msg)
320
-
321
-
322
- class InvalidWheelFilename(InstallationError):
323
- """Invalid wheel filename."""
324
-
325
-
326
- class UnsupportedWheel(InstallationError):
327
- """Unsupported wheel."""
328
-
329
-
330
- class InvalidWheel(InstallationError):
331
- """Invalid (e.g. corrupt) wheel."""
332
-
333
- def __init__(self, location: str, name: str):
334
- self.location = location
335
- self.name = name
336
-
337
- def __str__(self) -> str:
338
- return f"Wheel '{self.name}' located at {self.location} is invalid."
339
-
340
-
341
- class MetadataInconsistent(InstallationError):
342
- """Built metadata contains inconsistent information.
343
-
344
- This is raised when the metadata contains values (e.g. name and version)
345
- that do not match the information previously obtained from sdist filename,
346
- user-supplied ``#egg=`` value, or an install requirement name.
347
- """
348
-
349
- def __init__(
350
- self, ireq: "InstallRequirement", field: str, f_val: str, m_val: str
351
- ) -> None:
352
- self.ireq = ireq
353
- self.field = field
354
- self.f_val = f_val
355
- self.m_val = m_val
356
-
357
- def __str__(self) -> str:
358
- return (
359
- f"Requested {self.ireq} has inconsistent {self.field}: "
360
- f"expected {self.f_val!r}, but metadata has {self.m_val!r}"
361
- )
362
-
363
-
364
- class InstallationSubprocessError(DiagnosticPipError, InstallationError):
365
- """A subprocess call failed."""
366
-
367
- reference = "subprocess-exited-with-error"
368
-
369
- def __init__(
370
- self,
371
- *,
372
- command_description: str,
373
- exit_code: int,
374
- output_lines: Optional[List[str]],
375
- ) -> None:
376
- if output_lines is None:
377
- output_prompt = Text("See above for output.")
378
- else:
379
- output_prompt = (
380
- Text.from_markup(f"[red][{len(output_lines)} lines of output][/]\n")
381
- + Text("".join(output_lines))
382
- + Text.from_markup(R"[red]\[end of output][/]")
383
- )
384
-
385
- super().__init__(
386
- message=(
387
- f"[green]{escape(command_description)}[/] did not run successfully.\n"
388
- f"exit code: {exit_code}"
389
- ),
390
- context=output_prompt,
391
- hint_stmt=None,
392
- note_stmt=(
393
- "This error originates from a subprocess, and is likely not a "
394
- "problem with pip."
395
- ),
396
- )
397
-
398
- self.command_description = command_description
399
- self.exit_code = exit_code
400
-
401
- def __str__(self) -> str:
402
- return f"{self.command_description} exited with {self.exit_code}"
403
-
404
-
405
- class MetadataGenerationFailed(InstallationSubprocessError, InstallationError):
406
- reference = "metadata-generation-failed"
407
-
408
- def __init__(
409
- self,
410
- *,
411
- package_details: str,
412
- ) -> None:
413
- super(InstallationSubprocessError, self).__init__(
414
- message="Encountered error while generating package metadata.",
415
- context=escape(package_details),
416
- hint_stmt="See above for details.",
417
- note_stmt="This is an issue with the package mentioned above, not pip.",
418
- )
419
-
420
- def __str__(self) -> str:
421
- return "metadata generation failed"
422
-
423
-
424
- class HashErrors(InstallationError):
425
- """Multiple HashError instances rolled into one for reporting"""
426
-
427
- def __init__(self) -> None:
428
- self.errors: List["HashError"] = []
429
-
430
- def append(self, error: "HashError") -> None:
431
- self.errors.append(error)
432
-
433
- def __str__(self) -> str:
434
- lines = []
435
- self.errors.sort(key=lambda e: e.order)
436
- for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):
437
- lines.append(cls.head)
438
- lines.extend(e.body() for e in errors_of_cls)
439
- if lines:
440
- return "\n".join(lines)
441
- return ""
442
-
443
- def __bool__(self) -> bool:
444
- return bool(self.errors)
445
-
446
-
447
- class HashError(InstallationError):
448
- """
449
- A failure to verify a package against known-good hashes
450
-
451
- :cvar order: An int sorting hash exception classes by difficulty of
452
- recovery (lower being harder), so the user doesn't bother fretting
453
- about unpinned packages when he has deeper issues, like VCS
454
- dependencies, to deal with. Also keeps error reports in a
455
- deterministic order.
456
- :cvar head: A section heading for display above potentially many
457
- exceptions of this kind
458
- :ivar req: The InstallRequirement that triggered this error. This is
459
- pasted on after the exception is instantiated, because it's not
460
- typically available earlier.
461
-
462
- """
463
-
464
- req: Optional["InstallRequirement"] = None
465
- head = ""
466
- order: int = -1
467
-
468
- def body(self) -> str:
469
- """Return a summary of me for display under the heading.
470
-
471
- This default implementation simply prints a description of the
472
- triggering requirement.
473
-
474
- :param req: The InstallRequirement that provoked this error, with
475
- its link already populated by the resolver's _populate_link().
476
-
477
- """
478
- return f" {self._requirement_name()}"
479
-
480
- def __str__(self) -> str:
481
- return f"{self.head}\n{self.body()}"
482
-
483
- def _requirement_name(self) -> str:
484
- """Return a description of the requirement that triggered me.
485
-
486
- This default implementation returns long description of the req, with
487
- line numbers
488
-
489
- """
490
- return str(self.req) if self.req else "unknown package"
491
-
492
-
493
- class VcsHashUnsupported(HashError):
494
- """A hash was provided for a version-control-system-based requirement, but
495
- we don't have a method for hashing those."""
496
-
497
- order = 0
498
- head = (
499
- "Can't verify hashes for these requirements because we don't "
500
- "have a way to hash version control repositories:"
501
- )
502
-
503
-
504
- class DirectoryUrlHashUnsupported(HashError):
505
- """A hash was provided for a version-control-system-based requirement, but
506
- we don't have a method for hashing those."""
507
-
508
- order = 1
509
- head = (
510
- "Can't verify hashes for these file:// requirements because they "
511
- "point to directories:"
512
- )
513
-
514
-
515
- class HashMissing(HashError):
516
- """A hash was needed for a requirement but is absent."""
517
-
518
- order = 2
519
- head = (
520
- "Hashes are required in --require-hashes mode, but they are "
521
- "missing from some requirements. Here is a list of those "
522
- "requirements along with the hashes their downloaded archives "
523
- "actually had. Add lines like these to your requirements files to "
524
- "prevent tampering. (If you did not enable --require-hashes "
525
- "manually, note that it turns on automatically when any package "
526
- "has a hash.)"
527
- )
528
-
529
- def __init__(self, gotten_hash: str) -> None:
530
- """
531
- :param gotten_hash: The hash of the (possibly malicious) archive we
532
- just downloaded
533
- """
534
- self.gotten_hash = gotten_hash
535
-
536
- def body(self) -> str:
537
- # Dodge circular import.
538
- from pip._internal.utils.hashes import FAVORITE_HASH
539
-
540
- package = None
541
- if self.req:
542
- # In the case of URL-based requirements, display the original URL
543
- # seen in the requirements file rather than the package name,
544
- # so the output can be directly copied into the requirements file.
545
- package = (
546
- self.req.original_link
547
- if self.req.original_link
548
- # In case someone feeds something downright stupid
549
- # to InstallRequirement's constructor.
550
- else getattr(self.req, "req", None)
551
- )
552
- return " {} --hash={}:{}".format(
553
- package or "unknown package", FAVORITE_HASH, self.gotten_hash
554
- )
555
-
556
-
557
- class HashUnpinned(HashError):
558
- """A requirement had a hash specified but was not pinned to a specific
559
- version."""
560
-
561
- order = 3
562
- head = (
563
- "In --require-hashes mode, all requirements must have their "
564
- "versions pinned with ==. These do not:"
565
- )
566
-
567
-
568
- class HashMismatch(HashError):
569
- """
570
- Distribution file hash values don't match.
571
-
572
- :ivar package_name: The name of the package that triggered the hash
573
- mismatch. Feel free to write to this after the exception is raise to
574
- improve its error message.
575
-
576
- """
577
-
578
- order = 4
579
- head = (
580
- "THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS "
581
- "FILE. If you have updated the package versions, please update "
582
- "the hashes. Otherwise, examine the package contents carefully; "
583
- "someone may have tampered with them."
584
- )
585
-
586
- def __init__(self, allowed: Dict[str, List[str]], gots: Dict[str, "_Hash"]) -> None:
587
- """
588
- :param allowed: A dict of algorithm names pointing to lists of allowed
589
- hex digests
590
- :param gots: A dict of algorithm names pointing to hashes we
591
- actually got from the files under suspicion
592
- """
593
- self.allowed = allowed
594
- self.gots = gots
595
-
596
- def body(self) -> str:
597
- return " {}:\n{}".format(self._requirement_name(), self._hash_comparison())
598
-
599
- def _hash_comparison(self) -> str:
600
- """
601
- Return a comparison of actual and expected hash values.
602
-
603
- Example::
604
-
605
- Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde
606
- or 123451234512345123451234512345123451234512345
607
- Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef
608
-
609
- """
610
-
611
- def hash_then_or(hash_name: str) -> "chain[str]":
612
- # For now, all the decent hashes have 6-char names, so we can get
613
- # away with hard-coding space literals.
614
- return chain([hash_name], repeat(" or"))
615
-
616
- lines: List[str] = []
617
- for hash_name, expecteds in self.allowed.items():
618
- prefix = hash_then_or(hash_name)
619
- lines.extend(
620
- (" Expected {} {}".format(next(prefix), e)) for e in expecteds
621
- )
622
- lines.append(
623
- " Got {}\n".format(self.gots[hash_name].hexdigest())
624
- )
625
- return "\n".join(lines)
626
-
627
-
628
- class UnsupportedPythonVersion(InstallationError):
629
- """Unsupported python version according to Requires-Python package
630
- metadata."""
631
-
632
-
633
- class ConfigurationFileCouldNotBeLoaded(ConfigurationError):
634
- """When there are errors while loading a configuration file"""
635
-
636
- def __init__(
637
- self,
638
- reason: str = "could not be loaded",
639
- fname: Optional[str] = None,
640
- error: Optional[configparser.Error] = None,
641
- ) -> None:
642
- super().__init__(error)
643
- self.reason = reason
644
- self.fname = fname
645
- self.error = error
646
-
647
- def __str__(self) -> str:
648
- if self.fname is not None:
649
- message_part = f" in {self.fname}."
650
- else:
651
- assert self.error is not None
652
- message_part = f".\n{self.error}\n"
653
- return f"Configuration file {self.reason}{message_part}"
654
-
655
-
656
- _DEFAULT_EXTERNALLY_MANAGED_ERROR = f"""\
657
- The Python environment under {sys.prefix} is managed externally, and may not be
658
- manipulated by the user. Please use specific tooling from the distributor of
659
- the Python installation to interact with this environment instead.
660
- """
661
-
662
-
663
- class ExternallyManagedEnvironment(DiagnosticPipError):
664
- """The current environment is externally managed.
665
-
666
- This is raised when the current environment is externally managed, as
667
- defined by `PEP 668`_. The ``EXTERNALLY-MANAGED`` configuration is checked
668
- and displayed when the error is bubbled up to the user.
669
-
670
- :param error: The error message read from ``EXTERNALLY-MANAGED``.
671
- """
672
-
673
- reference = "externally-managed-environment"
674
-
675
- def __init__(self, error: Optional[str]) -> None:
676
- if error is None:
677
- context = Text(_DEFAULT_EXTERNALLY_MANAGED_ERROR)
678
- else:
679
- context = Text(error)
680
- super().__init__(
681
- message="This environment is externally managed",
682
- context=context,
683
- note_stmt=(
684
- "If you believe this is a mistake, please contact your "
685
- "Python installation or OS distribution provider. "
686
- "You can override this, at the risk of breaking your Python "
687
- "installation or OS, by passing --break-system-packages."
688
- ),
689
- hint_stmt=Text("See PEP 668 for the detailed specification."),
690
- )
691
-
692
- @staticmethod
693
- def _iter_externally_managed_error_keys() -> Iterator[str]:
694
- # LC_MESSAGES is in POSIX, but not the C standard. The most common
695
- # platform that does not implement this category is Windows, where
696
- # using other categories for console message localization is equally
697
- # unreliable, so we fall back to the locale-less vendor message. This
698
- # can always be re-evaluated when a vendor proposes a new alternative.
699
- try:
700
- category = locale.LC_MESSAGES
701
- except AttributeError:
702
- lang: Optional[str] = None
703
- else:
704
- lang, _ = locale.getlocale(category)
705
- if lang is not None:
706
- yield f"Error-{lang}"
707
- for sep in ("-", "_"):
708
- before, found, _ = lang.partition(sep)
709
- if not found:
710
- continue
711
- yield f"Error-{before}"
712
- yield "Error"
713
-
714
- @classmethod
715
- def from_config(
716
- cls,
717
- config: Union[pathlib.Path, str],
718
- ) -> "ExternallyManagedEnvironment":
719
- parser = configparser.ConfigParser(interpolation=None)
720
- try:
721
- parser.read(config, encoding="utf-8")
722
- section = parser["externally-managed"]
723
- for key in cls._iter_externally_managed_error_keys():
724
- with contextlib.suppress(KeyError):
725
- return cls(section[key])
726
- except KeyError:
727
- pass
728
- except (OSError, UnicodeDecodeError, configparser.ParsingError):
729
- from pip._internal.utils._log import VERBOSE
730
-
731
- exc_info = logger.isEnabledFor(VERBOSE)
732
- logger.warning("Failed to read %s", config, exc_info=exc_info)
733
- return cls(None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Big-Web/MMSD/env/Lib/site-packages/setuptools/_distutils/versionpredicate.py DELETED
@@ -1,175 +0,0 @@
1
- """Module for parsing and testing package version predicate strings.
2
- """
3
- import re
4
- import distutils.version
5
- import operator
6
-
7
-
8
- re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)", re.ASCII)
9
- # (package) (rest)
10
-
11
- re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
12
- re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$")
13
- # (comp) (version)
14
-
15
-
16
- def splitUp(pred):
17
- """Parse a single version comparison.
18
-
19
- Return (comparison string, StrictVersion)
20
- """
21
- res = re_splitComparison.match(pred)
22
- if not res:
23
- raise ValueError("bad package restriction syntax: %r" % pred)
24
- comp, verStr = res.groups()
25
- with distutils.version.suppress_known_deprecation():
26
- other = distutils.version.StrictVersion(verStr)
27
- return (comp, other)
28
-
29
-
30
- compmap = {
31
- "<": operator.lt,
32
- "<=": operator.le,
33
- "==": operator.eq,
34
- ">": operator.gt,
35
- ">=": operator.ge,
36
- "!=": operator.ne,
37
- }
38
-
39
-
40
- class VersionPredicate:
41
- """Parse and test package version predicates.
42
-
43
- >>> v = VersionPredicate('pyepat.abc (>1.0, <3333.3a1, !=1555.1b3)')
44
-
45
- The `name` attribute provides the full dotted name that is given::
46
-
47
- >>> v.name
48
- 'pyepat.abc'
49
-
50
- The str() of a `VersionPredicate` provides a normalized
51
- human-readable version of the expression::
52
-
53
- >>> print(v)
54
- pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)
55
-
56
- The `satisfied_by()` method can be used to determine with a given
57
- version number is included in the set described by the version
58
- restrictions::
59
-
60
- >>> v.satisfied_by('1.1')
61
- True
62
- >>> v.satisfied_by('1.4')
63
- True
64
- >>> v.satisfied_by('1.0')
65
- False
66
- >>> v.satisfied_by('4444.4')
67
- False
68
- >>> v.satisfied_by('1555.1b3')
69
- False
70
-
71
- `VersionPredicate` is flexible in accepting extra whitespace::
72
-
73
- >>> v = VersionPredicate(' pat( == 0.1 ) ')
74
- >>> v.name
75
- 'pat'
76
- >>> v.satisfied_by('0.1')
77
- True
78
- >>> v.satisfied_by('0.2')
79
- False
80
-
81
- If any version numbers passed in do not conform to the
82
- restrictions of `StrictVersion`, a `ValueError` is raised::
83
-
84
- >>> v = VersionPredicate('p1.p2.p3.p4(>=1.0, <=1.3a1, !=1.2zb3)')
85
- Traceback (most recent call last):
86
- ...
87
- ValueError: invalid version number '1.2zb3'
88
-
89
- It the module or package name given does not conform to what's
90
- allowed as a legal module or package name, `ValueError` is
91
- raised::
92
-
93
- >>> v = VersionPredicate('foo-bar')
94
- Traceback (most recent call last):
95
- ...
96
- ValueError: expected parenthesized list: '-bar'
97
-
98
- >>> v = VersionPredicate('foo bar (12.21)')
99
- Traceback (most recent call last):
100
- ...
101
- ValueError: expected parenthesized list: 'bar (12.21)'
102
-
103
- """
104
-
105
- def __init__(self, versionPredicateStr):
106
- """Parse a version predicate string."""
107
- # Fields:
108
- # name: package name
109
- # pred: list of (comparison string, StrictVersion)
110
-
111
- versionPredicateStr = versionPredicateStr.strip()
112
- if not versionPredicateStr:
113
- raise ValueError("empty package restriction")
114
- match = re_validPackage.match(versionPredicateStr)
115
- if not match:
116
- raise ValueError("bad package name in %r" % versionPredicateStr)
117
- self.name, paren = match.groups()
118
- paren = paren.strip()
119
- if paren:
120
- match = re_paren.match(paren)
121
- if not match:
122
- raise ValueError("expected parenthesized list: %r" % paren)
123
- str = match.groups()[0]
124
- self.pred = [splitUp(aPred) for aPred in str.split(",")]
125
- if not self.pred:
126
- raise ValueError("empty parenthesized list in %r" % versionPredicateStr)
127
- else:
128
- self.pred = []
129
-
130
- def __str__(self):
131
- if self.pred:
132
- seq = [cond + " " + str(ver) for cond, ver in self.pred]
133
- return self.name + " (" + ", ".join(seq) + ")"
134
- else:
135
- return self.name
136
-
137
- def satisfied_by(self, version):
138
- """True if version is compatible with all the predicates in self.
139
- The parameter version must be acceptable to the StrictVersion
140
- constructor. It may be either a string or StrictVersion.
141
- """
142
- for cond, ver in self.pred:
143
- if not compmap[cond](version, ver):
144
- return False
145
- return True
146
-
147
-
148
- _provision_rx = None
149
-
150
-
151
- def split_provision(value):
152
- """Return the name and optional version number of a provision.
153
-
154
- The version number, if given, will be returned as a `StrictVersion`
155
- instance, otherwise it will be `None`.
156
-
157
- >>> split_provision('mypkg')
158
- ('mypkg', None)
159
- >>> split_provision(' mypkg( 1.2 ) ')
160
- ('mypkg', StrictVersion ('1.2'))
161
- """
162
- global _provision_rx
163
- if _provision_rx is None:
164
- _provision_rx = re.compile(
165
- r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$", re.ASCII
166
- )
167
- value = value.strip()
168
- m = _provision_rx.match(value)
169
- if not m:
170
- raise ValueError("illegal provides specification: %r" % value)
171
- ver = m.group(2) or None
172
- if ver:
173
- with distutils.version.suppress_known_deprecation():
174
- ver = distutils.version.StrictVersion(ver)
175
- return m.group(1), ver
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Boranbruh/ehartford-WizardLM-7B-Uncensored/README.md DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: Ehartford WizardLM 7B Uncensored
3
- emoji: 🏆
4
- colorFrom: red
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 3.29.0
8
- app_file: app.py
9
- pinned: false
10
- license: cc
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/BridgeEight/internlm-20B-chat-w4-turbomind/download.sh DELETED
@@ -1,8 +0,0 @@
1
- #!/bin/sh
2
- # git clone [email protected]:lmdeploy/turbomind-internlm-chat-20b-w4
3
- if [ ! -d "turbomind-internlm-chat-20b-w4" ]
4
- then
5
- echo "Downloading..."
6
- git lfs clone https://huggingface.co/lmdeploy/turbomind-internlm-chat-20b-w4
7
- fi
8
- ls turbomind-internlm-chat-20b-w4
 
 
 
 
 
 
 
 
 
spaces/CVPR/Dual-Key_Backdoor_Attacks/datagen/detectron2/tests/test_visualizer.py DELETED
@@ -1,143 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
3
- # File:
4
-
5
- import numpy as np
6
- import unittest
7
- import torch
8
-
9
- from detectron2.data import MetadataCatalog
10
- from detectron2.structures import BoxMode, Instances, RotatedBoxes
11
- from detectron2.utils.visualizer import Visualizer
12
-
13
-
14
- class TestVisualizer(unittest.TestCase):
15
- def _random_data(self):
16
- H, W = 100, 100
17
- N = 10
18
- img = np.random.rand(H, W, 3) * 255
19
- boxxy = np.random.rand(N, 2) * (H // 2)
20
- boxes = np.concatenate((boxxy, boxxy + H // 2), axis=1)
21
-
22
- def _rand_poly():
23
- return np.random.rand(3, 2).flatten() * H
24
-
25
- polygons = [[_rand_poly() for _ in range(np.random.randint(1, 5))] for _ in range(N)]
26
-
27
- mask = np.zeros_like(img[:, :, 0], dtype=np.bool)
28
- mask[:10, 10:20] = 1
29
-
30
- labels = [str(i) for i in range(N)]
31
- return img, boxes, labels, polygons, [mask] * N
32
-
33
- @property
34
- def metadata(self):
35
- return MetadataCatalog.get("coco_2017_train")
36
-
37
- def test_draw_dataset_dict(self):
38
- img = np.random.rand(512, 512, 3) * 255
39
- dic = {
40
- "annotations": [
41
- {
42
- "bbox": [
43
- 368.9946492271106,
44
- 330.891438763377,
45
- 13.148537455410235,
46
- 13.644708680142685,
47
- ],
48
- "bbox_mode": BoxMode.XYWH_ABS,
49
- "category_id": 0,
50
- "iscrowd": 1,
51
- "segmentation": {
52
- "counts": "_jh52m?2N2N2N2O100O10O001N1O2MceP2",
53
- "size": [512, 512],
54
- },
55
- }
56
- ],
57
- "height": 512,
58
- "image_id": 1,
59
- "width": 512,
60
- }
61
- v = Visualizer(img, self.metadata)
62
- v.draw_dataset_dict(dic)
63
-
64
- def test_overlay_instances(self):
65
- img, boxes, labels, polygons, masks = self._random_data()
66
-
67
- v = Visualizer(img, self.metadata)
68
- output = v.overlay_instances(masks=polygons, boxes=boxes, labels=labels).get_image()
69
- self.assertEqual(output.shape, img.shape)
70
-
71
- # Test 2x scaling
72
- v = Visualizer(img, self.metadata, scale=2.0)
73
- output = v.overlay_instances(masks=polygons, boxes=boxes, labels=labels).get_image()
74
- self.assertEqual(output.shape[0], img.shape[0] * 2)
75
-
76
- # Test overlay masks
77
- v = Visualizer(img, self.metadata)
78
- output = v.overlay_instances(masks=masks, boxes=boxes, labels=labels).get_image()
79
- self.assertEqual(output.shape, img.shape)
80
-
81
- def test_overlay_instances_no_boxes(self):
82
- img, boxes, labels, polygons, _ = self._random_data()
83
- v = Visualizer(img, self.metadata)
84
- v.overlay_instances(masks=polygons, boxes=None, labels=labels).get_image()
85
-
86
- def test_draw_instance_predictions(self):
87
- img, boxes, _, _, masks = self._random_data()
88
- num_inst = len(boxes)
89
- inst = Instances((img.shape[0], img.shape[1]))
90
- inst.pred_classes = torch.randint(0, 80, size=(num_inst,))
91
- inst.scores = torch.rand(num_inst)
92
- inst.pred_boxes = torch.from_numpy(boxes)
93
- inst.pred_masks = torch.from_numpy(np.asarray(masks))
94
-
95
- v = Visualizer(img, self.metadata)
96
- v.draw_instance_predictions(inst)
97
-
98
- def test_draw_empty_mask_predictions(self):
99
- img, boxes, _, _, masks = self._random_data()
100
- num_inst = len(boxes)
101
- inst = Instances((img.shape[0], img.shape[1]))
102
- inst.pred_classes = torch.randint(0, 80, size=(num_inst,))
103
- inst.scores = torch.rand(num_inst)
104
- inst.pred_boxes = torch.from_numpy(boxes)
105
- inst.pred_masks = torch.from_numpy(np.zeros_like(np.asarray(masks)))
106
-
107
- v = Visualizer(img, self.metadata)
108
- v.draw_instance_predictions(inst)
109
-
110
- def test_correct_output_shape(self):
111
- img = np.random.rand(928, 928, 3) * 255
112
- v = Visualizer(img, self.metadata)
113
- out = v.output.get_image()
114
- self.assertEqual(out.shape, img.shape)
115
-
116
- def test_overlay_rotated_instances(self):
117
- H, W = 100, 150
118
- img = np.random.rand(H, W, 3) * 255
119
- num_boxes = 50
120
- boxes_5d = torch.zeros(num_boxes, 5)
121
- boxes_5d[:, 0] = torch.FloatTensor(num_boxes).uniform_(-0.1 * W, 1.1 * W)
122
- boxes_5d[:, 1] = torch.FloatTensor(num_boxes).uniform_(-0.1 * H, 1.1 * H)
123
- boxes_5d[:, 2] = torch.FloatTensor(num_boxes).uniform_(0, max(W, H))
124
- boxes_5d[:, 3] = torch.FloatTensor(num_boxes).uniform_(0, max(W, H))
125
- boxes_5d[:, 4] = torch.FloatTensor(num_boxes).uniform_(-1800, 1800)
126
- rotated_boxes = RotatedBoxes(boxes_5d)
127
- labels = [str(i) for i in range(num_boxes)]
128
-
129
- v = Visualizer(img, self.metadata)
130
- output = v.overlay_instances(boxes=rotated_boxes, labels=labels).get_image()
131
- self.assertEqual(output.shape, img.shape)
132
-
133
- def test_draw_no_metadata(self):
134
- img, boxes, _, _, masks = self._random_data()
135
- num_inst = len(boxes)
136
- inst = Instances((img.shape[0], img.shape[1]))
137
- inst.pred_classes = torch.randint(0, 80, size=(num_inst,))
138
- inst.scores = torch.rand(num_inst)
139
- inst.pred_boxes = torch.from_numpy(boxes)
140
- inst.pred_masks = torch.from_numpy(np.asarray(masks))
141
-
142
- v = Visualizer(img, MetadataCatalog.get("asdfasdf"))
143
- v.draw_instance_predictions(inst)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/WALT/configs/_base_/default_runtime.py DELETED
@@ -1,16 +0,0 @@
1
- checkpoint_config = dict(interval=1)
2
- # yapf:disable
3
- log_config = dict(
4
- interval=50,
5
- hooks=[
6
- dict(type='TextLoggerHook'),
7
- # dict(type='TensorboardLoggerHook')
8
- ])
9
- # yapf:enable
10
- custom_hooks = [dict(type='NumClassCheckHook')]
11
-
12
- dist_params = dict(backend='nccl')
13
- log_level = 'INFO'
14
- load_from = None
15
- resume_from = None
16
- workflow = [('train', 1)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/WALT/mmdet/models/roi_heads/point_rend_roi_head.py DELETED
@@ -1,218 +0,0 @@
1
- # Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend # noqa
2
-
3
- import torch
4
- import torch.nn.functional as F
5
- from mmcv.ops import point_sample, rel_roi_point_to_rel_img_point
6
-
7
- from mmdet.core import bbox2roi, bbox_mapping, merge_aug_masks
8
- from .. import builder
9
- from ..builder import HEADS
10
- from .standard_roi_head import StandardRoIHead
11
-
12
-
13
- @HEADS.register_module()
14
- class PointRendRoIHead(StandardRoIHead):
15
- """`PointRend <https://arxiv.org/abs/1912.08193>`_."""
16
-
17
- def __init__(self, point_head, *args, **kwargs):
18
- super().__init__(*args, **kwargs)
19
- assert self.with_bbox and self.with_mask
20
- self.init_point_head(point_head)
21
-
22
- def init_point_head(self, point_head):
23
- """Initialize ``point_head``"""
24
- self.point_head = builder.build_head(point_head)
25
-
26
- def init_weights(self, pretrained):
27
- """Initialize the weights in head.
28
-
29
- Args:
30
- pretrained (str, optional): Path to pre-trained weights.
31
- """
32
- super().init_weights(pretrained)
33
- self.point_head.init_weights()
34
-
35
- def _mask_forward_train(self, x, sampling_results, bbox_feats, gt_masks,
36
- img_metas):
37
- """Run forward function and calculate loss for mask head and point head
38
- in training."""
39
- mask_results = super()._mask_forward_train(x, sampling_results,
40
- bbox_feats, gt_masks,
41
- img_metas)
42
- if mask_results['loss_mask'] is not None:
43
- loss_point = self._mask_point_forward_train(
44
- x, sampling_results, mask_results['mask_pred'], gt_masks,
45
- img_metas)
46
- mask_results['loss_mask'].update(loss_point)
47
-
48
- return mask_results
49
-
50
- def _mask_point_forward_train(self, x, sampling_results, mask_pred,
51
- gt_masks, img_metas):
52
- """Run forward function and calculate loss for point head in
53
- training."""
54
- pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])
55
- rel_roi_points = self.point_head.get_roi_rel_points_train(
56
- mask_pred, pos_labels, cfg=self.train_cfg)
57
- rois = bbox2roi([res.pos_bboxes for res in sampling_results])
58
-
59
- fine_grained_point_feats = self._get_fine_grained_point_feats(
60
- x, rois, rel_roi_points, img_metas)
61
- coarse_point_feats = point_sample(mask_pred, rel_roi_points)
62
- mask_point_pred = self.point_head(fine_grained_point_feats,
63
- coarse_point_feats)
64
- mask_point_target = self.point_head.get_targets(
65
- rois, rel_roi_points, sampling_results, gt_masks, self.train_cfg)
66
- loss_mask_point = self.point_head.loss(mask_point_pred,
67
- mask_point_target, pos_labels)
68
-
69
- return loss_mask_point
70
-
71
- def _get_fine_grained_point_feats(self, x, rois, rel_roi_points,
72
- img_metas):
73
- """Sample fine grained feats from each level feature map and
74
- concatenate them together."""
75
- num_imgs = len(img_metas)
76
- fine_grained_feats = []
77
- for idx in range(self.mask_roi_extractor.num_inputs):
78
- feats = x[idx]
79
- spatial_scale = 1. / float(
80
- self.mask_roi_extractor.featmap_strides[idx])
81
- point_feats = []
82
- for batch_ind in range(num_imgs):
83
- # unravel batch dim
84
- feat = feats[batch_ind].unsqueeze(0)
85
- inds = (rois[:, 0].long() == batch_ind)
86
- if inds.any():
87
- rel_img_points = rel_roi_point_to_rel_img_point(
88
- rois[inds], rel_roi_points[inds], feat.shape[2:],
89
- spatial_scale).unsqueeze(0)
90
- point_feat = point_sample(feat, rel_img_points)
91
- point_feat = point_feat.squeeze(0).transpose(0, 1)
92
- point_feats.append(point_feat)
93
- fine_grained_feats.append(torch.cat(point_feats, dim=0))
94
- return torch.cat(fine_grained_feats, dim=1)
95
-
96
- def _mask_point_forward_test(self, x, rois, label_pred, mask_pred,
97
- img_metas):
98
- """Mask refining process with point head in testing."""
99
- refined_mask_pred = mask_pred.clone()
100
- for subdivision_step in range(self.test_cfg.subdivision_steps):
101
- refined_mask_pred = F.interpolate(
102
- refined_mask_pred,
103
- scale_factor=self.test_cfg.scale_factor,
104
- mode='bilinear',
105
- align_corners=False)
106
- # If `subdivision_num_points` is larger or equal to the
107
- # resolution of the next step, then we can skip this step
108
- num_rois, channels, mask_height, mask_width = \
109
- refined_mask_pred.shape
110
- if (self.test_cfg.subdivision_num_points >=
111
- self.test_cfg.scale_factor**2 * mask_height * mask_width
112
- and
113
- subdivision_step < self.test_cfg.subdivision_steps - 1):
114
- continue
115
- point_indices, rel_roi_points = \
116
- self.point_head.get_roi_rel_points_test(
117
- refined_mask_pred, label_pred, cfg=self.test_cfg)
118
- fine_grained_point_feats = self._get_fine_grained_point_feats(
119
- x, rois, rel_roi_points, img_metas)
120
- coarse_point_feats = point_sample(mask_pred, rel_roi_points)
121
- mask_point_pred = self.point_head(fine_grained_point_feats,
122
- coarse_point_feats)
123
-
124
- point_indices = point_indices.unsqueeze(1).expand(-1, channels, -1)
125
- refined_mask_pred = refined_mask_pred.reshape(
126
- num_rois, channels, mask_height * mask_width)
127
- refined_mask_pred = refined_mask_pred.scatter_(
128
- 2, point_indices, mask_point_pred)
129
- refined_mask_pred = refined_mask_pred.view(num_rois, channels,
130
- mask_height, mask_width)
131
-
132
- return refined_mask_pred
133
-
134
- def simple_test_mask(self,
135
- x,
136
- img_metas,
137
- det_bboxes,
138
- det_labels,
139
- rescale=False):
140
- """Obtain mask prediction without augmentation."""
141
- ori_shapes = tuple(meta['ori_shape'] for meta in img_metas)
142
- scale_factors = tuple(meta['scale_factor'] for meta in img_metas)
143
- num_imgs = len(det_bboxes)
144
- if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):
145
- segm_results = [[[] for _ in range(self.mask_head.num_classes)]
146
- for _ in range(num_imgs)]
147
- else:
148
- # if det_bboxes is rescaled to the original image size, we need to
149
- # rescale it back to the testing scale to obtain RoIs.
150
- if rescale and not isinstance(scale_factors[0], float):
151
- scale_factors = [
152
- torch.from_numpy(scale_factor).to(det_bboxes[0].device)
153
- for scale_factor in scale_factors
154
- ]
155
- _bboxes = [
156
- det_bboxes[i][:, :4] *
157
- scale_factors[i] if rescale else det_bboxes[i][:, :4]
158
- for i in range(len(det_bboxes))
159
- ]
160
- mask_rois = bbox2roi(_bboxes)
161
- mask_results = self._mask_forward(x, mask_rois)
162
- # split batch mask prediction back to each image
163
- mask_pred = mask_results['mask_pred']
164
- num_mask_roi_per_img = [len(det_bbox) for det_bbox in det_bboxes]
165
- mask_preds = mask_pred.split(num_mask_roi_per_img, 0)
166
- mask_rois = mask_rois.split(num_mask_roi_per_img, 0)
167
-
168
- # apply mask post-processing to each image individually
169
- segm_results = []
170
- for i in range(num_imgs):
171
- if det_bboxes[i].shape[0] == 0:
172
- segm_results.append(
173
- [[] for _ in range(self.mask_head.num_classes)])
174
- else:
175
- x_i = [xx[[i]] for xx in x]
176
- mask_rois_i = mask_rois[i]
177
- mask_rois_i[:, 0] = 0 # TODO: remove this hack
178
- mask_pred_i = self._mask_point_forward_test(
179
- x_i, mask_rois_i, det_labels[i], mask_preds[i],
180
- [img_metas])
181
- segm_result = self.mask_head.get_seg_masks(
182
- mask_pred_i, _bboxes[i], det_labels[i], self.test_cfg,
183
- ori_shapes[i], scale_factors[i], rescale)
184
- segm_results.append(segm_result)
185
- return segm_results
186
-
187
- def aug_test_mask(self, feats, img_metas, det_bboxes, det_labels):
188
- """Test for mask head with test time augmentation."""
189
- if det_bboxes.shape[0] == 0:
190
- segm_result = [[] for _ in range(self.mask_head.num_classes)]
191
- else:
192
- aug_masks = []
193
- for x, img_meta in zip(feats, img_metas):
194
- img_shape = img_meta[0]['img_shape']
195
- scale_factor = img_meta[0]['scale_factor']
196
- flip = img_meta[0]['flip']
197
- _bboxes = bbox_mapping(det_bboxes[:, :4], img_shape,
198
- scale_factor, flip)
199
- mask_rois = bbox2roi([_bboxes])
200
- mask_results = self._mask_forward(x, mask_rois)
201
- mask_results['mask_pred'] = self._mask_point_forward_test(
202
- x, mask_rois, det_labels, mask_results['mask_pred'],
203
- img_metas)
204
- # convert to numpy array to save memory
205
- aug_masks.append(
206
- mask_results['mask_pred'].sigmoid().cpu().numpy())
207
- merged_masks = merge_aug_masks(aug_masks, img_metas, self.test_cfg)
208
-
209
- ori_shape = img_metas[0][0]['ori_shape']
210
- segm_result = self.mask_head.get_seg_masks(
211
- merged_masks,
212
- det_bboxes,
213
- det_labels,
214
- self.test_cfg,
215
- ori_shape,
216
- scale_factor=1.0,
217
- rescale=False)
218
- return segm_result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/CVPR/regionclip-demo/detectron2/modeling/meta_arch/semantic_seg.py DELETED
@@ -1,250 +0,0 @@
1
- # Copyright (c) Facebook, Inc. and its affiliates.
2
- import numpy as np
3
- from typing import Callable, Dict, Optional, Tuple, Union
4
- import fvcore.nn.weight_init as weight_init
5
- import torch
6
- from torch import nn
7
- from torch.nn import functional as F
8
-
9
- from detectron2.config import configurable
10
- from detectron2.layers import Conv2d, ShapeSpec, get_norm
11
- from detectron2.structures import ImageList
12
- from detectron2.utils.registry import Registry
13
-
14
- from ..backbone import Backbone, build_backbone
15
- from ..postprocessing import sem_seg_postprocess
16
- from .build import META_ARCH_REGISTRY
17
-
18
- __all__ = ["SemanticSegmentor", "SEM_SEG_HEADS_REGISTRY", "SemSegFPNHead", "build_sem_seg_head"]
19
-
20
-
21
- SEM_SEG_HEADS_REGISTRY = Registry("SEM_SEG_HEADS")
22
- SEM_SEG_HEADS_REGISTRY.__doc__ = """
23
- Registry for semantic segmentation heads, which make semantic segmentation predictions
24
- from feature maps.
25
- """
26
-
27
-
28
- @META_ARCH_REGISTRY.register()
29
- class SemanticSegmentor(nn.Module):
30
- """
31
- Main class for semantic segmentation architectures.
32
- """
33
-
34
- @configurable
35
- def __init__(
36
- self,
37
- *,
38
- backbone: Backbone,
39
- sem_seg_head: nn.Module,
40
- pixel_mean: Tuple[float],
41
- pixel_std: Tuple[float],
42
- ):
43
- """
44
- Args:
45
- backbone: a backbone module, must follow detectron2's backbone interface
46
- sem_seg_head: a module that predicts semantic segmentation from backbone features
47
- pixel_mean, pixel_std: list or tuple with #channels element, representing
48
- the per-channel mean and std to be used to normalize the input image
49
- """
50
- super().__init__()
51
- self.backbone = backbone
52
- self.sem_seg_head = sem_seg_head
53
- self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False)
54
- self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False)
55
-
56
- @classmethod
57
- def from_config(cls, cfg):
58
- backbone = build_backbone(cfg)
59
- sem_seg_head = build_sem_seg_head(cfg, backbone.output_shape())
60
- return {
61
- "backbone": backbone,
62
- "sem_seg_head": sem_seg_head,
63
- "pixel_mean": cfg.MODEL.PIXEL_MEAN,
64
- "pixel_std": cfg.MODEL.PIXEL_STD,
65
- }
66
-
67
- @property
68
- def device(self):
69
- return self.pixel_mean.device
70
-
71
- def forward(self, batched_inputs):
72
- """
73
- Args:
74
- batched_inputs: a list, batched outputs of :class:`DatasetMapper`.
75
- Each item in the list contains the inputs for one image.
76
-
77
- For now, each item in the list is a dict that contains:
78
-
79
- * "image": Tensor, image in (C, H, W) format.
80
- * "sem_seg": semantic segmentation ground truth
81
- * Other information that's included in the original dicts, such as:
82
- "height", "width" (int): the output resolution of the model (may be different
83
- from input resolution), used in inference.
84
-
85
-
86
- Returns:
87
- list[dict]:
88
- Each dict is the output for one input image.
89
- The dict contains one key "sem_seg" whose value is a
90
- Tensor that represents the
91
- per-pixel segmentation prediced by the head.
92
- The prediction has shape KxHxW that represents the logits of
93
- each class for each pixel.
94
- """
95
- images = [x["image"].to(self.device) for x in batched_inputs]
96
- images = [(x - self.pixel_mean) / self.pixel_std for x in images]
97
- images = ImageList.from_tensors(images, self.backbone.size_divisibility)
98
-
99
- features = self.backbone(images.tensor)
100
-
101
- if "sem_seg" in batched_inputs[0]:
102
- targets = [x["sem_seg"].to(self.device) for x in batched_inputs]
103
- targets = ImageList.from_tensors(
104
- targets, self.backbone.size_divisibility, self.sem_seg_head.ignore_value
105
- ).tensor
106
- else:
107
- targets = None
108
- results, losses = self.sem_seg_head(features, targets)
109
-
110
- if self.training:
111
- return losses
112
-
113
- processed_results = []
114
- for result, input_per_image, image_size in zip(results, batched_inputs, images.image_sizes):
115
- height = input_per_image.get("height")
116
- width = input_per_image.get("width")
117
- r = sem_seg_postprocess(result, image_size, height, width)
118
- processed_results.append({"sem_seg": r})
119
- return processed_results
120
-
121
-
122
- def build_sem_seg_head(cfg, input_shape):
123
- """
124
- Build a semantic segmentation head from `cfg.MODEL.SEM_SEG_HEAD.NAME`.
125
- """
126
- name = cfg.MODEL.SEM_SEG_HEAD.NAME
127
- return SEM_SEG_HEADS_REGISTRY.get(name)(cfg, input_shape)
128
-
129
-
130
- @SEM_SEG_HEADS_REGISTRY.register()
131
- class SemSegFPNHead(nn.Module):
132
- """
133
- A semantic segmentation head described in :paper:`PanopticFPN`.
134
- It takes a list of FPN features as input, and applies a sequence of
135
- 3x3 convs and upsampling to scale all of them to the stride defined by
136
- ``common_stride``. Then these features are added and used to make final
137
- predictions by another 1x1 conv layer.
138
- """
139
-
140
- @configurable
141
- def __init__(
142
- self,
143
- input_shape: Dict[str, ShapeSpec],
144
- *,
145
- num_classes: int,
146
- conv_dims: int,
147
- common_stride: int,
148
- loss_weight: float = 1.0,
149
- norm: Optional[Union[str, Callable]] = None,
150
- ignore_value: int = -1,
151
- ):
152
- """
153
- NOTE: this interface is experimental.
154
-
155
- Args:
156
- input_shape: shapes (channels and stride) of the input features
157
- num_classes: number of classes to predict
158
- conv_dims: number of output channels for the intermediate conv layers.
159
- common_stride: the common stride that all features will be upscaled to
160
- loss_weight: loss weight
161
- norm (str or callable): normalization for all conv layers
162
- ignore_value: category id to be ignored during training.
163
- """
164
- super().__init__()
165
- input_shape = sorted(input_shape.items(), key=lambda x: x[1].stride)
166
- self.in_features = [k for k, v in input_shape]
167
- feature_strides = [v.stride for k, v in input_shape]
168
- feature_channels = [v.channels for k, v in input_shape]
169
-
170
- self.ignore_value = ignore_value
171
- self.common_stride = common_stride
172
- self.loss_weight = loss_weight
173
-
174
- self.scale_heads = []
175
- for in_feature, stride, channels in zip(
176
- self.in_features, feature_strides, feature_channels
177
- ):
178
- head_ops = []
179
- head_length = max(1, int(np.log2(stride) - np.log2(self.common_stride)))
180
- for k in range(head_length):
181
- norm_module = get_norm(norm, conv_dims)
182
- conv = Conv2d(
183
- channels if k == 0 else conv_dims,
184
- conv_dims,
185
- kernel_size=3,
186
- stride=1,
187
- padding=1,
188
- bias=not norm,
189
- norm=norm_module,
190
- activation=F.relu,
191
- )
192
- weight_init.c2_msra_fill(conv)
193
- head_ops.append(conv)
194
- if stride != self.common_stride:
195
- head_ops.append(
196
- nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False)
197
- )
198
- self.scale_heads.append(nn.Sequential(*head_ops))
199
- self.add_module(in_feature, self.scale_heads[-1])
200
- self.predictor = Conv2d(conv_dims, num_classes, kernel_size=1, stride=1, padding=0)
201
- weight_init.c2_msra_fill(self.predictor)
202
-
203
- @classmethod
204
- def from_config(cls, cfg, input_shape: Dict[str, ShapeSpec]):
205
- return {
206
- "input_shape": {
207
- k: v for k, v in input_shape.items() if k in cfg.MODEL.SEM_SEG_HEAD.IN_FEATURES
208
- },
209
- "ignore_value": cfg.MODEL.SEM_SEG_HEAD.IGNORE_VALUE,
210
- "num_classes": cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES,
211
- "conv_dims": cfg.MODEL.SEM_SEG_HEAD.CONVS_DIM,
212
- "common_stride": cfg.MODEL.SEM_SEG_HEAD.COMMON_STRIDE,
213
- "norm": cfg.MODEL.SEM_SEG_HEAD.NORM,
214
- "loss_weight": cfg.MODEL.SEM_SEG_HEAD.LOSS_WEIGHT,
215
- }
216
-
217
- def forward(self, features, targets=None):
218
- """
219
- Returns:
220
- In training, returns (None, dict of losses)
221
- In inference, returns (CxHxW logits, {})
222
- """
223
- x = self.layers(features)
224
- if self.training:
225
- return None, self.losses(x, targets)
226
- else:
227
- x = F.interpolate(
228
- x, scale_factor=self.common_stride, mode="bilinear", align_corners=False
229
- )
230
- return x, {}
231
-
232
- def layers(self, features):
233
- for i, f in enumerate(self.in_features):
234
- if i == 0:
235
- x = self.scale_heads[i](features[f])
236
- else:
237
- x = x + self.scale_heads[i](features[f])
238
- x = self.predictor(x)
239
- return x
240
-
241
- def losses(self, predictions, targets):
242
- predictions = predictions.float() # https://github.com/pytorch/pytorch/issues/48163
243
- predictions = F.interpolate(
244
- predictions, scale_factor=self.common_stride, mode="bilinear", align_corners=False
245
- )
246
- loss = F.cross_entropy(
247
- predictions, targets, reduction="mean", ignore_index=self.ignore_value
248
- )
249
- losses = {"loss_sem_seg": loss * self.loss_weight}
250
- return losses
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Caoyunkang/Segment-Any-Anomaly/GroundingDINO/groundingdino/models/GroundingDINO/backbone/swin_transformer.py DELETED
@@ -1,802 +0,0 @@
1
- # ------------------------------------------------------------------------
2
- # Grounding DINO
3
- # url: https://github.com/IDEA-Research/GroundingDINO
4
- # Copyright (c) 2023 IDEA. All Rights Reserved.
5
- # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
- # ------------------------------------------------------------------------
7
- # DINO
8
- # Copyright (c) 2022 IDEA. All Rights Reserved.
9
- # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
10
- # --------------------------------------------------------
11
- # modified from https://github.com/SwinTransformer/Swin-Transformer-Object-Detection/blob/master/mmdet/models/backbones/swin_transformer.py
12
- # --------------------------------------------------------
13
-
14
- import numpy as np
15
- import torch
16
- import torch.nn as nn
17
- import torch.nn.functional as F
18
- import torch.utils.checkpoint as checkpoint
19
- from timm.models.layers import DropPath, to_2tuple, trunc_normal_
20
-
21
- from groundingdino.util.misc import NestedTensor
22
-
23
-
24
- class Mlp(nn.Module):
25
- """Multilayer perceptron."""
26
-
27
- def __init__(
28
- self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0
29
- ):
30
- super().__init__()
31
- out_features = out_features or in_features
32
- hidden_features = hidden_features or in_features
33
- self.fc1 = nn.Linear(in_features, hidden_features)
34
- self.act = act_layer()
35
- self.fc2 = nn.Linear(hidden_features, out_features)
36
- self.drop = nn.Dropout(drop)
37
-
38
- def forward(self, x):
39
- x = self.fc1(x)
40
- x = self.act(x)
41
- x = self.drop(x)
42
- x = self.fc2(x)
43
- x = self.drop(x)
44
- return x
45
-
46
-
47
- def window_partition(x, window_size):
48
- """
49
- Args:
50
- x: (B, H, W, C)
51
- window_size (int): window size
52
- Returns:
53
- windows: (num_windows*B, window_size, window_size, C)
54
- """
55
- B, H, W, C = x.shape
56
- x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
57
- windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
58
- return windows
59
-
60
-
61
- def window_reverse(windows, window_size, H, W):
62
- """
63
- Args:
64
- windows: (num_windows*B, window_size, window_size, C)
65
- window_size (int): Window size
66
- H (int): Height of image
67
- W (int): Width of image
68
- Returns:
69
- x: (B, H, W, C)
70
- """
71
- B = int(windows.shape[0] / (H * W / window_size / window_size))
72
- x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
73
- x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
74
- return x
75
-
76
-
77
- class WindowAttention(nn.Module):
78
- """Window based multi-head self attention (W-MSA) module with relative position bias.
79
- It supports both of shifted and non-shifted window.
80
- Args:
81
- dim (int): Number of input channels.
82
- window_size (tuple[int]): The height and width of the window.
83
- num_heads (int): Number of attention heads.
84
- qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
85
- qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
86
- attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
87
- proj_drop (float, optional): Dropout ratio of output. Default: 0.0
88
- """
89
-
90
- def __init__(
91
- self,
92
- dim,
93
- window_size,
94
- num_heads,
95
- qkv_bias=True,
96
- qk_scale=None,
97
- attn_drop=0.0,
98
- proj_drop=0.0,
99
- ):
100
-
101
- super().__init__()
102
- self.dim = dim
103
- self.window_size = window_size # Wh, Ww
104
- self.num_heads = num_heads
105
- head_dim = dim // num_heads
106
- self.scale = qk_scale or head_dim**-0.5
107
-
108
- # define a parameter table of relative position bias
109
- self.relative_position_bias_table = nn.Parameter(
110
- torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
111
- ) # 2*Wh-1 * 2*Ww-1, nH
112
-
113
- # get pair-wise relative position index for each token inside the window
114
- coords_h = torch.arange(self.window_size[0])
115
- coords_w = torch.arange(self.window_size[1])
116
- coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
117
- coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
118
- relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
119
- relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
120
- relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
121
- relative_coords[:, :, 1] += self.window_size[1] - 1
122
- relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
123
- relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
124
- self.register_buffer("relative_position_index", relative_position_index)
125
-
126
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
127
- self.attn_drop = nn.Dropout(attn_drop)
128
- self.proj = nn.Linear(dim, dim)
129
- self.proj_drop = nn.Dropout(proj_drop)
130
-
131
- trunc_normal_(self.relative_position_bias_table, std=0.02)
132
- self.softmax = nn.Softmax(dim=-1)
133
-
134
- def forward(self, x, mask=None):
135
- """Forward function.
136
- Args:
137
- x: input features with shape of (num_windows*B, N, C)
138
- mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
139
- """
140
- B_, N, C = x.shape
141
- qkv = (
142
- self.qkv(x)
143
- .reshape(B_, N, 3, self.num_heads, C // self.num_heads)
144
- .permute(2, 0, 3, 1, 4)
145
- )
146
- q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
147
-
148
- q = q * self.scale
149
- attn = q @ k.transpose(-2, -1)
150
-
151
- relative_position_bias = self.relative_position_bias_table[
152
- self.relative_position_index.view(-1)
153
- ].view(
154
- self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
155
- ) # Wh*Ww,Wh*Ww,nH
156
- relative_position_bias = relative_position_bias.permute(
157
- 2, 0, 1
158
- ).contiguous() # nH, Wh*Ww, Wh*Ww
159
- attn = attn + relative_position_bias.unsqueeze(0)
160
-
161
- if mask is not None:
162
- nW = mask.shape[0]
163
- attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
164
- attn = attn.view(-1, self.num_heads, N, N)
165
- attn = self.softmax(attn)
166
- else:
167
- attn = self.softmax(attn)
168
-
169
- attn = self.attn_drop(attn)
170
-
171
- x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
172
- x = self.proj(x)
173
- x = self.proj_drop(x)
174
- return x
175
-
176
-
177
- class SwinTransformerBlock(nn.Module):
178
- """Swin Transformer Block.
179
- Args:
180
- dim (int): Number of input channels.
181
- num_heads (int): Number of attention heads.
182
- window_size (int): Window size.
183
- shift_size (int): Shift size for SW-MSA.
184
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
185
- qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
186
- qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
187
- drop (float, optional): Dropout rate. Default: 0.0
188
- attn_drop (float, optional): Attention dropout rate. Default: 0.0
189
- drop_path (float, optional): Stochastic depth rate. Default: 0.0
190
- act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
191
- norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
192
- """
193
-
194
- def __init__(
195
- self,
196
- dim,
197
- num_heads,
198
- window_size=7,
199
- shift_size=0,
200
- mlp_ratio=4.0,
201
- qkv_bias=True,
202
- qk_scale=None,
203
- drop=0.0,
204
- attn_drop=0.0,
205
- drop_path=0.0,
206
- act_layer=nn.GELU,
207
- norm_layer=nn.LayerNorm,
208
- ):
209
- super().__init__()
210
- self.dim = dim
211
- self.num_heads = num_heads
212
- self.window_size = window_size
213
- self.shift_size = shift_size
214
- self.mlp_ratio = mlp_ratio
215
- assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
216
-
217
- self.norm1 = norm_layer(dim)
218
- self.attn = WindowAttention(
219
- dim,
220
- window_size=to_2tuple(self.window_size),
221
- num_heads=num_heads,
222
- qkv_bias=qkv_bias,
223
- qk_scale=qk_scale,
224
- attn_drop=attn_drop,
225
- proj_drop=drop,
226
- )
227
-
228
- self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
229
- self.norm2 = norm_layer(dim)
230
- mlp_hidden_dim = int(dim * mlp_ratio)
231
- self.mlp = Mlp(
232
- in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop
233
- )
234
-
235
- self.H = None
236
- self.W = None
237
-
238
- def forward(self, x, mask_matrix):
239
- """Forward function.
240
- Args:
241
- x: Input feature, tensor size (B, H*W, C).
242
- H, W: Spatial resolution of the input feature.
243
- mask_matrix: Attention mask for cyclic shift.
244
- """
245
- B, L, C = x.shape
246
- H, W = self.H, self.W
247
- assert L == H * W, "input feature has wrong size"
248
-
249
- shortcut = x
250
- x = self.norm1(x)
251
- x = x.view(B, H, W, C)
252
-
253
- # pad feature maps to multiples of window size
254
- pad_l = pad_t = 0
255
- pad_r = (self.window_size - W % self.window_size) % self.window_size
256
- pad_b = (self.window_size - H % self.window_size) % self.window_size
257
- x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
258
- _, Hp, Wp, _ = x.shape
259
-
260
- # cyclic shift
261
- if self.shift_size > 0:
262
- shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
263
- attn_mask = mask_matrix
264
- else:
265
- shifted_x = x
266
- attn_mask = None
267
-
268
- # partition windows
269
- x_windows = window_partition(
270
- shifted_x, self.window_size
271
- ) # nW*B, window_size, window_size, C
272
- x_windows = x_windows.view(
273
- -1, self.window_size * self.window_size, C
274
- ) # nW*B, window_size*window_size, C
275
-
276
- # W-MSA/SW-MSA
277
- attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
278
-
279
- # merge windows
280
- attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
281
- shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
282
-
283
- # reverse cyclic shift
284
- if self.shift_size > 0:
285
- x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
286
- else:
287
- x = shifted_x
288
-
289
- if pad_r > 0 or pad_b > 0:
290
- x = x[:, :H, :W, :].contiguous()
291
-
292
- x = x.view(B, H * W, C)
293
-
294
- # FFN
295
- x = shortcut + self.drop_path(x)
296
- x = x + self.drop_path(self.mlp(self.norm2(x)))
297
-
298
- return x
299
-
300
-
301
- class PatchMerging(nn.Module):
302
- """Patch Merging Layer
303
- Args:
304
- dim (int): Number of input channels.
305
- norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
306
- """
307
-
308
- def __init__(self, dim, norm_layer=nn.LayerNorm):
309
- super().__init__()
310
- self.dim = dim
311
- self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
312
- self.norm = norm_layer(4 * dim)
313
-
314
- def forward(self, x, H, W):
315
- """Forward function.
316
- Args:
317
- x: Input feature, tensor size (B, H*W, C).
318
- H, W: Spatial resolution of the input feature.
319
- """
320
- B, L, C = x.shape
321
- assert L == H * W, "input feature has wrong size"
322
-
323
- x = x.view(B, H, W, C)
324
-
325
- # padding
326
- pad_input = (H % 2 == 1) or (W % 2 == 1)
327
- if pad_input:
328
- x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
329
-
330
- x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
331
- x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
332
- x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
333
- x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
334
- x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
335
- x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
336
-
337
- x = self.norm(x)
338
- x = self.reduction(x)
339
-
340
- return x
341
-
342
-
343
- class BasicLayer(nn.Module):
344
- """A basic Swin Transformer layer for one stage.
345
- Args:
346
- dim (int): Number of feature channels
347
- depth (int): Depths of this stage.
348
- num_heads (int): Number of attention head.
349
- window_size (int): Local window size. Default: 7.
350
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
351
- qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
352
- qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
353
- drop (float, optional): Dropout rate. Default: 0.0
354
- attn_drop (float, optional): Attention dropout rate. Default: 0.0
355
- drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
356
- norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
357
- downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
358
- use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
359
- """
360
-
361
- def __init__(
362
- self,
363
- dim,
364
- depth,
365
- num_heads,
366
- window_size=7,
367
- mlp_ratio=4.0,
368
- qkv_bias=True,
369
- qk_scale=None,
370
- drop=0.0,
371
- attn_drop=0.0,
372
- drop_path=0.0,
373
- norm_layer=nn.LayerNorm,
374
- downsample=None,
375
- use_checkpoint=False,
376
- ):
377
- super().__init__()
378
- self.window_size = window_size
379
- self.shift_size = window_size // 2
380
- self.depth = depth
381
- self.use_checkpoint = use_checkpoint
382
-
383
- # build blocks
384
- self.blocks = nn.ModuleList(
385
- [
386
- SwinTransformerBlock(
387
- dim=dim,
388
- num_heads=num_heads,
389
- window_size=window_size,
390
- shift_size=0 if (i % 2 == 0) else window_size // 2,
391
- mlp_ratio=mlp_ratio,
392
- qkv_bias=qkv_bias,
393
- qk_scale=qk_scale,
394
- drop=drop,
395
- attn_drop=attn_drop,
396
- drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
397
- norm_layer=norm_layer,
398
- )
399
- for i in range(depth)
400
- ]
401
- )
402
-
403
- # patch merging layer
404
- if downsample is not None:
405
- self.downsample = downsample(dim=dim, norm_layer=norm_layer)
406
- else:
407
- self.downsample = None
408
-
409
- def forward(self, x, H, W):
410
- """Forward function.
411
- Args:
412
- x: Input feature, tensor size (B, H*W, C).
413
- H, W: Spatial resolution of the input feature.
414
- """
415
-
416
- # calculate attention mask for SW-MSA
417
- Hp = int(np.ceil(H / self.window_size)) * self.window_size
418
- Wp = int(np.ceil(W / self.window_size)) * self.window_size
419
- img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
420
- h_slices = (
421
- slice(0, -self.window_size),
422
- slice(-self.window_size, -self.shift_size),
423
- slice(-self.shift_size, None),
424
- )
425
- w_slices = (
426
- slice(0, -self.window_size),
427
- slice(-self.window_size, -self.shift_size),
428
- slice(-self.shift_size, None),
429
- )
430
- cnt = 0
431
- for h in h_slices:
432
- for w in w_slices:
433
- img_mask[:, h, w, :] = cnt
434
- cnt += 1
435
-
436
- mask_windows = window_partition(
437
- img_mask, self.window_size
438
- ) # nW, window_size, window_size, 1
439
- mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
440
- attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
441
- attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
442
- attn_mask == 0, float(0.0)
443
- )
444
-
445
- for blk in self.blocks:
446
- blk.H, blk.W = H, W
447
- if self.use_checkpoint:
448
- x = checkpoint.checkpoint(blk, x, attn_mask)
449
- else:
450
- x = blk(x, attn_mask)
451
- if self.downsample is not None:
452
- x_down = self.downsample(x, H, W)
453
- Wh, Ww = (H + 1) // 2, (W + 1) // 2
454
- return x, H, W, x_down, Wh, Ww
455
- else:
456
- return x, H, W, x, H, W
457
-
458
-
459
- class PatchEmbed(nn.Module):
460
- """Image to Patch Embedding
461
- Args:
462
- patch_size (int): Patch token size. Default: 4.
463
- in_chans (int): Number of input image channels. Default: 3.
464
- embed_dim (int): Number of linear projection output channels. Default: 96.
465
- norm_layer (nn.Module, optional): Normalization layer. Default: None
466
- """
467
-
468
- def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
469
- super().__init__()
470
- patch_size = to_2tuple(patch_size)
471
- self.patch_size = patch_size
472
-
473
- self.in_chans = in_chans
474
- self.embed_dim = embed_dim
475
-
476
- self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
477
- if norm_layer is not None:
478
- self.norm = norm_layer(embed_dim)
479
- else:
480
- self.norm = None
481
-
482
- def forward(self, x):
483
- """Forward function."""
484
- # padding
485
- _, _, H, W = x.size()
486
- if W % self.patch_size[1] != 0:
487
- x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
488
- if H % self.patch_size[0] != 0:
489
- x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
490
-
491
- x = self.proj(x) # B C Wh Ww
492
- if self.norm is not None:
493
- Wh, Ww = x.size(2), x.size(3)
494
- x = x.flatten(2).transpose(1, 2)
495
- x = self.norm(x)
496
- x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
497
-
498
- return x
499
-
500
-
501
- class SwinTransformer(nn.Module):
502
- """Swin Transformer backbone.
503
- A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
504
- https://arxiv.org/pdf/2103.14030
505
- Args:
506
- pretrain_img_size (int): Input image size for training the pretrained model,
507
- used in absolute postion embedding. Default 224.
508
- patch_size (int | tuple(int)): Patch size. Default: 4.
509
- in_chans (int): Number of input image channels. Default: 3.
510
- embed_dim (int): Number of linear projection output channels. Default: 96.
511
- depths (tuple[int]): Depths of each Swin Transformer stage.
512
- num_heads (tuple[int]): Number of attention head of each stage.
513
- window_size (int): Window size. Default: 7.
514
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
515
- qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
516
- qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
517
- drop_rate (float): Dropout rate.
518
- attn_drop_rate (float): Attention dropout rate. Default: 0.
519
- drop_path_rate (float): Stochastic depth rate. Default: 0.2.
520
- norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
521
- ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
522
- patch_norm (bool): If True, add normalization after patch embedding. Default: True.
523
- out_indices (Sequence[int]): Output from which stages.
524
- frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
525
- -1 means not freezing any parameters.
526
- use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
527
- dilation (bool): if True, the output size if 16x downsample, ow 32x downsample.
528
- """
529
-
530
- def __init__(
531
- self,
532
- pretrain_img_size=224,
533
- patch_size=4,
534
- in_chans=3,
535
- embed_dim=96,
536
- depths=[2, 2, 6, 2],
537
- num_heads=[3, 6, 12, 24],
538
- window_size=7,
539
- mlp_ratio=4.0,
540
- qkv_bias=True,
541
- qk_scale=None,
542
- drop_rate=0.0,
543
- attn_drop_rate=0.0,
544
- drop_path_rate=0.2,
545
- norm_layer=nn.LayerNorm,
546
- ape=False,
547
- patch_norm=True,
548
- out_indices=(0, 1, 2, 3),
549
- frozen_stages=-1,
550
- dilation=False,
551
- use_checkpoint=False,
552
- ):
553
- super().__init__()
554
-
555
- self.pretrain_img_size = pretrain_img_size
556
- self.num_layers = len(depths)
557
- self.embed_dim = embed_dim
558
- self.ape = ape
559
- self.patch_norm = patch_norm
560
- self.out_indices = out_indices
561
- self.frozen_stages = frozen_stages
562
- self.dilation = dilation
563
-
564
- # if use_checkpoint:
565
- # print("use_checkpoint!!!!!!!!!!!!!!!!!!!!!!!!")
566
-
567
- # split image into non-overlapping patches
568
- self.patch_embed = PatchEmbed(
569
- patch_size=patch_size,
570
- in_chans=in_chans,
571
- embed_dim=embed_dim,
572
- norm_layer=norm_layer if self.patch_norm else None,
573
- )
574
-
575
- # absolute position embedding
576
- if self.ape:
577
- pretrain_img_size = to_2tuple(pretrain_img_size)
578
- patch_size = to_2tuple(patch_size)
579
- patches_resolution = [
580
- pretrain_img_size[0] // patch_size[0],
581
- pretrain_img_size[1] // patch_size[1],
582
- ]
583
-
584
- self.absolute_pos_embed = nn.Parameter(
585
- torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])
586
- )
587
- trunc_normal_(self.absolute_pos_embed, std=0.02)
588
-
589
- self.pos_drop = nn.Dropout(p=drop_rate)
590
-
591
- # stochastic depth
592
- dpr = [
593
- x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
594
- ] # stochastic depth decay rule
595
-
596
- # build layers
597
- self.layers = nn.ModuleList()
598
- # prepare downsample list
599
- downsamplelist = [PatchMerging for i in range(self.num_layers)]
600
- downsamplelist[-1] = None
601
- num_features = [int(embed_dim * 2**i) for i in range(self.num_layers)]
602
- if self.dilation:
603
- downsamplelist[-2] = None
604
- num_features[-1] = int(embed_dim * 2 ** (self.num_layers - 1)) // 2
605
- for i_layer in range(self.num_layers):
606
- layer = BasicLayer(
607
- # dim=int(embed_dim * 2 ** i_layer),
608
- dim=num_features[i_layer],
609
- depth=depths[i_layer],
610
- num_heads=num_heads[i_layer],
611
- window_size=window_size,
612
- mlp_ratio=mlp_ratio,
613
- qkv_bias=qkv_bias,
614
- qk_scale=qk_scale,
615
- drop=drop_rate,
616
- attn_drop=attn_drop_rate,
617
- drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],
618
- norm_layer=norm_layer,
619
- # downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
620
- downsample=downsamplelist[i_layer],
621
- use_checkpoint=use_checkpoint,
622
- )
623
- self.layers.append(layer)
624
-
625
- # num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
626
- self.num_features = num_features
627
-
628
- # add a norm layer for each output
629
- for i_layer in out_indices:
630
- layer = norm_layer(num_features[i_layer])
631
- layer_name = f"norm{i_layer}"
632
- self.add_module(layer_name, layer)
633
-
634
- self._freeze_stages()
635
-
636
- def _freeze_stages(self):
637
- if self.frozen_stages >= 0:
638
- self.patch_embed.eval()
639
- for param in self.patch_embed.parameters():
640
- param.requires_grad = False
641
-
642
- if self.frozen_stages >= 1 and self.ape:
643
- self.absolute_pos_embed.requires_grad = False
644
-
645
- if self.frozen_stages >= 2:
646
- self.pos_drop.eval()
647
- for i in range(0, self.frozen_stages - 1):
648
- m = self.layers[i]
649
- m.eval()
650
- for param in m.parameters():
651
- param.requires_grad = False
652
-
653
- # def init_weights(self, pretrained=None):
654
- # """Initialize the weights in backbone.
655
- # Args:
656
- # pretrained (str, optional): Path to pre-trained weights.
657
- # Defaults to None.
658
- # """
659
-
660
- # def _init_weights(m):
661
- # if isinstance(m, nn.Linear):
662
- # trunc_normal_(m.weight, std=.02)
663
- # if isinstance(m, nn.Linear) and m.bias is not None:
664
- # nn.init.constant_(m.bias, 0)
665
- # elif isinstance(m, nn.LayerNorm):
666
- # nn.init.constant_(m.bias, 0)
667
- # nn.init.constant_(m.weight, 1.0)
668
-
669
- # if isinstance(pretrained, str):
670
- # self.apply(_init_weights)
671
- # logger = get_root_logger()
672
- # load_checkpoint(self, pretrained, strict=False, logger=logger)
673
- # elif pretrained is None:
674
- # self.apply(_init_weights)
675
- # else:
676
- # raise TypeError('pretrained must be a str or None')
677
-
678
- def forward_raw(self, x):
679
- """Forward function."""
680
- x = self.patch_embed(x)
681
-
682
- Wh, Ww = x.size(2), x.size(3)
683
- if self.ape:
684
- # interpolate the position embedding to the corresponding size
685
- absolute_pos_embed = F.interpolate(
686
- self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"
687
- )
688
- x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C
689
- else:
690
- x = x.flatten(2).transpose(1, 2)
691
- x = self.pos_drop(x)
692
-
693
- outs = []
694
- for i in range(self.num_layers):
695
- layer = self.layers[i]
696
- x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
697
- # import ipdb; ipdb.set_trace()
698
-
699
- if i in self.out_indices:
700
- norm_layer = getattr(self, f"norm{i}")
701
- x_out = norm_layer(x_out)
702
-
703
- out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
704
- outs.append(out)
705
- # in:
706
- # torch.Size([2, 3, 1024, 1024])
707
- # outs:
708
- # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \
709
- # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])]
710
- return tuple(outs)
711
-
712
- def forward(self, tensor_list: NestedTensor):
713
- x = tensor_list.tensors
714
-
715
- """Forward function."""
716
- x = self.patch_embed(x)
717
-
718
- Wh, Ww = x.size(2), x.size(3)
719
- if self.ape:
720
- # interpolate the position embedding to the corresponding size
721
- absolute_pos_embed = F.interpolate(
722
- self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"
723
- )
724
- x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C
725
- else:
726
- x = x.flatten(2).transpose(1, 2)
727
- x = self.pos_drop(x)
728
-
729
- outs = []
730
- for i in range(self.num_layers):
731
- layer = self.layers[i]
732
- x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
733
-
734
- if i in self.out_indices:
735
- norm_layer = getattr(self, f"norm{i}")
736
- x_out = norm_layer(x_out)
737
-
738
- out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
739
- outs.append(out)
740
- # in:
741
- # torch.Size([2, 3, 1024, 1024])
742
- # out:
743
- # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \
744
- # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])]
745
-
746
- # collect for nesttensors
747
- outs_dict = {}
748
- for idx, out_i in enumerate(outs):
749
- m = tensor_list.mask
750
- assert m is not None
751
- mask = F.interpolate(m[None].float(), size=out_i.shape[-2:]).to(torch.bool)[0]
752
- outs_dict[idx] = NestedTensor(out_i, mask)
753
-
754
- return outs_dict
755
-
756
- def train(self, mode=True):
757
- """Convert the model into training mode while keep layers freezed."""
758
- super(SwinTransformer, self).train(mode)
759
- self._freeze_stages()
760
-
761
-
762
- def build_swin_transformer(modelname, pretrain_img_size, **kw):
763
- assert modelname in [
764
- "swin_T_224_1k",
765
- "swin_B_224_22k",
766
- "swin_B_384_22k",
767
- "swin_L_224_22k",
768
- "swin_L_384_22k",
769
- ]
770
-
771
- model_para_dict = {
772
- "swin_T_224_1k": dict(
773
- embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7
774
- ),
775
- "swin_B_224_22k": dict(
776
- embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7
777
- ),
778
- "swin_B_384_22k": dict(
779
- embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12
780
- ),
781
- "swin_L_224_22k": dict(
782
- embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=7
783
- ),
784
- "swin_L_384_22k": dict(
785
- embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12
786
- ),
787
- }
788
- kw_cgf = model_para_dict[modelname]
789
- kw_cgf.update(kw)
790
- model = SwinTransformer(pretrain_img_size=pretrain_img_size, **kw_cgf)
791
- return model
792
-
793
-
794
- if __name__ == "__main__":
795
- model = build_swin_transformer("swin_L_384_22k", 384, dilation=True)
796
- x = torch.rand(2, 3, 1024, 1024)
797
- y = model.forward_raw(x)
798
- import ipdb
799
-
800
- ipdb.set_trace()
801
- x = torch.rand(2, 3, 384, 384)
802
- y = model.forward_raw(x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ChandraMohanNayal/AutoGPT/autogpt/commands/git_operations.py DELETED
@@ -1,26 +0,0 @@
1
- """Git operations for autogpt"""
2
- import git
3
-
4
- from autogpt.config import Config
5
- from autogpt.workspace import path_in_workspace
6
-
7
- CFG = Config()
8
-
9
-
10
- def clone_repository(repo_url: str, clone_path: str) -> str:
11
- """Clone a GitHub repository locally
12
-
13
- Args:
14
- repo_url (str): The URL of the repository to clone
15
- clone_path (str): The path to clone the repository to
16
-
17
- Returns:
18
- str: The result of the clone operation"""
19
- split_url = repo_url.split("//")
20
- auth_repo_url = f"//{CFG.github_username}:{CFG.github_api_key}@".join(split_url)
21
- safe_clone_path = path_in_workspace(clone_path)
22
- try:
23
- git.Repo.clone_from(auth_repo_url, safe_clone_path)
24
- return f"""Cloned {repo_url} to {safe_clone_path}"""
25
- except Exception as e:
26
- return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Chujinze/Res2Net/app.py DELETED
@@ -1,332 +0,0 @@
1
- import gradio as gr
2
- import torch.nn as nn
3
- import math
4
- import torch.utils.model_zoo as model_zoo
5
- import torch
6
- import torch.nn.functional as F
7
-
8
- __all__ = ['Res2Net', 'res2net50_v1b', 'res2net101_v1b']
9
-
10
- model_urls = {
11
- 'res2net50_v1b_26w_4s': 'https://shanghuagao.oss-cn-beijing.aliyuncs.com/res2net/res2net50_v1b_26w_4s-3cf99910.pth',
12
- 'res2net101_v1b_26w_4s': 'https://shanghuagao.oss-cn-beijing.aliyuncs.com/res2net/res2net101_v1b_26w_4s-0812c246.pth',
13
- }
14
-
15
-
16
- class Bottle2neck(nn.Module):
17
- expansion = 4
18
-
19
- def __init__(self, inplanes, planes, stride=1, downsample=None, baseWidth=26, scale=4, stype='normal'):
20
- """ Constructor
21
- Args:
22
- inplanes: input channel dimensionality
23
- planes: output channel dimensionality
24
- stride: conv stride. Replaces pooling layer.
25
- downsample: None when stride = 1
26
- baseWidth: basic width of conv3x3
27
- scale: number of scale.
28
- type: 'normal': normal set. 'stage': first block of a new stage.
29
- """
30
- super(Bottle2neck, self).__init__()
31
-
32
- width = int(math.floor(planes * (baseWidth / 64.0)))
33
- self.conv1 = nn.Conv2d(inplanes, width * scale, kernel_size=1, bias=False)
34
- self.bn1 = nn.BatchNorm2d(width * scale)
35
-
36
- if scale == 1:
37
- self.nums = 1
38
- else:
39
- self.nums = scale - 1
40
- if stype == 'stage':
41
- self.pool = nn.AvgPool2d(kernel_size=3, stride=stride, padding=1)
42
- convs = []
43
- bns = []
44
- for i in range(self.nums):
45
- convs.append(nn.Conv2d(width, width, kernel_size=3, stride=stride, padding=1, bias=False))
46
- bns.append(nn.BatchNorm2d(width))
47
- self.convs = nn.ModuleList(convs)
48
- self.bns = nn.ModuleList(bns)
49
-
50
- self.conv3 = nn.Conv2d(width * scale, planes * self.expansion, kernel_size=1, bias=False)
51
- self.bn3 = nn.BatchNorm2d(planes * self.expansion)
52
-
53
- self.relu = nn.ReLU(inplace=True)
54
- self.downsample = downsample
55
- self.stype = stype
56
- self.scale = scale
57
- self.width = width
58
-
59
- def forward(self, x):
60
- residual = x
61
-
62
- out = self.conv1(x)
63
- out = self.bn1(out)
64
- out = self.relu(out)
65
-
66
- spx = torch.split(out, self.width, 1)
67
- for i in range(self.nums):
68
- if i == 0 or self.stype == 'stage':
69
- sp = spx[i]
70
- else:
71
- sp = sp + spx[i]
72
- sp = self.convs[i](sp)
73
- sp = self.relu(self.bns[i](sp))
74
- if i == 0:
75
- out = sp
76
- else:
77
- out = torch.cat((out, sp), 1)
78
- if self.scale != 1 and self.stype == 'normal':
79
- out = torch.cat((out, spx[self.nums]), 1)
80
- elif self.scale != 1 and self.stype == 'stage':
81
- out = torch.cat((out, self.pool(spx[self.nums])), 1)
82
-
83
- out = self.conv3(out)
84
- out = self.bn3(out)
85
-
86
- if self.downsample is not None:
87
- residual = self.downsample(x)
88
-
89
- out += residual
90
- out = self.relu(out)
91
-
92
- return out
93
-
94
-
95
- class Res2Net(nn.Module):
96
-
97
- def __init__(self, block, layers, baseWidth=26, scale=4, num_classes=1000):
98
- self.inplanes = 64
99
- super(Res2Net, self).__init__()
100
- self.baseWidth = baseWidth
101
- self.scale = scale
102
- self.conv1 = nn.Sequential(
103
- nn.Conv2d(3, 32, 3, 2, 1, bias=False),
104
- nn.BatchNorm2d(32),
105
- nn.ReLU(inplace=True),
106
- nn.Conv2d(32, 32, 3, 1, 1, bias=False),
107
- nn.BatchNorm2d(32),
108
- nn.ReLU(inplace=True),
109
- nn.Conv2d(32, 64, 3, 1, 1, bias=False)
110
- )
111
- self.bn1 = nn.BatchNorm2d(64)
112
- self.relu = nn.ReLU()
113
- self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
114
- self.layer1 = self._make_layer(block, 64, layers[0])
115
- self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
116
- self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
117
- self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
118
- self.avgpool = nn.AdaptiveAvgPool2d(1)
119
- self.fc = nn.Linear(512 * block.expansion, num_classes)
120
-
121
- for m in self.modules():
122
- if isinstance(m, nn.Conv2d):
123
- nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
124
- elif isinstance(m, nn.BatchNorm2d):
125
- nn.init.constant_(m.weight, 1)
126
- nn.init.constant_(m.bias, 0)
127
-
128
- def _make_layer(self, block, planes, blocks, stride=1):
129
- downsample = None
130
- if stride != 1 or self.inplanes != planes * block.expansion:
131
- downsample = nn.Sequential(
132
- nn.AvgPool2d(kernel_size=stride, stride=stride,
133
- ceil_mode=True, count_include_pad=False),
134
- nn.Conv2d(self.inplanes, planes * block.expansion,
135
- kernel_size=1, stride=1, bias=False),
136
- nn.BatchNorm2d(planes * block.expansion),
137
- )
138
-
139
- layers = []
140
- layers.append(block(self.inplanes, planes, stride, downsample=downsample,
141
- stype='stage', baseWidth=self.baseWidth, scale=self.scale))
142
- self.inplanes = planes * block.expansion
143
- for i in range(1, blocks):
144
- layers.append(block(self.inplanes, planes, baseWidth=self.baseWidth, scale=self.scale))
145
-
146
- return nn.Sequential(*layers)
147
-
148
- def forward(self, x):
149
- x = self.conv1(x)
150
- x = self.bn1(x)
151
- x = self.relu(x)
152
- x = self.maxpool(x)
153
-
154
- x = self.layer1(x)
155
- x = self.layer2(x)
156
- x = self.layer3(x)
157
- x = self.layer4(x)
158
-
159
- x = self.avgpool(x)
160
- x = x.view(x.size(0), -1)
161
- x = self.fc(x)
162
-
163
- return x
164
-
165
-
166
- def res2net50_v1b(pretrained=False, **kwargs):
167
- """Constructs a Res2Net-50_v1b model.
168
- Res2Net-50 refers to the Res2Net-50_v1b_26w_4s.
169
- Args:
170
- pretrained (bool): If True, returns a model pre-trained on ImageNet
171
- """
172
- model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth=26, scale=4, **kwargs)
173
- if pretrained:
174
- model.load_state_dict(model_zoo.load_url(model_urls['res2net50_v1b_26w_4s']))
175
- return model
176
-
177
-
178
- def res2net101_v1b(pretrained=False, **kwargs):
179
- """Constructs a Res2Net-50_v1b_26w_4s model.
180
- Args:
181
- pretrained (bool): If True, returns a model pre-trained on ImageNet
182
- """
183
- model = Res2Net(Bottle2neck, [3, 4, 23, 3], baseWidth=26, scale=4, **kwargs)
184
- if pretrained:
185
- model.load_state_dict(model_zoo.load_url(model_urls['res2net101_v1b_26w_4s']))
186
- return model
187
-
188
-
189
- def res2net50_v1b_26w_4s(pretrained=False, **kwargs):
190
- """Constructs a Res2Net-50_v1b_26w_4s model.
191
- Args:
192
- pretrained (bool): If True, returns a model pre-trained on ImageNet
193
- """
194
- model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth=26, scale=4, **kwargs)
195
- if pretrained:
196
- model.load_state_dict(torch.load(pthfile, map_location='cpu')) # load model
197
- return model
198
-
199
-
200
- def res2net101_v1b_26w_4s(pretrained=False, **kwargs):
201
- """Constructs a Res2Net-50_v1b_26w_4s model.
202
- Args:
203
- pretrained (bool): If True, returns a model pre-trained on ImageNet
204
- """
205
- model = Res2Net(Bottle2neck, [3, 4, 23, 3], baseWidth=26, scale=4, **kwargs)
206
- if pretrained:
207
- model.load_state_dict(model_zoo.load_url(model_urls['res2net101_v1b_26w_4s']))
208
- return model
209
-
210
-
211
- def res2net152_v1b_26w_4s(pretrained=False, **kwargs):
212
- """Constructs a Res2Net-50_v1b_26w_4s model.
213
- Args:
214
- pretrained (bool): If True, returns a model pre-trained on ImageNet
215
- """
216
- model = Res2Net(Bottle2neck, [3, 8, 36, 3], baseWidth=26, scale=4, **kwargs)
217
- if pretrained:
218
- model.load_state_dict(model_zoo.load_url(model_urls['res2net152_v1b_26w_4s']))
219
- return model
220
-
221
-
222
- class mutil_model(nn.Module):
223
-
224
- def __init__(self, category_num=10):
225
- super(mutil_model, self).__init__()
226
- self.model1 = res2net50_v1b_26w_4s(pretrained=False)
227
- self.model1.fc = nn.Sequential(
228
- nn.Linear(in_features=2048, out_features=category_num, bias=True),
229
- )
230
- self.model2 = torch.load('./enet_b2_8' + '.pt', map_location=torch.device('cpu'))
231
- self.model2.classifier = nn.Sequential(
232
- nn.Linear(in_features=1408, out_features=category_num, bias=True),
233
- )
234
- self.fc = nn.Linear(in_features=category_num * 2, out_features=category_num, bias=True)
235
-
236
- def forward(self, x):
237
- x1 = self.model1(x)
238
- x2 = self.model2(x)
239
- x = torch.cat((x1, x2), 1)
240
- x = self.fc(x)
241
- return x
242
-
243
-
244
- pth_path = './res2net_pretrain_model_999.pt'
245
- category_num = 9
246
-
247
- # "cuda" only when GPUs are available.
248
- #device = "cuda" if torch.cuda.is_available() else "cpu"
249
- device = "cpu"
250
- #Initialize a model, and put it on the device specified.
251
- # 导入res2net预训练模型
252
- # pthfile = './res2net50_v1b.pth'
253
- model = res2net50_v1b_26w_4s(pretrained=False)
254
- # 修改全连接层,输出维度为预测 分类
255
- num_ftrs = model.fc.in_features
256
- model.fc = nn.Sequential(
257
- nn.Linear(in_features=2048, out_features=1000, bias=True),
258
- nn.Dropout(0.5),
259
- nn.Linear(1000, out_features=category_num)
260
- )
261
- model.fc = nn.Sequential(
262
- nn.Linear(in_features=2048, out_features=category_num, bias=True),
263
- )
264
-
265
- model = model.to(device)
266
- model.device = device
267
- model.load_state_dict(torch.load(pth_path,torch.device('cpu')))
268
- model.eval()
269
-
270
-
271
- # 增加人脸识别模型
272
- #model = mutil_model(category_num=7)
273
- #model_state = torch.load('./add_face_emotion_model_7.pt', map_location=torch.device('cpu')).state_dict()
274
- #model.load_state_dict(model_state) # 加载模型参数
275
- #model.eval()
276
-
277
- labels = ['中国风', '古典', '电子', '摇滚', '乡村', '说唱', '民谣', '动漫', '现代']
278
-
279
- import requests
280
- import torch
281
-
282
- import gradio as gr
283
- import torchvision.transforms as transforms
284
-
285
- # import cv2
286
- # from PIL import Image
287
- # PIL
288
- # from PIL import Image
289
- # inception_net = tf.keras.applications.MobileNetV2() # load the model
290
-
291
- # Download human-readable labels for ImageNet.
292
- # response = requests.get("https://git.io/JJkYN")
293
- # labels = response.text.split("\n")
294
- print(len(labels))
295
-
296
-
297
- def classify_image(inp):
298
- # inp = inp.convert('RGB')
299
- # inp = Image.fromarray(inp.astype('uint8'), 'RGB')
300
- transform_test = transforms.Compose([
301
- # transforms.ToPILImage(),
302
- transforms.Resize((256, 256)),
303
- transforms.ToTensor(),
304
- transforms.Normalize((0.485, 0.456, 0.406),
305
- (0.229, 0.224, 0.225)),
306
- ])
307
- inp = transform_test(inp)
308
- print(inp)
309
- with torch.no_grad():
310
- prediction = model(torch.unsqueeze(inp, 0)).flatten()
311
- print(prediction)
312
- prediction = torch.nn.Softmax(dim=0)(prediction)
313
- print(prediction)
314
- return {labels[i]: float(prediction[i].item()) for i in range(len(labels))}
315
-
316
-
317
- # print(classify_image("/jj.jpg"))
318
- # image = gr.inputs.Image(shape=(256, 256))
319
- # image = gr.inputs.Image()
320
- # print(image)
321
- # label = gr.outputs.Label(num_top_classes=6)
322
-
323
- gr.Interface(
324
- classify_image,
325
- # gr.inputs.Image(),
326
- gr.inputs.Image(type='pil'),
327
- outputs='label'
328
- # inputs='image',
329
- # outputs='label',
330
- # examples=[["images/cheetah1.jpg"], ["images/lion.jpg"]],
331
- ).launch(share=True)
332
- # share=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/ClearLove443/Robby-chatbot/modules/embedder.py DELETED
@@ -1,87 +0,0 @@
1
- import os
2
- import pickle
3
- import tempfile
4
-
5
- from langchain.document_loaders import PyPDFLoader, TextLoader
6
- from langchain.document_loaders.csv_loader import CSVLoader
7
- from langchain.embeddings.openai import OpenAIEmbeddings
8
- from langchain.text_splitter import RecursiveCharacterTextSplitter
9
- from langchain.vectorstores import FAISS
10
-
11
-
12
- class Embedder:
13
- def __init__(self):
14
- self.PATH = "embeddings"
15
- self.createEmbeddingsDir()
16
-
17
- def createEmbeddingsDir(self):
18
- """
19
- Creates a directory to store the embeddings vectors
20
- """
21
- if not os.path.exists(self.PATH):
22
- os.mkdir(self.PATH)
23
-
24
- def storeDocEmbeds(self, file, original_filename):
25
- """
26
- Stores document embeddings using Langchain and FAISS
27
- """
28
- with tempfile.NamedTemporaryFile(mode="wb", delete=False) as tmp_file:
29
- tmp_file.write(file)
30
- tmp_file_path = tmp_file.name
31
-
32
- def get_file_extension(uploaded_file):
33
- file_extension = os.path.splitext(uploaded_file)[1].lower()
34
-
35
- return file_extension
36
-
37
- text_splitter = RecursiveCharacterTextSplitter(
38
- chunk_size=2000,
39
- chunk_overlap=100,
40
- length_function=len,
41
- )
42
-
43
- file_extension = get_file_extension(original_filename)
44
-
45
- if file_extension == ".csv":
46
- loader = CSVLoader(
47
- file_path=tmp_file_path,
48
- encoding="utf-8",
49
- csv_args={
50
- "delimiter": ",",
51
- },
52
- )
53
- data = loader.load()
54
-
55
- elif file_extension == ".pdf":
56
- loader = PyPDFLoader(file_path=tmp_file_path)
57
- data = loader.load_and_split(text_splitter)
58
-
59
- elif file_extension == ".txt":
60
- loader = TextLoader(file_path=tmp_file_path, encoding="utf-8")
61
- data = loader.load_and_split(text_splitter)
62
-
63
- # embeddings = OpenAIEmbeddings()
64
- from langchain.embeddings import HuggingFaceEmbeddings
65
-
66
- modelpath = "intfloat/e5-large-v2"
67
- embeddings = HuggingFaceEmbeddings(model_name=modelpath)
68
-
69
- vectors = FAISS.from_documents(data, embeddings)
70
- os.remove(tmp_file_path)
71
-
72
- # Save the vectors to a pickle file
73
- with open(f"{self.PATH}/{original_filename}.pkl", "wb") as f:
74
- pickle.dump(vectors, f)
75
-
76
- def getDocEmbeds(self, file, original_filename):
77
- """
78
- Retrieves document embeddings
79
- """
80
- if not os.path.isfile(f"{self.PATH}/{original_filename}.pkl"):
81
- self.storeDocEmbeds(file, original_filename)
82
-
83
- # Load the vectors from the pickle file
84
- with open(f"{self.PATH}/{original_filename}.pkl", "rb") as f:
85
- vectors = pickle.load(f)
86
-
87
- return vectors
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/Cletrason/Cletrason-toad-in-the-mario-movie/utils (2).py DELETED
@@ -1,6 +0,0 @@
1
- def is_google_colab():
2
- try:
3
- import google.colab
4
- return True
5
- except:
6
- return False
 
 
 
 
 
 
 
spaces/Codecooker/rvcapi/src/rmvpe.py DELETED
@@ -1,409 +0,0 @@
1
- import numpy as np
2
- import torch
3
- import torch.nn as nn
4
- import torch.nn.functional as F
5
- from librosa.filters import mel
6
-
7
-
8
- class BiGRU(nn.Module):
9
- def __init__(self, input_features, hidden_features, num_layers):
10
- super(BiGRU, self).__init__()
11
- self.gru = nn.GRU(
12
- input_features,
13
- hidden_features,
14
- num_layers=num_layers,
15
- batch_first=True,
16
- bidirectional=True,
17
- )
18
-
19
- def forward(self, x):
20
- return self.gru(x)[0]
21
-
22
-
23
- class ConvBlockRes(nn.Module):
24
- def __init__(self, in_channels, out_channels, momentum=0.01):
25
- super(ConvBlockRes, self).__init__()
26
- self.conv = nn.Sequential(
27
- nn.Conv2d(
28
- in_channels=in_channels,
29
- out_channels=out_channels,
30
- kernel_size=(3, 3),
31
- stride=(1, 1),
32
- padding=(1, 1),
33
- bias=False,
34
- ),
35
- nn.BatchNorm2d(out_channels, momentum=momentum),
36
- nn.ReLU(),
37
- nn.Conv2d(
38
- in_channels=out_channels,
39
- out_channels=out_channels,
40
- kernel_size=(3, 3),
41
- stride=(1, 1),
42
- padding=(1, 1),
43
- bias=False,
44
- ),
45
- nn.BatchNorm2d(out_channels, momentum=momentum),
46
- nn.ReLU(),
47
- )
48
- if in_channels != out_channels:
49
- self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
50
- self.is_shortcut = True
51
- else:
52
- self.is_shortcut = False
53
-
54
- def forward(self, x):
55
- if self.is_shortcut:
56
- return self.conv(x) + self.shortcut(x)
57
- else:
58
- return self.conv(x) + x
59
-
60
-
61
- class Encoder(nn.Module):
62
- def __init__(
63
- self,
64
- in_channels,
65
- in_size,
66
- n_encoders,
67
- kernel_size,
68
- n_blocks,
69
- out_channels=16,
70
- momentum=0.01,
71
- ):
72
- super(Encoder, self).__init__()
73
- self.n_encoders = n_encoders
74
- self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
75
- self.layers = nn.ModuleList()
76
- self.latent_channels = []
77
- for i in range(self.n_encoders):
78
- self.layers.append(
79
- ResEncoderBlock(
80
- in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
81
- )
82
- )
83
- self.latent_channels.append([out_channels, in_size])
84
- in_channels = out_channels
85
- out_channels *= 2
86
- in_size //= 2
87
- self.out_size = in_size
88
- self.out_channel = out_channels
89
-
90
- def forward(self, x):
91
- concat_tensors = []
92
- x = self.bn(x)
93
- for i in range(self.n_encoders):
94
- _, x = self.layers[i](x)
95
- concat_tensors.append(_)
96
- return x, concat_tensors
97
-
98
-
99
- class ResEncoderBlock(nn.Module):
100
- def __init__(
101
- self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
102
- ):
103
- super(ResEncoderBlock, self).__init__()
104
- self.n_blocks = n_blocks
105
- self.conv = nn.ModuleList()
106
- self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
107
- for i in range(n_blocks - 1):
108
- self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
109
- self.kernel_size = kernel_size
110
- if self.kernel_size is not None:
111
- self.pool = nn.AvgPool2d(kernel_size=kernel_size)
112
-
113
- def forward(self, x):
114
- for i in range(self.n_blocks):
115
- x = self.conv[i](x)
116
- if self.kernel_size is not None:
117
- return x, self.pool(x)
118
- else:
119
- return x
120
-
121
-
122
- class Intermediate(nn.Module): #
123
- def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
124
- super(Intermediate, self).__init__()
125
- self.n_inters = n_inters
126
- self.layers = nn.ModuleList()
127
- self.layers.append(
128
- ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
129
- )
130
- for i in range(self.n_inters - 1):
131
- self.layers.append(
132
- ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
133
- )
134
-
135
- def forward(self, x):
136
- for i in range(self.n_inters):
137
- x = self.layers[i](x)
138
- return x
139
-
140
-
141
- class ResDecoderBlock(nn.Module):
142
- def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
143
- super(ResDecoderBlock, self).__init__()
144
- out_padding = (0, 1) if stride == (1, 2) else (1, 1)
145
- self.n_blocks = n_blocks
146
- self.conv1 = nn.Sequential(
147
- nn.ConvTranspose2d(
148
- in_channels=in_channels,
149
- out_channels=out_channels,
150
- kernel_size=(3, 3),
151
- stride=stride,
152
- padding=(1, 1),
153
- output_padding=out_padding,
154
- bias=False,
155
- ),
156
- nn.BatchNorm2d(out_channels, momentum=momentum),
157
- nn.ReLU(),
158
- )
159
- self.conv2 = nn.ModuleList()
160
- self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
161
- for i in range(n_blocks - 1):
162
- self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
163
-
164
- def forward(self, x, concat_tensor):
165
- x = self.conv1(x)
166
- x = torch.cat((x, concat_tensor), dim=1)
167
- for i in range(self.n_blocks):
168
- x = self.conv2[i](x)
169
- return x
170
-
171
-
172
- class Decoder(nn.Module):
173
- def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
174
- super(Decoder, self).__init__()
175
- self.layers = nn.ModuleList()
176
- self.n_decoders = n_decoders
177
- for i in range(self.n_decoders):
178
- out_channels = in_channels // 2
179
- self.layers.append(
180
- ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
181
- )
182
- in_channels = out_channels
183
-
184
- def forward(self, x, concat_tensors):
185
- for i in range(self.n_decoders):
186
- x = self.layers[i](x, concat_tensors[-1 - i])
187
- return x
188
-
189
-
190
- class DeepUnet(nn.Module):
191
- def __init__(
192
- self,
193
- kernel_size,
194
- n_blocks,
195
- en_de_layers=5,
196
- inter_layers=4,
197
- in_channels=1,
198
- en_out_channels=16,
199
- ):
200
- super(DeepUnet, self).__init__()
201
- self.encoder = Encoder(
202
- in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
203
- )
204
- self.intermediate = Intermediate(
205
- self.encoder.out_channel // 2,
206
- self.encoder.out_channel,
207
- inter_layers,
208
- n_blocks,
209
- )
210
- self.decoder = Decoder(
211
- self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
212
- )
213
-
214
- def forward(self, x):
215
- x, concat_tensors = self.encoder(x)
216
- x = self.intermediate(x)
217
- x = self.decoder(x, concat_tensors)
218
- return x
219
-
220
-
221
- class E2E(nn.Module):
222
- def __init__(
223
- self,
224
- n_blocks,
225
- n_gru,
226
- kernel_size,
227
- en_de_layers=5,
228
- inter_layers=4,
229
- in_channels=1,
230
- en_out_channels=16,
231
- ):
232
- super(E2E, self).__init__()
233
- self.unet = DeepUnet(
234
- kernel_size,
235
- n_blocks,
236
- en_de_layers,
237
- inter_layers,
238
- in_channels,
239
- en_out_channels,
240
- )
241
- self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
242
- if n_gru:
243
- self.fc = nn.Sequential(
244
- BiGRU(3 * 128, 256, n_gru),
245
- nn.Linear(512, 360),
246
- nn.Dropout(0.25),
247
- nn.Sigmoid(),
248
- )
249
- else:
250
- self.fc = nn.Sequential(
251
- nn.Linear(3 * N_MELS, N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
252
- )
253
-
254
- def forward(self, mel):
255
- mel = mel.transpose(-1, -2).unsqueeze(1)
256
- x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
257
- x = self.fc(x)
258
- return x
259
-
260
-
261
- class MelSpectrogram(torch.nn.Module):
262
- def __init__(
263
- self,
264
- is_half,
265
- n_mel_channels,
266
- sampling_rate,
267
- win_length,
268
- hop_length,
269
- n_fft=None,
270
- mel_fmin=0,
271
- mel_fmax=None,
272
- clamp=1e-5,
273
- ):
274
- super().__init__()
275
- n_fft = win_length if n_fft is None else n_fft
276
- self.hann_window = {}
277
- mel_basis = mel(
278
- sr=sampling_rate,
279
- n_fft=n_fft,
280
- n_mels=n_mel_channels,
281
- fmin=mel_fmin,
282
- fmax=mel_fmax,
283
- htk=True,
284
- )
285
- mel_basis = torch.from_numpy(mel_basis).float()
286
- self.register_buffer("mel_basis", mel_basis)
287
- self.n_fft = win_length if n_fft is None else n_fft
288
- self.hop_length = hop_length
289
- self.win_length = win_length
290
- self.sampling_rate = sampling_rate
291
- self.n_mel_channels = n_mel_channels
292
- self.clamp = clamp
293
- self.is_half = is_half
294
-
295
- def forward(self, audio, keyshift=0, speed=1, center=True):
296
- factor = 2 ** (keyshift / 12)
297
- n_fft_new = int(np.round(self.n_fft * factor))
298
- win_length_new = int(np.round(self.win_length * factor))
299
- hop_length_new = int(np.round(self.hop_length * speed))
300
- keyshift_key = str(keyshift) + "_" + str(audio.device)
301
- if keyshift_key not in self.hann_window:
302
- self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
303
- audio.device
304
- )
305
- fft = torch.stft(
306
- audio,
307
- n_fft=n_fft_new,
308
- hop_length=hop_length_new,
309
- win_length=win_length_new,
310
- window=self.hann_window[keyshift_key],
311
- center=center,
312
- return_complex=True,
313
- )
314
- magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
315
- if keyshift != 0:
316
- size = self.n_fft // 2 + 1
317
- resize = magnitude.size(1)
318
- if resize < size:
319
- magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
320
- magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
321
- mel_output = torch.matmul(self.mel_basis, magnitude)
322
- if self.is_half == True:
323
- mel_output = mel_output.half()
324
- log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
325
- return log_mel_spec
326
-
327
-
328
- class RMVPE:
329
- def __init__(self, model_path, is_half, device=None):
330
- self.resample_kernel = {}
331
- model = E2E(4, 1, (2, 2))
332
- ckpt = torch.load(model_path, map_location="cpu")
333
- model.load_state_dict(ckpt)
334
- model.eval()
335
- if is_half == True:
336
- model = model.half()
337
- self.model = model
338
- self.resample_kernel = {}
339
- self.is_half = is_half
340
- if device is None:
341
- device = "cuda" if torch.cuda.is_available() else "cpu"
342
- self.device = device
343
- self.mel_extractor = MelSpectrogram(
344
- is_half, 128, 16000, 1024, 160, None, 30, 8000
345
- ).to(device)
346
- self.model = self.model.to(device)
347
- cents_mapping = 20 * np.arange(360) + 1997.3794084376191
348
- self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
349
-
350
- def mel2hidden(self, mel):
351
- with torch.no_grad():
352
- n_frames = mel.shape[-1]
353
- mel = F.pad(
354
- mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect"
355
- )
356
- hidden = self.model(mel)
357
- return hidden[:, :n_frames]
358
-
359
- def decode(self, hidden, thred=0.03):
360
- cents_pred = self.to_local_average_cents(hidden, thred=thred)
361
- f0 = 10 * (2 ** (cents_pred / 1200))
362
- f0[f0 == 10] = 0
363
- # f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
364
- return f0
365
-
366
- def infer_from_audio(self, audio, thred=0.03):
367
- audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0)
368
- # torch.cuda.synchronize()
369
- # t0=ttime()
370
- mel = self.mel_extractor(audio, center=True)
371
- # torch.cuda.synchronize()
372
- # t1=ttime()
373
- hidden = self.mel2hidden(mel)
374
- # torch.cuda.synchronize()
375
- # t2=ttime()
376
- hidden = hidden.squeeze(0).cpu().numpy()
377
- if self.is_half == True:
378
- hidden = hidden.astype("float32")
379
- f0 = self.decode(hidden, thred=thred)
380
- # torch.cuda.synchronize()
381
- # t3=ttime()
382
- # print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
383
- return f0
384
-
385
- def to_local_average_cents(self, salience, thred=0.05):
386
- # t0 = ttime()
387
- center = np.argmax(salience, axis=1) # 帧长#index
388
- salience = np.pad(salience, ((0, 0), (4, 4))) # 帧长,368
389
- # t1 = ttime()
390
- center += 4
391
- todo_salience = []
392
- todo_cents_mapping = []
393
- starts = center - 4
394
- ends = center + 5
395
- for idx in range(salience.shape[0]):
396
- todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
397
- todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
398
- # t2 = ttime()
399
- todo_salience = np.array(todo_salience) # 帧长,9
400
- todo_cents_mapping = np.array(todo_cents_mapping) # 帧长,9
401
- product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
402
- weight_sum = np.sum(todo_salience, 1) # 帧长
403
- devided = product_sum / weight_sum # 帧长
404
- # t3 = ttime()
405
- maxx = np.max(salience, axis=1) # 帧长
406
- devided[maxx <= thred] = 0
407
- # t4 = ttime()
408
- # print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
409
- return devided
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/F_F_T_M_.py DELETED
@@ -1,42 +0,0 @@
1
- from fontTools.misc import sstruct
2
- from fontTools.misc.textTools import safeEval
3
- from fontTools.misc.timeTools import timestampFromString, timestampToString
4
- from . import DefaultTable
5
-
6
- FFTMFormat = """
7
- > # big endian
8
- version: I
9
- FFTimeStamp: Q
10
- sourceCreated: Q
11
- sourceModified: Q
12
- """
13
-
14
-
15
- class table_F_F_T_M_(DefaultTable.DefaultTable):
16
- def decompile(self, data, ttFont):
17
- dummy, rest = sstruct.unpack2(FFTMFormat, data, self)
18
-
19
- def compile(self, ttFont):
20
- data = sstruct.pack(FFTMFormat, self)
21
- return data
22
-
23
- def toXML(self, writer, ttFont):
24
- writer.comment(
25
- "FontForge's timestamp, font source creation and modification dates"
26
- )
27
- writer.newline()
28
- formatstring, names, fixes = sstruct.getformat(FFTMFormat)
29
- for name in names:
30
- value = getattr(self, name)
31
- if name in ("FFTimeStamp", "sourceCreated", "sourceModified"):
32
- value = timestampToString(value)
33
- writer.simpletag(name, value=value)
34
- writer.newline()
35
-
36
- def fromXML(self, name, attrs, content, ttFont):
37
- value = attrs["value"]
38
- if name in ("FFTimeStamp", "sourceCreated", "sourceModified"):
39
- value = timestampFromString(value)
40
- else:
41
- value = safeEval(value)
42
- setattr(self, name, value)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
spaces/DQChoi/gpt-demo/venv/lib/python3.11/site-packages/fontTools/ttLib/tables/M_E_T_A_.py DELETED
@@ -1,346 +0,0 @@
1
- from fontTools.misc import sstruct
2
- from fontTools.misc.textTools import byteord, safeEval
3
- from . import DefaultTable
4
- import pdb
5
- import struct
6
-
7
-
8
- METAHeaderFormat = """
9
- > # big endian
10
- tableVersionMajor: H
11
- tableVersionMinor: H
12
- metaEntriesVersionMajor: H
13
- metaEntriesVersionMinor: H
14
- unicodeVersion: L
15
- metaFlags: H
16
- nMetaRecs: H
17
- """
18
- # This record is followed by nMetaRecs of METAGlyphRecordFormat.
19
- # This in turn is followd by as many METAStringRecordFormat entries
20
- # as specified by the METAGlyphRecordFormat entries
21
- # this is followed by the strings specifried in the METAStringRecordFormat
22
- METAGlyphRecordFormat = """
23
- > # big endian
24
- glyphID: H
25
- nMetaEntry: H
26
- """
27
- # This record is followd by a variable data length field:
28
- # USHORT or ULONG hdrOffset
29
- # Offset from start of META table to the beginning
30
- # of this glyphs array of ns Metadata string entries.
31
- # Size determined by metaFlags field
32
- # METAGlyphRecordFormat entries must be sorted by glyph ID
33
-
34
- METAStringRecordFormat = """
35
- > # big endian
36
- labelID: H
37
- stringLen: H
38
- """
39
- # This record is followd by a variable data length field:
40
- # USHORT or ULONG stringOffset
41
- # METAStringRecordFormat entries must be sorted in order of labelID
42
- # There may be more than one entry with the same labelID
43
- # There may be more than one strign with the same content.
44
-
45
- # Strings shall be Unicode UTF-8 encoded, and null-terminated.
46
-
47
- METALabelDict = {
48
- 0: "MojikumiX4051", # An integer in the range 1-20
49
- 1: "UNIUnifiedBaseChars",
50
- 2: "BaseFontName",
51
- 3: "Language",
52
- 4: "CreationDate",
53
- 5: "FoundryName",
54
- 6: "FoundryCopyright",
55
- 7: "OwnerURI",
56
- 8: "WritingScript",
57
- 10: "StrokeCount",
58
- 11: "IndexingRadical",
59
- }
60
-
61
-
62
- def getLabelString(labelID):
63
- try:
64
- label = METALabelDict[labelID]
65
- except KeyError:
66
- label = "Unknown label"
67
- return str(label)
68
-
69
-
70
- class table_M_E_T_A_(DefaultTable.DefaultTable):
71
-
72
- dependencies = []
73
-
74
- def decompile(self, data, ttFont):
75
- dummy, newData = sstruct.unpack2(METAHeaderFormat, data, self)
76
- self.glyphRecords = []
77
- for i in range(self.nMetaRecs):
78
- glyphRecord, newData = sstruct.unpack2(
79
- METAGlyphRecordFormat, newData, GlyphRecord()
80
- )
81
- if self.metaFlags == 0:
82
- [glyphRecord.offset] = struct.unpack(">H", newData[:2])
83
- newData = newData[2:]
84
- elif self.metaFlags == 1:
85
- [glyphRecord.offset] = struct.unpack(">H", newData[:4])
86
- newData = newData[4:]
87
- else:
88
- assert 0, (
89
- "The metaFlags field in the META table header has a value other than 0 or 1 :"
90
- + str(self.metaFlags)
91
- )
92
- glyphRecord.stringRecs = []
93
- newData = data[glyphRecord.offset :]
94
- for j in range(glyphRecord.nMetaEntry):
95
- stringRec, newData = sstruct.unpack2(
96
- METAStringRecordFormat, newData, StringRecord()
97
- )
98
- if self.metaFlags == 0:
99
- [stringRec.offset] = struct.unpack(">H", newData[:2])
100
- newData = newData[2:]
101
- else:
102
- [stringRec.offset] = struct.unpack(">H", newData[:4])
103
- newData = newData[4:]
104
- stringRec.string = data[
105
- stringRec.offset : stringRec.offset + stringRec.stringLen
106
- ]
107
- glyphRecord.stringRecs.append(stringRec)
108
- self.glyphRecords.append(glyphRecord)
109
-
110
- def compile(self, ttFont):
111
- offsetOK = 0
112
- self.nMetaRecs = len(self.glyphRecords)
113
- count = 0
114
- while offsetOK != 1:
115
- count = count + 1
116
- if count > 4:
117
- pdb.set_trace()
118
- metaData = sstruct.pack(METAHeaderFormat, self)
119
- stringRecsOffset = len(metaData) + self.nMetaRecs * (
120
- 6 + 2 * (self.metaFlags & 1)
121
- )
122
- stringRecSize = 6 + 2 * (self.metaFlags & 1)
123
- for glyphRec in self.glyphRecords:
124
- glyphRec.offset = stringRecsOffset
125
- if (glyphRec.offset > 65535) and ((self.metaFlags & 1) == 0):
126
- self.metaFlags = self.metaFlags + 1
127
- offsetOK = -1
128
- break
129
- metaData = metaData + glyphRec.compile(self)
130
- stringRecsOffset = stringRecsOffset + (
131
- glyphRec.nMetaEntry * stringRecSize
132
- )
133
- # this will be the String Record offset for the next GlyphRecord.
134
- if offsetOK == -1:
135
- offsetOK = 0
136
- continue
137
-
138
- # metaData now contains the header and all of the GlyphRecords. Its length should bw
139
- # the offset to the first StringRecord.
140
- stringOffset = stringRecsOffset
141
- for glyphRec in self.glyphRecords:
142
- assert glyphRec.offset == len(
143
- metaData
144
- ), "Glyph record offset did not compile correctly! for rec:" + str(
145
- glyphRec
146
- )
147
- for stringRec in glyphRec.stringRecs:
148
- stringRec.offset = stringOffset
149
- if (stringRec.offset > 65535) and ((self.metaFlags & 1) == 0):
150
- self.metaFlags = self.metaFlags + 1
151
- offsetOK = -1
152
- break
153
- metaData = metaData + stringRec.compile(self)
154
- stringOffset = stringOffset + stringRec.stringLen
155
- if offsetOK == -1:
156
- offsetOK = 0
157
- continue
158
-
159
- if ((self.metaFlags & 1) == 1) and (stringOffset < 65536):
160
- self.metaFlags = self.metaFlags - 1
161
- continue
162
- else:
163
- offsetOK = 1
164
-
165
- # metaData now contains the header and all of the GlyphRecords and all of the String Records.
166
- # Its length should be the offset to the first string datum.
167
- for glyphRec in self.glyphRecords:
168
- for stringRec in glyphRec.stringRecs:
169
- assert stringRec.offset == len(
170
- metaData
171
- ), "String offset did not compile correctly! for string:" + str(
172
- stringRec.string
173
- )
174
- metaData = metaData + stringRec.string
175
-
176
- return metaData
177
-
178
- def toXML(self, writer, ttFont):
179
- writer.comment(
180
- "Lengths and number of entries in this table will be recalculated by the compiler"
181
- )
182
- writer.newline()
183
- formatstring, names, fixes = sstruct.getformat(METAHeaderFormat)
184
- for name in names:
185
- value = getattr(self, name)
186
- writer.simpletag(name, value=value)
187
- writer.newline()
188
- for glyphRec in self.glyphRecords:
189
- glyphRec.toXML(writer, ttFont)
190
-
191
- def fromXML(self, name, attrs, content, ttFont):
192
- if name == "GlyphRecord":
193
- if not hasattr(self, "glyphRecords"):
194
- self.glyphRecords = []
195
- glyphRec = GlyphRecord()
196
- self.glyphRecords.append(glyphRec)
197
- for element in content:
198
- if isinstance(element, str):
199
- continue
200
- name, attrs, content = element
201
- glyphRec.fromXML(name, attrs, content, ttFont)
202
- glyphRec.offset = -1
203
- glyphRec.nMetaEntry = len(glyphRec.stringRecs)
204
- else:
205
- setattr(self, name, safeEval(attrs["value"]))
206
-
207
-
208
- class GlyphRecord(object):
209
- def __init__(self):
210
- self.glyphID = -1
211
- self.nMetaEntry = -1
212
- self.offset = -1
213
- self.stringRecs = []
214
-
215
- def toXML(self, writer, ttFont):
216
- writer.begintag("GlyphRecord")
217
- writer.newline()
218
- writer.simpletag("glyphID", value=self.glyphID)
219
- writer.newline()
220
- writer.simpletag("nMetaEntry", value=self.nMetaEntry)
221
- writer.newline()
222
- for stringRec in self.stringRecs:
223
- stringRec.toXML(writer, ttFont)
224
- writer.endtag("GlyphRecord")
225
- writer.newline()
226
-
227
- def fromXML(self, name, attrs, content, ttFont):
228
- if name == "StringRecord":
229
- stringRec = StringRecord()
230
- self.stringRecs.append(stringRec)
231
- for element in content:
232
- if isinstance(element, str):
233
- continue
234
- stringRec.fromXML(name, attrs, content, ttFont)
235
- stringRec.stringLen = len(stringRec.string)
236
- else:
237
- setattr(self, name, safeEval(attrs["value"]))
238
-
239
- def compile(self, parentTable):
240
- data = sstruct.pack(METAGlyphRecordFormat, self)
241
- if parentTable.metaFlags == 0:
242
- datum = struct.pack(">H", self.offset)
243
- elif parentTable.metaFlags == 1:
244
- datum = struct.pack(">L", self.offset)
245
- data = data + datum
246
- return data
247
-
248
- def __repr__(self):
249
- return (
250
- "GlyphRecord[ glyphID: "
251
- + str(self.glyphID)
252
- + ", nMetaEntry: "
253
- + str(self.nMetaEntry)
254
- + ", offset: "
255
- + str(self.offset)
256
- + " ]"
257
- )
258
-
259
-
260
- # XXX The following two functions are really broken around UTF-8 vs Unicode
261
-
262
-
263
- def mapXMLToUTF8(string):
264
- uString = str()
265
- strLen = len(string)
266
- i = 0
267
- while i < strLen:
268
- prefixLen = 0
269
- if string[i : i + 3] == "&#x":
270
- prefixLen = 3
271
- elif string[i : i + 7] == "&amp;#x":
272
- prefixLen = 7
273
- if prefixLen:
274
- i = i + prefixLen
275
- j = i
276
- while string[i] != ";":
277
- i = i + 1
278
- valStr = string[j:i]
279
-
280
- uString = uString + chr(eval("0x" + valStr))
281
- else:
282
- uString = uString + chr(byteord(string[i]))
283
- i = i + 1
284
-
285
- return uString.encode("utf_8")
286
-
287
-
288
- def mapUTF8toXML(string):
289
- uString = string.decode("utf_8")
290
- string = ""
291
- for uChar in uString:
292
- i = ord(uChar)
293
- if (i < 0x80) and (i > 0x1F):
294
- string = string + uChar
295
- else:
296
- string = string + "&#x" + hex(i)[2:] + ";"
297
- return string
298
-
299
-
300
- class StringRecord(object):
301
- def toXML(self, writer, ttFont):
302
- writer.begintag("StringRecord")
303
- writer.newline()
304
- writer.simpletag("labelID", value=self.labelID)
305
- writer.comment(getLabelString(self.labelID))
306
- writer.newline()
307
- writer.newline()
308
- writer.simpletag("string", value=mapUTF8toXML(self.string))
309
- writer.newline()
310
- writer.endtag("StringRecord")
311
- writer.newline()
312
-
313
- def fromXML(self, name, attrs, content, ttFont):
314
- for element in content:
315
- if isinstance(element, str):
316
- continue
317
- name, attrs, content = element
318
- value = attrs["value"]
319
- if name == "string":
320
- self.string = mapXMLToUTF8(value)
321
- else:
322
- setattr(self, name, safeEval(value))
323
-
324
- def compile(self, parentTable):
325
- data = sstruct.pack(METAStringRecordFormat, self)
326
- if parentTable.metaFlags == 0:
327
- datum = struct.pack(">H", self.offset)
328
- elif parentTable.metaFlags == 1:
329
- datum = struct.pack(">L", self.offset)
330
- data = data + datum
331
- return data
332
-
333
- def __repr__(self):
334
- return (
335
- "StringRecord [ labelID: "
336
- + str(self.labelID)
337
- + " aka "
338
- + getLabelString(self.labelID)
339
- + ", offset: "
340
- + str(self.offset)
341
- + ", length: "
342
- + str(self.stringLen)
343
- + ", string: "
344
- + self.string
345
- + " ]"
346
- )